mirror of
https://github.com/outline/outline.git
synced 2026-06-13 11:25:03 +03:00
Compare commits
42 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6a4b99ca43 | |||
| 9bf8c5c633 | |||
| fe3e712555 | |||
| 6e85e99f78 | |||
| 0e07d06a91 | |||
| cc38c4fedb | |||
| 749b9cc6b8 | |||
| be4ce4ba2e | |||
| 7afcce47ae | |||
| 7eb2bc9a16 | |||
| 67adb66c8b | |||
| 247a50be62 | |||
| 225449796a | |||
| 7e1adab035 | |||
| aca6f55ea0 | |||
| ce51fa9957 | |||
| 676e89a58e | |||
| c1d4a8e373 | |||
| 7801bcb8e7 | |||
| d4cdf4288e | |||
| efcea0a7f2 | |||
| 5004281077 | |||
| 2443be9329 | |||
| 6f49cb62c3 | |||
| 6f50ea1d60 | |||
| 52679db853 | |||
| 9a94e2dcf2 | |||
| c990ace2e2 | |||
| 7a7912b07e | |||
| 05a7627148 | |||
| 5ba613ac27 | |||
| c717e8e3eb | |||
| 144d83e68c | |||
| abd6518854 | |||
| 9c12498162 | |||
| aa879d8fab | |||
| 28aebc9fbf | |||
| abaeba5952 | |||
| b666d8f13d | |||
| 8e4844fd84 | |||
| 15892a9364 | |||
| 23a89c4d7b |
@@ -1,5 +1,8 @@
|
||||
URL=https://local.outline.dev:3000
|
||||
|
||||
DATABASE_URL=postgres://user:pass@127.0.0.1:5432/outline
|
||||
REDIS_URL=redis://127.0.0.1:6379
|
||||
|
||||
SMTP_FROM_EMAIL=hello@example.com
|
||||
|
||||
# Enable unsafe-inline in script-src CSP directive
|
||||
|
||||
+2
-2
@@ -12,14 +12,14 @@ UTILS_SECRET=generate_a_new_key
|
||||
|
||||
# For production point these at your databases, in development the default
|
||||
# should work out of the box.
|
||||
DATABASE_URL=postgres://user:pass@localhost:5432/outline
|
||||
DATABASE_URL=postgres://user:pass@postgres:5432/outline
|
||||
DATABASE_CONNECTION_POOL_MIN=
|
||||
DATABASE_CONNECTION_POOL_MAX=
|
||||
# Uncomment this to disable SSL for connecting to Postgres
|
||||
# PGSSLMODE=disable
|
||||
|
||||
# For redis you can either specify an ioredis compatible url like this
|
||||
REDIS_URL=redis://localhost:6379
|
||||
REDIS_URL=redis://redis:6379
|
||||
# or alternatively, if you would like to provide additional connection options,
|
||||
# use a base64 encoded JSON connection option object. Refer to the ioredis documentation
|
||||
# for a list of available options.
|
||||
|
||||
@@ -7,9 +7,10 @@ export enum AvatarSize {
|
||||
Small = 16,
|
||||
Toast = 18,
|
||||
Medium = 24,
|
||||
Large = 32,
|
||||
XLarge = 48,
|
||||
XXLarge = 64,
|
||||
Large = 28,
|
||||
XLarge = 32,
|
||||
XXLarge = 48,
|
||||
Upload = 64,
|
||||
}
|
||||
|
||||
export interface IAvatar {
|
||||
@@ -20,36 +21,37 @@ export interface IAvatar {
|
||||
}
|
||||
|
||||
type Props = {
|
||||
/** The size of the avatar */
|
||||
size: AvatarSize;
|
||||
/** The source of the avatar image, if not passing a model. */
|
||||
src?: string;
|
||||
/** The avatar model, if not passing a source. */
|
||||
model?: IAvatar;
|
||||
/** The alt text for the image */
|
||||
alt?: string;
|
||||
showBorder?: boolean;
|
||||
/** Optional click handler */
|
||||
onClick?: React.MouseEventHandler<HTMLImageElement>;
|
||||
/** Optional class name */
|
||||
className?: string;
|
||||
/** Optional style */
|
||||
style?: React.CSSProperties;
|
||||
};
|
||||
|
||||
function Avatar(props: Props) {
|
||||
const { showBorder, model, style, ...rest } = props;
|
||||
const { model, style, ...rest } = props;
|
||||
const src = props.src || model?.avatarUrl;
|
||||
const [error, handleError] = useBoolean(false);
|
||||
|
||||
return (
|
||||
<Relative style={style}>
|
||||
{src && !error ? (
|
||||
<CircleImg
|
||||
onError={handleError}
|
||||
src={src}
|
||||
$showBorder={showBorder}
|
||||
{...rest}
|
||||
/>
|
||||
<CircleImg onError={handleError} src={src} {...rest} />
|
||||
) : model ? (
|
||||
<Initials color={model.color} $showBorder={showBorder} {...rest}>
|
||||
<Initials color={model.color} {...rest}>
|
||||
{model.initial}
|
||||
</Initials>
|
||||
) : (
|
||||
<Initials $showBorder={showBorder} {...rest} />
|
||||
<Initials {...rest} />
|
||||
)}
|
||||
</Relative>
|
||||
);
|
||||
@@ -65,15 +67,11 @@ const Relative = styled.div`
|
||||
flex-shrink: 0;
|
||||
`;
|
||||
|
||||
const CircleImg = styled.img<{ size: number; $showBorder?: boolean }>`
|
||||
const CircleImg = styled.img<{ size: number }>`
|
||||
display: block;
|
||||
width: ${(props) => props.size}px;
|
||||
height: ${(props) => props.size}px;
|
||||
border-radius: 50%;
|
||||
border: ${(props) =>
|
||||
props.$showBorder === false
|
||||
? "none"
|
||||
: `2px solid ${props.theme.background}`};
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
`;
|
||||
|
||||
@@ -5,7 +5,7 @@ import styled, { css } from "styled-components";
|
||||
import { s } from "@shared/styles";
|
||||
import User from "~/models/User";
|
||||
import Tooltip from "~/components/Tooltip";
|
||||
import Avatar from "./Avatar";
|
||||
import Avatar, { AvatarSize } from "./Avatar";
|
||||
|
||||
type Props = {
|
||||
user: User;
|
||||
@@ -14,6 +14,8 @@ type Props = {
|
||||
isObserving: boolean;
|
||||
isCurrentUser: boolean;
|
||||
onClick?: React.MouseEventHandler<HTMLImageElement>;
|
||||
size?: AvatarSize;
|
||||
style?: React.CSSProperties;
|
||||
};
|
||||
|
||||
function AvatarWithPresence({
|
||||
@@ -23,6 +25,8 @@ function AvatarWithPresence({
|
||||
isEditing,
|
||||
isObserving,
|
||||
isCurrentUser,
|
||||
size = AvatarSize.Large,
|
||||
style,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const status = isPresent
|
||||
@@ -47,13 +51,14 @@ function AvatarWithPresence({
|
||||
}
|
||||
placement="bottom"
|
||||
>
|
||||
<AvatarWrapper
|
||||
<AvatarPresence
|
||||
$isPresent={isPresent}
|
||||
$isObserving={isObserving}
|
||||
$color={user.color}
|
||||
style={style}
|
||||
>
|
||||
<Avatar model={user} onClick={onClick} size={32} />
|
||||
</AvatarWrapper>
|
||||
<Avatar model={user} onClick={onClick} size={size} />
|
||||
</AvatarPresence>
|
||||
</Tooltip>
|
||||
</>
|
||||
);
|
||||
@@ -69,7 +74,7 @@ type AvatarWrapperProps = {
|
||||
$color: string;
|
||||
};
|
||||
|
||||
const AvatarWrapper = styled.div<AvatarWrapperProps>`
|
||||
const AvatarPresence = styled.div<AvatarWrapperProps>`
|
||||
opacity: ${(props) => (props.$isPresent ? 1 : 0.5)};
|
||||
transition: opacity 250ms ease-in-out;
|
||||
border-radius: 50%;
|
||||
|
||||
@@ -3,9 +3,12 @@ import { s } from "@shared/styles";
|
||||
import Flex from "~/components/Flex";
|
||||
|
||||
const Initials = styled(Flex)<{
|
||||
/** The color of the background, defaults to textTertiary. */
|
||||
color?: string;
|
||||
/** Content is only used to calculate font size, use children to render. */
|
||||
content?: string;
|
||||
/** The size of the avatar */
|
||||
size: number;
|
||||
$showBorder?: boolean;
|
||||
}>`
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -13,15 +16,14 @@ const Initials = styled(Flex)<{
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
color: ${s("white75")};
|
||||
background-color: ${(props) => props.color};
|
||||
background-color: ${(props) => props.color ?? props.theme.textTertiary};
|
||||
width: ${(props) => props.size}px;
|
||||
height: ${(props) => props.size}px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid
|
||||
${(props) =>
|
||||
props.$showBorder === false ? "transparent" : props.theme.background};
|
||||
flex-shrink: 0;
|
||||
font-size: ${(props) => props.size / 2}px;
|
||||
|
||||
// adjust font size down for each additional character
|
||||
font-size: ${(props) => props.size / 2 - (props.content?.length ?? 0)}px;
|
||||
font-weight: 500;
|
||||
`;
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { usePopoverState, PopoverDisclosure } from "reakit/Popover";
|
||||
import Document from "~/models/Document";
|
||||
import { AvatarWithPresence } from "~/components/Avatar";
|
||||
import { AvatarSize, AvatarWithPresence } from "~/components/Avatar";
|
||||
import DocumentViews from "~/components/DocumentViews";
|
||||
import Facepile from "~/components/Facepile";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
@@ -78,49 +78,56 @@ function Collaborators(props: Props) {
|
||||
placement: "bottom-end",
|
||||
});
|
||||
|
||||
const renderAvatar = React.useCallback(
|
||||
({ model: collaborator, ...rest }) => {
|
||||
const isPresent = presentIds.includes(collaborator.id);
|
||||
const isEditing = editingIds.includes(collaborator.id);
|
||||
const isObserving = ui.observingUserId === collaborator.id;
|
||||
const isObservable = collaborator.id !== currentUserId;
|
||||
|
||||
return (
|
||||
<AvatarWithPresence
|
||||
{...rest}
|
||||
key={collaborator.id}
|
||||
user={collaborator}
|
||||
isPresent={isPresent}
|
||||
isEditing={isEditing}
|
||||
isObserving={isObserving}
|
||||
isCurrentUser={currentUserId === collaborator.id}
|
||||
onClick={
|
||||
isObservable
|
||||
? (ev) => {
|
||||
if (isPresent) {
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
ui.setObservingUser(
|
||||
isObserving ? undefined : collaborator.id
|
||||
);
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[presentIds, ui, currentUserId, editingIds]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PopoverDisclosure {...popover}>
|
||||
{(popoverProps) => (
|
||||
<NudeButton
|
||||
width={Math.min(collaborators.length, limit) * 32}
|
||||
height={32}
|
||||
width={Math.min(collaborators.length, limit) * AvatarSize.Large}
|
||||
height={AvatarSize.Large}
|
||||
{...popoverProps}
|
||||
>
|
||||
<Facepile
|
||||
size={AvatarSize.Large}
|
||||
limit={limit}
|
||||
overflow={collaborators.length - limit}
|
||||
overflow={Math.max(0, collaborators.length - limit)}
|
||||
users={collaborators}
|
||||
renderAvatar={(collaborator) => {
|
||||
const isPresent = presentIds.includes(collaborator.id);
|
||||
const isEditing = editingIds.includes(collaborator.id);
|
||||
const isObserving = ui.observingUserId === collaborator.id;
|
||||
const isObservable = collaborator.id !== user.id;
|
||||
|
||||
return (
|
||||
<AvatarWithPresence
|
||||
key={collaborator.id}
|
||||
user={collaborator}
|
||||
isPresent={isPresent}
|
||||
isEditing={isEditing}
|
||||
isObserving={isObserving}
|
||||
isCurrentUser={currentUserId === collaborator.id}
|
||||
onClick={
|
||||
isObservable
|
||||
? (ev) => {
|
||||
if (isPresent) {
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
ui.setObservingUser(
|
||||
isObserving ? undefined : collaborator.id
|
||||
);
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
renderAvatar={renderAvatar}
|
||||
/>
|
||||
</NudeButton>
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import debounce from "lodash/debounce";
|
||||
import { observer } from "mobx-react";
|
||||
import { transparentize } from "polished";
|
||||
import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
@@ -8,23 +7,14 @@ import styled from "styled-components";
|
||||
import { richExtensions } from "@shared/editor/nodes";
|
||||
import { s } from "@shared/styles";
|
||||
import Collection from "~/models/Collection";
|
||||
import Arrow from "~/components/Arrow";
|
||||
import ButtonLink from "~/components/ButtonLink";
|
||||
import Editor from "~/components/Editor";
|
||||
import LoadingIndicator from "~/components/LoadingIndicator";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
import BlockMenuExtension from "~/editor/extensions/BlockMenu";
|
||||
import EmojiMenuExtension from "~/editor/extensions/EmojiMenu";
|
||||
import HoverPreviewsExtension from "~/editor/extensions/HoverPreviews";
|
||||
import { withUIExtensions } from "~/editor/extensions";
|
||||
import usePolicy from "~/hooks/usePolicy";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import Text from "./Text";
|
||||
|
||||
const extensions = [
|
||||
...richExtensions,
|
||||
BlockMenuExtension,
|
||||
EmojiMenuExtension,
|
||||
HoverPreviewsExtension,
|
||||
];
|
||||
const extensions = withUIExtensions(richExtensions);
|
||||
|
||||
type Props = {
|
||||
collection: Collection;
|
||||
@@ -33,33 +23,8 @@ type Props = {
|
||||
function CollectionDescription({ collection }: Props) {
|
||||
const { collections } = useStores();
|
||||
const { t } = useTranslation();
|
||||
const [isExpanded, setExpanded] = React.useState(false);
|
||||
const [isEditing, setEditing] = React.useState(false);
|
||||
const [isDirty, setDirty] = React.useState(false);
|
||||
const can = usePolicy(collection);
|
||||
|
||||
const handleStartEditing = React.useCallback(() => {
|
||||
setEditing(true);
|
||||
}, []);
|
||||
|
||||
const handleStopEditing = React.useCallback(() => {
|
||||
setEditing(false);
|
||||
}, []);
|
||||
|
||||
const handleClickDisclosure = React.useCallback(
|
||||
(event) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (isExpanded && document.activeElement) {
|
||||
// @ts-expect-error ts-migrate(2339) FIXME: Property 'blur' does not exist on type 'Element'.
|
||||
document.activeElement.blur();
|
||||
}
|
||||
|
||||
setExpanded(!isExpanded);
|
||||
},
|
||||
[isExpanded]
|
||||
);
|
||||
|
||||
const handleSave = React.useMemo(
|
||||
() =>
|
||||
debounce(async (getValue) => {
|
||||
@@ -67,7 +32,6 @@ function CollectionDescription({ collection }: Props) {
|
||||
await collection.save({
|
||||
data: getValue(false),
|
||||
});
|
||||
setDirty(false);
|
||||
} catch (err) {
|
||||
toast.error(t("Sorry, an error occurred saving the collection"));
|
||||
throw err;
|
||||
@@ -76,162 +40,44 @@ function CollectionDescription({ collection }: Props) {
|
||||
[collection, t]
|
||||
);
|
||||
|
||||
const handleChange = React.useCallback(
|
||||
async (getValue) => {
|
||||
setDirty(true);
|
||||
await handleSave(getValue);
|
||||
},
|
||||
[handleSave]
|
||||
const childRef = React.useRef<HTMLDivElement>(null);
|
||||
const childOffsetHeight = childRef.current?.offsetHeight || 0;
|
||||
const editorStyle = React.useMemo(
|
||||
() => ({
|
||||
padding: "0 32px",
|
||||
margin: "0 -32px",
|
||||
paddingBottom: `calc(50vh - ${childOffsetHeight}px)`,
|
||||
}),
|
||||
[childOffsetHeight]
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
setEditing(false);
|
||||
}, [collection.id]);
|
||||
const placeholder = `${t("Add a description")}…`;
|
||||
const key = isEditing || isDirty ? "draft" : collection.updatedAt;
|
||||
|
||||
return (
|
||||
<MaxHeight data-editing={isEditing} data-expanded={isExpanded}>
|
||||
<Input data-editing={isEditing} data-expanded={isExpanded}>
|
||||
<span onClick={can.update ? handleStartEditing : undefined}>
|
||||
{collections.isSaving && <LoadingIndicator />}
|
||||
{collection.hasDescription || isEditing || isDirty ? (
|
||||
<React.Suspense
|
||||
fallback={
|
||||
<Placeholder
|
||||
onClick={() => {
|
||||
//
|
||||
}}
|
||||
>
|
||||
Loading…
|
||||
</Placeholder>
|
||||
}
|
||||
>
|
||||
<Editor
|
||||
key={key}
|
||||
defaultValue={collection.data}
|
||||
onChange={handleChange}
|
||||
placeholder={placeholder}
|
||||
readOnly={!isEditing}
|
||||
autoFocus={isEditing}
|
||||
onBlur={handleStopEditing}
|
||||
extensions={extensions}
|
||||
maxLength={1000}
|
||||
embedsDisabled
|
||||
canUpdate
|
||||
/>
|
||||
</React.Suspense>
|
||||
) : (
|
||||
can.update && (
|
||||
<Placeholder
|
||||
onClick={() => {
|
||||
//
|
||||
}}
|
||||
>
|
||||
{placeholder}
|
||||
</Placeholder>
|
||||
)
|
||||
)}
|
||||
</span>
|
||||
</Input>
|
||||
{!isEditing && (
|
||||
<Disclosure
|
||||
onClick={handleClickDisclosure}
|
||||
aria-label={isExpanded ? t("Collapse") : t("Expand")}
|
||||
size={30}
|
||||
>
|
||||
<Arrow />
|
||||
</Disclosure>
|
||||
<>
|
||||
{collections.isSaving && <LoadingIndicator />}
|
||||
{(collection.hasDescription || can.update) && (
|
||||
<React.Suspense fallback={<Placeholder>Loading…</Placeholder>}>
|
||||
<Editor
|
||||
defaultValue={collection.data}
|
||||
onChange={handleSave}
|
||||
placeholder={`${t("Add a description")}…`}
|
||||
extensions={extensions}
|
||||
maxLength={1000}
|
||||
canUpdate={can.update}
|
||||
readOnly={!can.update}
|
||||
editorStyle={editorStyle}
|
||||
embedsDisabled
|
||||
/>
|
||||
<div ref={childRef} />
|
||||
</React.Suspense>
|
||||
)}
|
||||
</MaxHeight>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const Disclosure = styled(NudeButton)`
|
||||
opacity: 0;
|
||||
color: ${s("divider")};
|
||||
position: absolute;
|
||||
top: calc(25vh - 50px);
|
||||
left: 50%;
|
||||
z-index: 1;
|
||||
transform: rotate(-90deg) translateX(-50%);
|
||||
transition: opacity 100ms ease-in-out;
|
||||
|
||||
&:focus,
|
||||
&:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
&:active {
|
||||
color: ${s("sidebarText")};
|
||||
}
|
||||
`;
|
||||
|
||||
const Placeholder = styled(ButtonLink)`
|
||||
const Placeholder = styled(Text)`
|
||||
color: ${s("placeholder")};
|
||||
cursor: text;
|
||||
min-height: 27px;
|
||||
`;
|
||||
|
||||
const MaxHeight = styled.div`
|
||||
position: relative;
|
||||
max-height: 25vh;
|
||||
overflow: hidden;
|
||||
margin: 8px -8px -8px;
|
||||
padding: 8px;
|
||||
|
||||
&[data-editing="true"],
|
||||
&[data-expanded="true"] {
|
||||
max-height: initial;
|
||||
overflow: initial;
|
||||
|
||||
${Disclosure} {
|
||||
top: initial;
|
||||
bottom: 0;
|
||||
transform: rotate(90deg) translateX(-50%);
|
||||
}
|
||||
}
|
||||
|
||||
&:hover ${Disclosure} {
|
||||
opacity: 1;
|
||||
}
|
||||
`;
|
||||
|
||||
const Input = styled.div`
|
||||
margin: -8px;
|
||||
padding: 8px;
|
||||
border-radius: 8px;
|
||||
|
||||
&:after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: calc(25vh - 50px);
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 50px;
|
||||
pointer-events: none;
|
||||
background: linear-gradient(
|
||||
180deg,
|
||||
${(props) => transparentize(1, props.theme.background)} 0%,
|
||||
${s("background")} 100%
|
||||
);
|
||||
}
|
||||
|
||||
&[data-editing="true"],
|
||||
&[data-expanded="true"] {
|
||||
&:after {
|
||||
background: transparent;
|
||||
}
|
||||
}
|
||||
|
||||
&[data-editing="true"] {
|
||||
background: ${s("backgroundSecondary")};
|
||||
}
|
||||
|
||||
.block-menu-trigger,
|
||||
.heading-anchor {
|
||||
display: none !important;
|
||||
}
|
||||
`;
|
||||
|
||||
export default observer(CollectionDescription);
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { observer } from "mobx-react";
|
||||
import * as React from "react";
|
||||
import { Trans, useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { CollectionPermission, NavigationNode } from "@shared/types";
|
||||
import type Collection from "~/models/Collection";
|
||||
import ConfirmationDialog from "~/components/ConfirmationDialog";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { AuthorizationError } from "~/utils/errors";
|
||||
|
||||
type Props = {
|
||||
/** The navigation node to move, must represent a document. */
|
||||
@@ -30,12 +32,29 @@ function ConfirmMoveDialog({ collection, item, ...rest }: Props) {
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
await documents.move({
|
||||
documentId: item.id,
|
||||
collectionId: collection.id,
|
||||
...rest,
|
||||
});
|
||||
dialogs.closeAllModals();
|
||||
try {
|
||||
await documents.move({
|
||||
documentId: item.id,
|
||||
collectionId: collection.id,
|
||||
...rest,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof AuthorizationError) {
|
||||
toast.error(
|
||||
t(
|
||||
"You do not have permission to move {{ documentName }} to the {{ collectionName }} collection",
|
||||
{
|
||||
documentName: item.title,
|
||||
collectionName: collection.name,
|
||||
}
|
||||
)
|
||||
);
|
||||
} else {
|
||||
toast.error(err.message);
|
||||
}
|
||||
} finally {
|
||||
dialogs.closeAllModals();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -105,14 +105,15 @@ function DocumentBreadcrumb(
|
||||
}
|
||||
|
||||
path.slice(0, -1).forEach((node: NavigationNode) => {
|
||||
const title = node.title || t("Untitled");
|
||||
output.push({
|
||||
type: "route",
|
||||
title: node.icon ? (
|
||||
<>
|
||||
<StyledIcon value={node.icon} color={node.color} /> {node.title}
|
||||
<StyledIcon value={node.icon} color={node.color} /> {title}
|
||||
</>
|
||||
) : (
|
||||
node.title
|
||||
title
|
||||
),
|
||||
to: {
|
||||
pathname: node.url,
|
||||
@@ -121,7 +122,7 @@ function DocumentBreadcrumb(
|
||||
});
|
||||
});
|
||||
return output;
|
||||
}, [path, category, sidebarContext, collectionNode]);
|
||||
}, [t, path, category, sidebarContext, collectionNode]);
|
||||
|
||||
if (!collections.isLoaded) {
|
||||
return null;
|
||||
@@ -134,7 +135,7 @@ function DocumentBreadcrumb(
|
||||
{path.slice(0, -1).map((node: NavigationNode) => (
|
||||
<React.Fragment key={node.id}>
|
||||
<SmallSlash />
|
||||
{node.title}
|
||||
{node.title || t("Untitled")}
|
||||
</React.Fragment>
|
||||
))}
|
||||
</>
|
||||
|
||||
@@ -6,7 +6,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { dateLocale, dateToRelative } from "@shared/utils/date";
|
||||
import Document from "~/models/Document";
|
||||
import User from "~/models/User";
|
||||
import { Avatar } from "~/components/Avatar";
|
||||
import { Avatar, AvatarSize } from "~/components/Avatar";
|
||||
import ListItem from "~/components/List/Item";
|
||||
import PaginatedList from "~/components/PaginatedList";
|
||||
import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
@@ -71,7 +71,13 @@ function DocumentViews({ document, isOpen }: Props) {
|
||||
key={model.id}
|
||||
title={model.name}
|
||||
subtitle={subtitle}
|
||||
image={<Avatar key={model.id} model={model} size={32} />}
|
||||
image={
|
||||
<Avatar
|
||||
key={model.id}
|
||||
model={model}
|
||||
size={AvatarSize.Large}
|
||||
/>
|
||||
}
|
||||
border={false}
|
||||
small
|
||||
/>
|
||||
|
||||
@@ -17,7 +17,7 @@ import useDictionary from "~/hooks/useDictionary";
|
||||
import useEditorClickHandlers from "~/hooks/useEditorClickHandlers";
|
||||
import useEmbeds from "~/hooks/useEmbeds";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { uploadFile } from "~/utils/files";
|
||||
import { uploadFile, uploadFileFromUrl } from "~/utils/files";
|
||||
import lazyWithRetry from "~/utils/lazyWithRetry";
|
||||
|
||||
const LazyLoadedEditor = lazyWithRetry(() => import("~/editor"));
|
||||
@@ -49,11 +49,15 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
|
||||
const previousCommentIds = React.useRef<string[]>();
|
||||
|
||||
const handleUploadFile = React.useCallback(
|
||||
async (file: File) => {
|
||||
const result = await uploadFile(file, {
|
||||
async (file: File | string) => {
|
||||
const options = {
|
||||
documentId: id,
|
||||
preset: AttachmentPreset.DocumentAttachment,
|
||||
});
|
||||
};
|
||||
const result =
|
||||
file instanceof File
|
||||
? await uploadFile(file, options)
|
||||
: await uploadFileFromUrl(file, options);
|
||||
return result.url;
|
||||
},
|
||||
[id]
|
||||
|
||||
@@ -16,7 +16,7 @@ import EventBoundary from "@shared/components/EventBoundary";
|
||||
import { s, hover } from "@shared/styles";
|
||||
import Document from "~/models/Document";
|
||||
import Event from "~/models/Event";
|
||||
import { Avatar } from "~/components/Avatar";
|
||||
import { Avatar, AvatarSize } from "~/components/Avatar";
|
||||
import Item, { Actions, Props as ItemProps } from "~/components/List/Item";
|
||||
import Time from "~/components/Time";
|
||||
import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext";
|
||||
@@ -153,7 +153,7 @@ const EventListItem = ({ event, latest, document, ...rest }: Props) => {
|
||||
onClick={handleTimeClick}
|
||||
/>
|
||||
}
|
||||
image={<Avatar model={event.actor} size={32} />}
|
||||
image={<Avatar model={event.actor} size={AvatarSize.Large} />}
|
||||
subtitle={
|
||||
<Subtitle>
|
||||
{icon}
|
||||
|
||||
+62
-38
@@ -1,17 +1,26 @@
|
||||
import { observer } from "mobx-react";
|
||||
import * as React from "react";
|
||||
import styled from "styled-components";
|
||||
import { s } from "@shared/styles";
|
||||
import User from "~/models/User";
|
||||
import { Avatar, AvatarSize } from "~/components/Avatar";
|
||||
import Flex from "~/components/Flex";
|
||||
import Initials from "./Avatar/Initials";
|
||||
|
||||
type Props = {
|
||||
/** The users to display */
|
||||
users: User[];
|
||||
/** The size of the avatars, defaults to AvatarSize.Large */
|
||||
size?: number;
|
||||
/** A number to show as the number of additional users */
|
||||
overflow?: number;
|
||||
/** The maximum number of users to display, defaults to 8 */
|
||||
limit?: number;
|
||||
renderAvatar?: (user: User) => React.ReactNode;
|
||||
/** A component to render the avatar, defaults to Avatar. */
|
||||
renderAvatar?: React.ComponentType<
|
||||
React.ComponentProps<typeof Avatar> & {
|
||||
model: User;
|
||||
}
|
||||
>;
|
||||
};
|
||||
|
||||
function Facepile({
|
||||
@@ -19,55 +28,70 @@ function Facepile({
|
||||
overflow = 0,
|
||||
size = AvatarSize.Large,
|
||||
limit = 8,
|
||||
renderAvatar = DefaultAvatar,
|
||||
renderAvatar = Avatar,
|
||||
...rest
|
||||
}: Props) {
|
||||
const filtered = users.filter(Boolean).slice(-limit);
|
||||
const Component = renderAvatar;
|
||||
|
||||
return (
|
||||
<Avatars {...rest}>
|
||||
{overflow > 0 && (
|
||||
<More size={size}>
|
||||
<span>
|
||||
{users.length ? "+" : ""}
|
||||
{overflow}
|
||||
</span>
|
||||
</More>
|
||||
<Initials size={size} content={String(overflow)}>
|
||||
{users.length ? "+" : ""}
|
||||
{overflow}
|
||||
</Initials>
|
||||
)}
|
||||
{users
|
||||
.filter(Boolean)
|
||||
.slice(0, limit)
|
||||
.map((user) => (
|
||||
<AvatarWrapper key={user.id}>{renderAvatar(user)}</AvatarWrapper>
|
||||
))}
|
||||
{filtered.map((model, index) => {
|
||||
const lastChild = index === 0 && overflow <= 0;
|
||||
return (
|
||||
<Component
|
||||
key={model.id}
|
||||
{...{
|
||||
model,
|
||||
size,
|
||||
style: {
|
||||
marginRight: lastChild ? 0 : -4,
|
||||
...(lastChild || filtered.length === 1
|
||||
? {}
|
||||
: { clipPath: `url(#${clipPathId(size)})` }),
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
<FacepileClip size={size} />
|
||||
</Avatars>
|
||||
);
|
||||
}
|
||||
|
||||
function DefaultAvatar(user: User) {
|
||||
return <Avatar model={user} size={AvatarSize.Large} />;
|
||||
function FacepileClip({ size }: { size: number }) {
|
||||
return (
|
||||
<SVG
|
||||
width="25"
|
||||
height="28"
|
||||
viewBox="0 0 25 28"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<clipPath id={clipPathId(size)}>
|
||||
<path
|
||||
transform={size !== 28 ? `scale(${size / 28})` : ""}
|
||||
d="M14.0633 0.5C18.1978 0.5 21.8994 2.34071 24.3876 5.24462C22.8709 7.81315 22.0012 10.8061 22.0012 14C22.0012 17.1939 22.8709 20.1868 24.3876 22.7554C21.8994 25.6593 18.1978 27.5 14.0633 27.5C6.57035 27.5 0.5 21.4537 0.5 14C0.5 6.54628 6.57035 0.5 14.0633 0.5Z"
|
||||
/>
|
||||
</clipPath>
|
||||
</SVG>
|
||||
);
|
||||
}
|
||||
|
||||
const AvatarWrapper = styled.div`
|
||||
margin-right: -8px;
|
||||
function clipPathId(size: number) {
|
||||
return `facepile-${size}`;
|
||||
}
|
||||
|
||||
&:first-child {
|
||||
margin-right: 0;
|
||||
}
|
||||
`;
|
||||
|
||||
const More = styled.div<{ size: number }>`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: ${(props) => props.size}px;
|
||||
height: ${(props) => props.size}px;
|
||||
border-radius: 100%;
|
||||
background: ${(props) => props.theme.textTertiary};
|
||||
color: ${s("white")};
|
||||
border: 2px solid ${s("background")};
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
const SVG = styled.svg`
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
`;
|
||||
|
||||
const Avatars = styled(Flex)`
|
||||
|
||||
@@ -6,12 +6,12 @@ import * as React from "react";
|
||||
import { mergeRefs } from "react-merge-refs";
|
||||
import styled from "styled-components";
|
||||
import breakpoint from "styled-components-breakpoint";
|
||||
import { useComponentSize } from "@shared/hooks/useComponentSize";
|
||||
import { depths, s } from "@shared/styles";
|
||||
import { supportsPassiveListener } from "@shared/utils/browser";
|
||||
import Button from "~/components/Button";
|
||||
import Fade from "~/components/Fade";
|
||||
import Flex from "~/components/Flex";
|
||||
import useComponentSize from "~/hooks/useComponentSize";
|
||||
import useEventListener from "~/hooks/useEventListener";
|
||||
import useMobile from "~/hooks/useMobile";
|
||||
import useStores from "~/hooks/useStores";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { m, TargetAndTransition } from "framer-motion";
|
||||
import * as React from "react";
|
||||
import { mergeRefs } from "react-merge-refs";
|
||||
import useComponentSize from "~/hooks/useComponentSize";
|
||||
import { useComponentSize } from "@shared/hooks/useComponentSize";
|
||||
|
||||
type Props = {
|
||||
/** The children to render */
|
||||
|
||||
@@ -201,11 +201,7 @@ export const AccessControlList = observer(
|
||||
<ListItem
|
||||
key={membership.id}
|
||||
image={
|
||||
<Avatar
|
||||
model={membership.user}
|
||||
size={AvatarSize.Medium}
|
||||
showBorder={false}
|
||||
/>
|
||||
<Avatar model={membership.user} size={AvatarSize.Medium} />
|
||||
}
|
||||
title={membership.user.name}
|
||||
subtitle={membership.user.email}
|
||||
|
||||
@@ -146,7 +146,7 @@ export const AccessControlList = observer(
|
||||
/>
|
||||
) : (
|
||||
<ListItem
|
||||
image={<Avatar model={user} showBorder={false} />}
|
||||
image={<Avatar model={user} />}
|
||||
title={user.name}
|
||||
subtitle={t("You have full access")}
|
||||
actions={<AccessTooltip>{t("Can edit")}</AccessTooltip>}
|
||||
@@ -160,9 +160,7 @@ export const AccessControlList = observer(
|
||||
) : document.isDraft ? (
|
||||
<>
|
||||
<ListItem
|
||||
image={
|
||||
<Avatar model={document.createdBy} showBorder={false} />
|
||||
}
|
||||
image={<Avatar model={document.createdBy} />}
|
||||
title={document.createdBy?.name}
|
||||
actions={
|
||||
<AccessTooltip content={t("Created the document")}>
|
||||
|
||||
@@ -73,9 +73,7 @@ const DocumentMemberListItem = ({
|
||||
return (
|
||||
<ListItem
|
||||
title={user.name}
|
||||
image={
|
||||
<Avatar model={user} size={AvatarSize.Medium} showBorder={false} />
|
||||
}
|
||||
image={<Avatar model={user} size={AvatarSize.Medium} />}
|
||||
subtitle={
|
||||
membership?.sourceId ? (
|
||||
<Trans>
|
||||
|
||||
@@ -158,13 +158,7 @@ export const Suggestions = observer(
|
||||
: suggestion.isViewer
|
||||
? t("Viewer")
|
||||
: t("Editor"),
|
||||
image: (
|
||||
<Avatar
|
||||
model={suggestion}
|
||||
size={AvatarSize.Medium}
|
||||
showBorder={false}
|
||||
/>
|
||||
),
|
||||
image: <Avatar model={suggestion} size={AvatarSize.Medium} />,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import history from "~/utils/history";
|
||||
import { homePath, sharedDocumentPath } from "~/utils/routeHelpers";
|
||||
import { AvatarSize } from "../Avatar";
|
||||
import { useTeamContext } from "../TeamContext";
|
||||
import TeamLogo from "../TeamLogo";
|
||||
import Sidebar from "./Sidebar";
|
||||
@@ -40,7 +41,9 @@ function SharedSidebar({ rootNode, shareId }: Props) {
|
||||
{teamAvailable && (
|
||||
<SidebarButton
|
||||
title={team.name}
|
||||
image={<TeamLogo model={team} size={32} alt={t("Logo")} />}
|
||||
image={
|
||||
<TeamLogo model={team} size={AvatarSize.XLarge} alt={t("Logo")} />
|
||||
}
|
||||
onClick={() =>
|
||||
history.push(
|
||||
user ? homePath() : sharedDocumentPath(shareId, rootNode.url)
|
||||
|
||||
@@ -228,7 +228,6 @@ const Sidebar = React.forwardRef<HTMLDivElement, Props>(function _Sidebar(
|
||||
alt={user.name}
|
||||
model={user}
|
||||
size={24}
|
||||
showBorder={false}
|
||||
style={{ marginLeft: 4 }}
|
||||
/>
|
||||
}
|
||||
|
||||
@@ -2,26 +2,29 @@ import { Location } from "history";
|
||||
import { observer } from "mobx-react";
|
||||
import { PlusIcon } from "outline-icons";
|
||||
import * as React from "react";
|
||||
import { useDrop } from "react-dnd";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { CollectionValidation } from "@shared/validations";
|
||||
import { mergeRefs } from "react-merge-refs";
|
||||
import { useHistory } from "react-router-dom";
|
||||
import { UserPreference } from "@shared/types";
|
||||
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
|
||||
import { CollectionValidation, DocumentValidation } from "@shared/validations";
|
||||
import Collection from "~/models/Collection";
|
||||
import Document from "~/models/Document";
|
||||
import ConfirmMoveDialog from "~/components/ConfirmMoveDialog";
|
||||
import Fade from "~/components/Fade";
|
||||
import CollectionIcon from "~/components/Icons/CollectionIcon";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
import { createDocument } from "~/actions/definitions/documents";
|
||||
import useActionContext from "~/hooks/useActionContext";
|
||||
import useBoolean from "~/hooks/useBoolean";
|
||||
import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
import usePolicy from "~/hooks/usePolicy";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import CollectionMenu from "~/menus/CollectionMenu";
|
||||
import { documentEditPath } from "~/utils/routeHelpers";
|
||||
import { useDropToChangeCollection } from "../hooks/useDragAndDrop";
|
||||
import DropToImport from "./DropToImport";
|
||||
import EditableTitle, { RefHandle } from "./EditableTitle";
|
||||
import Relative from "./Relative";
|
||||
import { SidebarContextType, useSidebarContext } from "./SidebarContext";
|
||||
import SidebarLink, { DragObject } from "./SidebarLink";
|
||||
import SidebarLink from "./SidebarLink";
|
||||
|
||||
type Props = {
|
||||
collection: Collection;
|
||||
@@ -41,12 +44,14 @@ const CollectionLink: React.FC<Props> = ({
|
||||
depth,
|
||||
onClick,
|
||||
}: Props) => {
|
||||
const { dialogs, documents, collections } = useStores();
|
||||
const [menuOpen, handleMenuOpen, handleMenuClose] = useBoolean();
|
||||
const [isEditing, setIsEditing] = React.useState(false);
|
||||
const { documents } = useStores();
|
||||
const history = useHistory();
|
||||
const can = usePolicy(collection);
|
||||
const { t } = useTranslation();
|
||||
const sidebarContext = useSidebarContext();
|
||||
const user = useCurrentUser();
|
||||
const editableTitleRef = React.useRef<RefHandle>(null);
|
||||
|
||||
const handleTitleChange = React.useCallback(
|
||||
@@ -58,119 +63,127 @@ const CollectionLink: React.FC<Props> = ({
|
||||
[collection]
|
||||
);
|
||||
|
||||
// Drop to re-parent document
|
||||
const [{ isOver, canDrop }, drop] = useDrop({
|
||||
accept: "document",
|
||||
drop: async (item: DragObject, monitor) => {
|
||||
const { id, collectionId } = item;
|
||||
if (monitor.didDrop()) {
|
||||
return;
|
||||
}
|
||||
if (!collection) {
|
||||
return;
|
||||
}
|
||||
const handleExpand = React.useCallback(() => {
|
||||
if (!expanded) {
|
||||
onDisclosureClick();
|
||||
}
|
||||
}, [expanded, onDisclosureClick]);
|
||||
|
||||
const document = documents.get(id);
|
||||
if (collection.id === collectionId && !document?.parentDocumentId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const prevCollection = collections.get(collectionId);
|
||||
|
||||
if (
|
||||
prevCollection &&
|
||||
prevCollection.permission !== collection.permission &&
|
||||
!document?.isDraft
|
||||
) {
|
||||
dialogs.openModal({
|
||||
title: t("Change permissions?"),
|
||||
content: <ConfirmMoveDialog item={item} collection={collection} />,
|
||||
});
|
||||
} else {
|
||||
await documents.move({ documentId: id, collectionId: collection.id });
|
||||
|
||||
if (!expanded) {
|
||||
onDisclosureClick();
|
||||
}
|
||||
}
|
||||
},
|
||||
canDrop: () => can.createDocument,
|
||||
collect: (monitor) => ({
|
||||
isOver: !!monitor.isOver({
|
||||
shallow: true,
|
||||
}),
|
||||
canDrop: monitor.canDrop(),
|
||||
}),
|
||||
});
|
||||
const parentRef = React.useRef<HTMLDivElement>(null);
|
||||
const [{ isOver, canDrop }, dropRef] = useDropToChangeCollection(
|
||||
collection,
|
||||
handleExpand,
|
||||
parentRef
|
||||
);
|
||||
|
||||
const handlePrefetch = React.useCallback(() => {
|
||||
void collection.fetchDocuments();
|
||||
}, [collection]);
|
||||
|
||||
const context = useActionContext({
|
||||
activeCollectionId: collection.id,
|
||||
sidebarContext,
|
||||
});
|
||||
|
||||
const handleRename = React.useCallback(() => {
|
||||
editableTitleRef.current?.setIsEditing(true);
|
||||
}, [editableTitleRef]);
|
||||
|
||||
const [isAddingNewChild, setIsAddingNewChild, closeAddingNewChild] =
|
||||
useBoolean();
|
||||
|
||||
const handleNewDoc = React.useCallback(
|
||||
async (input) => {
|
||||
const newDocument = await documents.create(
|
||||
{
|
||||
collectionId: collection.id,
|
||||
title: input,
|
||||
fullWidth: user.getPreference(UserPreference.FullWidthDocuments),
|
||||
data: ProsemirrorHelper.getEmptyDocument(),
|
||||
},
|
||||
{ publish: true }
|
||||
);
|
||||
collection?.addDocument(newDocument);
|
||||
|
||||
closeAddingNewChild();
|
||||
history.replace(documentEditPath(newDocument));
|
||||
},
|
||||
[user, closeAddingNewChild, history, collection, documents]
|
||||
);
|
||||
|
||||
return (
|
||||
<Relative ref={drop}>
|
||||
<DropToImport collectionId={collection.id}>
|
||||
<>
|
||||
<Relative ref={mergeRefs([parentRef, dropRef])}>
|
||||
<DropToImport collectionId={collection.id}>
|
||||
<SidebarLink
|
||||
onClick={onClick}
|
||||
to={{
|
||||
pathname: collection.path,
|
||||
state: { sidebarContext },
|
||||
}}
|
||||
expanded={expanded}
|
||||
onDisclosureClick={onDisclosureClick}
|
||||
onClickIntent={handlePrefetch}
|
||||
icon={
|
||||
<CollectionIcon collection={collection} expanded={expanded} />
|
||||
}
|
||||
showActions={menuOpen}
|
||||
isActiveDrop={isOver && canDrop}
|
||||
isActive={(
|
||||
match,
|
||||
location: Location<{ sidebarContext?: SidebarContextType }>
|
||||
) => !!match && location.state?.sidebarContext === sidebarContext}
|
||||
label={
|
||||
<EditableTitle
|
||||
title={collection.name}
|
||||
onSubmit={handleTitleChange}
|
||||
onEditing={setIsEditing}
|
||||
canUpdate={can.update}
|
||||
maxLength={CollectionValidation.maxNameLength}
|
||||
ref={editableTitleRef}
|
||||
/>
|
||||
}
|
||||
exact={false}
|
||||
depth={depth ? depth : 0}
|
||||
menu={
|
||||
!isEditing &&
|
||||
!isDraggingAnyCollection && (
|
||||
<Fade>
|
||||
<NudeButton
|
||||
tooltip={{ content: t("New doc"), delay: 500 }}
|
||||
onClick={(ev) => {
|
||||
ev.preventDefault();
|
||||
setIsAddingNewChild();
|
||||
handleExpand();
|
||||
}}
|
||||
>
|
||||
<PlusIcon />
|
||||
</NudeButton>
|
||||
<CollectionMenu
|
||||
collection={collection}
|
||||
onRename={handleRename}
|
||||
onOpen={handleMenuOpen}
|
||||
onClose={handleMenuClose}
|
||||
/>
|
||||
</Fade>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</DropToImport>
|
||||
</Relative>
|
||||
{isAddingNewChild && (
|
||||
<SidebarLink
|
||||
onClick={onClick}
|
||||
to={{
|
||||
pathname: collection.path,
|
||||
state: { sidebarContext },
|
||||
}}
|
||||
expanded={expanded}
|
||||
onDisclosureClick={onDisclosureClick}
|
||||
onClickIntent={handlePrefetch}
|
||||
icon={<CollectionIcon collection={collection} expanded={expanded} />}
|
||||
showActions={menuOpen}
|
||||
isActiveDrop={isOver && canDrop}
|
||||
isActive={(
|
||||
match,
|
||||
location: Location<{ sidebarContext?: SidebarContextType }>
|
||||
) => !!match && location.state?.sidebarContext === sidebarContext}
|
||||
depth={2}
|
||||
isActive={() => true}
|
||||
label={
|
||||
<EditableTitle
|
||||
title={collection.name}
|
||||
onSubmit={handleTitleChange}
|
||||
onEditing={setIsEditing}
|
||||
canUpdate={can.update}
|
||||
maxLength={CollectionValidation.maxNameLength}
|
||||
ref={editableTitleRef}
|
||||
title=""
|
||||
canUpdate
|
||||
isEditing
|
||||
placeholder={`${t("New doc")}…`}
|
||||
onCancel={closeAddingNewChild}
|
||||
onSubmit={handleNewDoc}
|
||||
maxLength={DocumentValidation.maxTitleLength}
|
||||
/>
|
||||
}
|
||||
exact={false}
|
||||
depth={depth ? depth : 0}
|
||||
menu={
|
||||
!isEditing &&
|
||||
!isDraggingAnyCollection && (
|
||||
<Fade>
|
||||
<NudeButton
|
||||
tooltip={{ content: t("New doc"), delay: 500 }}
|
||||
action={createDocument}
|
||||
context={context}
|
||||
hideOnActionDisabled
|
||||
>
|
||||
<PlusIcon />
|
||||
</NudeButton>
|
||||
<CollectionMenu
|
||||
collection={collection}
|
||||
onRename={handleRename}
|
||||
onOpen={handleMenuOpen}
|
||||
onClose={handleMenuClose}
|
||||
/>
|
||||
</Fade>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</DropToImport>
|
||||
</Relative>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,25 +1,23 @@
|
||||
import noop from "lodash/noop";
|
||||
import { observer } from "mobx-react";
|
||||
import * as React from "react";
|
||||
import { useDrop } from "react-dnd";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Waypoint } from "react-waypoint";
|
||||
import { toast } from "sonner";
|
||||
import styled from "styled-components";
|
||||
import Collection from "~/models/Collection";
|
||||
import Document from "~/models/Document";
|
||||
import ConfirmMoveDialog from "~/components/ConfirmMoveDialog";
|
||||
import DocumentsLoader from "~/components/DocumentsLoader";
|
||||
import { ResizingHeightContainer } from "~/components/ResizingHeightContainer";
|
||||
import Text from "~/components/Text";
|
||||
import usePolicy from "~/hooks/usePolicy";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import history from "~/utils/history";
|
||||
import useCollectionDocuments from "../hooks/useCollectionDocuments";
|
||||
import { useDropToChangeCollection } from "../hooks/useDragAndDrop";
|
||||
import DocumentLink from "./DocumentLink";
|
||||
import DropCursor from "./DropCursor";
|
||||
import Folder from "./Folder";
|
||||
import PlaceholderCollections from "./PlaceholderCollections";
|
||||
import SidebarLink, { DragObject } from "./SidebarLink";
|
||||
import SidebarLink from "./SidebarLink";
|
||||
|
||||
type Props = {
|
||||
/** The collection to render the children of. */
|
||||
@@ -36,55 +34,17 @@ function CollectionLinkChildren({
|
||||
prefetchDocument,
|
||||
}: Props) {
|
||||
const pageSize = 250;
|
||||
const can = usePolicy(collection);
|
||||
const manualSort = collection.sort.field === "index";
|
||||
const { documents, dialogs, collections } = useStores();
|
||||
const { documents } = useStores();
|
||||
const { t } = useTranslation();
|
||||
const childDocuments = useCollectionDocuments(collection, documents.active);
|
||||
const [showing, setShowing] = React.useState(pageSize);
|
||||
const dummyRef = React.useRef<HTMLDivElement>(null);
|
||||
|
||||
// Drop to reorder document
|
||||
const [{ isOverReorder, isDraggingAnyDocument }, dropToReorder] = useDrop({
|
||||
accept: "document",
|
||||
drop: (item: DragObject) => {
|
||||
if (!manualSort && item.collectionId === collection?.id) {
|
||||
toast.message(
|
||||
t(
|
||||
"You can't reorder documents in an alphabetically sorted collection"
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!collection) {
|
||||
return;
|
||||
}
|
||||
|
||||
const prevCollection = collections.get(item.collectionId);
|
||||
|
||||
if (
|
||||
prevCollection &&
|
||||
prevCollection.permission !== collection.permission
|
||||
) {
|
||||
dialogs.openModal({
|
||||
title: t("Change permissions?"),
|
||||
content: (
|
||||
<ConfirmMoveDialog item={item} collection={collection} index={0} />
|
||||
),
|
||||
});
|
||||
} else {
|
||||
void documents.move({
|
||||
documentId: item.id,
|
||||
collectionId: collection.id,
|
||||
index: 0,
|
||||
});
|
||||
}
|
||||
},
|
||||
collect: (monitor) => ({
|
||||
isOverReorder: !!monitor.isOver(),
|
||||
isDraggingAnyDocument: !!monitor.canDrop(),
|
||||
}),
|
||||
});
|
||||
const [{ isOver, canDrop }, dropRef] = useDropToChangeCollection(
|
||||
collection,
|
||||
noop,
|
||||
dummyRef
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!expanded) {
|
||||
@@ -100,12 +60,8 @@ function CollectionLinkChildren({
|
||||
|
||||
return (
|
||||
<Folder expanded={expanded}>
|
||||
{isDraggingAnyDocument && can.createDocument && manualSort && (
|
||||
<DropCursor
|
||||
isActiveDrop={isOverReorder}
|
||||
innerRef={dropToReorder}
|
||||
position="top"
|
||||
/>
|
||||
{canDrop && collection.isManualSort && (
|
||||
<DropCursor isActiveDrop={isOver} innerRef={dropRef} position="top" />
|
||||
)}
|
||||
<DocumentsLoader collection={collection} enabled={expanded}>
|
||||
{!childDocuments && (
|
||||
|
||||
@@ -10,6 +10,7 @@ import Error from "~/components/List/Error";
|
||||
import PaginatedList from "~/components/PaginatedList";
|
||||
import { createCollection } from "~/actions/definitions/collections";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { DragObject } from "../hooks/useDragAndDrop";
|
||||
import DraggableCollectionLink from "./DraggableCollectionLink";
|
||||
import DropCursor from "./DropCursor";
|
||||
import Header from "./Header";
|
||||
@@ -17,7 +18,6 @@ import PlaceholderCollections from "./PlaceholderCollections";
|
||||
import Relative from "./Relative";
|
||||
import SidebarAction from "./SidebarAction";
|
||||
import SidebarContext from "./SidebarContext";
|
||||
import { DragObject } from "./SidebarLink";
|
||||
|
||||
function Collections() {
|
||||
const { documents, collections } = useStores();
|
||||
|
||||
@@ -3,10 +3,11 @@ import { observer } from "mobx-react";
|
||||
import { PlusIcon } from "outline-icons";
|
||||
import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router-dom";
|
||||
import { useHistory } from "react-router-dom";
|
||||
import styled from "styled-components";
|
||||
import Icon from "@shared/components/Icon";
|
||||
import { NavigationNode } from "@shared/types";
|
||||
import { NavigationNode, UserPreference } from "@shared/types";
|
||||
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
|
||||
import { sortNavigationNodes } from "@shared/utils/collections";
|
||||
import { DocumentValidation } from "@shared/validations";
|
||||
import Collection from "~/models/Collection";
|
||||
@@ -15,10 +16,11 @@ import Fade from "~/components/Fade";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
import Tooltip from "~/components/Tooltip";
|
||||
import useBoolean from "~/hooks/useBoolean";
|
||||
import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
import usePolicy from "~/hooks/usePolicy";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import DocumentMenu from "~/menus/DocumentMenu";
|
||||
import { newNestedDocumentPath } from "~/utils/routeHelpers";
|
||||
import { documentEditPath } from "~/utils/routeHelpers";
|
||||
import {
|
||||
useDragDocument,
|
||||
useDropToReorderDocument,
|
||||
@@ -58,6 +60,7 @@ function InnerDocumentLink(
|
||||
) {
|
||||
const { documents, policies } = useStores();
|
||||
const { t } = useTranslation();
|
||||
const history = useHistory();
|
||||
const canUpdate = usePolicy(node.id).update;
|
||||
const isActiveDocument = activeDocument && activeDocument.id === node.id;
|
||||
const hasChildDocuments =
|
||||
@@ -67,6 +70,7 @@ function InnerDocumentLink(
|
||||
const [isEditing, setIsEditing] = React.useState(false);
|
||||
const editableTitleRef = React.useRef<RefHandle>(null);
|
||||
const sidebarContext = useSidebarContext();
|
||||
const user = useCurrentUser();
|
||||
|
||||
React.useEffect(() => {
|
||||
if (
|
||||
@@ -216,6 +220,31 @@ function InnerDocumentLink(
|
||||
[setExpanded, setCollapsed, hasChildren, expanded]
|
||||
);
|
||||
|
||||
const [isAddingNewChild, setIsAddingNewChild, closeAddingNewChild] =
|
||||
useBoolean();
|
||||
|
||||
const handleNewDoc = React.useCallback(
|
||||
async (input) => {
|
||||
const newDocument = await documents.create(
|
||||
{
|
||||
collectionId: collection?.id,
|
||||
parentDocumentId: node.id,
|
||||
fullWidth:
|
||||
doc?.fullWidth ??
|
||||
user.getPreference(UserPreference.FullWidthDocuments),
|
||||
title: input,
|
||||
data: ProsemirrorHelper.getEmptyDocument(),
|
||||
},
|
||||
{ publish: true }
|
||||
);
|
||||
collection?.addDocument(newDocument, node.id);
|
||||
|
||||
closeAddingNewChild();
|
||||
history.replace(documentEditPath(newDocument));
|
||||
},
|
||||
[documents, collection, user, node, doc, history, closeAddingNewChild]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Relative ref={parentRef}>
|
||||
@@ -282,8 +311,11 @@ function InnerDocumentLink(
|
||||
<NudeButton
|
||||
type={undefined}
|
||||
aria-label={t("New nested document")}
|
||||
as={Link}
|
||||
to={newNestedDocumentPath(document.id)}
|
||||
onClick={(ev) => {
|
||||
ev.preventDefault();
|
||||
setIsAddingNewChild();
|
||||
setExpanded();
|
||||
}}
|
||||
>
|
||||
<PlusIcon />
|
||||
</NudeButton>
|
||||
@@ -308,8 +340,25 @@ function InnerDocumentLink(
|
||||
<DropCursor isActiveDrop={isOverReorder} innerRef={dropToReorder} />
|
||||
)}
|
||||
</Relative>
|
||||
{isAddingNewChild && (
|
||||
<SidebarLink
|
||||
isActive={() => true}
|
||||
depth={depth + 1}
|
||||
label={
|
||||
<EditableTitle
|
||||
title=""
|
||||
canUpdate
|
||||
isEditing
|
||||
placeholder={`${t("New doc")}…`}
|
||||
onCancel={closeAddingNewChild}
|
||||
onSubmit={handleNewDoc}
|
||||
maxLength={DocumentValidation.maxTitleLength}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<Folder expanded={expanded && !isDragging}>
|
||||
{nodeChildren.map((childNode, index) => (
|
||||
{nodeChildren.map((childNode, childIndex) => (
|
||||
<DocumentLink
|
||||
key={childNode.id}
|
||||
collection={collection}
|
||||
@@ -318,7 +367,7 @@ function InnerDocumentLink(
|
||||
prefetchDocument={prefetchDocument}
|
||||
isDraft={childNode.isDraft}
|
||||
depth={depth + 1}
|
||||
index={index}
|
||||
index={childIndex}
|
||||
parentId={node.id}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -9,12 +9,12 @@ import Document from "~/models/Document";
|
||||
import CollectionIcon from "~/components/Icons/CollectionIcon";
|
||||
import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { DragObject } from "../hooks/useDragAndDrop";
|
||||
import CollectionLink from "./CollectionLink";
|
||||
import CollectionLinkChildren from "./CollectionLinkChildren";
|
||||
import DropCursor from "./DropCursor";
|
||||
import Relative from "./Relative";
|
||||
import { useSidebarContext } from "./SidebarContext";
|
||||
import { DragObject } from "./SidebarLink";
|
||||
|
||||
type Props = {
|
||||
collection: Collection;
|
||||
|
||||
@@ -3,23 +3,33 @@ import { toast } from "sonner";
|
||||
import styled from "styled-components";
|
||||
import { s } from "@shared/styles";
|
||||
|
||||
type Props = {
|
||||
onSubmit: (title: string) => Promise<void>;
|
||||
type Props = Omit<React.HTMLAttributes<HTMLInputElement>, "onSubmit"> & {
|
||||
/** A callback when the title is submitted. */
|
||||
onSubmit: (title: string) => Promise<void> | void;
|
||||
/** A callback when the editing status changes. */
|
||||
onEditing?: (isEditing: boolean) => void;
|
||||
/** A callback when editing is canceled. */
|
||||
onCancel?: () => void;
|
||||
/** The default title. */
|
||||
title: string;
|
||||
/** Whether the user can update the title. */
|
||||
canUpdate: boolean;
|
||||
/** The maximum length of the title. */
|
||||
maxLength?: number;
|
||||
/** The default editing state. */
|
||||
isEditing?: boolean;
|
||||
};
|
||||
|
||||
export type RefHandle = {
|
||||
/** A function to set the editing state. */
|
||||
setIsEditing: (isEditing: boolean) => void;
|
||||
};
|
||||
|
||||
function EditableTitle(
|
||||
{ title, onSubmit, canUpdate, onEditing, ...rest }: Props,
|
||||
{ title, onSubmit, canUpdate, onEditing, onCancel, ...rest }: Props,
|
||||
ref: React.RefObject<RefHandle>
|
||||
) {
|
||||
const [isEditing, setIsEditing] = React.useState(false);
|
||||
const [isEditing, setIsEditing] = React.useState(rest.isEditing || false);
|
||||
const [originalValue, setOriginalValue] = React.useState(title);
|
||||
const [value, setValue] = React.useState(title);
|
||||
|
||||
@@ -59,6 +69,7 @@ function EditableTitle(
|
||||
|
||||
if (trimmedValue === originalValue || trimmedValue.length === 0) {
|
||||
setValue(originalValue);
|
||||
onCancel?.();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -73,7 +84,7 @@ function EditableTitle(
|
||||
}
|
||||
}
|
||||
},
|
||||
[originalValue, value, onSubmit]
|
||||
[originalValue, value, onCancel, onSubmit]
|
||||
);
|
||||
|
||||
const handleKeyDown = React.useCallback(
|
||||
@@ -83,13 +94,14 @@ function EditableTitle(
|
||||
}
|
||||
if (ev.key === "Escape") {
|
||||
setIsEditing(false);
|
||||
onCancel?.();
|
||||
setValue(originalValue);
|
||||
}
|
||||
if (ev.key === "Enter") {
|
||||
await handleSave(ev);
|
||||
}
|
||||
},
|
||||
[handleSave, originalValue]
|
||||
[handleSave, onCancel, originalValue]
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
|
||||
@@ -4,7 +4,6 @@ import styled, { useTheme, css } from "styled-components";
|
||||
import breakpoint from "styled-components-breakpoint";
|
||||
import EventBoundary from "@shared/components/EventBoundary";
|
||||
import { s } from "@shared/styles";
|
||||
import { NavigationNode } from "@shared/types";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
import { UnreadBadge } from "~/components/UnreadBadge";
|
||||
import useUnmount from "~/hooks/useUnmount";
|
||||
@@ -12,11 +11,6 @@ import { undraggableOnDesktop } from "~/styles";
|
||||
import Disclosure from "./Disclosure";
|
||||
import NavLink, { Props as NavLinkProps } from "./NavLink";
|
||||
|
||||
export type DragObject = NavigationNode & {
|
||||
depth: number;
|
||||
collectionId: string;
|
||||
};
|
||||
|
||||
type Props = Omit<NavLinkProps, "to"> & {
|
||||
to?: LocationDescriptor;
|
||||
innerRef?: (ref: HTMLElement | null | undefined) => void;
|
||||
|
||||
@@ -6,7 +6,8 @@ import { useTranslation } from "react-i18next";
|
||||
import DocumentDelete from "~/scenes/DocumentDelete";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { trashPath } from "~/utils/routeHelpers";
|
||||
import SidebarLink, { DragObject } from "./SidebarLink";
|
||||
import { DragObject } from "../hooks/useDragAndDrop";
|
||||
import SidebarLink from "./SidebarLink";
|
||||
|
||||
function TrashLink() {
|
||||
const { policies, dialogs, documents } = useStores();
|
||||
|
||||
@@ -15,10 +15,49 @@ import Star from "~/models/Star";
|
||||
import UserMembership from "~/models/UserMembership";
|
||||
import ConfirmMoveDialog from "~/components/ConfirmMoveDialog";
|
||||
import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
import usePolicy from "~/hooks/usePolicy";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { DragObject } from "../components/SidebarLink";
|
||||
import { AuthorizationError } from "~/utils/errors";
|
||||
import { useSidebarLabelAndIcon } from "./useSidebarLabelAndIcon";
|
||||
|
||||
export type DragObject = NavigationNode & {
|
||||
depth: number;
|
||||
collectionId: string;
|
||||
};
|
||||
|
||||
function useHover(
|
||||
elementRef: React.RefObject<HTMLDivElement>,
|
||||
callback: () => void
|
||||
) {
|
||||
const hoverTimeoutRef = React.useRef<ReturnType<typeof setTimeout>>();
|
||||
|
||||
const startHover = React.useCallback(() => {
|
||||
if (!hoverTimeoutRef.current) {
|
||||
hoverTimeoutRef.current = setTimeout(() => {
|
||||
hoverTimeoutRef.current = undefined;
|
||||
callback();
|
||||
}, 500);
|
||||
}
|
||||
}, [callback]);
|
||||
|
||||
const unsetHover = React.useCallback(() => {
|
||||
if (hoverTimeoutRef.current) {
|
||||
clearTimeout(hoverTimeoutRef.current);
|
||||
hoverTimeoutRef.current = undefined;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// We set a timeout when the user first starts hovering over the document link,
|
||||
// to trigger expansion of children. Clear this timeout when they stop hovering.
|
||||
React.useEffect(() => {
|
||||
const element = elementRef.current;
|
||||
element?.addEventListener("dragleave", unsetHover);
|
||||
return () => element?.removeEventListener("dragleave", unsetHover);
|
||||
}, [elementRef, unsetHover]);
|
||||
|
||||
return startHover;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for shared logic that allows dragging a Starred item
|
||||
*
|
||||
@@ -162,6 +201,84 @@ export function useDragDocument(
|
||||
return [{ isDragging }, draggableRef] as const;
|
||||
}
|
||||
|
||||
export function useDropToChangeCollection(
|
||||
collection: Collection,
|
||||
expandNode: () => void,
|
||||
parentRef: React.RefObject<HTMLDivElement>
|
||||
) {
|
||||
const { t } = useTranslation();
|
||||
const { documents, collections, dialogs } = useStores();
|
||||
const can = usePolicy(collection);
|
||||
const startHover = useHover(parentRef, expandNode);
|
||||
|
||||
return useDrop<
|
||||
DragObject,
|
||||
Promise<void>,
|
||||
{ isOver: boolean; canDrop: boolean }
|
||||
>({
|
||||
accept: "document",
|
||||
drop: async (item, monitor) => {
|
||||
if (monitor.didDrop()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { id, collectionId } = item;
|
||||
const prevCollection = collections.get(collectionId);
|
||||
const document = documents.get(id);
|
||||
|
||||
if (
|
||||
prevCollection &&
|
||||
prevCollection.permission !== collection.permission &&
|
||||
!document?.isDraft
|
||||
) {
|
||||
dialogs.openModal({
|
||||
title: t("Change permissions?"),
|
||||
content: (
|
||||
<ConfirmMoveDialog item={item} collection={collection} index={0} />
|
||||
),
|
||||
});
|
||||
} else {
|
||||
try {
|
||||
await documents.move({
|
||||
documentId: id,
|
||||
collectionId: collection.id,
|
||||
index: 0,
|
||||
});
|
||||
expandNode();
|
||||
} catch (err) {
|
||||
if (err instanceof AuthorizationError) {
|
||||
toast.error(
|
||||
t(
|
||||
"You do not have permission to move {{ documentName }} to the {{ collectionName }} collection",
|
||||
{
|
||||
documentName: item.title,
|
||||
collectionName: collection.name,
|
||||
}
|
||||
)
|
||||
);
|
||||
} else {
|
||||
toast.error(err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
canDrop: () => can.createDocument,
|
||||
hover: (_, monitor) => {
|
||||
if (
|
||||
collection.hasDocuments &&
|
||||
monitor.canDrop() &&
|
||||
monitor.isOver({ shallow: true })
|
||||
) {
|
||||
startHover();
|
||||
}
|
||||
},
|
||||
collect: (monitor) => ({
|
||||
isOver: monitor.isOver({ shallow: true }),
|
||||
canDrop: monitor.canDrop(),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for shared logic that allows dropping documents to reparent
|
||||
*
|
||||
@@ -175,7 +292,7 @@ export function useDropToReparentDocument(
|
||||
parentRef: React.RefObject<HTMLDivElement>
|
||||
) {
|
||||
const { t } = useTranslation();
|
||||
const { documents, collections, dialogs, policies } = useStores();
|
||||
const { documents, collections, dialogs } = useStores();
|
||||
const hasChildDocuments = !!node?.children.length;
|
||||
const document = node ? documents.get(node.id) : undefined;
|
||||
const pathToNode = React.useMemo(
|
||||
@@ -183,25 +300,7 @@ export function useDropToReparentDocument(
|
||||
[document]
|
||||
);
|
||||
|
||||
const hoverExpanding = React.useRef<ReturnType<typeof setTimeout>>();
|
||||
|
||||
// We set a timeout when the user first starts hovering over the document link,
|
||||
// to trigger expansion of children. Clear this timeout when they stop hovering.
|
||||
React.useEffect(() => {
|
||||
const resetHoverExpanding = () => {
|
||||
if (hoverExpanding.current) {
|
||||
clearTimeout(hoverExpanding.current);
|
||||
hoverExpanding.current = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const element = parentRef.current;
|
||||
element?.addEventListener("dragleave", resetHoverExpanding);
|
||||
|
||||
return () => {
|
||||
element?.removeEventListener("dragleave", resetHoverExpanding);
|
||||
};
|
||||
}, [parentRef]);
|
||||
const startHover = useHover(parentRef, setExpanded);
|
||||
|
||||
return useDrop<
|
||||
DragObject,
|
||||
@@ -214,7 +313,9 @@ export function useDropToReparentDocument(
|
||||
return;
|
||||
}
|
||||
|
||||
const collection = documents.get(node.id)?.collection;
|
||||
const collection = node.collectionId
|
||||
? collections.get(node.collectionId)
|
||||
: undefined;
|
||||
const prevCollection = collections.get(item.collectionId);
|
||||
|
||||
if (
|
||||
@@ -233,22 +334,40 @@ export function useDropToReparentDocument(
|
||||
),
|
||||
});
|
||||
} else {
|
||||
await documents.move({
|
||||
documentId: item.id,
|
||||
parentDocumentId: node.id,
|
||||
});
|
||||
try {
|
||||
await documents.move({
|
||||
documentId: item.id,
|
||||
parentDocumentId: node.id,
|
||||
});
|
||||
setExpanded();
|
||||
} catch (err) {
|
||||
if (err instanceof AuthorizationError) {
|
||||
toast.error(
|
||||
t(
|
||||
"{{ documentName }} cannot be moved within {{ parentDocumentName }}",
|
||||
{
|
||||
documentName: item.title,
|
||||
parentDocumentName: node.title,
|
||||
}
|
||||
)
|
||||
);
|
||||
} else {
|
||||
toast.error(err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
canDrop: (item) => {
|
||||
if (!node || item.id === node.id) {
|
||||
return false;
|
||||
}
|
||||
|
||||
setExpanded();
|
||||
if (!document) {
|
||||
return true; // optimistic, in case the document is not loaded yet; server will check for permissions before performing the move.
|
||||
}
|
||||
|
||||
return document.isActive && !!pathToNode && !pathToNode.includes(item.id);
|
||||
},
|
||||
canDrop: (item, monitor) =>
|
||||
!!node &&
|
||||
!!pathToNode &&
|
||||
!pathToNode.includes(monitor.getItem().id) &&
|
||||
item.id !== node.id &&
|
||||
!!document?.isActive &&
|
||||
policies.abilities(node.id).update &&
|
||||
policies.abilities(item.id).move,
|
||||
hover: (_item, monitor) => {
|
||||
// Enables expansion of document children when hovering over the document
|
||||
// for more than half a second.
|
||||
@@ -259,15 +378,7 @@ export function useDropToReparentDocument(
|
||||
shallow: true,
|
||||
})
|
||||
) {
|
||||
if (!hoverExpanding.current) {
|
||||
hoverExpanding.current = setTimeout(() => {
|
||||
hoverExpanding.current = undefined;
|
||||
|
||||
if (monitor.isOver({ shallow: true })) {
|
||||
setExpanded();
|
||||
}
|
||||
}, 500);
|
||||
}
|
||||
startHover();
|
||||
}
|
||||
},
|
||||
collect: (monitor) => ({
|
||||
@@ -297,7 +408,7 @@ export function useDropToReorderDocument(
|
||||
}
|
||||
) {
|
||||
const { t } = useTranslation();
|
||||
const { documents, collections, dialogs, policies } = useStores();
|
||||
const { documents, collections, dialogs } = useStores();
|
||||
|
||||
const document = documents.get(node.id);
|
||||
|
||||
@@ -308,22 +419,9 @@ export function useDropToReorderDocument(
|
||||
>({
|
||||
accept: "document",
|
||||
canDrop: (item: DragObject) => {
|
||||
if (
|
||||
item.id === node.id ||
|
||||
!policies.abilities(item.id)?.move ||
|
||||
!document?.isActive
|
||||
) {
|
||||
if (item.id === node.id || (document && !document.isActive)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const params = getMoveParams(item);
|
||||
if (params?.collectionId) {
|
||||
return policies.abilities(params.collectionId)?.updateDocument;
|
||||
}
|
||||
if (params?.parentDocumentId) {
|
||||
return policies.abilities(params.parentDocumentId)?.update;
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
drop: async (item) => {
|
||||
@@ -357,7 +455,19 @@ export function useDropToReorderDocument(
|
||||
),
|
||||
});
|
||||
} else {
|
||||
void documents.move(params);
|
||||
try {
|
||||
await documents.move(params);
|
||||
} catch (err) {
|
||||
if (err instanceof AuthorizationError) {
|
||||
toast.error(
|
||||
t("The {{ documentName }} cannot be moved here", {
|
||||
documentName: item.title,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
toast.error(err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -190,7 +190,7 @@ class WebsocketProvider extends React.Component<Props> {
|
||||
if (collection?.updatedAt === collectionDescriptor.updatedAt) {
|
||||
continue;
|
||||
}
|
||||
if (!collection?.documents?.length && !event.fetchIfMissing) {
|
||||
if (!collection?.documents && !event.fetchIfMissing) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,10 +6,10 @@ import styled, { css } from "styled-components";
|
||||
import { isCode } from "@shared/editor/lib/isCode";
|
||||
import { findParentNode } from "@shared/editor/queries/findParentNode";
|
||||
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
|
||||
import { useComponentSize } from "@shared/hooks/useComponentSize";
|
||||
import { depths, s } from "@shared/styles";
|
||||
import { HEADER_HEIGHT } from "~/components/Header";
|
||||
import { Portal } from "~/components/Portal";
|
||||
import useComponentSize from "~/hooks/useComponentSize";
|
||||
import useEventListener from "~/hooks/useEventListener";
|
||||
import useMobile from "~/hooks/useMobile";
|
||||
import useWindowSize from "~/hooks/useWindowSize";
|
||||
@@ -184,10 +184,10 @@ function usePosition({
|
||||
// of the selection still
|
||||
const offset = left - (centerOfSelection - menuWidth / 2);
|
||||
return {
|
||||
left: Math.round(left - offsetParent.left),
|
||||
left: Math.max(margin, Math.round(left - offsetParent.left)),
|
||||
top: Math.round(top - offsetParent.top),
|
||||
offset: Math.round(offset),
|
||||
maxWidth: Math.min(window.innerWidth - margin * 2, offsetParent.width),
|
||||
maxWidth: Math.min(window.innerWidth, offsetParent.width) - margin * 2,
|
||||
blockSelection: codeBlock || isColSelection || isRowSelection,
|
||||
visible: true,
|
||||
};
|
||||
|
||||
@@ -187,7 +187,7 @@ class LinkEditor extends React.Component<Props, State> {
|
||||
};
|
||||
|
||||
render() {
|
||||
const { dictionary } = this.props;
|
||||
const { view, dictionary } = this.props;
|
||||
const { value } = this.state;
|
||||
const isInternal = isInternalUrl(value);
|
||||
|
||||
@@ -202,6 +202,7 @@ class LinkEditor extends React.Component<Props, State> {
|
||||
onChange={this.handleSearch}
|
||||
onFocus={this.handleSearch}
|
||||
autoFocus={this.href === ""}
|
||||
readOnly={!view.editable}
|
||||
/>
|
||||
|
||||
<Tooltip
|
||||
@@ -211,11 +212,13 @@ class LinkEditor extends React.Component<Props, State> {
|
||||
{isInternal ? <ArrowIcon /> : <OpenIcon />}
|
||||
</ToolbarButton>
|
||||
</Tooltip>
|
||||
<Tooltip content={dictionary.removeLink}>
|
||||
<ToolbarButton onClick={this.handleRemoveLink}>
|
||||
<CloseIcon />
|
||||
</ToolbarButton>
|
||||
</Tooltip>
|
||||
{view.editable && (
|
||||
<Tooltip content={dictionary.removeLink}>
|
||||
<ToolbarButton onClick={this.handleRemoveLink}>
|
||||
<CloseIcon />
|
||||
</ToolbarButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Wrapper>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -84,7 +84,6 @@ function MentionMenu({ search, isActive, ...rest }: Props) {
|
||||
>
|
||||
<Avatar
|
||||
model={user}
|
||||
showBorder={false}
|
||||
alt={t("Profile picture")}
|
||||
size={AvatarSize.Small}
|
||||
/>
|
||||
@@ -158,6 +157,9 @@ function MentionMenu({ search, isActive, ...rest }: Props) {
|
||||
if (item.attrs.type === MentionType.Document) {
|
||||
return;
|
||||
}
|
||||
if (!documentId) {
|
||||
return;
|
||||
}
|
||||
// Check if the mentioned user has access to the document
|
||||
const res = await client.post("/documents.users", {
|
||||
id: documentId,
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import { Plugin, PluginKey } from "prosemirror-state";
|
||||
import Extension from "@shared/editor/lib/Extension";
|
||||
import textBetween from "@shared/editor/lib/textBetween";
|
||||
import { getTextSerializers } from "@shared/editor/lib/textSerializers";
|
||||
|
||||
/**
|
||||
* A plugin that allows overriding the default behavior of the editor to allow
|
||||
* copying text for nodes that do not inherently have text children by defining
|
||||
* a `toPlainText` method in the node spec.
|
||||
* copying text including the markdown formatting.
|
||||
*/
|
||||
export default class ClipboardTextSerializer extends Extension {
|
||||
get name() {
|
||||
@@ -14,20 +11,16 @@ export default class ClipboardTextSerializer extends Extension {
|
||||
}
|
||||
|
||||
get plugins() {
|
||||
const textSerializers = getTextSerializers(this.editor.schema);
|
||||
const serializer = this.editor.extensions.serializer();
|
||||
|
||||
return [
|
||||
new Plugin({
|
||||
key: new PluginKey("clipboardTextSerializer"),
|
||||
props: {
|
||||
clipboardTextSerializer: () => {
|
||||
const { doc, selection } = this.editor.view.state;
|
||||
const { ranges } = selection;
|
||||
const from = Math.min(...ranges.map((range) => range.$from.pos));
|
||||
const to = Math.max(...ranges.map((range) => range.$to.pos));
|
||||
|
||||
return textBetween(doc, from, to, textSerializers);
|
||||
},
|
||||
clipboardTextSerializer: (slice) =>
|
||||
serializer.serialize(slice.content, {
|
||||
softBreak: true,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import isEqual from "lodash/isEqual";
|
||||
import { Plugin } from "prosemirror-state";
|
||||
import {
|
||||
ySyncPlugin,
|
||||
yCursorPlugin,
|
||||
@@ -8,6 +9,7 @@ import {
|
||||
} from "y-prosemirror";
|
||||
import * as Y from "yjs";
|
||||
import Extension from "@shared/editor/lib/Extension";
|
||||
import { isRemoteTransaction } from "@shared/editor/lib/multiplayer";
|
||||
import { Second } from "@shared/utils/time";
|
||||
|
||||
type UserAwareness = {
|
||||
@@ -103,6 +105,11 @@ export default class Multiplayer extends Extension {
|
||||
selectionBuilder,
|
||||
}),
|
||||
yUndoPlugin(),
|
||||
new Plugin({
|
||||
props: {
|
||||
handleScrollToSelection: (view) => isRemoteTransaction(view.state.tr),
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -148,6 +148,13 @@ export default class PasteHandler extends Extension {
|
||||
const supportsCodeMark = !!state.schema.marks.code_inline;
|
||||
|
||||
if (!this.shiftKey) {
|
||||
// If the HTML on the clipboard is from Prosemirror then the best
|
||||
// compatability is to just use the HTML parser, regardless of
|
||||
// whether it "looks" like Markdown, see: outline/outline#2416
|
||||
if (html?.includes("data-pm-slice")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if the clipboard contents can be parsed as a single url
|
||||
if (isUrl(text)) {
|
||||
// If there is selected text then we want to wrap it in a link to the url
|
||||
@@ -249,13 +256,6 @@ export default class PasteHandler extends Extension {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// If the HTML on the clipboard is from Prosemirror then the best
|
||||
// compatability is to just use the HTML parser, regardless of
|
||||
// whether it "looks" like Markdown, see: outline/outline#2416
|
||||
if (html?.includes("data-pm-slice")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// If the text on the clipboard looks like Markdown OR there is no
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import Extension from "@shared/editor/lib/Extension";
|
||||
import Mark from "@shared/editor/marks/Mark";
|
||||
import Node from "@shared/editor/nodes/Node";
|
||||
import BlockMenuExtension from "~/editor/extensions/BlockMenu";
|
||||
import ClipboardTextSerializer from "~/editor/extensions/ClipboardTextSerializer";
|
||||
import EmojiMenuExtension from "~/editor/extensions/EmojiMenu";
|
||||
import FindAndReplaceExtension from "~/editor/extensions/FindAndReplace";
|
||||
import HoverPreviewsExtension from "~/editor/extensions/HoverPreviews";
|
||||
import Keys from "~/editor/extensions/Keys";
|
||||
import MentionMenuExtension from "~/editor/extensions/MentionMenu";
|
||||
import PasteHandler from "~/editor/extensions/PasteHandler";
|
||||
import PreventTab from "~/editor/extensions/PreventTab";
|
||||
import SmartText from "~/editor/extensions/SmartText";
|
||||
|
||||
type Nodes = (typeof Node | typeof Mark | typeof Extension)[];
|
||||
|
||||
export const withUIExtensions = (nodes: Nodes) => [
|
||||
...nodes,
|
||||
SmartText,
|
||||
PasteHandler,
|
||||
ClipboardTextSerializer,
|
||||
BlockMenuExtension,
|
||||
EmojiMenuExtension,
|
||||
MentionMenuExtension,
|
||||
FindAndReplaceExtension,
|
||||
HoverPreviewsExtension,
|
||||
// Order these default key handlers last
|
||||
PreventTab,
|
||||
Keys,
|
||||
];
|
||||
@@ -1,35 +0,0 @@
|
||||
import { useState, useLayoutEffect } from "react";
|
||||
|
||||
export default function useComponentSize(
|
||||
ref: React.RefObject<HTMLElement | null>
|
||||
): {
|
||||
width: number;
|
||||
height: number;
|
||||
} {
|
||||
const [size, setSize] = useState({ width: 0, height: 0 });
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const sizeObserver = new ResizeObserver((entries) => {
|
||||
entries.forEach(({ target }) => {
|
||||
if (
|
||||
size.width !== target.clientWidth ||
|
||||
size.height !== target.clientHeight
|
||||
) {
|
||||
setSize({ width: target.clientWidth, height: target.clientHeight });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (ref.current) {
|
||||
setSize({
|
||||
width: ref.current?.clientWidth,
|
||||
height: ref.current?.clientHeight,
|
||||
});
|
||||
sizeObserver.observe(ref.current);
|
||||
}
|
||||
|
||||
return () => sizeObserver.disconnect();
|
||||
}, [ref, size.height, size.width]);
|
||||
|
||||
return size;
|
||||
}
|
||||
@@ -6,11 +6,16 @@ import Field from "./decorators/Field";
|
||||
class ApiKey extends ParanoidModel {
|
||||
static modelName = "ApiKey";
|
||||
|
||||
/** The user chosen name of the API key. */
|
||||
/** The human-readable name of this API key */
|
||||
@Field
|
||||
@observable
|
||||
name: string;
|
||||
|
||||
/** A list of scopes that this API key has access to. If empty, the key has full access. */
|
||||
@Field
|
||||
@observable
|
||||
scope?: string[];
|
||||
|
||||
/** An optional datetime that the API key expires. */
|
||||
@Field
|
||||
@observable
|
||||
|
||||
@@ -181,6 +181,11 @@ export default class Collection extends ParanoidModel {
|
||||
return !this.isArchived && !this.isDeleted;
|
||||
}
|
||||
|
||||
@computed
|
||||
get hasDocuments() {
|
||||
return !!this.documents?.length;
|
||||
}
|
||||
|
||||
fetchDocuments = async (options?: { force: boolean }) => {
|
||||
if (this.isFetching) {
|
||||
return;
|
||||
@@ -258,6 +263,36 @@ export default class Collection extends ParanoidModel {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the document identified by the given id to the collection in
|
||||
* memory. Does not add the document to the database or store.
|
||||
*
|
||||
* @param document The document to add.
|
||||
* @param parentDocumentId The id of the document to add the new document to.
|
||||
*/
|
||||
@action
|
||||
addDocument(document: Document, parentDocumentId?: string) {
|
||||
if (!this.documents) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!parentDocumentId) {
|
||||
this.documents.unshift(document.asNavigationNode);
|
||||
return;
|
||||
}
|
||||
|
||||
const travelNodes = (nodes: NavigationNode[]) =>
|
||||
nodes.forEach((node) => {
|
||||
if (node.id === parentDocumentId) {
|
||||
node.children = [document.asNavigationNode, ...(node.children ?? [])];
|
||||
} else {
|
||||
travelNodes(node.children);
|
||||
}
|
||||
});
|
||||
|
||||
travelNodes(this.documents);
|
||||
}
|
||||
|
||||
@action
|
||||
updateIndex(index: string) {
|
||||
this.index = index;
|
||||
|
||||
@@ -72,8 +72,7 @@ function AuthenticatedRoutes() {
|
||||
<Redirect exact from="/templates" to={settingsPath("templates")} />
|
||||
<Redirect exact from="/collections/*" to="/collection/*" />
|
||||
<Route exact path="/collection/:id/new" component={DocumentNew} />
|
||||
<Route exact path="/collection/:id/:tab" component={Collection} />
|
||||
<Route exact path="/collection/:id" component={Collection} />
|
||||
<Route exact path="/collection/:id/:tab?" component={Collection} />
|
||||
<Route exact path="/doc/new" component={DocumentNew} />
|
||||
<Route exact path={`/d/${slug}`} component={RedirectDocument} />
|
||||
<Route
|
||||
|
||||
@@ -22,6 +22,7 @@ type Props = {
|
||||
|
||||
function ApiKeyNew({ onSubmit }: Props) {
|
||||
const [name, setName] = React.useState("");
|
||||
const [scope, setScope] = React.useState("");
|
||||
const [expiryType, setExpiryType] = React.useState<ExpiryType>(
|
||||
ExpiryType.Week
|
||||
);
|
||||
@@ -51,6 +52,10 @@ function ApiKeyNew({ onSubmit }: Props) {
|
||||
setName(event.target.value);
|
||||
}, []);
|
||||
|
||||
const handleScopeChange = React.useCallback((event) => {
|
||||
setScope(event.target.value);
|
||||
}, []);
|
||||
|
||||
const handleExpiryTypeChange = React.useCallback((value: string) => {
|
||||
const expiry = value as ExpiryType;
|
||||
setExpiryType(expiry);
|
||||
@@ -70,6 +75,7 @@ function ApiKeyNew({ onSubmit }: Props) {
|
||||
await apiKeys.create({
|
||||
name,
|
||||
expiresAt: expiresAt?.toISOString(),
|
||||
scope: scope ? scope.split(" ") : undefined,
|
||||
});
|
||||
toast.success(
|
||||
t(
|
||||
@@ -83,20 +89,16 @@ function ApiKeyNew({ onSubmit }: Props) {
|
||||
setIsSaving(false);
|
||||
}
|
||||
},
|
||||
[t, name, expiresAt, onSubmit, apiKeys]
|
||||
[t, name, scope, expiresAt, onSubmit, apiKeys]
|
||||
);
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit}>
|
||||
<Text as="p" type="secondary">
|
||||
{t(
|
||||
`Name your key something that will help you to remember it's use in the future, for example "local development" or "continuous integration".`
|
||||
)}
|
||||
</Text>
|
||||
<Flex column>
|
||||
<Input
|
||||
type="text"
|
||||
label={t("Name")}
|
||||
placeholder={t("Development")}
|
||||
onChange={handleNameChange}
|
||||
value={name}
|
||||
minLength={ApiKeyValidation.minNameLength}
|
||||
@@ -105,6 +107,20 @@ function ApiKeyNew({ onSubmit }: Props) {
|
||||
autoFocus
|
||||
flex
|
||||
/>
|
||||
<Input
|
||||
type="text"
|
||||
label={t("Scopes")}
|
||||
placeholder="documents.info"
|
||||
onChange={handleScopeChange}
|
||||
value={scope}
|
||||
flex
|
||||
/>
|
||||
<Text type="secondary" size="small" as="p">
|
||||
{t(
|
||||
"Space-separated scopes restrict the access of this API key to specific parts of the API. Leave blank for full access"
|
||||
)}
|
||||
.
|
||||
</Text>
|
||||
<Flex align="center" gap={16}>
|
||||
<StyledExpirySelect
|
||||
ariaLabel={t("Expiration")}
|
||||
|
||||
@@ -4,7 +4,7 @@ import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PAGINATION_SYMBOL } from "~/stores/base/Store";
|
||||
import Collection from "~/models/Collection";
|
||||
import { Avatar, AvatarSize } from "~/components/Avatar";
|
||||
import { AvatarSize } from "~/components/Avatar";
|
||||
import Facepile from "~/components/Facepile";
|
||||
import Fade from "~/components/Fade";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
@@ -44,10 +44,10 @@ const MembershipPreview = ({ collection, limit = 8 }: Props) => {
|
||||
groupMemberships.fetchPage(options),
|
||||
]);
|
||||
if (users[PAGINATION_SYMBOL]) {
|
||||
setUsersCount(users[PAGINATION_SYMBOL].total);
|
||||
setUsersCount(users[PAGINATION_SYMBOL].total ?? 0);
|
||||
}
|
||||
if (groups[PAGINATION_SYMBOL]) {
|
||||
setGroupsCount(groups[PAGINATION_SYMBOL].total);
|
||||
setGroupsCount(groups[PAGINATION_SYMBOL].total ?? 0);
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
@@ -101,12 +101,10 @@ const MembershipPreview = ({ collection, limit = 8 }: Props) => {
|
||||
>
|
||||
<Fade>
|
||||
<Facepile
|
||||
size={AvatarSize.Large}
|
||||
users={sortBy(collectionUsers, "lastActiveAt")}
|
||||
overflow={overflow}
|
||||
limit={limit}
|
||||
renderAvatar={(item) => (
|
||||
<Avatar model={item} size={AvatarSize.Large} />
|
||||
)}
|
||||
/>
|
||||
</Fade>
|
||||
</NudeButton>
|
||||
|
||||
+188
-102
@@ -3,12 +3,12 @@ import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
useParams,
|
||||
Redirect,
|
||||
Switch,
|
||||
Route,
|
||||
useHistory,
|
||||
useRouteMatch,
|
||||
useLocation,
|
||||
Redirect,
|
||||
} from "react-router-dom";
|
||||
import styled from "styled-components";
|
||||
import breakpoint from "styled-components-breakpoint";
|
||||
@@ -30,12 +30,13 @@ import PaginatedDocumentList from "~/components/PaginatedDocumentList";
|
||||
import PinnedDocuments from "~/components/PinnedDocuments";
|
||||
import PlaceholderText from "~/components/PlaceholderText";
|
||||
import Scene from "~/components/Scene";
|
||||
import Subheading from "~/components/Subheading";
|
||||
import Tab from "~/components/Tab";
|
||||
import Tabs from "~/components/Tabs";
|
||||
import { editCollection } from "~/actions/definitions/collections";
|
||||
import useCommandBarActions from "~/hooks/useCommandBarActions";
|
||||
import { useLastVisitedPath } from "~/hooks/useLastVisitedPath";
|
||||
import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext";
|
||||
import usePersistedState from "~/hooks/usePersistedState";
|
||||
import { usePinnedDocuments } from "~/hooks/usePinnedDocuments";
|
||||
import usePolicy from "~/hooks/usePolicy";
|
||||
import useStores from "~/hooks/useStores";
|
||||
@@ -49,7 +50,16 @@ import ShareButton from "./components/ShareButton";
|
||||
|
||||
const IconPicker = React.lazy(() => import("~/components/IconPicker"));
|
||||
|
||||
function CollectionScene() {
|
||||
enum CollectionPath {
|
||||
Overview = "overview",
|
||||
Recent = "recent",
|
||||
Updated = "updated",
|
||||
Published = "published",
|
||||
Old = "old",
|
||||
Alphabetical = "alphabetical",
|
||||
}
|
||||
|
||||
const CollectionScene = observer(function _CollectionScene() {
|
||||
const params = useParams<{ id?: string }>();
|
||||
const history = useHistory();
|
||||
const match = useRouteMatch();
|
||||
@@ -60,17 +70,26 @@ function CollectionScene() {
|
||||
const [error, setError] = React.useState<Error | undefined>();
|
||||
const currentPath = location.pathname;
|
||||
const [, setLastVisitedPath] = useLastVisitedPath();
|
||||
const sidebarContext = useLocationSidebarContext();
|
||||
|
||||
const id = params.id || "";
|
||||
const collection: Collection | null | undefined =
|
||||
collections.getByUrl(id) || collections.get(id);
|
||||
const can = usePolicy(collection);
|
||||
const { pins, count } = usePinnedDocuments(id, collection?.id);
|
||||
const [collectionTab, setCollectionTab] = usePersistedState<CollectionPath>(
|
||||
`collection-tab:${collection?.id}`,
|
||||
collection?.hasDescription
|
||||
? CollectionPath.Overview
|
||||
: CollectionPath.Recent,
|
||||
{
|
||||
listen: false,
|
||||
}
|
||||
);
|
||||
|
||||
const handleIconChange = React.useCallback(
|
||||
async (icon: string | null, color: string | null) => {
|
||||
await collection?.save({ icon, color });
|
||||
},
|
||||
(icon: string | null, color: string | null) =>
|
||||
collection?.save({ icon, color }),
|
||||
[collection]
|
||||
);
|
||||
|
||||
@@ -120,6 +139,8 @@ function CollectionScene() {
|
||||
return <Search notFound />;
|
||||
}
|
||||
|
||||
const hasOverview = can.update || collection?.hasDescription;
|
||||
|
||||
const fallbackIcon = collection ? (
|
||||
<Icon
|
||||
value={collection.icon ?? "collection"}
|
||||
@@ -128,11 +149,17 @@ function CollectionScene() {
|
||||
/>
|
||||
) : null;
|
||||
|
||||
const tabProps = (path: CollectionPath) => ({
|
||||
exact: true,
|
||||
onClick: () => setCollectionTab(path),
|
||||
to: {
|
||||
pathname: collectionPath(collection!.path, path),
|
||||
state: { sidebarContext },
|
||||
},
|
||||
});
|
||||
|
||||
return collection ? (
|
||||
<Scene
|
||||
// Forced mount prevents animation of pinned documents when navigating
|
||||
// _between_ collections, speeds up perceived performance.
|
||||
key={collection.id}
|
||||
centered={false}
|
||||
textTitle={collection.name}
|
||||
left={
|
||||
@@ -196,105 +223,156 @@ function CollectionScene() {
|
||||
canUpdate={can.update}
|
||||
placeholderCount={count}
|
||||
/>
|
||||
<CollectionDescription collection={collection} />
|
||||
|
||||
<Documents>
|
||||
{!collection.isArchived && (
|
||||
<Tabs>
|
||||
<Tab to={collectionPath(collection.path)} exact>
|
||||
{t("Documents")}
|
||||
<Tabs>
|
||||
{hasOverview && (
|
||||
<Tab {...tabProps(CollectionPath.Overview)}>
|
||||
{t("Overview")}
|
||||
</Tab>
|
||||
<Tab to={collectionPath(collection.path, "updated")} exact>
|
||||
{t("Recently updated")}
|
||||
</Tab>
|
||||
<Tab to={collectionPath(collection.path, "published")} exact>
|
||||
{t("Recently published")}
|
||||
</Tab>
|
||||
<Tab to={collectionPath(collection.path, "old")} exact>
|
||||
{t("Least recently updated")}
|
||||
</Tab>
|
||||
<Tab to={collectionPath(collection.path, "alphabetical")} exact>
|
||||
{t("A–Z")}
|
||||
</Tab>
|
||||
</Tabs>
|
||||
)}
|
||||
{collection.isEmpty ? (
|
||||
<Empty collection={collection} />
|
||||
) : !collection.isArchived ? (
|
||||
<Switch>
|
||||
<Route path={collectionPath(collection.path, "alphabetical")}>
|
||||
<PaginatedDocumentList
|
||||
key="alphabetical"
|
||||
documents={documents.alphabeticalInCollection(
|
||||
collection.id
|
||||
)}
|
||||
<Tab {...tabProps(CollectionPath.Recent)}>{t("Documents")}</Tab>
|
||||
{!collection.isArchived && (
|
||||
<>
|
||||
<Tab {...tabProps(CollectionPath.Updated)}>
|
||||
{t("Recently updated")}
|
||||
</Tab>
|
||||
<Tab {...tabProps(CollectionPath.Published)}>
|
||||
{t("Recently published")}
|
||||
</Tab>
|
||||
<Tab {...tabProps(CollectionPath.Old)}>
|
||||
{t("Least recently updated")}
|
||||
</Tab>
|
||||
<Tab {...tabProps(CollectionPath.Alphabetical)}>
|
||||
{t("A–Z")}
|
||||
</Tab>
|
||||
</>
|
||||
)}
|
||||
</Tabs>
|
||||
<Switch>
|
||||
<Route path={collectionPath(collection.path)} exact>
|
||||
<Redirect
|
||||
to={{
|
||||
pathname: collectionPath(collection!.path, collectionTab),
|
||||
state: { sidebarContext },
|
||||
}}
|
||||
/>
|
||||
</Route>
|
||||
<Route
|
||||
path={collectionPath(collection.path, CollectionPath.Overview)}
|
||||
>
|
||||
{hasOverview ? (
|
||||
<CollectionDescription collection={collection} />
|
||||
) : (
|
||||
<Redirect
|
||||
to={{
|
||||
pathname: collectionPath(
|
||||
collection.path,
|
||||
CollectionPath.Recent
|
||||
),
|
||||
state: { sidebarContext },
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Route>
|
||||
{collection.isEmpty ? (
|
||||
<Empty collection={collection} />
|
||||
) : !collection.isArchived ? (
|
||||
<>
|
||||
<Route
|
||||
path={collectionPath(
|
||||
collection.path,
|
||||
CollectionPath.Alphabetical
|
||||
)}
|
||||
fetch={documents.fetchAlphabetical}
|
||||
options={{
|
||||
collectionId: collection.id,
|
||||
}}
|
||||
/>
|
||||
</Route>
|
||||
<Route path={collectionPath(collection.path, "old")}>
|
||||
<PaginatedDocumentList
|
||||
key="old"
|
||||
documents={documents.leastRecentlyUpdatedInCollection(
|
||||
collection.id
|
||||
>
|
||||
<PaginatedDocumentList
|
||||
key="alphabetical"
|
||||
documents={documents.alphabeticalInCollection(
|
||||
collection.id
|
||||
)}
|
||||
fetch={documents.fetchAlphabetical}
|
||||
options={{
|
||||
collectionId: collection.id,
|
||||
}}
|
||||
/>
|
||||
</Route>
|
||||
<Route
|
||||
path={collectionPath(collection.path, CollectionPath.Old)}
|
||||
>
|
||||
<PaginatedDocumentList
|
||||
key="old"
|
||||
documents={documents.leastRecentlyUpdatedInCollection(
|
||||
collection.id
|
||||
)}
|
||||
fetch={documents.fetchLeastRecentlyUpdated}
|
||||
options={{
|
||||
collectionId: collection.id,
|
||||
}}
|
||||
/>
|
||||
</Route>
|
||||
<Route
|
||||
path={collectionPath(
|
||||
collection.path,
|
||||
CollectionPath.Published
|
||||
)}
|
||||
fetch={documents.fetchLeastRecentlyUpdated}
|
||||
options={{
|
||||
collectionId: collection.id,
|
||||
}}
|
||||
/>
|
||||
</Route>
|
||||
<Route path={collectionPath(collection.path, "recent")}>
|
||||
<Redirect to={collectionPath(collection.path, "published")} />
|
||||
</Route>
|
||||
<Route path={collectionPath(collection.path, "published")}>
|
||||
<PaginatedDocumentList
|
||||
key="published"
|
||||
documents={documents.recentlyPublishedInCollection(
|
||||
collection.id
|
||||
>
|
||||
<PaginatedDocumentList
|
||||
key="published"
|
||||
documents={documents.recentlyPublishedInCollection(
|
||||
collection.id
|
||||
)}
|
||||
fetch={documents.fetchRecentlyPublished}
|
||||
options={{
|
||||
collectionId: collection.id,
|
||||
}}
|
||||
showPublished
|
||||
/>
|
||||
</Route>
|
||||
<Route
|
||||
path={collectionPath(
|
||||
collection.path,
|
||||
CollectionPath.Updated
|
||||
)}
|
||||
fetch={documents.fetchRecentlyPublished}
|
||||
options={{
|
||||
collectionId: collection.id,
|
||||
}}
|
||||
showPublished
|
||||
/>
|
||||
</Route>
|
||||
<Route path={collectionPath(collection.path, "updated")}>
|
||||
<PaginatedDocumentList
|
||||
key="updated"
|
||||
documents={documents.recentlyUpdatedInCollection(
|
||||
collection.id
|
||||
>
|
||||
<PaginatedDocumentList
|
||||
key="updated"
|
||||
documents={documents.recentlyUpdatedInCollection(
|
||||
collection.id
|
||||
)}
|
||||
fetch={documents.fetchRecentlyUpdated}
|
||||
options={{
|
||||
collectionId: collection.id,
|
||||
}}
|
||||
/>
|
||||
</Route>
|
||||
<Route
|
||||
path={collectionPath(
|
||||
collection.path,
|
||||
CollectionPath.Recent
|
||||
)}
|
||||
fetch={documents.fetchRecentlyUpdated}
|
||||
options={{
|
||||
collectionId: collection.id,
|
||||
}}
|
||||
/>
|
||||
</Route>
|
||||
<Route path={collectionPath(collection.path)} exact>
|
||||
<PaginatedDocumentList
|
||||
documents={documents.rootInCollection(collection.id)}
|
||||
fetch={documents.fetchPage}
|
||||
options={{
|
||||
collectionId: collection.id,
|
||||
parentDocumentId: null,
|
||||
sort: collection.sort.field,
|
||||
direction: collection.sort.direction,
|
||||
}}
|
||||
showParentDocuments
|
||||
/>
|
||||
</Route>
|
||||
</Switch>
|
||||
) : (
|
||||
<Switch>
|
||||
<Route path={collectionPath(collection.path)} exact>
|
||||
exact
|
||||
>
|
||||
<PaginatedDocumentList
|
||||
documents={documents.rootInCollection(collection.id)}
|
||||
fetch={documents.fetchPage}
|
||||
options={{
|
||||
collectionId: collection.id,
|
||||
parentDocumentId: null,
|
||||
sort: collection.sort.field,
|
||||
direction: collection.sort.direction,
|
||||
}}
|
||||
showParentDocuments
|
||||
/>
|
||||
</Route>
|
||||
</>
|
||||
) : (
|
||||
<Route
|
||||
path={collectionPath(collection.path, CollectionPath.Recent)}
|
||||
exact
|
||||
>
|
||||
<PaginatedDocumentList
|
||||
documents={documents.archivedInCollection(collection.id)}
|
||||
fetch={documents.fetchPage}
|
||||
heading={<Subheading sticky>{t("Documents")}</Subheading>}
|
||||
options={{
|
||||
collectionId: collection.id,
|
||||
parentDocumentId: null,
|
||||
@@ -305,8 +383,8 @@ function CollectionScene() {
|
||||
showParentDocuments
|
||||
/>
|
||||
</Route>
|
||||
</Switch>
|
||||
)}
|
||||
)}
|
||||
</Switch>
|
||||
</Documents>
|
||||
</CenteredContent>
|
||||
</DropToImport>
|
||||
@@ -319,7 +397,15 @@ function CollectionScene() {
|
||||
<PlaceholderList count={5} />
|
||||
</CenteredContent>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const KeyedCollection = () => {
|
||||
const params = useParams<{ id?: string }>();
|
||||
|
||||
// Forced mount prevents animation of pinned documents when navigating
|
||||
// _between_ collections, speeds up perceived performance.
|
||||
return <CollectionScene key={params.id} />;
|
||||
};
|
||||
|
||||
const Documents = styled.div`
|
||||
position: relative;
|
||||
@@ -337,4 +423,4 @@ const CollectionHeading = styled(Heading)`
|
||||
`}
|
||||
`;
|
||||
|
||||
export default observer(CollectionScene);
|
||||
export default KeyedCollection;
|
||||
|
||||
@@ -11,7 +11,7 @@ import { ProsemirrorData } from "@shared/types";
|
||||
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
|
||||
import Comment from "~/models/Comment";
|
||||
import Document from "~/models/Document";
|
||||
import { Avatar, AvatarSize } from "~/components/Avatar";
|
||||
import { AvatarSize } from "~/components/Avatar";
|
||||
import { useDocumentContext } from "~/components/DocumentContext";
|
||||
import Facepile from "~/components/Facepile";
|
||||
import Fade from "~/components/Fade";
|
||||
@@ -149,9 +149,6 @@ function CommentThread({
|
||||
limit={limit}
|
||||
overflow={overflow}
|
||||
size={AvatarSize.Medium}
|
||||
renderAvatar={(item) => (
|
||||
<Avatar size={AvatarSize.Medium} model={item} />
|
||||
)}
|
||||
/>
|
||||
</ShowMore>
|
||||
);
|
||||
|
||||
@@ -380,24 +380,23 @@ class DocumentScene extends React.Component<Props> {
|
||||
AUTOSAVE_DELAY
|
||||
);
|
||||
|
||||
updateIsDirty = () => {
|
||||
updateIsDirty = action(() => {
|
||||
const { document } = this.props;
|
||||
const doc = this.editor.current?.view.state.doc;
|
||||
this.isEditorDirty = !isEqual(doc?.toJSON(), document.data);
|
||||
|
||||
// a single hash is a doc with just an empty title
|
||||
this.isEditorDirty = !isEqual(doc?.toJSON(), document.data);
|
||||
this.isEmpty = (!doc || ProsemirrorHelper.isEmpty(doc)) && !this.title;
|
||||
};
|
||||
});
|
||||
|
||||
updateIsDirtyDebounced = debounce(this.updateIsDirty, 500);
|
||||
|
||||
onFileUploadStart = () => {
|
||||
onFileUploadStart = action(() => {
|
||||
this.isUploading = true;
|
||||
};
|
||||
});
|
||||
|
||||
onFileUploadStop = () => {
|
||||
onFileUploadStop = action(() => {
|
||||
this.isUploading = false;
|
||||
};
|
||||
});
|
||||
|
||||
handleChangeTitle = action((value: string) => {
|
||||
this.title = value;
|
||||
@@ -584,6 +583,7 @@ class DocumentScene extends React.Component<Props> {
|
||||
readOnly={readOnly}
|
||||
canUpdate={abilities.update}
|
||||
canComment={abilities.comment}
|
||||
autoFocus={document.createdAt === document.updatedAt}
|
||||
>
|
||||
{shareId ? (
|
||||
<ReferencesWrapper>
|
||||
|
||||
@@ -13,16 +13,7 @@ import { RefHandle } from "~/components/ContentEditable";
|
||||
import { useDocumentContext } from "~/components/DocumentContext";
|
||||
import Editor, { Props as EditorProps } from "~/components/Editor";
|
||||
import Flex from "~/components/Flex";
|
||||
import BlockMenuExtension from "~/editor/extensions/BlockMenu";
|
||||
import ClipboardTextSerializer from "~/editor/extensions/ClipboardTextSerializer";
|
||||
import EmojiMenuExtension from "~/editor/extensions/EmojiMenu";
|
||||
import FindAndReplaceExtension from "~/editor/extensions/FindAndReplace";
|
||||
import HoverPreviewsExtension from "~/editor/extensions/HoverPreviews";
|
||||
import Keys from "~/editor/extensions/Keys";
|
||||
import MentionMenuExtension from "~/editor/extensions/MentionMenu";
|
||||
import PasteHandler from "~/editor/extensions/PasteHandler";
|
||||
import PreventTab from "~/editor/extensions/PreventTab";
|
||||
import SmartText from "~/editor/extensions/SmartText";
|
||||
import { withUIExtensions } from "~/editor/extensions";
|
||||
import useCurrentTeam from "~/hooks/useCurrentTeam";
|
||||
import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
import useFocusedComment from "~/hooks/useFocusedComment";
|
||||
@@ -40,20 +31,7 @@ import MultiplayerEditor from "./AsyncMultiplayerEditor";
|
||||
import DocumentMeta from "./DocumentMeta";
|
||||
import DocumentTitle from "./DocumentTitle";
|
||||
|
||||
const extensions = [
|
||||
...withComments(richExtensions),
|
||||
SmartText,
|
||||
PasteHandler,
|
||||
ClipboardTextSerializer,
|
||||
BlockMenuExtension,
|
||||
EmojiMenuExtension,
|
||||
MentionMenuExtension,
|
||||
FindAndReplaceExtension,
|
||||
HoverPreviewsExtension,
|
||||
// Order these default key handlers last
|
||||
PreventTab,
|
||||
Keys,
|
||||
];
|
||||
const extensions = withUIExtensions(withComments(richExtensions));
|
||||
|
||||
type Props = Omit<EditorProps, "editorStyle"> & {
|
||||
onChangeTitle: (title: string) => void;
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router-dom";
|
||||
import styled, { useTheme } from "styled-components";
|
||||
import Icon from "@shared/components/Icon";
|
||||
import { useComponentSize } from "@shared/hooks/useComponentSize";
|
||||
import { NavigationNode } from "@shared/types";
|
||||
import { altDisplay, metaDisplay } from "@shared/utils/keyboard";
|
||||
import { Theme } from "~/stores/UiStore";
|
||||
@@ -31,7 +32,6 @@ import { publishDocument } from "~/actions/definitions/documents";
|
||||
import { navigateToTemplateSettings } from "~/actions/definitions/navigation";
|
||||
import { restoreRevision } from "~/actions/definitions/revisions";
|
||||
import useActionContext from "~/hooks/useActionContext";
|
||||
import useComponentSize from "~/hooks/useComponentSize";
|
||||
import useCurrentTeam from "~/hooks/useCurrentTeam";
|
||||
import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
import useEditingFocus from "~/hooks/useEditingFocus";
|
||||
|
||||
@@ -6,7 +6,7 @@ import styled from "styled-components";
|
||||
import { s } from "@shared/styles";
|
||||
import { stringToColor } from "@shared/utils/color";
|
||||
import User from "~/models/User";
|
||||
import { Avatar } from "~/components/Avatar";
|
||||
import { Avatar, AvatarSize } from "~/components/Avatar";
|
||||
import { useDocumentContext } from "~/components/DocumentContext";
|
||||
import DocumentViews from "~/components/DocumentViews";
|
||||
import Flex from "~/components/Flex";
|
||||
@@ -136,7 +136,7 @@ function Insights() {
|
||||
avatarUrl: null,
|
||||
initial: document.sourceMetadata.createdByName[0],
|
||||
}}
|
||||
size={32}
|
||||
size={AvatarSize.Large}
|
||||
/>
|
||||
}
|
||||
subtitle={t("Creator")}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as React from "react";
|
||||
import useComponentSize from "@shared/hooks/useComponentSize";
|
||||
import { useComponentSize } from "@shared/hooks/useComponentSize";
|
||||
|
||||
export const MeasuredContainer = <T extends React.ElementType>({
|
||||
as: As,
|
||||
|
||||
@@ -50,7 +50,7 @@ function DocumentNew({ template }: Props) {
|
||||
user.getPreference(UserPreference.FullWidthDocuments),
|
||||
templateId: query.get("templateId") ?? undefined,
|
||||
template,
|
||||
title: "",
|
||||
title: query.get("title") ?? "",
|
||||
data: ProsemirrorHelper.getEmptyDocument(),
|
||||
},
|
||||
{ publish: collection?.id || parentDocumentId ? true : undefined }
|
||||
|
||||
@@ -10,6 +10,7 @@ import { s } from "@shared/styles";
|
||||
import { UserPreference } from "@shared/types";
|
||||
import { parseDomain } from "@shared/utils/domains";
|
||||
import { Config } from "~/stores/AuthStore";
|
||||
import { AvatarSize } from "~/components/Avatar";
|
||||
import ButtonLarge from "~/components/ButtonLarge";
|
||||
import ChangeLanguage from "~/components/ChangeLanguage";
|
||||
import Fade from "~/components/Fade";
|
||||
@@ -249,9 +250,9 @@ function Login({ children }: Props) {
|
||||
/>
|
||||
<Logo>
|
||||
{config.logo && !isCreate ? (
|
||||
<TeamLogo size={48} src={config.logo} />
|
||||
<TeamLogo size={AvatarSize.XXLarge} src={config.logo} />
|
||||
) : (
|
||||
<OutlineIcon size={48} />
|
||||
<OutlineIcon size={AvatarSize.XXLarge} />
|
||||
)}
|
||||
</Logo>
|
||||
{isCreate ? (
|
||||
|
||||
@@ -25,7 +25,7 @@ function UserFilter(props: Props) {
|
||||
const userOptions = users.all.map((user) => ({
|
||||
key: user.id,
|
||||
label: user.name,
|
||||
icon: <Avatar model={user} showBorder={false} size={AvatarSize.Small} />,
|
||||
icon: <Avatar model={user} size={AvatarSize.Small} />,
|
||||
}));
|
||||
return [
|
||||
{
|
||||
|
||||
@@ -10,6 +10,7 @@ import Flex from "~/components/Flex";
|
||||
import ListItem from "~/components/List/Item";
|
||||
import Text from "~/components/Text";
|
||||
import Time from "~/components/Time";
|
||||
import Tooltip from "~/components/Tooltip";
|
||||
import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
import useUserLocale from "~/hooks/useUserLocale";
|
||||
import ApiKeyMenu from "~/menus/ApiKeyMenu";
|
||||
@@ -35,7 +36,7 @@ const ApiKeyListItem = ({ apiKey }: Props) => {
|
||||
·{" "}
|
||||
</Text>
|
||||
{apiKey.lastActiveAt && (
|
||||
<Text type={"tertiary"}>
|
||||
<Text type="tertiary">
|
||||
{t("Last used")} <Time dateTime={apiKey.lastActiveAt} addSuffix />{" "}
|
||||
·{" "}
|
||||
</Text>
|
||||
@@ -44,7 +45,20 @@ const ApiKeyListItem = ({ apiKey }: Props) => {
|
||||
{apiKey.expiresAt
|
||||
? dateToExpiry(apiKey.expiresAt, t, userLocale)
|
||||
: t("No expiry")}
|
||||
{apiKey.scope && <> · </>}
|
||||
</Text>
|
||||
{apiKey.scope && (
|
||||
<Tooltip
|
||||
content={apiKey.scope.map((s) => (
|
||||
<>
|
||||
{s}
|
||||
<br />
|
||||
</>
|
||||
))}
|
||||
>
|
||||
<Text type="tertiary">{t("Restricted scope")}</Text>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
|
||||
@@ -434,7 +434,7 @@ const GroupMemberListItem = observer(function ({
|
||||
{user.isAdmin && <Badge primary={user.isAdmin}>{t("Admin")}</Badge>}
|
||||
</>
|
||||
}
|
||||
image={<Avatar model={user} size={32} />}
|
||||
image={<Avatar model={user} size={AvatarSize.Large} />}
|
||||
actions={
|
||||
<Flex align="center">
|
||||
{onRemove && <GroupMemberMenu onRemove={onRemove} />}
|
||||
|
||||
@@ -18,7 +18,7 @@ export default function ImageInput({ model, onSuccess, ...rest }: Props) {
|
||||
<Flex gap={8} justify="space-between">
|
||||
<ImageBox>
|
||||
<ImageUpload onSuccess={onSuccess} {...rest}>
|
||||
<StyledAvatar model={model} size={AvatarSize.XXLarge} />
|
||||
<StyledAvatar model={model} size={AvatarSize.Upload} />
|
||||
<Flex auto align="center" justify="center" className="upload">
|
||||
{t("Upload")}
|
||||
</Flex>
|
||||
@@ -34,8 +34,8 @@ export default function ImageInput({ model, onSuccess, ...rest }: Props) {
|
||||
}
|
||||
|
||||
const avatarStyles = `
|
||||
width: ${AvatarSize.XXLarge}px;
|
||||
height: ${AvatarSize.XXLarge}px;
|
||||
width: ${AvatarSize.Upload}px;
|
||||
height: ${AvatarSize.Upload}px;
|
||||
`;
|
||||
|
||||
const StyledAvatar = styled(Avatar)`
|
||||
|
||||
@@ -3,7 +3,7 @@ import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import styled from "styled-components";
|
||||
import User from "~/models/User";
|
||||
import { Avatar } from "~/components/Avatar";
|
||||
import { Avatar, AvatarSize } from "~/components/Avatar";
|
||||
import Badge from "~/components/Badge";
|
||||
import Flex from "~/components/Flex";
|
||||
import { HEADER_HEIGHT } from "~/components/Header";
|
||||
@@ -38,7 +38,7 @@ export function PeopleTable({ canManage, ...rest }: Props) {
|
||||
accessor: (user) => user.name,
|
||||
component: (user) => (
|
||||
<Flex align="center" gap={8}>
|
||||
<Avatar model={user} size={32} /> {user.name}{" "}
|
||||
<Avatar model={user} size={AvatarSize.Large} /> {user.name}{" "}
|
||||
{currentUser.id === user.id && `(${t("You")})`}
|
||||
</Flex>
|
||||
),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { observable, action } from "mobx";
|
||||
import { AwarenessChangeEvent } from "~/types";
|
||||
import RootStore from "./RootStore";
|
||||
|
||||
type DocumentPresence = Map<
|
||||
string,
|
||||
@@ -17,6 +18,12 @@ export default class PresenceStore {
|
||||
|
||||
offlineTimeout = 30000;
|
||||
|
||||
private rootStore: RootStore;
|
||||
|
||||
constructor(rootStore: RootStore) {
|
||||
this.rootStore = rootStore;
|
||||
}
|
||||
|
||||
// called when a user leaves the document
|
||||
@action
|
||||
public leave(documentId: string, userId: string) {
|
||||
@@ -38,7 +45,7 @@ export default class PresenceStore {
|
||||
|
||||
event.states.forEach((state) => {
|
||||
const { user, cursor } = state;
|
||||
if (user) {
|
||||
if (user && this.rootStore.auth.currentUserId !== user.id) {
|
||||
this.update(documentId, user.id, !!cursor);
|
||||
existingUserIds = existingUserIds.filter((id) => id !== user.id);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,31 @@ type UploadOptions = {
|
||||
onProgress?: (fractionComplete: number) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Upload a file from a URL
|
||||
*
|
||||
* @param url The remote URL to download the file from
|
||||
* @param options The upload options
|
||||
* @returns The attachment object
|
||||
*/
|
||||
export const uploadFileFromUrl = async (
|
||||
url: string,
|
||||
options: UploadOptions
|
||||
) => {
|
||||
const response = await client.post("/attachments.createFromUrl", {
|
||||
documentId: options.documentId,
|
||||
url,
|
||||
});
|
||||
return response.data;
|
||||
};
|
||||
|
||||
/**
|
||||
* Upload a file
|
||||
*
|
||||
* @param file The file to upload
|
||||
* @param options The upload options
|
||||
* @returns The attachment object
|
||||
*/
|
||||
export const uploadFile = async (
|
||||
file: File | Blob,
|
||||
options: UploadOptions = {
|
||||
@@ -74,6 +99,12 @@ export const uploadFile = async (
|
||||
return attachment;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert a data URL to a Blob
|
||||
*
|
||||
* @param dataURL The data URL to convert
|
||||
* @returns The Blob
|
||||
*/
|
||||
export const dataUrlToBlob = (dataURL: string) => {
|
||||
const blobBin = atob(dataURL.split(",")[1]);
|
||||
const array = [];
|
||||
|
||||
+9
-9
@@ -48,11 +48,11 @@
|
||||
"> 0.25%, not dead"
|
||||
],
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "3.693.0",
|
||||
"@aws-sdk/lib-storage": "3.693.0",
|
||||
"@aws-sdk/s3-presigned-post": "3.693.0",
|
||||
"@aws-sdk/s3-request-presigner": "3.693.0",
|
||||
"@aws-sdk/signature-v4-crt": "^3.693.0",
|
||||
"@aws-sdk/client-s3": "3.740.0",
|
||||
"@aws-sdk/lib-storage": "3.740.0",
|
||||
"@aws-sdk/s3-presigned-post": "3.740.0",
|
||||
"@aws-sdk/s3-request-presigner": "3.740.0",
|
||||
"@aws-sdk/signature-v4-crt": "^3.740.0",
|
||||
"@babel/core": "^7.26.7",
|
||||
"@babel/plugin-proposal-decorators": "^7.25.9",
|
||||
"@babel/plugin-transform-class-properties": "^7.25.9",
|
||||
@@ -127,7 +127,7 @@
|
||||
"http-errors": "2.0.0",
|
||||
"i18next": "^22.5.1",
|
||||
"i18next-fs-backend": "^2.6.0",
|
||||
"i18next-http-backend": "^2.7.1",
|
||||
"i18next-http-backend": "^2.7.3",
|
||||
"invariant": "^2.2.4",
|
||||
"ioredis": "^5.4.1",
|
||||
"is-printable-key-event": "^1.0.0",
|
||||
@@ -243,7 +243,7 @@
|
||||
"validator": "13.12.0",
|
||||
"vite": "^5.4.12",
|
||||
"vite-plugin-pwa": "^0.20.3",
|
||||
"winston": "^3.13.0",
|
||||
"winston": "^3.17.0",
|
||||
"ws": "^7.5.10",
|
||||
"y-indexeddb": "^9.0.11",
|
||||
"y-prosemirror": "^1.2.12",
|
||||
@@ -265,7 +265,7 @@
|
||||
"@types/dotenv": "^8.2.3",
|
||||
"@types/emoji-regex": "^9.2.0",
|
||||
"@types/escape-html": "^1.0.4",
|
||||
"@types/express-useragent": "^1.0.2",
|
||||
"@types/express-useragent": "^1.0.5",
|
||||
"@types/formidable": "^2.0.6",
|
||||
"@types/fs-extra": "^11.0.4",
|
||||
"@types/fuzzy-search": "^2.1.5",
|
||||
@@ -354,7 +354,7 @@
|
||||
"react-refresh": "^0.14.2",
|
||||
"rimraf": "^2.5.4",
|
||||
"rollup-plugin-webpack-stats": "^2.0.1",
|
||||
"terser": "^5.36.0",
|
||||
"terser": "^5.37.0",
|
||||
"typescript": "^5.7.2",
|
||||
"vite-plugin-static-copy": "^0.17.0",
|
||||
"yarn-deduplicate": "^6.0.2"
|
||||
|
||||
@@ -57,10 +57,14 @@ if (env.AZURE_CLIENT_ID && env.AZURE_CLIENT_SECRET) {
|
||||
const [profileResponse, organizationResponse] = await Promise.all([
|
||||
// Load the users profile from the Microsoft Graph API
|
||||
// https://docs.microsoft.com/en-us/graph/api/resources/users?view=graph-rest-1.0
|
||||
request(`https://graph.microsoft.com/v1.0/me`, accessToken),
|
||||
request("GET", `https://graph.microsoft.com/v1.0/me`, accessToken),
|
||||
// Load the organization profile from the Microsoft Graph API
|
||||
// https://docs.microsoft.com/en-us/graph/api/organization-get?view=graph-rest-1.0
|
||||
request(`https://graph.microsoft.com/v1.0/organization`, accessToken),
|
||||
request(
|
||||
"GET",
|
||||
`https://graph.microsoft.com/v1.0/organization`,
|
||||
accessToken
|
||||
),
|
||||
]);
|
||||
|
||||
if (!profileResponse) {
|
||||
|
||||
@@ -70,6 +70,7 @@ if (env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET) {
|
||||
const client = getClientFromContext(ctx);
|
||||
/** Fetch the user's profile */
|
||||
const profile: RESTGetAPICurrentUserResult = await request(
|
||||
"GET",
|
||||
"https://discord.com/api/users/@me",
|
||||
accessToken
|
||||
);
|
||||
@@ -105,6 +106,7 @@ if (env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET) {
|
||||
if (env.DISCORD_SERVER_ID) {
|
||||
/** Fetch the guilds a user is in */
|
||||
const guilds: RESTGetAPICurrentUserGuildsResult = await request(
|
||||
"GET",
|
||||
"https://discord.com/api/users/@me/guilds",
|
||||
accessToken
|
||||
);
|
||||
@@ -146,6 +148,7 @@ if (env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET) {
|
||||
/** Fetch the user's member object in the server for nickname and roles */
|
||||
const guildMember: RESTGetCurrentUserGuildMemberResult =
|
||||
await request(
|
||||
"GET",
|
||||
`https://discord.com/api/users/@me/guilds/${env.DISCORD_SERVER_ID}/member`,
|
||||
accessToken
|
||||
);
|
||||
|
||||
@@ -116,7 +116,6 @@ function GitHub() {
|
||||
<TeamLogo
|
||||
src={githubAccount?.avatarUrl}
|
||||
size={AvatarSize.Large}
|
||||
showBorder={false}
|
||||
/>
|
||||
}
|
||||
actions={
|
||||
|
||||
@@ -81,8 +81,14 @@ if (
|
||||
) => void
|
||||
) {
|
||||
try {
|
||||
// Some providers require a POST request to the userinfo endpoint, add them as exceptions here.
|
||||
const usePostMethod = [
|
||||
"https://api.dropboxapi.com/2/openid/userinfo",
|
||||
];
|
||||
|
||||
const profile = await request(
|
||||
env.OIDC_USERINFO_URI ?? "",
|
||||
usePostMethod.includes(env.OIDC_USERINFO_URI!) ? "POST" : "GET",
|
||||
env.OIDC_USERINFO_URI!,
|
||||
accessToken
|
||||
);
|
||||
|
||||
|
||||
@@ -102,6 +102,7 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
|
||||
case "api_keys.create":
|
||||
case "api_keys.delete":
|
||||
case "attachments.create":
|
||||
case "attachments.update":
|
||||
case "attachments.delete":
|
||||
case "subscriptions.create":
|
||||
case "subscriptions.delete":
|
||||
|
||||
@@ -210,6 +210,7 @@ describe("subscriptionCreator", () => {
|
||||
where: {
|
||||
teamId: user.teamId,
|
||||
},
|
||||
order: [["createdAt", "ASC"]],
|
||||
});
|
||||
expect(events.length).toEqual(3);
|
||||
|
||||
|
||||
@@ -80,7 +80,13 @@ export default function auth(options: AuthenticationOptions = {}) {
|
||||
}
|
||||
|
||||
if (apiKey.expiresAt && apiKey.expiresAt < new Date()) {
|
||||
throw AuthenticationError("Invalid API key");
|
||||
throw AuthenticationError("API key is expired");
|
||||
}
|
||||
|
||||
if (!apiKey.canAccess(ctx.request.url)) {
|
||||
throw AuthenticationError(
|
||||
"API key does not have access to this resource"
|
||||
);
|
||||
}
|
||||
|
||||
user = await User.findByPk(apiKey.userId, {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"use strict";
|
||||
|
||||
/** @type {import('sequelize-cli').Migration} */
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.sequelize.transaction(async transaction => {
|
||||
await queryInterface.addColumn("apiKeys", "scope", {
|
||||
type: Sequelize.ARRAY(Sequelize.STRING),
|
||||
allowNull: true,
|
||||
}, { transaction });
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.sequelize.transaction(async transaction => {
|
||||
await queryInterface.removeColumn("apiKeys", "scope", { transaction });
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -4,26 +4,26 @@ import ApiKey from "./ApiKey";
|
||||
|
||||
describe("#ApiKey", () => {
|
||||
describe("match", () => {
|
||||
test("should match an API secret", async () => {
|
||||
it("should match an API secret", async () => {
|
||||
const apiKey = await buildApiKey();
|
||||
expect(ApiKey.match(apiKey.value!)).toBe(true);
|
||||
expect(ApiKey.match(`${randomstring.generate(38)}`)).toBe(true);
|
||||
});
|
||||
|
||||
test("should not match non secrets", async () => {
|
||||
it("should not match non secrets", async () => {
|
||||
expect(ApiKey.match("123")).toBe(false);
|
||||
expect(ApiKey.match("1234567890")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("lastActiveAt", () => {
|
||||
test("should update lastActiveAt", async () => {
|
||||
it("should update lastActiveAt", async () => {
|
||||
const apiKey = await buildApiKey();
|
||||
await apiKey.updateActiveAt();
|
||||
expect(apiKey.lastActiveAt).toBeTruthy();
|
||||
});
|
||||
|
||||
test("should not update lastActiveAt within 5 minutes", async () => {
|
||||
it("should not update lastActiveAt within 5 minutes", async () => {
|
||||
const apiKey = await buildApiKey();
|
||||
await apiKey.updateActiveAt();
|
||||
expect(apiKey.lastActiveAt).toBeTruthy();
|
||||
@@ -35,7 +35,7 @@ describe("#ApiKey", () => {
|
||||
});
|
||||
|
||||
describe("findByToken", () => {
|
||||
test("should find by hash", async () => {
|
||||
it("should find by hash", async () => {
|
||||
const apiKey = await buildApiKey({
|
||||
name: "Dev",
|
||||
});
|
||||
@@ -44,4 +44,62 @@ describe("#ApiKey", () => {
|
||||
expect(found?.last4).toEqual(apiKey.value!.slice(-4));
|
||||
});
|
||||
});
|
||||
|
||||
describe("canAccess", () => {
|
||||
it("should return true for all resources if no scope", async () => {
|
||||
const apiKey = await buildApiKey({
|
||||
name: "Dev",
|
||||
});
|
||||
|
||||
expect(apiKey.canAccess("/api/documents.info")).toBe(true);
|
||||
expect(apiKey.canAccess("/api/collections.create")).toBe(true);
|
||||
expect(apiKey.canAccess("/api/apiKeys.list")).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false if no matching scope", async () => {
|
||||
const apiKey = await buildApiKey({
|
||||
name: "Dev",
|
||||
scope: ["/api/documents.info"],
|
||||
});
|
||||
|
||||
expect(apiKey.canAccess("/api/documents.info")).toBe(true);
|
||||
expect(apiKey.canAccess("/api/collections.create")).toBe(false);
|
||||
expect(apiKey.canAccess("/api/apiKeys.list")).toBe(false);
|
||||
});
|
||||
|
||||
it("should allow wildcard methods", async () => {
|
||||
const apiKey = await buildApiKey({
|
||||
name: "Dev",
|
||||
scope: ["/api/documents.*"],
|
||||
});
|
||||
|
||||
expect(apiKey.canAccess("/api/documents.info")).toBe(true);
|
||||
expect(apiKey.canAccess("/api/documents.create")).toBe(true);
|
||||
expect(apiKey.canAccess("/api/collections.create")).toBe(false);
|
||||
});
|
||||
|
||||
it("should allow wildcard namespaces", async () => {
|
||||
const apiKey = await buildApiKey({
|
||||
name: "Dev",
|
||||
scope: ["/api/*.info"],
|
||||
});
|
||||
|
||||
expect(apiKey.canAccess("/api/documents.info")).toBe(true);
|
||||
expect(apiKey.canAccess("/api/documents.create")).toBe(false);
|
||||
expect(apiKey.canAccess("/api/collections.create")).toBe(false);
|
||||
});
|
||||
|
||||
it("should allow multiple scopes", async () => {
|
||||
const apiKey = await buildApiKey({
|
||||
name: "Dev",
|
||||
scope: ["/api/*.info", "/api/collections.list"],
|
||||
});
|
||||
|
||||
expect(apiKey.canAccess("/api/shares.info")).toBe(true);
|
||||
expect(apiKey.canAccess("/api/documents.info")).toBe(true);
|
||||
expect(apiKey.canAccess("/api/collections.list")).toBe(true);
|
||||
expect(apiKey.canAccess("/api/documents.create")).toBe(false);
|
||||
expect(apiKey.canAccess("/api/collections.create")).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import crypto from "crypto";
|
||||
import { Matches } from "class-validator";
|
||||
import { subMinutes } from "date-fns";
|
||||
import randomstring from "randomstring";
|
||||
import { InferAttributes, InferCreationAttributes, Op } from "sequelize";
|
||||
@@ -31,6 +32,7 @@ class ApiKey extends ParanoidModel<
|
||||
|
||||
static eventNamespace = "api_keys";
|
||||
|
||||
/** The human-readable name of this API key */
|
||||
@Length({
|
||||
min: ApiKeyValidation.minNameLength,
|
||||
max: ApiKeyValidation.maxNameLength,
|
||||
@@ -39,6 +41,13 @@ class ApiKey extends ParanoidModel<
|
||||
@Column
|
||||
name: string;
|
||||
|
||||
/** A space-separated list of scopes that this API key has access to */
|
||||
@Matches(/[\/\.\w\s]*/, {
|
||||
each: true,
|
||||
})
|
||||
@Column(DataType.ARRAY(DataType.STRING))
|
||||
scope: string[] | null;
|
||||
|
||||
/** @deprecated The plain text value of the API key, removed soon. */
|
||||
@Unique
|
||||
@Column
|
||||
@@ -59,10 +68,12 @@ class ApiKey extends ParanoidModel<
|
||||
@SkipChangeset
|
||||
last4: string;
|
||||
|
||||
/** The date and time when this API key will expire */
|
||||
@IsDate
|
||||
@Column
|
||||
expiresAt: Date | null;
|
||||
|
||||
/** The date and time when this API key was last used */
|
||||
@IsDate
|
||||
@Column
|
||||
@SkipChangeset
|
||||
@@ -156,6 +167,27 @@ class ApiKey extends ParanoidModel<
|
||||
|
||||
return this.save({ silent: true });
|
||||
};
|
||||
|
||||
/** Checks if the API key has access to the given path */
|
||||
canAccess = (path: string) => {
|
||||
if (!this.scope) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const resource = path.split("/").pop() ?? "";
|
||||
const [namespace, method] = resource.split(".");
|
||||
|
||||
return this.scope.some((scope) => {
|
||||
const [scopeNamespace, scopeMethod] = scope
|
||||
.replace("/api/", "")
|
||||
.split(".");
|
||||
return (
|
||||
scope.startsWith("/api/") &&
|
||||
(namespace === scopeNamespace || scopeNamespace === "*") &&
|
||||
(method === scopeMethod || scopeMethod === "*")
|
||||
);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export default ApiKey;
|
||||
|
||||
@@ -338,6 +338,7 @@ class Collection extends ParanoidModel<
|
||||
createdById: model.createdById,
|
||||
},
|
||||
transaction: options.transaction,
|
||||
hooks: false,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -18,12 +18,15 @@ import {
|
||||
AfterCreate,
|
||||
AfterUpdate,
|
||||
Length,
|
||||
AfterDestroy,
|
||||
} from "sequelize-typescript";
|
||||
import { CollectionPermission, DocumentPermission } from "@shared/types";
|
||||
import { APIContext } from "@server/types";
|
||||
import Collection from "./Collection";
|
||||
import Document from "./Document";
|
||||
import User from "./User";
|
||||
import IdModel from "./base/IdModel";
|
||||
import { HookContext } from "./base/Model";
|
||||
import Fix from "./decorators/Fix";
|
||||
|
||||
/**
|
||||
@@ -209,6 +212,16 @@ class UserMembership extends IdModel<
|
||||
return this.recreateSourcedMemberships(model, options);
|
||||
}
|
||||
|
||||
@AfterCreate
|
||||
static async publishAddUserEventAfterCreate(
|
||||
model: UserMembership,
|
||||
context: APIContext["context"]
|
||||
) {
|
||||
await model.insertEvent(context, "add_user", {
|
||||
isNew: true,
|
||||
});
|
||||
}
|
||||
|
||||
@AfterUpdate
|
||||
static async updateSourcedMemberships(
|
||||
model: UserMembership,
|
||||
@@ -236,6 +249,24 @@ class UserMembership extends IdModel<
|
||||
}
|
||||
}
|
||||
|
||||
@AfterUpdate
|
||||
static async publishAddUserEventAfterUpdate(
|
||||
model: UserMembership,
|
||||
context: APIContext["context"]
|
||||
) {
|
||||
await model.insertEvent(context, "add_user", {
|
||||
isNew: false,
|
||||
});
|
||||
}
|
||||
|
||||
@AfterDestroy
|
||||
static async publishRemoveUserEvent(
|
||||
model: UserMembership,
|
||||
context: APIContext["context"]
|
||||
) {
|
||||
await model.insertEvent(context, "remove_user");
|
||||
}
|
||||
|
||||
/**
|
||||
* Recreate all sourced permissions for a given permission.
|
||||
*/
|
||||
@@ -293,10 +324,28 @@ class UserMembership extends IdModel<
|
||||
},
|
||||
{
|
||||
transaction,
|
||||
hooks: false,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async insertEvent(
|
||||
ctx: APIContext["context"],
|
||||
name: string,
|
||||
data?: Record<string, unknown>
|
||||
) {
|
||||
const hookContext = {
|
||||
...ctx,
|
||||
event: { name, data, create: true },
|
||||
} as HookContext;
|
||||
|
||||
if (this.collectionId) {
|
||||
await Collection.insertEvent(name, this, hookContext);
|
||||
} else {
|
||||
await Document.insertEvent(name, this, hookContext);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default UserMembership;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import env from "@server/env";
|
||||
import { IncorrectEditionError } from "@server/errors";
|
||||
import { User, Team } from "@server/models";
|
||||
import Model from "@server/models/base/Model";
|
||||
|
||||
@@ -97,9 +96,7 @@ export function isTeamMutable(_actor: User, _model?: Model | null) {
|
||||
*/
|
||||
export function isCloudHosted() {
|
||||
if (!env.isCloudHosted) {
|
||||
throw IncorrectEditionError(
|
||||
"Functionality is not available in this edition"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ export default function presentApiKey(apiKey: ApiKey) {
|
||||
id: apiKey.id,
|
||||
userId: apiKey.userId,
|
||||
name: apiKey.name,
|
||||
scope: apiKey.scope,
|
||||
value: apiKey.value,
|
||||
last4: apiKey.last4,
|
||||
createdAt: apiKey.createdAt,
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { Transaction } from "sequelize";
|
||||
import subscriptionCreator from "@server/commands/subscriptionCreator";
|
||||
import { createContext } from "@server/context";
|
||||
import { Subscription, User } from "@server/models";
|
||||
import { sequelize } from "@server/storage/database";
|
||||
import { DocumentUserEvent, Event } from "@server/types";
|
||||
import BaseProcessor from "./BaseProcessor";
|
||||
|
||||
export default class DocumentSubscriptionProcessor extends BaseProcessor {
|
||||
static applicableEvents: Event["name"][] = [
|
||||
"documents.add_user",
|
||||
"documents.remove_user",
|
||||
];
|
||||
|
||||
async perform(event: DocumentUserEvent) {
|
||||
const user = await User.findByPk(event.userId);
|
||||
if (!user) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (event.name) {
|
||||
case "documents.add_user": {
|
||||
return this.addUser(event, user);
|
||||
}
|
||||
|
||||
case "documents.remove_user": {
|
||||
return this.removeUser(event, user);
|
||||
}
|
||||
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
private async addUser(event: DocumentUserEvent, user: User) {
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
await subscriptionCreator({
|
||||
ctx: createContext({
|
||||
user,
|
||||
authType: event.authType,
|
||||
ip: event.ip,
|
||||
transaction,
|
||||
}),
|
||||
documentId: event.documentId,
|
||||
event: "documents.update",
|
||||
resubscribe: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private async removeUser(event: DocumentUserEvent, user: User) {
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
const subscription = await Subscription.findOne({
|
||||
where: {
|
||||
userId: user.id,
|
||||
documentId: event.documentId,
|
||||
event: "documents.update",
|
||||
},
|
||||
transaction,
|
||||
lock: Transaction.LOCK.UPDATE,
|
||||
});
|
||||
|
||||
await subscription?.destroyWithCtx(
|
||||
createContext({
|
||||
user,
|
||||
authType: event.authType,
|
||||
ip: event.ip,
|
||||
transaction,
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import subscriptionCreator from "@server/commands/subscriptionCreator";
|
||||
import { createContext } from "@server/context";
|
||||
import { User } from "@server/models";
|
||||
import { sequelize } from "@server/storage/database";
|
||||
import { DocumentUserEvent, Event } from "@server/types";
|
||||
import BaseProcessor from "./BaseProcessor";
|
||||
|
||||
export default class DocumentUserAddedProcessor extends BaseProcessor {
|
||||
static applicableEvents: Event["name"][] = ["documents.add_user"];
|
||||
|
||||
async perform(event: DocumentUserEvent) {
|
||||
const user = await User.findByPk(event.userId);
|
||||
if (!user) {
|
||||
return;
|
||||
}
|
||||
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
await subscriptionCreator({
|
||||
ctx: createContext({
|
||||
user,
|
||||
authType: event.authType,
|
||||
ip: event.ip,
|
||||
transaction,
|
||||
}),
|
||||
documentId: event.documentId,
|
||||
event: "documents.update",
|
||||
resubscribe: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { createContext } from "@server/context";
|
||||
import { Attachment } from "@server/models";
|
||||
import FileStorage from "@server/storage/files";
|
||||
import BaseTask, { TaskPriority } from "./BaseTask";
|
||||
|
||||
type Props = {
|
||||
/** The ID of the attachment */
|
||||
attachmentId: string;
|
||||
/** The remote URL to upload */
|
||||
url: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A task that uploads the provided url to a known attachment.
|
||||
*/
|
||||
export default class UploadAttachmentFromUrlTask extends BaseTask<Props> {
|
||||
public async perform(props: Props) {
|
||||
const attachment = await Attachment.findByPk(props.attachmentId, {
|
||||
rejectOnEmpty: true,
|
||||
include: [{ association: "user" }],
|
||||
});
|
||||
|
||||
try {
|
||||
const res = await FileStorage.storeFromUrl(
|
||||
props.url,
|
||||
attachment.key,
|
||||
attachment.acl
|
||||
);
|
||||
|
||||
if (res?.url) {
|
||||
const ctx = createContext({ user: attachment.user });
|
||||
await attachment.updateWithCtx(ctx, {
|
||||
url: res.url,
|
||||
size: res.contentLength,
|
||||
contentType: res.contentType,
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
return { error: err.message };
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
public get options() {
|
||||
return {
|
||||
attempts: 3,
|
||||
priority: TaskPriority.Normal,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,27 @@ describe("#apiKeys.create", () => {
|
||||
expect(body.data.lastActiveAt).toBeNull();
|
||||
});
|
||||
|
||||
it("should allow creating an api key with scopes", async () => {
|
||||
const user = await buildUser();
|
||||
|
||||
const res = await server.post("/api/apiKeys.create", {
|
||||
body: {
|
||||
token: user.getJwtToken(),
|
||||
name: "My API Key",
|
||||
scope: ["/api/documents.list", "*.info", "users.*"],
|
||||
},
|
||||
});
|
||||
const body = await res.json();
|
||||
|
||||
expect(res.status).toEqual(200);
|
||||
expect(body.data.name).toEqual("My API Key");
|
||||
expect(body.data.scope).toEqual([
|
||||
"/api/documents.list",
|
||||
"/api/*.info",
|
||||
"/api/users.*",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should require authentication", async () => {
|
||||
const res = await server.post("/api/apiKeys.create");
|
||||
expect(res.status).toEqual(401);
|
||||
|
||||
@@ -19,7 +19,7 @@ router.post(
|
||||
validate(T.APIKeysCreateSchema),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.APIKeysCreateReq>) => {
|
||||
const { name, expiresAt } = ctx.input.body;
|
||||
const { name, scope, expiresAt } = ctx.input.body;
|
||||
const { user } = ctx.state.auth;
|
||||
|
||||
authorize(user, "createApiKey", user.team);
|
||||
@@ -28,6 +28,7 @@ router.post(
|
||||
name,
|
||||
userId: user.id,
|
||||
expiresAt,
|
||||
scope: scope?.map((s) => (s.startsWith("/api/") ? s : `/api/${s}`)),
|
||||
});
|
||||
|
||||
ctx.body = {
|
||||
|
||||
@@ -7,6 +7,8 @@ export const APIKeysCreateSchema = BaseSchema.extend({
|
||||
name: z.string(),
|
||||
/** API Key expiry date */
|
||||
expiresAt: z.coerce.date().optional(),
|
||||
/** A list of scopes that this API key has access to */
|
||||
scope: z.array(z.string()).optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import Router from "koa-router";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { AttachmentPreset } from "@shared/types";
|
||||
import { bytesToHumanReadable } from "@shared/utils/files";
|
||||
import { bytesToHumanReadable, getFileNameFromUrl } from "@shared/utils/files";
|
||||
import { AttachmentValidation } from "@shared/validations";
|
||||
import { AuthorizationError, ValidationError } from "@server/errors";
|
||||
import { createContext } from "@server/context";
|
||||
import {
|
||||
AuthorizationError,
|
||||
InvalidRequestError,
|
||||
ValidationError,
|
||||
} from "@server/errors";
|
||||
import auth from "@server/middlewares/authentication";
|
||||
import { rateLimiter } from "@server/middlewares/rateLimiter";
|
||||
import { transaction } from "@server/middlewares/transaction";
|
||||
@@ -12,6 +17,8 @@ import { Attachment, Document } from "@server/models";
|
||||
import AttachmentHelper from "@server/models/helpers/AttachmentHelper";
|
||||
import { authorize } from "@server/policies";
|
||||
import { presentAttachment } from "@server/presenters";
|
||||
import UploadAttachmentFromUrlTask from "@server/queues/tasks/UploadAttachmentFromUrlTask";
|
||||
import { sequelize } from "@server/storage/database";
|
||||
import FileStorage from "@server/storage/files";
|
||||
import BaseStorage from "@server/storage/files/BaseStorage";
|
||||
import { APIContext } from "@server/types";
|
||||
@@ -105,6 +112,76 @@ router.post(
|
||||
}
|
||||
);
|
||||
|
||||
router.post(
|
||||
"attachments.createFromUrl",
|
||||
rateLimiter(RateLimiterStrategy.TwentyFivePerMinute),
|
||||
auth(),
|
||||
validate(T.AttachmentsCreateFromUrlSchema),
|
||||
async (ctx: APIContext<T.AttachmentCreateFromUrlReq>) => {
|
||||
const { url, documentId, preset } = ctx.input.body;
|
||||
const { user, type } = ctx.state.auth;
|
||||
|
||||
if (preset !== AttachmentPreset.DocumentAttachment || !documentId) {
|
||||
throw ValidationError(
|
||||
"Only document attachments can be created from a URL"
|
||||
);
|
||||
}
|
||||
|
||||
const document = await Document.findByPk(documentId, {
|
||||
userId: user.id,
|
||||
});
|
||||
authorize(user, "update", document);
|
||||
|
||||
const name = getFileNameFromUrl(url) ?? "file";
|
||||
const modelId = uuidv4();
|
||||
const acl = AttachmentHelper.presetToAcl(preset);
|
||||
const key = AttachmentHelper.getKey({
|
||||
acl,
|
||||
id: modelId,
|
||||
name,
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
// Does not use transaction middleware, as attachment must be persisted
|
||||
// before the job is scheduled.
|
||||
const attachment = await sequelize.transaction(async (transaction) =>
|
||||
Attachment.createWithCtx(
|
||||
createContext({
|
||||
authType: type,
|
||||
user,
|
||||
ip: ctx.ip,
|
||||
transaction,
|
||||
}),
|
||||
{
|
||||
id: modelId,
|
||||
key,
|
||||
acl,
|
||||
size: 0,
|
||||
expiresAt: AttachmentHelper.presetToExpiry(preset),
|
||||
contentType: "application/octet-stream",
|
||||
documentId,
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
const job = await UploadAttachmentFromUrlTask.schedule({
|
||||
attachmentId: attachment.id,
|
||||
url,
|
||||
});
|
||||
|
||||
const response = await job.finished();
|
||||
if ("error" in response) {
|
||||
throw InvalidRequestError(response.error);
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
data: presentAttachment(attachment),
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
router.post(
|
||||
"attachments.delete",
|
||||
auth(),
|
||||
|
||||
@@ -26,6 +26,25 @@ export const AttachmentsCreateSchema = BaseSchema.extend({
|
||||
|
||||
export type AttachmentCreateReq = z.infer<typeof AttachmentsCreateSchema>;
|
||||
|
||||
export const AttachmentsCreateFromUrlSchema = BaseSchema.extend({
|
||||
body: z.object({
|
||||
/** Attachment url */
|
||||
url: z.string(),
|
||||
|
||||
/** Id of the document to which the Attachment belongs */
|
||||
documentId: z.string().uuid().optional(),
|
||||
|
||||
/** Attachment type */
|
||||
preset: z
|
||||
.nativeEnum(AttachmentPreset)
|
||||
.default(AttachmentPreset.DocumentAttachment),
|
||||
}),
|
||||
});
|
||||
|
||||
export type AttachmentCreateFromUrlReq = z.infer<
|
||||
typeof AttachmentsCreateFromUrlSchema
|
||||
>;
|
||||
|
||||
export const AttachmentDeleteSchema = BaseSchema.extend({
|
||||
body: z.object({
|
||||
/** Id of the attachment to be deleted */
|
||||
|
||||
@@ -353,8 +353,8 @@ router.post(
|
||||
validate(T.CollectionsAddUserSchema),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.CollectionsAddUserReq>) => {
|
||||
const { auth, transaction } = ctx.state;
|
||||
const actor = auth.user;
|
||||
const { transaction } = ctx.state;
|
||||
const { user: actor } = ctx.state.auth;
|
||||
const { id, userId, permission } = ctx.input.body;
|
||||
|
||||
const [collection, user] = await Promise.all([
|
||||
@@ -375,26 +375,15 @@ router.post(
|
||||
permission: permission || user.defaultCollectionPermission,
|
||||
createdById: actor.id,
|
||||
},
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
...ctx.context,
|
||||
});
|
||||
|
||||
if (permission) {
|
||||
if (!isNew && permission) {
|
||||
membership.permission = permission;
|
||||
await membership.save({ transaction });
|
||||
await membership.save(ctx.context);
|
||||
}
|
||||
|
||||
await Event.createFromContext(ctx, {
|
||||
name: "collections.add_user",
|
||||
userId,
|
||||
modelId: membership.id,
|
||||
collectionId: collection.id,
|
||||
data: {
|
||||
isNew,
|
||||
permission: membership.permission,
|
||||
},
|
||||
});
|
||||
|
||||
ctx.body = {
|
||||
data: {
|
||||
users: [presentUser(user)],
|
||||
@@ -410,8 +399,8 @@ router.post(
|
||||
validate(T.CollectionsRemoveUserSchema),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.CollectionsRemoveUserReq>) => {
|
||||
const { auth, transaction } = ctx.state;
|
||||
const actor = auth.user;
|
||||
const { transaction } = ctx.state;
|
||||
const { user: actor } = ctx.state.auth;
|
||||
const { id, userId } = ctx.input.body;
|
||||
|
||||
const [collection, user] = await Promise.all([
|
||||
@@ -431,17 +420,7 @@ router.post(
|
||||
ctx.throw(400, "User is not a collection member");
|
||||
}
|
||||
|
||||
await collection.$remove("user", user, { transaction });
|
||||
|
||||
await Event.createFromContext(ctx, {
|
||||
name: "collections.remove_user",
|
||||
userId,
|
||||
modelId: membership.id,
|
||||
collectionId: collection.id,
|
||||
data: {
|
||||
name: user.name,
|
||||
},
|
||||
});
|
||||
await membership.destroy(ctx.context);
|
||||
|
||||
ctx.body = {
|
||||
success: true,
|
||||
|
||||
@@ -1680,8 +1680,8 @@ router.post(
|
||||
rateLimiter(RateLimiterStrategy.OneHundredPerHour),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.DocumentsAddUserReq>) => {
|
||||
const { auth, transaction } = ctx.state;
|
||||
const actor = auth.user;
|
||||
const { transaction } = ctx.state;
|
||||
const { user: actor } = ctx.state.auth;
|
||||
const { id, userId, permission } = ctx.input.body;
|
||||
|
||||
if (userId === actor.id) {
|
||||
@@ -1734,31 +1734,19 @@ router.post(
|
||||
permission: permission || user.defaultDocumentPermission,
|
||||
createdById: actor.id,
|
||||
},
|
||||
transaction,
|
||||
lock: transaction.LOCK.UPDATE,
|
||||
...ctx.context,
|
||||
});
|
||||
|
||||
if (permission) {
|
||||
if (!isNew && permission) {
|
||||
membership.permission = permission;
|
||||
|
||||
// disconnect from the source if the permission is manually updated
|
||||
membership.sourceId = null;
|
||||
|
||||
await membership.save({ transaction });
|
||||
await membership.save(ctx.context);
|
||||
}
|
||||
|
||||
await Event.createFromContext(ctx, {
|
||||
name: "documents.add_user",
|
||||
userId,
|
||||
modelId: membership.id,
|
||||
documentId: document.id,
|
||||
data: {
|
||||
title: document.title,
|
||||
isNew,
|
||||
permission: membership.permission,
|
||||
},
|
||||
});
|
||||
|
||||
ctx.body = {
|
||||
data: {
|
||||
users: [presentUser(user)],
|
||||
@@ -1805,14 +1793,7 @@ router.post(
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
|
||||
await membership.destroy({ transaction });
|
||||
|
||||
await Event.createFromContext(ctx, {
|
||||
name: "documents.remove_user",
|
||||
userId,
|
||||
modelId: membership.id,
|
||||
documentId: document.id,
|
||||
});
|
||||
await membership.destroy(ctx.context);
|
||||
|
||||
ctx.body = {
|
||||
success: true,
|
||||
|
||||
@@ -12,6 +12,7 @@ export default async function main(exit = false, limit = 100) {
|
||||
let apiKeys: ApiKey[] = [];
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
apiKeys = await ApiKey.unscoped().findAll({
|
||||
attributes: ["id", "secret", "value", "hash"],
|
||||
limit,
|
||||
offset: page * limit,
|
||||
order: [["createdAt", "ASC"]],
|
||||
|
||||
@@ -129,13 +129,15 @@ export default abstract class BaseStorage {
|
||||
* @param key The path to store the file at
|
||||
* @param acl The ACL to use
|
||||
* @param init Optional fetch options to use
|
||||
* @param options Optional upload options
|
||||
* @returns A promise that resolves when the file is uploaded
|
||||
*/
|
||||
public async storeFromUrl(
|
||||
url: string,
|
||||
key: string,
|
||||
acl: string,
|
||||
init?: RequestInit
|
||||
init?: RequestInit,
|
||||
options?: { maxUploadSize?: number }
|
||||
): Promise<
|
||||
| {
|
||||
url: string;
|
||||
@@ -162,7 +164,10 @@ export default abstract class BaseStorage {
|
||||
const res = await fetch(url, {
|
||||
follow: 3,
|
||||
redirect: "follow",
|
||||
size: env.FILE_STORAGE_UPLOAD_MAX_SIZE,
|
||||
size: Math.min(
|
||||
options?.maxUploadSize ?? Infinity,
|
||||
env.FILE_STORAGE_UPLOAD_MAX_SIZE
|
||||
),
|
||||
timeout: 10000,
|
||||
...init,
|
||||
});
|
||||
|
||||
+4
-4
@@ -7,7 +7,6 @@ import {
|
||||
NavigationNode,
|
||||
Client,
|
||||
CollectionPermission,
|
||||
DocumentPermission,
|
||||
JSONValue,
|
||||
UnfurlResourceType,
|
||||
ProsemirrorData,
|
||||
@@ -117,6 +116,10 @@ export type AttachmentEvent = BaseEvent<Attachment> &
|
||||
source?: "import";
|
||||
};
|
||||
}
|
||||
| {
|
||||
name: "attachments.update";
|
||||
modelId: string;
|
||||
}
|
||||
| {
|
||||
name: "attachments.delete";
|
||||
modelId: string;
|
||||
@@ -265,7 +268,6 @@ export type CollectionUserEvent = BaseEvent<UserMembership> & {
|
||||
collectionId: string;
|
||||
data: {
|
||||
isNew?: boolean;
|
||||
permission?: CollectionPermission;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -282,9 +284,7 @@ export type DocumentUserEvent = BaseEvent<UserMembership> & {
|
||||
modelId: string;
|
||||
documentId: string;
|
||||
data: {
|
||||
title: string;
|
||||
isNew?: boolean;
|
||||
permission?: DocumentPermission;
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -68,9 +68,13 @@ export class StateStore {
|
||||
};
|
||||
}
|
||||
|
||||
export async function request(endpoint: string, accessToken: string) {
|
||||
export async function request(
|
||||
method: "GET" | "POST",
|
||||
endpoint: string,
|
||||
accessToken: string
|
||||
) {
|
||||
const response = await fetch(endpoint, {
|
||||
method: "GET",
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
import { Node } from "prosemirror-model";
|
||||
import { EditorView } from "prosemirror-view";
|
||||
import { toast } from "sonner";
|
||||
import type { Dictionary } from "~/hooks/useDictionary";
|
||||
|
||||
function findPlaceholderLink(doc: Node, href: string) {
|
||||
let result: { pos: number; node: Node } | undefined;
|
||||
|
||||
doc.descendants((node: Node, pos = 0) => {
|
||||
// get text nodes
|
||||
if (node.type.name === "text") {
|
||||
// get marks for text nodes
|
||||
node.marks.forEach((mark) => {
|
||||
// any of the marks links?
|
||||
if (mark.type.name === "link") {
|
||||
// any of the links to other docs?
|
||||
if (mark.attrs.href === href) {
|
||||
result = { node, pos };
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!node.content.size) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
const createAndInsertLink = async function (
|
||||
view: EditorView,
|
||||
title: string,
|
||||
href: string,
|
||||
options: {
|
||||
dictionary: Dictionary;
|
||||
nested?: boolean;
|
||||
onCreateLink: (title: string, nested?: boolean) => Promise<string>;
|
||||
}
|
||||
) {
|
||||
const { dispatch, state } = view;
|
||||
const { onCreateLink } = options;
|
||||
|
||||
try {
|
||||
const url = await onCreateLink(title, options.nested);
|
||||
const result = findPlaceholderLink(view.state.doc, href);
|
||||
|
||||
if (!result) {
|
||||
return;
|
||||
}
|
||||
|
||||
dispatch(
|
||||
view.state.tr
|
||||
.removeMark(
|
||||
result.pos,
|
||||
result.pos + result.node.nodeSize,
|
||||
state.schema.marks.link
|
||||
)
|
||||
.addMark(
|
||||
result.pos,
|
||||
result.pos + result.node.nodeSize,
|
||||
state.schema.marks.link.create({ href: url })
|
||||
)
|
||||
);
|
||||
} catch (err) {
|
||||
const result = findPlaceholderLink(view.state.doc, href);
|
||||
if (!result) {
|
||||
return;
|
||||
}
|
||||
|
||||
dispatch(
|
||||
view.state.tr.removeMark(
|
||||
result.pos,
|
||||
result.pos + result.node.nodeSize,
|
||||
state.schema.marks.link
|
||||
)
|
||||
);
|
||||
|
||||
toast.error(options.dictionary.createLinkError);
|
||||
}
|
||||
};
|
||||
|
||||
export default createAndInsertLink;
|
||||
@@ -16,7 +16,7 @@ export type Options = {
|
||||
/** Set to true to replace any existing image at the users selection */
|
||||
replaceExisting?: boolean;
|
||||
/** Callback fired to upload a file */
|
||||
uploadFile?: (file: File) => Promise<string>;
|
||||
uploadFile?: (file: File | string) => Promise<string>;
|
||||
/** Callback fired when the user starts a file upload */
|
||||
onFileUploadStart?: () => void;
|
||||
/** Callback fired when the user completes a file upload */
|
||||
|
||||
@@ -18,7 +18,7 @@ type Props = ComponentProps & {
|
||||
const Embed = (props: Props) => {
|
||||
const ref = React.useRef<HTMLIFrameElement>(null);
|
||||
const { node, isEditable, onChangeSize } = props;
|
||||
const naturalWidth = 10000;
|
||||
const naturalWidth = 0;
|
||||
const naturalHeight = 400;
|
||||
const isResizable = !!onChangeSize;
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as React from "react";
|
||||
import useComponentSize from "../../hooks/useComponentSize";
|
||||
import { useComponentSize } from "../../hooks/useComponentSize";
|
||||
import Frame from "../components/Frame";
|
||||
import { EmbedProps as Props } from ".";
|
||||
|
||||
|
||||
@@ -13,7 +13,8 @@ import { Decoration, DecorationSet } from "prosemirror-view";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { isCode } from "../lib/isCode";
|
||||
import { isRemoteTransaction } from "../lib/multiplayer";
|
||||
import { findBlockNodes, NodeWithPos } from "../queries/findChildren";
|
||||
import { findBlockNodes } from "../queries/findChildren";
|
||||
import { NodeWithPos } from "../types";
|
||||
|
||||
type MermaidState = {
|
||||
decorationSet: DecorationSet;
|
||||
|
||||
@@ -21,6 +21,23 @@ export default class FileHelper {
|
||||
return file.type.startsWith("video/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Download a file from a URL and return it as a File object.
|
||||
*
|
||||
* @param url The URL to download the file from
|
||||
* @returns The downloaded file
|
||||
*/
|
||||
static async getFileForUrl(url: string): Promise<File> {
|
||||
const response = await fetch(url);
|
||||
const blob = await response.blob();
|
||||
const fileName = (response.headers.get("content-disposition") || "").split(
|
||||
"filename="
|
||||
)[1];
|
||||
return new File([blob], fileName || "file", {
|
||||
type: blob.type,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the dimensions of a video file.
|
||||
*
|
||||
|
||||
@@ -65,7 +65,7 @@ export default class Link extends Mark {
|
||||
inclusive: false,
|
||||
parseDOM: [
|
||||
{
|
||||
tag: "a[href]",
|
||||
tag: "a[href]:not(.embed)",
|
||||
getAttrs: (dom: HTMLElement) => ({
|
||||
href: dom.getAttribute("href"),
|
||||
title: dom.getAttribute("title"),
|
||||
|
||||
@@ -16,7 +16,7 @@ import splitHeading from "../commands/splitHeading";
|
||||
import toggleBlockType from "../commands/toggleBlockType";
|
||||
import headingToSlug, { headingToPersistenceKey } from "../lib/headingToSlug";
|
||||
import { MarkdownSerializerState } from "../lib/markdown/serializer";
|
||||
import { FoldingHeadersPlugin } from "../plugins/FoldingHeaders";
|
||||
import { findCollapsedNodes } from "../queries/findCollapsedNodes";
|
||||
import Node from "./Node";
|
||||
|
||||
export default class Heading extends Node {
|
||||
@@ -274,7 +274,23 @@ export default class Heading extends Node {
|
||||
},
|
||||
});
|
||||
|
||||
return [new FoldingHeadersPlugin(this.editor.props.id), plugin];
|
||||
const foldPlugin: Plugin = new Plugin({
|
||||
props: {
|
||||
decorations: (state) => {
|
||||
const { doc } = state;
|
||||
const decorations: Decoration[] = findCollapsedNodes(doc).map(
|
||||
(block) =>
|
||||
Decoration.node(block.pos, block.pos + block.node.nodeSize, {
|
||||
class: "folded-content",
|
||||
})
|
||||
);
|
||||
|
||||
return DecorationSet.create(doc, decorations);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return [foldPlugin, plugin];
|
||||
}
|
||||
|
||||
inputRules({ type }: { type: NodeType }) {
|
||||
|
||||
@@ -17,6 +17,10 @@ export default class TableRow extends Node {
|
||||
};
|
||||
}
|
||||
|
||||
toMarkdown() {
|
||||
// see: renderTable
|
||||
}
|
||||
|
||||
parseMarkdown() {
|
||||
return { block: "tr" };
|
||||
}
|
||||
|
||||
@@ -107,6 +107,7 @@ export const richExtensions: Nodes = [
|
||||
TemplatePlaceholder,
|
||||
Math,
|
||||
MathBlock,
|
||||
Mention,
|
||||
// Container type nodes should be last so that key handlers are registered for content inside
|
||||
// the container nodes first.
|
||||
...listExtensions,
|
||||
@@ -116,4 +117,8 @@ export const richExtensions: Nodes = [
|
||||
/**
|
||||
* Add commenting and mentions to a set of nodes
|
||||
*/
|
||||
export const withComments = (nodes: Nodes) => [...nodes, Mention, Comment];
|
||||
export const withComments = (nodes: Nodes) => [
|
||||
...nodes.filter((node) => node !== Mention),
|
||||
Mention,
|
||||
Comment,
|
||||
];
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
import { Plugin, PluginKey } from "prosemirror-state";
|
||||
import { Decoration, DecorationSet } from "prosemirror-view";
|
||||
import Storage from "../../utils/Storage";
|
||||
import { headingToPersistenceKey } from "../lib/headingToSlug";
|
||||
import { findBlockNodes } from "../queries/findChildren";
|
||||
import { findCollapsedNodes } from "../queries/findCollapsedNodes";
|
||||
|
||||
export class FoldingHeadersPlugin extends Plugin {
|
||||
constructor(documentId: string | undefined) {
|
||||
const plugin = new PluginKey("folding");
|
||||
let loaded = false;
|
||||
|
||||
super({
|
||||
key: plugin,
|
||||
view: (view) => {
|
||||
loaded = false;
|
||||
view.dispatch(view.state.tr.setMeta("folding", { loaded: true }));
|
||||
return {};
|
||||
},
|
||||
appendTransaction: (transactions, oldState, newState) => {
|
||||
if (loaded) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!transactions.some((transaction) => transaction.getMeta("folding"))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
let modified = false;
|
||||
const tr = newState.tr;
|
||||
const blocks = findBlockNodes(newState.doc);
|
||||
|
||||
for (const block of blocks) {
|
||||
if (block.node.type.name === "heading") {
|
||||
const persistKey = headingToPersistenceKey(block.node, documentId);
|
||||
const persistedState = Storage.get(persistKey);
|
||||
|
||||
if (persistedState === "collapsed") {
|
||||
tr.setNodeMarkup(block.pos, undefined, {
|
||||
...block.node.attrs,
|
||||
collapsed: true,
|
||||
});
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loaded = true;
|
||||
return modified ? tr : null;
|
||||
},
|
||||
props: {
|
||||
decorations: (state) => {
|
||||
const { doc } = state;
|
||||
const decorations: Decoration[] = findCollapsedNodes(doc).map(
|
||||
(block) =>
|
||||
Decoration.node(block.pos, block.pos + block.node.nodeSize, {
|
||||
class: "folded-content",
|
||||
})
|
||||
);
|
||||
|
||||
return DecorationSet.create(doc, decorations);
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user