mirror of
https://github.com/outline/outline.git
synced 2026-12-03 18:10:36 +03:00
Merge remote-tracking branch 'origin/main' into tommoor/draft-document-ordering
# Conflicts: # server/models/Collection.ts
This commit is contained in:
225 files changed
+10136
-2998
No files matched your search
@@ -125,32 +125,6 @@
|
||||
"react-hooks/exhaustive-deps": "error"
|
||||
},
|
||||
"plugins": ["eslint", "oxc", "react", "typescript", "import"]
|
||||
},
|
||||
{
|
||||
"files": ["shared/**/*.{js,jsx,ts,tsx}"],
|
||||
"rules": {
|
||||
"no-restricted-imports": [
|
||||
"error",
|
||||
{
|
||||
"paths": [
|
||||
{
|
||||
"name": "prosemirror-tables",
|
||||
"importNames": [
|
||||
"addRowBefore",
|
||||
"addRowAfter",
|
||||
"addColumnBefore",
|
||||
"addColumnAfter"
|
||||
],
|
||||
"message": "Use the wrappers from shared/editor/commands/table instead, which respect the target index and place the cursor in the inserted cell."
|
||||
},
|
||||
{
|
||||
"name": "sonner",
|
||||
"message": "Do not import a toast library within shared; surface notifications through the onNotice callback so shared code stays decoupled from the app's toast implementation."
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -16,6 +16,18 @@
|
||||
"no-restricted-imports": [
|
||||
"error",
|
||||
{
|
||||
"paths": [
|
||||
{
|
||||
"name": "prosemirror-tables",
|
||||
"importNames": [
|
||||
"addRowBefore",
|
||||
"addRowAfter",
|
||||
"addColumnBefore",
|
||||
"addColumnAfter"
|
||||
],
|
||||
"message": "Use the wrappers from shared/editor/commands/table instead, which respect the target index and place the cursor in the inserted cell."
|
||||
}
|
||||
],
|
||||
"patterns": [
|
||||
{
|
||||
"group": ["mime-types"],
|
||||
|
||||
@@ -133,9 +133,10 @@ export const clearIndexedDB = createAction({
|
||||
icon: <TrashIcon />,
|
||||
keywords: "cache clear database",
|
||||
section: DeveloperSection,
|
||||
perform: async ({ t }) => {
|
||||
perform: async ({ t, stores }) => {
|
||||
history.push(homePath());
|
||||
await deleteAllDatabases();
|
||||
stores.enablePersistence();
|
||||
toast.success(t("IndexedDB cache cleared"));
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import copy from "copy-to-clipboard";
|
||||
import type { TFunction } from "i18next";
|
||||
import invariant from "invariant";
|
||||
import { capitalize, uniqBy } from "es-toolkit/compat";
|
||||
import {
|
||||
@@ -30,6 +31,7 @@ import {
|
||||
GlobeIcon,
|
||||
LogoutIcon,
|
||||
CaseSensitiveIcon,
|
||||
OrderedListIcon,
|
||||
RestoreIcon,
|
||||
EditIcon,
|
||||
EmbedIcon,
|
||||
@@ -42,7 +44,12 @@ import {
|
||||
import { toast } from "sonner";
|
||||
import Icon from "@shared/components/Icon";
|
||||
import type { NavigationNode } from "@shared/types";
|
||||
import { ExportContentType, UserPreference } from "@shared/types";
|
||||
import {
|
||||
DocumentPreference,
|
||||
ExportContentType,
|
||||
HeadingPrefixStyle,
|
||||
UserPreference,
|
||||
} from "@shared/types";
|
||||
import { isMobile } from "@shared/utils/browser";
|
||||
import { Week } from "@shared/utils/time";
|
||||
import type UserMembership from "~/models/UserMembership";
|
||||
@@ -928,23 +935,25 @@ export const duplicateDocument = createAction({
|
||||
},
|
||||
});
|
||||
|
||||
function pinToCollectionName({ getActiveModels, t, stores }: ActionContext) {
|
||||
const documents = getActiveModels(Document);
|
||||
if (documents.length === 1) {
|
||||
const collectionName = stores.documents.getCollectionForDocument(
|
||||
documents[0]
|
||||
)?.name;
|
||||
return t("Pin to {{collectionName}}", {
|
||||
collectionName: collectionName ?? t("collection"),
|
||||
});
|
||||
}
|
||||
return t("Pin");
|
||||
}
|
||||
|
||||
/**
|
||||
* Pin a document to a collection. Pinned documents will be displayed at the top
|
||||
* of the collection for all collection members to see.
|
||||
*/
|
||||
export const pinDocumentToCollection = createAction({
|
||||
name: ({ getActiveModels, t, stores }) => {
|
||||
const documents = getActiveModels(Document);
|
||||
if (documents.length === 1) {
|
||||
const collectionName = stores.documents.getCollectionForDocument(
|
||||
documents[0]
|
||||
)?.name;
|
||||
return t("Pin to {{collectionName}}", {
|
||||
collectionName: collectionName ?? t("collection"),
|
||||
});
|
||||
}
|
||||
return t("Pin");
|
||||
},
|
||||
name: pinToCollectionName,
|
||||
analyticsName: "Pin document to collection",
|
||||
section: ActiveDocumentSection,
|
||||
icon: <PinIcon />,
|
||||
@@ -1006,14 +1015,6 @@ export const pinDocumentToHome = createAction({
|
||||
},
|
||||
});
|
||||
|
||||
export const pinDocument = createActionWithChildren({
|
||||
name: ({ t }) => t("Pin"),
|
||||
analyticsName: "Pin document",
|
||||
section: ActiveDocumentSection,
|
||||
icon: <PinIcon />,
|
||||
children: [pinDocumentToCollection, pinDocumentToHome],
|
||||
});
|
||||
|
||||
export const unpinDocument = createAction({
|
||||
name: ({ t }) => t("Unpin"),
|
||||
analyticsName: "Unpin document",
|
||||
@@ -1039,6 +1040,82 @@ export const unpinDocument = createAction({
|
||||
),
|
||||
});
|
||||
|
||||
const allPinnedToCollection = (context: ActionContext) =>
|
||||
everyActiveModel(context, Document, (document) => document.pinned);
|
||||
|
||||
const nonePinnedToCollection = (context: ActionContext) =>
|
||||
everyActiveModel(context, Document, (document) => !document.pinned);
|
||||
|
||||
/**
|
||||
* Toggle whether a document is pinned to its collection, the current state is
|
||||
* reflected in the item so the label does not change between the two.
|
||||
*/
|
||||
export const togglePinDocumentToCollection = createAction({
|
||||
name: pinToCollectionName,
|
||||
analyticsName: "Toggle pin document to collection",
|
||||
section: ActiveDocumentSection,
|
||||
icon: <PinIcon />,
|
||||
iconInContextMenu: false,
|
||||
selected: allPinnedToCollection,
|
||||
visible: (context) =>
|
||||
// A mixed selection has no single state to toggle to, the one-way Pin and
|
||||
// Unpin actions cover that case instead.
|
||||
(allPinnedToCollection(context) || nonePinnedToCollection(context)) &&
|
||||
everyActiveModel(context, Document, (document) => {
|
||||
const can = context.stores.policies.abilities(document.id);
|
||||
return !!document.collectionId && (document.pinned ? can.unpin : can.pin);
|
||||
}),
|
||||
perform: (context) =>
|
||||
allPinnedToCollection(context)
|
||||
? unpinDocument.perform(context)
|
||||
: pinDocumentToCollection.perform(context),
|
||||
});
|
||||
|
||||
/**
|
||||
* Toggle whether a document is pinned to team home, the current state is
|
||||
* reflected in the item so the label does not change between the two.
|
||||
*/
|
||||
export const togglePinDocumentToHome = createAction({
|
||||
name: ({ t }) => t("Pin to home"),
|
||||
analyticsName: "Toggle pin document to home",
|
||||
section: ActiveDocumentSection,
|
||||
icon: <PinIcon />,
|
||||
iconInContextMenu: false,
|
||||
selected: ({ activeDocumentId, stores }) =>
|
||||
!!activeDocumentId &&
|
||||
!!stores.documents.get(activeDocumentId)?.pinnedToHome,
|
||||
visible: ({ activeDocumentId, currentTeamId, stores }) =>
|
||||
!!currentTeamId &&
|
||||
!!activeDocumentId &&
|
||||
!!stores.policies.abilities(activeDocumentId).pinToHome,
|
||||
perform: async (context) => {
|
||||
const { activeDocumentId, location, t, stores } = context;
|
||||
if (!activeDocumentId) {
|
||||
return;
|
||||
}
|
||||
const document = stores.documents.get(activeDocumentId);
|
||||
|
||||
if (!document?.pinnedToHome) {
|
||||
await pinDocumentToHome.perform(context);
|
||||
return;
|
||||
}
|
||||
|
||||
await document.unpin();
|
||||
|
||||
if (location.pathname !== homePath()) {
|
||||
toast.success(t("Unpinned"));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
export const pinDocument = createActionWithChildren({
|
||||
name: ({ t }) => t("Pin"),
|
||||
analyticsName: "Pin document",
|
||||
section: ActiveDocumentSection,
|
||||
icon: <PinIcon />,
|
||||
children: [togglePinDocumentToCollection, togglePinDocumentToHome],
|
||||
});
|
||||
|
||||
export const searchInDocument = createInternalLinkAction({
|
||||
name: ({ t }) => t("Search in document"),
|
||||
analyticsName: "Search document",
|
||||
@@ -1720,6 +1797,75 @@ export const toggleDocumentStats = createAction({
|
||||
},
|
||||
});
|
||||
|
||||
/** An example of the numbering each style produces, used to aid search. */
|
||||
const headingPrefixExamples: Record<HeadingPrefixStyle, string> = {
|
||||
[HeadingPrefixStyle.None]: "",
|
||||
[HeadingPrefixStyle.Numeric]: "1.1.1",
|
||||
[HeadingPrefixStyle.Alphanumeric]: "1.a.i",
|
||||
[HeadingPrefixStyle.Outline]: "I.A.1",
|
||||
};
|
||||
|
||||
const headingPrefixNames: Record<HeadingPrefixStyle, (t: TFunction) => string> =
|
||||
{
|
||||
[HeadingPrefixStyle.None]: (t) => t("None"),
|
||||
[HeadingPrefixStyle.Numeric]: (t) => t("Multi-level decimal"),
|
||||
[HeadingPrefixStyle.Alphanumeric]: (t) => t("Alphanumeric"),
|
||||
[HeadingPrefixStyle.Outline]: (t) => t("Harvard"),
|
||||
};
|
||||
|
||||
const changeHeadingPrefixFactory = (style: HeadingPrefixStyle) =>
|
||||
createAction({
|
||||
name: ({ t }) => headingPrefixNames[style](t),
|
||||
// The example is displayed in the shortcut slot of menu items, but must
|
||||
// not be set on the command bar action where shortcuts are registered as
|
||||
// key sequences.
|
||||
shortcut: ({ isMenu }) =>
|
||||
isMenu && headingPrefixExamples[style]
|
||||
? [headingPrefixExamples[style]]
|
||||
: undefined,
|
||||
keywords: headingPrefixExamples[style],
|
||||
analyticsName: "Change heading numbering",
|
||||
section: ActiveDocumentSection,
|
||||
selected: ({ activeDocumentId, stores }) => {
|
||||
const document = activeDocumentId
|
||||
? stores.documents.get(activeDocumentId)
|
||||
: undefined;
|
||||
return (
|
||||
(document?.getPreference(DocumentPreference.HeadingPrefix) ??
|
||||
HeadingPrefixStyle.None) === style
|
||||
);
|
||||
},
|
||||
perform: async ({ activeDocumentId, stores }) => {
|
||||
const document = activeDocumentId
|
||||
? stores.documents.get(activeDocumentId)
|
||||
: undefined;
|
||||
if (!document) {
|
||||
return;
|
||||
}
|
||||
document.setPreference(DocumentPreference.HeadingPrefix, style);
|
||||
await document.save();
|
||||
},
|
||||
});
|
||||
|
||||
export const changeHeadingPrefix = createActionWithChildren({
|
||||
name: ({ t }) => t("Heading numbering"),
|
||||
analyticsName: "Change heading numbering",
|
||||
section: ActiveDocumentSection,
|
||||
icon: <OrderedListIcon />,
|
||||
visible: ({ activeDocumentId, stores }) => {
|
||||
const document = activeDocumentId
|
||||
? stores.documents.get(activeDocumentId)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
!!document &&
|
||||
!document.isDeleted &&
|
||||
stores.policies.abilities(document.id).update
|
||||
);
|
||||
},
|
||||
children: Object.values(HeadingPrefixStyle).map(changeHeadingPrefixFactory),
|
||||
});
|
||||
|
||||
export const leaveDocument = createAction({
|
||||
name: ({ t }) => t("Leave document"),
|
||||
analyticsName: "Leave document",
|
||||
@@ -1820,4 +1966,5 @@ export const rootDocumentActions = [
|
||||
openDocumentInSplit,
|
||||
shareDocument,
|
||||
toggleDocumentStats,
|
||||
changeHeadingPrefix,
|
||||
];
|
||||
@@ -94,7 +94,7 @@ export const deleteRevision = createAction({
|
||||
dangerous: true,
|
||||
visible: ({ activeDocumentId }) =>
|
||||
!!activeDocumentId && stores.policies.abilities(activeDocumentId).update,
|
||||
perform: async ({ t, event, location, activeDocumentId }) => {
|
||||
perform: async ({ t, event, location, activeDocumentId, sidebarContext }) => {
|
||||
event?.preventDefault();
|
||||
if (!activeDocumentId) {
|
||||
return;
|
||||
@@ -113,7 +113,7 @@ export const deleteRevision = createAction({
|
||||
const revision = stores.revisions.get(revisionId);
|
||||
await revision?.delete();
|
||||
toast.success(t("This version of the document was deleted"));
|
||||
history.push(documentHistoryPath(document));
|
||||
history.push(documentHistoryPath(document), { sidebarContext });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -166,6 +166,7 @@ export function actionToMenuItem(
|
||||
const title = resolve<string>(action.name, context);
|
||||
const visible = resolve<boolean>(action.visible, context) ?? true;
|
||||
const disabled = resolve<boolean>(action.disabled, context);
|
||||
const shortcut = resolve<string[] | undefined>(action.shortcut, context);
|
||||
const icon =
|
||||
!!action.icon && action.iconInContextMenu !== false
|
||||
? resolve<React.ReactNode>(action.icon, context)
|
||||
@@ -182,7 +183,7 @@ export function actionToMenuItem(
|
||||
tooltip: resolve<React.ReactChild>(action.tooltip, context),
|
||||
selected: resolve<boolean>(action.selected, context),
|
||||
dangerous: action.dangerous,
|
||||
shortcut: action.shortcut,
|
||||
shortcut,
|
||||
onClick: () => performAction(action, context),
|
||||
};
|
||||
|
||||
@@ -194,7 +195,7 @@ export function actionToMenuItem(
|
||||
icon,
|
||||
visible,
|
||||
disabled,
|
||||
shortcut: action.shortcut,
|
||||
shortcut,
|
||||
to,
|
||||
};
|
||||
}
|
||||
@@ -206,7 +207,7 @@ export function actionToMenuItem(
|
||||
icon,
|
||||
visible,
|
||||
disabled,
|
||||
shortcut: action.shortcut,
|
||||
shortcut,
|
||||
href: action.target
|
||||
? { url: action.url, target: action.target }
|
||||
: action.url,
|
||||
@@ -261,6 +262,7 @@ export function actionToKBar(
|
||||
}
|
||||
|
||||
const name = resolve<string>(action.name, context);
|
||||
const shortcut = resolve<string[] | undefined>(action.shortcut, context);
|
||||
const icon = resolve<React.ReactElement>(action.icon, context);
|
||||
const badge = resolve<React.ReactNode>(action.badge, context);
|
||||
const section = resolve<string>(action.section, context);
|
||||
@@ -294,7 +296,7 @@ export function actionToKBar(
|
||||
name,
|
||||
section: sectionWithPriority,
|
||||
keywords: action.keywords,
|
||||
shortcut: action.shortcut,
|
||||
shortcut,
|
||||
subtitle,
|
||||
icon,
|
||||
badge,
|
||||
@@ -320,7 +322,7 @@ export function actionToKBar(
|
||||
name,
|
||||
section: sectionWithPriority,
|
||||
keywords: action.keywords,
|
||||
shortcut: action.shortcut,
|
||||
shortcut,
|
||||
icon,
|
||||
badge,
|
||||
subtitle,
|
||||
|
||||
@@ -10,7 +10,7 @@ import { Link } from "react-router-dom";
|
||||
import styled, { useTheme } from "styled-components";
|
||||
import Icon from "@shared/components/Icon";
|
||||
import Squircle from "@shared/components/Squircle";
|
||||
import { s, hover, ellipsis } from "@shared/styles";
|
||||
import { s, hover, ellipsis, borderRadius } from "@shared/styles";
|
||||
import { IconType } from "@shared/types";
|
||||
import { determineIconType } from "@shared/utils/icon";
|
||||
import type Document from "~/models/Document";
|
||||
@@ -20,6 +20,7 @@ import NudeButton from "~/components/NudeButton";
|
||||
import Time from "~/components/Time";
|
||||
import usePolicy from "~/hooks/usePolicy";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { DocumentContextMenu } from "~/menus/DocumentContextMenu";
|
||||
import CollectionIcon from "./Icons/CollectionIcon";
|
||||
import Text from "./Text";
|
||||
import Tooltip from "./Tooltip";
|
||||
@@ -73,7 +74,7 @@ function DocumentCard(props: Props) {
|
||||
};
|
||||
|
||||
const handleUnpin = useCallback(
|
||||
async (ev) => {
|
||||
async (ev: React.MouseEvent) => {
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
await pin?.delete();
|
||||
@@ -81,6 +82,12 @@ function DocumentCard(props: Props) {
|
||||
[pin]
|
||||
);
|
||||
|
||||
// Keep the drag sensor from claiming the pointer, otherwise holding the
|
||||
// button for longer than the activation delay starts a drag
|
||||
const handleActionsPointerDown = useCallback((ev: React.PointerEvent) => {
|
||||
ev.stopPropagation();
|
||||
}, []);
|
||||
|
||||
// If the document was updated within the last 7 days, show a timestamp instead of reading time
|
||||
const isRecentlyUpdated =
|
||||
new Date(document.updatedAt) > subDays(new Date(), 7);
|
||||
@@ -113,78 +120,84 @@ function DocumentCard(props: Props) {
|
||||
}}
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
>
|
||||
<DocumentLink
|
||||
dir={document.dir}
|
||||
$isDragging={isDragging}
|
||||
to={{
|
||||
pathname: document.path,
|
||||
state: {
|
||||
title: document.titleWithDefault,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Content justify="space-between" column>
|
||||
<Fold
|
||||
width="20"
|
||||
height="21"
|
||||
viewBox="0 0 20 21"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path d="M19.5 20.5H6C2.96243 20.5 0.5 18.0376 0.5 15V0.5H0.792893L19.5 19.2071V20.5Z" />
|
||||
<path d="M19.5 19.5H6C2.96243 19.5 0.5 17.0376 0.5 14V0.5H0.792893L19.5 19.2071V19.5Z" />
|
||||
</Fold>
|
||||
|
||||
{document.icon ? (
|
||||
<DocumentSquircle
|
||||
icon={document.icon}
|
||||
color={document.color ?? undefined}
|
||||
initial={document.initial}
|
||||
/>
|
||||
) : (
|
||||
<Squircle
|
||||
color={
|
||||
collection?.color ??
|
||||
(pinnedToHome ? theme.slateLight : theme.slateDark)
|
||||
}
|
||||
<DocumentContextMenu document={document}>
|
||||
<DocumentLink
|
||||
dir={document.dir}
|
||||
$isDragging={isDragging}
|
||||
to={{
|
||||
pathname: document.path,
|
||||
state: {
|
||||
title: document.titleWithDefault,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Content justify="space-between" column>
|
||||
<Fold
|
||||
width="20"
|
||||
height="21"
|
||||
viewBox="0 0 20 21"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
{collection?.icon &&
|
||||
collection?.icon !== "letter" &&
|
||||
collection?.icon !== "collection" &&
|
||||
pinnedToHome ? (
|
||||
<CollectionIcon collection={collection} color="white" />
|
||||
) : (
|
||||
<DocumentIcon color="white" />
|
||||
)}
|
||||
</Squircle>
|
||||
<path d="M19.5 20.5H6C2.96243 20.5 0.5 18.0376 0.5 15V0.5H0.792893L19.5 19.2071V20.5Z" />
|
||||
<path d="M19.5 19.5H6C2.96243 19.5 0.5 17.0376 0.5 14V0.5H0.792893L19.5 19.2071V19.5Z" />
|
||||
</Fold>
|
||||
|
||||
{document.icon ? (
|
||||
<DocumentSquircle
|
||||
icon={document.icon}
|
||||
color={document.color ?? undefined}
|
||||
initial={document.initial}
|
||||
/>
|
||||
) : (
|
||||
<Squircle
|
||||
color={
|
||||
collection?.color ??
|
||||
(pinnedToHome ? theme.slateLight : theme.slateDark)
|
||||
}
|
||||
>
|
||||
{collection?.icon &&
|
||||
collection?.icon !== "letter" &&
|
||||
collection?.icon !== "collection" &&
|
||||
pinnedToHome ? (
|
||||
<CollectionIcon collection={collection} color="white" />
|
||||
) : (
|
||||
<DocumentIcon color="white" />
|
||||
)}
|
||||
</Squircle>
|
||||
)}
|
||||
<div>
|
||||
<Heading dir={document.dir}>
|
||||
{hasEmojiInTitle
|
||||
? document.titleWithDefault.replace(document.icon!, "")
|
||||
: document.titleWithDefault}
|
||||
</Heading>
|
||||
<DocumentMeta size="xsmall">
|
||||
{isRecentlyUpdated ? (
|
||||
updatedAt
|
||||
) : (
|
||||
<Suspense fallback={updatedAt}>
|
||||
<ReadingTime document={document} />
|
||||
</Suspense>
|
||||
)}
|
||||
</DocumentMeta>
|
||||
</div>
|
||||
</Content>
|
||||
{canUnpin && !isDragging && pin && (
|
||||
<Actions
|
||||
dir={document.dir}
|
||||
gap={4}
|
||||
onPointerDown={handleActionsPointerDown}
|
||||
>
|
||||
<Tooltip content={t("Unpin")}>
|
||||
<PinButton onClick={handleUnpin} aria-label={t("Unpin")}>
|
||||
<CloseIcon />
|
||||
</PinButton>
|
||||
</Tooltip>
|
||||
</Actions>
|
||||
)}
|
||||
<div>
|
||||
<Heading dir={document.dir}>
|
||||
{hasEmojiInTitle
|
||||
? document.titleWithDefault.replace(document.icon!, "")
|
||||
: document.titleWithDefault}
|
||||
</Heading>
|
||||
<DocumentMeta size="xsmall">
|
||||
{isRecentlyUpdated ? (
|
||||
updatedAt
|
||||
) : (
|
||||
<Suspense fallback={updatedAt}>
|
||||
<ReadingTime document={document} />
|
||||
</Suspense>
|
||||
)}
|
||||
</DocumentMeta>
|
||||
</div>
|
||||
</Content>
|
||||
{canUnpin && !isDragging && pin && (
|
||||
<Actions dir={document.dir} gap={4}>
|
||||
<Tooltip content={t("Unpin")}>
|
||||
<PinButton onClick={handleUnpin} aria-label={t("Unpin")}>
|
||||
<CloseIcon />
|
||||
</PinButton>
|
||||
</Tooltip>
|
||||
</Actions>
|
||||
)}
|
||||
</DocumentLink>
|
||||
</DocumentLink>
|
||||
</DocumentContextMenu>
|
||||
</AnimatePresence>
|
||||
</Reorderable>
|
||||
);
|
||||
@@ -292,7 +305,7 @@ const DocumentLink = styled(Link)<{
|
||||
padding: 12px;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 8px;
|
||||
${borderRadius(8)}
|
||||
cursor: var(--pointer);
|
||||
background: ${s("background")};
|
||||
transition: transform 50ms ease-in-out;
|
||||
@@ -304,10 +317,13 @@ const DocumentLink = styled(Link)<{
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
// data-state is set by the context menu trigger, so the treatment stays
|
||||
// active while the menu is open
|
||||
&:${hover},
|
||||
&:active,
|
||||
&:focus,
|
||||
&:focus-within {
|
||||
&:focus-within,
|
||||
&[data-state="open"] {
|
||||
transform: ${(props) => (props.$isDragging ? "scale(1.1)" : "scale(1.08)")}
|
||||
rotate(-2deg);
|
||||
box-shadow: ${(props) =>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { observer } from "mobx-react";
|
||||
import { DocumentIcon } from "outline-icons";
|
||||
import { CloseIcon, DocumentIcon } from "outline-icons";
|
||||
import { useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router-dom";
|
||||
import styled from "styled-components";
|
||||
import Icon from "@shared/components/Icon";
|
||||
@@ -7,10 +9,17 @@ import { s, hover, ellipsis } from "@shared/styles";
|
||||
import { IconType } from "@shared/types";
|
||||
import { determineIconType } from "@shared/utils/icon";
|
||||
import type Document from "~/models/Document";
|
||||
import type Pin from "~/models/Pin";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
import Tooltip from "~/components/Tooltip";
|
||||
import usePolicy from "~/hooks/usePolicy";
|
||||
import { DocumentContextMenu } from "~/menus/DocumentContextMenu";
|
||||
|
||||
type Props = {
|
||||
/** The document to display */
|
||||
document: Document;
|
||||
/** The pin related to the document, when given an unpin control is shown */
|
||||
pin?: Pin;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -19,32 +28,58 @@ type Props = {
|
||||
*/
|
||||
export const DocumentChip = observer(function DocumentChip_({
|
||||
document,
|
||||
pin,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { icon, color } = document;
|
||||
const canPin = usePolicy(pin);
|
||||
const canDocument = usePolicy(document);
|
||||
const title = document.titleWithDefault;
|
||||
const isEmoji = determineIconType(icon) === IconType.Emoji;
|
||||
|
||||
// Pins in a collection are governed by the document policy, pins on home by
|
||||
// the policy of the pin itself.
|
||||
const canUnpin = pin?.collectionId ? canDocument.unpin : canPin.delete;
|
||||
|
||||
const handleUnpin = useCallback(
|
||||
async (ev: React.MouseEvent) => {
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
await pin?.delete();
|
||||
},
|
||||
[pin]
|
||||
);
|
||||
|
||||
return (
|
||||
<Chip
|
||||
dir={document.dir}
|
||||
to={{
|
||||
pathname: document.path,
|
||||
state: {
|
||||
title,
|
||||
},
|
||||
}}
|
||||
>
|
||||
{icon ? (
|
||||
<Icon
|
||||
value={icon}
|
||||
color={color ?? undefined}
|
||||
initial={document.initial}
|
||||
/>
|
||||
) : (
|
||||
<DocumentIcon />
|
||||
)}
|
||||
<Title>{isEmoji ? title.replace(icon!, "") : title}</Title>
|
||||
</Chip>
|
||||
<DocumentContextMenu document={document}>
|
||||
<Chip
|
||||
dir={document.dir}
|
||||
to={{
|
||||
pathname: document.path,
|
||||
state: {
|
||||
title,
|
||||
},
|
||||
}}
|
||||
>
|
||||
{icon ? (
|
||||
<Icon
|
||||
value={icon}
|
||||
color={color ?? undefined}
|
||||
initial={document.initial}
|
||||
/>
|
||||
) : (
|
||||
<DocumentIcon />
|
||||
)}
|
||||
<Title>{isEmoji ? title.replace(icon!, "") : title}</Title>
|
||||
{pin && canUnpin && (
|
||||
<Tooltip content={t("Unpin")}>
|
||||
<PinButton onClick={handleUnpin} aria-label={t("Unpin")}>
|
||||
<CloseIcon size={18} />
|
||||
</PinButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Chip>
|
||||
</DocumentContextMenu>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -55,6 +90,20 @@ const Title = styled.span`
|
||||
color: ${s("text")};
|
||||
`;
|
||||
|
||||
const PinButton = styled(NudeButton)`
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
flex-shrink: 0;
|
||||
color: ${s("textTertiary")};
|
||||
opacity: 0;
|
||||
transition: opacity 100ms ease-in-out;
|
||||
|
||||
&:${hover},
|
||||
&:active {
|
||||
color: ${s("text")};
|
||||
}
|
||||
`;
|
||||
|
||||
const Chip = styled(Link)`
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -73,4 +122,9 @@ const Chip = styled(Link)`
|
||||
&:focus-visible {
|
||||
background: ${s("listItemHoverBackground")};
|
||||
}
|
||||
|
||||
&:${hover} ${PinButton},
|
||||
&:focus-within ${PinButton} {
|
||||
opacity: 1;
|
||||
}
|
||||
`;
|
||||
@@ -30,7 +30,8 @@ class DocumentContext {
|
||||
|
||||
@computed
|
||||
get hasHeadings() {
|
||||
return this.headings.length > 0;
|
||||
// Headings inside tables are not listed in the table of contents.
|
||||
return this.headings.some((heading) => !heading.inTable);
|
||||
}
|
||||
|
||||
/** Statistics for the text content of the document, kept up to date as it is edited */
|
||||
|
||||
@@ -34,7 +34,7 @@ import { useDragDocument } from "./Sidebar/hooks/useDragAndDrop";
|
||||
import { ActionContextProvider } from "~/hooks/useActionContext";
|
||||
import { useDocumentMenuAction } from "~/hooks/useDocumentMenuAction";
|
||||
import { ContextMenu } from "./Menu/ContextMenu";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import { useDocumentActiveModels } from "~/hooks/useDocumentActiveModels";
|
||||
|
||||
type Props = {
|
||||
document: Document;
|
||||
@@ -60,7 +60,6 @@ function DocumentListItem(
|
||||
const { t } = useTranslation();
|
||||
const user = useCurrentUser();
|
||||
const theme = useTheme();
|
||||
const { userMemberships, groupMemberships } = useStores();
|
||||
const locationSidebarContext = useLocationSidebarContext();
|
||||
const [menuOpen, handleMenuOpen, handleMenuClose] = useBoolean();
|
||||
const isMobile = useMobile();
|
||||
@@ -122,10 +121,7 @@ function DocumentListItem(
|
||||
}
|
||||
};
|
||||
|
||||
const isShared = !!(
|
||||
userMemberships.getByDocumentId(document.id) ||
|
||||
groupMemberships.getByDocumentId(document.id)
|
||||
);
|
||||
const activeModels = useDocumentActiveModels(document);
|
||||
|
||||
const sidebarContext = determineSidebarContext({
|
||||
document,
|
||||
@@ -153,14 +149,7 @@ function DocumentListItem(
|
||||
);
|
||||
|
||||
return (
|
||||
<ActionContextProvider
|
||||
value={{
|
||||
activeModels: [
|
||||
document,
|
||||
...(!isShared && document.collection ? [document.collection] : []),
|
||||
],
|
||||
}}
|
||||
>
|
||||
<ActionContextProvider value={{ activeModels }}>
|
||||
<ContextMenu
|
||||
action={contextMenuAction}
|
||||
ariaLabel={t("Document options")}
|
||||
|
||||
@@ -5,13 +5,13 @@ import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router-dom";
|
||||
import styled from "styled-components";
|
||||
import { s, ellipsis } from "@shared/styles";
|
||||
import { ellipsis } from "@shared/styles";
|
||||
import type Document from "~/models/Document";
|
||||
import type Revision from "~/models/Revision";
|
||||
import DocumentBreadcrumb from "~/components/DocumentBreadcrumb";
|
||||
import DocumentTasks from "~/components/DocumentTasks";
|
||||
import Flex from "~/components/Flex";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
import { MetaButton, Separator, metaStyles } from "~/components/HeaderMeta";
|
||||
import Time from "~/components/Time";
|
||||
import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
import useStores from "~/hooks/useStores";
|
||||
@@ -93,9 +93,11 @@ const DocumentMeta: React.FC<Props> = ({
|
||||
} else if (deletedAt) {
|
||||
content = (
|
||||
<span>
|
||||
{lastUpdatedByCurrentUser
|
||||
{document.deletedBy?.id === user.id
|
||||
? t("You deleted")
|
||||
: t("{{ userName }} deleted", { userName })}{" "}
|
||||
: t("{{ userName }} deleted", {
|
||||
userName: document.deletedBy?.name ?? t("Unknown"),
|
||||
})}{" "}
|
||||
<Time dateTime={deletedAt} addSuffix />
|
||||
</span>
|
||||
);
|
||||
@@ -227,42 +229,12 @@ const DocumentMeta: React.FC<Props> = ({
|
||||
);
|
||||
};
|
||||
|
||||
/** A button that visually matches the surrounding meta text. */
|
||||
export const MetaButton = styled(NudeButton)`
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
width: auto;
|
||||
height: auto;
|
||||
border-radius: 0;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: inherit;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
`;
|
||||
|
||||
export const Separator = styled.span`
|
||||
padding: 0 0.4em;
|
||||
|
||||
&::after {
|
||||
content: "•";
|
||||
}
|
||||
`;
|
||||
|
||||
const Strong = styled.strong`
|
||||
font-weight: 550;
|
||||
`;
|
||||
|
||||
const Container = styled(Flex)<{ $rtl?: boolean }>`
|
||||
justify-content: ${(props) => (props.$rtl ? "flex-end" : "flex-start")};
|
||||
color: ${s("textTertiary")};
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
${metaStyles}
|
||||
`;
|
||||
|
||||
const Viewed = styled.span`
|
||||
|
||||
@@ -1,22 +1,16 @@
|
||||
import { difference } from "es-toolkit/compat";
|
||||
import { observer } from "mobx-react";
|
||||
import { DOMParser as ProsemirrorDOMParser } from "prosemirror-model";
|
||||
import { TextSelection } from "prosemirror-state";
|
||||
import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { mergeRefs } from "react-merge-refs";
|
||||
import type { Optional } from "utility-types";
|
||||
import insertFiles from "@shared/editor/commands/insertFiles";
|
||||
import EditorContainer from "@shared/editor/components/Styles";
|
||||
import { AttachmentPreset } from "@shared/types";
|
||||
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
|
||||
import { getDataTransferFiles } from "@shared/utils/files";
|
||||
import { AttachmentValidation } from "@shared/validations";
|
||||
import ClickablePadding from "~/components/ClickablePadding";
|
||||
import ErrorBoundary from "~/components/ErrorBoundary";
|
||||
import type { Props as EditorProps, Editor as SharedEditor } from "~/editor";
|
||||
import { toastNotice } from "~/editor/toastNotice";
|
||||
import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
import useEditorClickHandlers from "~/hooks/useEditorClickHandlers";
|
||||
import useEmbeds from "~/hooks/useEmbeds";
|
||||
@@ -135,61 +129,9 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
|
||||
}, [localRef]);
|
||||
|
||||
const handleDrop = React.useCallback(
|
||||
(event: React.DragEvent<HTMLDivElement>) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const files = getDataTransferFiles(event);
|
||||
|
||||
const view = localRef?.current?.view;
|
||||
if (!view) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Find a valid position at the end of the document to insert our content
|
||||
const pos = TextSelection.near(
|
||||
view.state.doc.resolve(view.state.doc.nodeSize - 2)
|
||||
).from;
|
||||
|
||||
// If there are no files in the drop event attempt to parse the html
|
||||
// as a fragment and insert it at the end of the document
|
||||
if (files.length === 0) {
|
||||
const text =
|
||||
event.dataTransfer.getData("text/html") ||
|
||||
event.dataTransfer.getData("text/plain");
|
||||
|
||||
const dom = new DOMParser().parseFromString(text, "text/html");
|
||||
|
||||
view.dispatch(
|
||||
view.state.tr.insert(
|
||||
pos,
|
||||
ProsemirrorDOMParser.fromSchema(view.state.schema).parse(dom)
|
||||
)
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Insert all files as attachments if any of the files are not images.
|
||||
const isAttachment = files.some(
|
||||
(file) => !AttachmentValidation.imageContentTypes.includes(file.type)
|
||||
);
|
||||
|
||||
return insertFiles(view, event, pos, files, {
|
||||
uploadFile: handleUploadFile,
|
||||
onFileUploadStart: handleFileUploadStart,
|
||||
onFileUploadStop: handleFileUploadStop,
|
||||
onFileUploadProgress: handleFileUploadProgress,
|
||||
onNotice: toastNotice,
|
||||
isAttachment,
|
||||
});
|
||||
},
|
||||
[
|
||||
localRef,
|
||||
handleFileUploadStart,
|
||||
handleFileUploadStop,
|
||||
handleFileUploadProgress,
|
||||
handleUploadFile,
|
||||
]
|
||||
(event: React.DragEvent<HTMLDivElement>) =>
|
||||
localRef.current?.insertDroppedContent(event),
|
||||
[]
|
||||
);
|
||||
|
||||
// see: https://stackoverflow.com/a/50233827/192065
|
||||
|
||||
@@ -29,6 +29,14 @@ const topHandlerNames = [
|
||||
const isWithinEditor = (target: EventTarget | null): boolean =>
|
||||
target instanceof Element && Boolean(target.closest(".ProseMirror"));
|
||||
|
||||
// A file dragged over an element marked `data-drop-area`, which accepts native
|
||||
// file drops itself. react-dnd never tracks these drags, so its handlers would
|
||||
// otherwise reject them.
|
||||
const isFileOverDropArea = (event: DragEvent): boolean =>
|
||||
Boolean(event.dataTransfer?.types.includes("Files")) &&
|
||||
event.target instanceof Element &&
|
||||
Boolean(event.target.closest("[data-drop-area]"));
|
||||
|
||||
/**
|
||||
* An HTML5 drag-and-drop backend that ignores drag events originating within the
|
||||
* rich text editor so that ProseMirror can handle them itself.
|
||||
@@ -57,7 +65,7 @@ export const EditorAwareHTML5Backend: BackendFactory = (
|
||||
const original = handlers[name];
|
||||
if (typeof original === "function") {
|
||||
handlers[name] = (event: DragEvent) => {
|
||||
if (isWithinEditor(event.target)) {
|
||||
if (isWithinEditor(event.target) || isFileOverDropArea(event)) {
|
||||
return;
|
||||
}
|
||||
// A drag that began or entered the page over the editor is never
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import styled, { css } from "styled-components";
|
||||
import breakpoint from "styled-components-breakpoint";
|
||||
import { s } from "@shared/styles";
|
||||
import Flex from "~/components/Flex";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
|
||||
/** A dot separating two pieces of meta information. */
|
||||
export const Separator = styled.span`
|
||||
padding: 0 0.4em;
|
||||
|
||||
&::after {
|
||||
content: "•";
|
||||
}
|
||||
`;
|
||||
|
||||
/** A button that visually matches the surrounding meta text. */
|
||||
export const MetaButton = styled(NudeButton)`
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
width: auto;
|
||||
height: auto;
|
||||
border-radius: 0;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: inherit;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
`;
|
||||
|
||||
/** Lays out a line of meta information about a document or collection. */
|
||||
export const metaStyles = css<{ $rtl?: boolean }>`
|
||||
justify-content: ${(props) => (props.$rtl ? "flex-end" : "flex-start")};
|
||||
color: ${s("textTertiary")};
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
`;
|
||||
|
||||
/**
|
||||
* Additional styles for a line of meta information rendered directly beneath a
|
||||
* page title. Composed by `HeaderMeta`, and applied directly by consumers that
|
||||
* style an existing meta component rather than rendering their own.
|
||||
*/
|
||||
export const headerMetaStyles = css`
|
||||
margin: -12px 0 2em 0;
|
||||
font-size: 14px;
|
||||
position: relative;
|
||||
user-select: none;
|
||||
z-index: 1;
|
||||
|
||||
${breakpoint("mobile", "tablet")`
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
line-height: 1.6;
|
||||
|
||||
${Separator} {
|
||||
display: none;
|
||||
}
|
||||
`}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
cursor: var(--pointer);
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
@media print {
|
||||
display: none;
|
||||
}
|
||||
`;
|
||||
|
||||
/**
|
||||
* A line of meta information rendered directly beneath a page title, stacking
|
||||
* into a list on mobile and hidden when printing.
|
||||
*/
|
||||
export const HeaderMeta = styled(Flex)<{ $rtl?: boolean }>`
|
||||
${metaStyles}
|
||||
${headerMetaStyles}
|
||||
`;
|
||||
@@ -91,7 +91,7 @@ export const ContextMenu = observer(
|
||||
return (
|
||||
<MenuProvider variant="context">
|
||||
<Menu open={open} onOpenChange={handleOpenChange}>
|
||||
<MenuTrigger aria-label={ariaLabel}>{children}</MenuTrigger>
|
||||
<MenuTrigger>{children}</MenuTrigger>
|
||||
<MenuContent
|
||||
aria-label={ariaLabel}
|
||||
onAnimationStart={disablePointerEvents}
|
||||
|
||||
@@ -5,7 +5,7 @@ import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import styled from "styled-components";
|
||||
import breakpoint from "styled-components-breakpoint";
|
||||
import { depths, s } from "@shared/styles";
|
||||
import { depths, s, borderRadius } from "@shared/styles";
|
||||
import Flex from "~/components/Flex";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
import Scrollable from "~/components/Scrollable";
|
||||
@@ -255,7 +255,7 @@ const Wrapper = styled.div<{
|
||||
align-items: flex-start;
|
||||
background: ${s("modalBackground")};
|
||||
box-shadow: ${s("modalShadow")};
|
||||
border-radius: 8px;
|
||||
${borderRadius(10)}
|
||||
outline: none;
|
||||
|
||||
${NudeButton} {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { CloseIcon } from "outline-icons";
|
||||
import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import styled, { css } from "styled-components";
|
||||
import { depths, s } from "@shared/styles";
|
||||
import { depths, s, borderRadius } from "@shared/styles";
|
||||
import type { ModelSelection } from "~/components/ModelSelection";
|
||||
import Flex from "~/components/Flex";
|
||||
import NudeButton from "~/components/NudeButton";
|
||||
@@ -137,7 +137,7 @@ const Wrapper = styled.div<{ $active: boolean }>`
|
||||
const Background = styled(Flex)`
|
||||
background-color: ${s("menuBackground")};
|
||||
box-shadow: ${s("menuShadow")};
|
||||
border-radius: 8px;
|
||||
${borderRadius(8)}
|
||||
height: 40px;
|
||||
padding: 0 8px;
|
||||
`;
|
||||
|
||||
@@ -149,8 +149,10 @@ function PinnedDocuments({
|
||||
<Chips>
|
||||
{items.map((documentId) => {
|
||||
const document = documents.get(documentId);
|
||||
const pin = pins.find((p) => p.documentId === documentId);
|
||||
|
||||
return document ? (
|
||||
<DocumentChip key={documentId} document={document} />
|
||||
<DocumentChip key={documentId} document={document} pin={pin} />
|
||||
) : null;
|
||||
})}
|
||||
</Chips>
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useHistory } from "react-router-dom";
|
||||
import styled from "styled-components";
|
||||
import { SidebarSection, UserPreference } from "@shared/types";
|
||||
import { metaDisplay } from "@shared/utils/keyboard";
|
||||
import Scrollable from "~/components/Scrollable";
|
||||
import { navigateToImport } from "~/actions/definitions/navigation";
|
||||
@@ -24,6 +25,9 @@ import Tooltip from "../Tooltip";
|
||||
import Sidebar from "./Sidebar";
|
||||
import ArchiveLink from "./components/ArchiveLink";
|
||||
import Collections from "./components/Collections";
|
||||
import DraggableSection, {
|
||||
normalizeSidebarSectionOrder,
|
||||
} from "./components/DraggableSection";
|
||||
import { DraftsLink } from "./components/DraftsLink";
|
||||
import DragPlaceholder from "./components/DragPlaceholder";
|
||||
import { DismissableSidebarAction } from "./components/DismissableSidebarAction";
|
||||
@@ -72,6 +76,16 @@ function AppSidebar() {
|
||||
setScrollArea(scrollRef.current);
|
||||
}, []);
|
||||
|
||||
const sectionOrder = normalizeSidebarSectionOrder(
|
||||
user.getPreference(UserPreference.SidebarSectionOrder, [])
|
||||
);
|
||||
|
||||
const sectionContent = {
|
||||
[SidebarSection.Starred]: <Starred />,
|
||||
[SidebarSection.SharedWithMe]: <SharedWithMe />,
|
||||
[SidebarSection.Collections]: <Collections />,
|
||||
};
|
||||
|
||||
return (
|
||||
<Sidebar hidden={!ui.readyToShow}>
|
||||
<DragActiveProvider>
|
||||
@@ -127,15 +141,11 @@ function AppSidebar() {
|
||||
</Overflow>
|
||||
<Scrollable flex shadow ref={scrollRef}>
|
||||
<SidebarScrollProvider value={scrollArea}>
|
||||
<Section>
|
||||
<Starred />
|
||||
</Section>
|
||||
<Section>
|
||||
<SharedWithMe />
|
||||
</Section>
|
||||
<Section>
|
||||
<Collections />
|
||||
</Section>
|
||||
{sectionOrder.map((section) => (
|
||||
<DraggableSection key={section} section={section}>
|
||||
{sectionContent[section]}
|
||||
</DraggableSection>
|
||||
))}
|
||||
{can.createDocument && (
|
||||
<Section auto>
|
||||
<ArchiveLink />
|
||||
|
||||
@@ -227,7 +227,9 @@ function CollectionRow({
|
||||
);
|
||||
|
||||
return (
|
||||
<ActionContextProvider value={{ activeModels: [collection] }}>
|
||||
<ActionContextProvider
|
||||
value={{ activeModels: [collection], sidebarContext }}
|
||||
>
|
||||
<Relative ref={mergedRef}>
|
||||
<DropToImport collectionId={collection.id}>
|
||||
{sidebarLinkElement}
|
||||
|
||||
@@ -284,6 +284,7 @@ function DocumentRow({
|
||||
<ActionContextProvider
|
||||
value={{
|
||||
activeModels: document ? [document] : [],
|
||||
sidebarContext,
|
||||
}}
|
||||
>
|
||||
<Relative ref={parentRef}>
|
||||
|
||||
@@ -6,6 +6,7 @@ import Flex from "~/components/Flex";
|
||||
import Text from "~/components/Text";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import * as Scenes from "~/routes/scenes";
|
||||
import { popIn } from "~/styles/animations";
|
||||
import { draftsPath } from "~/utils/routeHelpers";
|
||||
import { useDropToUnpublish } from "../hooks/useDragAndDrop";
|
||||
import SidebarLink from "./SidebarLink";
|
||||
@@ -14,6 +15,8 @@ export const DraftsLink = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
const { documents } = useStores();
|
||||
const [{ isOver, canDrop }, dropRef] = useDropToUnpublish();
|
||||
const totalDrafts =
|
||||
documents.totalDrafts > 25 ? "25+" : String(documents.totalDrafts);
|
||||
|
||||
return (
|
||||
<div ref={dropRef}>
|
||||
@@ -25,8 +28,8 @@ export const DraftsLink = observer(() => {
|
||||
<Flex align="center" justify="space-between">
|
||||
{t("Drafts")}
|
||||
{documents.totalDrafts > 0 ? (
|
||||
<Drafts size="xsmall" type="tertiary">
|
||||
{documents.totalDrafts > 25 ? "25+" : documents.totalDrafts}
|
||||
<Drafts key={totalDrafts} size="xsmall" type="tertiary">
|
||||
{totalDrafts}
|
||||
</Drafts>
|
||||
) : null}
|
||||
</Flex>
|
||||
@@ -38,5 +41,7 @@ export const DraftsLink = observer(() => {
|
||||
});
|
||||
|
||||
const Drafts = styled(Text)`
|
||||
display: inline-block;
|
||||
margin: 0 4px;
|
||||
animation: ${popIn} 250ms cubic-bezier(0.34, 1.56, 0.64, 1) both;
|
||||
`;
|
||||
@@ -0,0 +1,183 @@
|
||||
import { observer } from "mobx-react";
|
||||
import { createContext, useEffect, useState, type ReactNode } from "react";
|
||||
import type { ConnectDragSource } from "react-dnd";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import styled from "styled-components";
|
||||
import { SidebarSection, UserPreference } from "@shared/types";
|
||||
import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
import {
|
||||
useDragSidebarSection,
|
||||
useDropToReorderSidebarSection,
|
||||
} from "../hooks/useDragAndDrop";
|
||||
import DropCursor from "./DropCursor";
|
||||
import Section from "./Section";
|
||||
|
||||
/**
|
||||
* Carries the drag connector for a sidebar section so the section header can
|
||||
* register itself as the drag handle.
|
||||
*/
|
||||
export const SectionDragContext = createContext<ConnectDragSource | null>(null);
|
||||
|
||||
/**
|
||||
* Normalizes a persisted sidebar section order — unknown values and
|
||||
* duplicates are removed, and missing sections are appended in their default
|
||||
* order.
|
||||
*
|
||||
* @param saved The persisted section order, if any.
|
||||
* @returns the full list of sidebar sections in display order.
|
||||
*/
|
||||
export function normalizeSidebarSectionOrder(
|
||||
saved?: SidebarSection[]
|
||||
): SidebarSection[] {
|
||||
const all = Object.values(SidebarSection);
|
||||
const valid = [...new Set(saved)].filter((section) => all.includes(section));
|
||||
return [...valid, ...all.filter((section) => !valid.includes(section))];
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the sidebar section order after moving a section next to another.
|
||||
*
|
||||
* @param order The current section order.
|
||||
* @param section The section being moved.
|
||||
* @param position Whether to place the section before or after the target.
|
||||
* @param target The section to place it relative to.
|
||||
* @returns the new order, or undefined when the move would not change it.
|
||||
*/
|
||||
export function moveSidebarSection(
|
||||
order: SidebarSection[],
|
||||
section: SidebarSection,
|
||||
position: "before" | "after",
|
||||
target: SidebarSection
|
||||
): SidebarSection[] | undefined {
|
||||
if (section === target) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const result = order.filter((s) => s !== section);
|
||||
const targetIndex = result.indexOf(target);
|
||||
result.splice(
|
||||
position === "after" ? targetIndex + 1 : targetIndex,
|
||||
0,
|
||||
section
|
||||
);
|
||||
|
||||
return result.every((s, i) => s === order[i]) ? undefined : result;
|
||||
}
|
||||
|
||||
type Props = {
|
||||
/** The section being rendered. */
|
||||
section: SidebarSection;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
/**
|
||||
* Wraps a sidebar section so it can be reordered by dragging its header. The
|
||||
* resulting order is persisted to the server as a user preference. Sections
|
||||
* whose children render nothing are hidden along with their drop targets.
|
||||
*/
|
||||
function DraggableSection({ section, children }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const user = useCurrentUser();
|
||||
|
||||
const titles: Record<SidebarSection, string> = {
|
||||
[SidebarSection.Starred]: t("Starred"),
|
||||
[SidebarSection.SharedWithMe]: t("Shared with me"),
|
||||
[SidebarSection.Collections]: t("Collections"),
|
||||
};
|
||||
|
||||
const order = normalizeSidebarSectionOrder(
|
||||
user.getPreference(UserPreference.SidebarSectionOrder, [])
|
||||
);
|
||||
|
||||
const [{ isDragging }, dragRef] = useDragSidebarSection(
|
||||
section,
|
||||
titles[section]
|
||||
);
|
||||
const [topProps, dropTopRef] = useDropToReorderSidebarSection((dragged) =>
|
||||
moveSidebarSection(order, dragged, "before", section)
|
||||
);
|
||||
const [bottomProps, dropBottomRef] = useDropToReorderSidebarSection(
|
||||
(dragged) => moveSidebarSection(order, dragged, "after", section)
|
||||
);
|
||||
|
||||
// The drop cursors and the drag styling must not appear inside the
|
||||
// browser's dragstart dispatch — Chromium aborts the drag when the element
|
||||
// under the drag origin changes before the drag session starts.
|
||||
const showCursors = useDeferredFlag(bottomProps.isDragging);
|
||||
const isDraggingDeferred = useDeferredFlag(isDragging);
|
||||
|
||||
return (
|
||||
<SectionWrapper>
|
||||
{showCursors && (
|
||||
<TopDropCursor
|
||||
isActiveDrop={topProps.isOverCursor}
|
||||
innerRef={dropTopRef}
|
||||
position="top"
|
||||
/>
|
||||
)}
|
||||
<Draggable $isDragging={isDraggingDeferred}>
|
||||
<SectionDragContext.Provider value={dragRef}>
|
||||
{children}
|
||||
</SectionDragContext.Provider>
|
||||
</Draggable>
|
||||
{showCursors && (
|
||||
<SectionDropCursor
|
||||
isActiveDrop={bottomProps.isOverCursor}
|
||||
innerRef={dropBottomRef}
|
||||
/>
|
||||
)}
|
||||
</SectionWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the given flag with its rising edge deferred by one task. A falling
|
||||
* edge resets immediately.
|
||||
*
|
||||
* @param value The flag to defer.
|
||||
* @returns the deferred flag.
|
||||
*/
|
||||
function useDeferredFlag(value: boolean): boolean {
|
||||
const [deferred, setDeferred] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!value) {
|
||||
setDeferred(false);
|
||||
return undefined;
|
||||
}
|
||||
const timer = setTimeout(() => setDeferred(true), 0);
|
||||
return () => clearTimeout(timer);
|
||||
}, [value]);
|
||||
|
||||
return deferred;
|
||||
}
|
||||
|
||||
const Draggable = styled.div<{ $isDragging: boolean }>`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
transition: opacity 250ms ease;
|
||||
opacity: ${(props) => (props.$isDragging ? 0.1 : 1)};
|
||||
pointer-events: ${(props) => (props.$isDragging ? "none" : "inherit")};
|
||||
`;
|
||||
|
||||
// Centers the cursor line in the 12px gap between sections — the visible
|
||||
// band sits 6px from the cursor's top.
|
||||
const SectionDropCursor = styled(DropCursor)`
|
||||
${(props) => (props.position === "top" ? "top: -13px;" : "bottom: -13px;")}
|
||||
`;
|
||||
|
||||
const TopDropCursor = styled(SectionDropCursor)``;
|
||||
|
||||
const SectionWrapper = styled(Section)`
|
||||
/* Hide the section entirely when its content renders nothing. */
|
||||
&:has(${Draggable}:empty) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Only the first visible section offers a drop slot above itself. */
|
||||
&:not(:has(${Draggable}:empty)) ~ & ${TopDropCursor} {
|
||||
display: none;
|
||||
}
|
||||
`;
|
||||
|
||||
export default observer(DraggableSection);
|
||||
@@ -5,10 +5,18 @@ type Props = {
|
||||
isActiveDrop: boolean;
|
||||
innerRef: React.Ref<HTMLDivElement>;
|
||||
position?: "top";
|
||||
className?: string;
|
||||
};
|
||||
|
||||
function DropCursor({ isActiveDrop, innerRef, position }: Props) {
|
||||
return <Cursor isOver={isActiveDrop} ref={innerRef} position={position} />;
|
||||
function DropCursor({ isActiveDrop, innerRef, position, className }: Props) {
|
||||
return (
|
||||
<Cursor
|
||||
isOver={isActiveDrop}
|
||||
ref={innerRef}
|
||||
position={position}
|
||||
className={className}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// transparent hover zone with a thin visible band vertically centered
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { CollapsedIcon } from "outline-icons";
|
||||
import * as React from "react";
|
||||
import styled, { keyframes } from "styled-components";
|
||||
import { extraArea, s } from "@shared/styles";
|
||||
import { s } from "@shared/styles";
|
||||
import usePersistedState from "~/hooks/usePersistedState";
|
||||
import { undraggableOnDesktop } from "~/styles";
|
||||
import { SectionDragContext } from "./DraggableSection";
|
||||
|
||||
type Props = {
|
||||
/** Unique header id – if passed the header will become toggleable */
|
||||
@@ -21,6 +22,7 @@ export function getHeaderExpandedKey(id: string) {
|
||||
*/
|
||||
export const Header: React.FC<Props> = ({ id, title, children }: Props) => {
|
||||
const [firstRender, setFirstRender] = React.useState(true);
|
||||
const dragRef = React.useContext(SectionDragContext);
|
||||
const [expanded, setExpanded] = usePersistedState<boolean>(
|
||||
getHeaderExpandedKey(id ?? ""),
|
||||
true
|
||||
@@ -38,7 +40,7 @@ export const Header: React.FC<Props> = ({ id, title, children }: Props) => {
|
||||
|
||||
return (
|
||||
<>
|
||||
<H3>
|
||||
<H3 ref={dragRef}>
|
||||
<Button onClick={handleClick} disabled={!id}>
|
||||
{title}
|
||||
{id && <Disclosure $expanded={expanded} size={20} />}
|
||||
@@ -66,8 +68,9 @@ const Fade = styled.span`
|
||||
`;
|
||||
|
||||
const Button = styled.button`
|
||||
display: inline-flex;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
user-select: none;
|
||||
@@ -83,13 +86,18 @@ const Button = styled.button`
|
||||
-webkit-appearance: none;
|
||||
transition: all 100ms ease;
|
||||
${undraggableOnDesktop()}
|
||||
${extraArea(4)}
|
||||
|
||||
&:not(:disabled):hover,
|
||||
&:not(:disabled):active {
|
||||
color: ${s("textSecondary")};
|
||||
background: ${s("sidebarHoverBackground")};
|
||||
cursor: var(--pointer);
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
&:not(:disabled):hover {
|
||||
color: ${s("text")};
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const Disclosure = styled(CollapsedIcon)<{ $expanded?: boolean }>`
|
||||
|
||||
@@ -7,7 +7,11 @@ import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { errToString } from "@shared/utils/error";
|
||||
import Icon from "@shared/components/Icon";
|
||||
import type { NavigationNode } from "@shared/types";
|
||||
import {
|
||||
type NavigationNode,
|
||||
type SidebarSection,
|
||||
UserPreference,
|
||||
} from "@shared/types";
|
||||
import type Collection from "~/models/Collection";
|
||||
import type Document from "~/models/Document";
|
||||
import type GroupMembership from "~/models/GroupMembership";
|
||||
@@ -169,6 +173,63 @@ export function useDropToReorderStar(getIndex?: () => string) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for shared logic that allows dragging a sidebar section by its header.
|
||||
*
|
||||
* @param section The section to drag.
|
||||
* @param title The localized title of the section, shown in the drag preview.
|
||||
*/
|
||||
export function useDragSidebarSection(
|
||||
section: SidebarSection,
|
||||
title: string
|
||||
): [{ isDragging: boolean }, ConnectDragSource] {
|
||||
const [{ isDragging }, draggableRef, preview] = useDrag({
|
||||
type: "sidebarSection",
|
||||
item: () => ({ id: section, title }),
|
||||
collect: (monitor) => ({
|
||||
isDragging: !!monitor.isDragging(),
|
||||
}),
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
preview(getEmptyImage(), { captureDraggingState: true });
|
||||
}, [preview]);
|
||||
|
||||
return [{ isDragging }, draggableRef];
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for shared logic that allows dropping a sidebar section to reorder it,
|
||||
* persisting the new order as a user preference.
|
||||
*
|
||||
* @param getNewOrder A function that returns the section order after dropping the given section here, or undefined when the drop would not change the order.
|
||||
*/
|
||||
export function useDropToReorderSidebarSection(
|
||||
getNewOrder: (section: SidebarSection) => SidebarSection[] | undefined
|
||||
) {
|
||||
const user = useCurrentUser();
|
||||
|
||||
return useDrop<
|
||||
{ id: SidebarSection; title: string },
|
||||
void,
|
||||
{ isOverCursor: boolean; isDragging: boolean }
|
||||
>({
|
||||
accept: "sidebarSection",
|
||||
drop: (item) => {
|
||||
const order = getNewOrder(item.id);
|
||||
if (order) {
|
||||
user.setPreference(UserPreference.SidebarSectionOrder, order);
|
||||
void user.save();
|
||||
}
|
||||
},
|
||||
canDrop: (item) => !!getNewOrder(item.id),
|
||||
collect: (monitor) => ({
|
||||
isOverCursor: monitor.isOver() && monitor.canDrop(),
|
||||
isDragging: monitor.getItemType() === "sidebarSection",
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for shared logic that allows dragging documents.
|
||||
*
|
||||
|
||||
@@ -4,7 +4,7 @@ import { ClockIcon } from "outline-icons";
|
||||
import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import styled from "styled-components";
|
||||
import { depths, s } from "@shared/styles";
|
||||
import { depths, s, borderRadius } from "@shared/styles";
|
||||
import Avatar, { AvatarSize } from "~/components/Avatar/Avatar";
|
||||
import Badge from "~/components/Badge";
|
||||
import Flex from "~/components/Flex";
|
||||
@@ -162,7 +162,7 @@ const Content = styled(HoverCardPrimitive.Content)`
|
||||
transform-origin: var(--radix-hover-card-content-transform-origin);
|
||||
background: ${s("menuBackground")};
|
||||
box-shadow: ${s("menuShadow")};
|
||||
border-radius: 6px;
|
||||
${borderRadius(8)}
|
||||
padding: 12px;
|
||||
min-width: 180px;
|
||||
max-width: 320px;
|
||||
|
||||
@@ -792,6 +792,10 @@ function useNotificationHandlers() {
|
||||
}
|
||||
);
|
||||
|
||||
socket.on("notifications.delete", (event: WebsocketEntityDeletedEvent) => {
|
||||
notifications.remove(event.modelId);
|
||||
});
|
||||
|
||||
socket.on(
|
||||
"subscriptions.create",
|
||||
(event: PartialExcept<Subscription, "id">) => {
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as VisuallyHidden from "@radix-ui/react-visually-hidden";
|
||||
import * as React from "react";
|
||||
import styled from "styled-components";
|
||||
import { Drawer as DrawerPrimitive } from "vaul";
|
||||
import { depths, s } from "@shared/styles";
|
||||
import { depths, s, borderRadius } from "@shared/styles";
|
||||
import Flex from "../Flex";
|
||||
import Text from "../Text";
|
||||
import { Overlay } from "./components/Overlay";
|
||||
@@ -95,7 +95,7 @@ const StyledContent = styled(m.div)`
|
||||
min-height: 44px;
|
||||
max-height: 90vh;
|
||||
|
||||
border-radius: 6px;
|
||||
${borderRadius(8)}
|
||||
|
||||
background: ${s("menuBackground")};
|
||||
`;
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as InputSelectPrimitive from "@radix-ui/react-select";
|
||||
import * as React from "react";
|
||||
import styled from "styled-components";
|
||||
import Text from "@shared/components/Text";
|
||||
import { depths, s } from "@shared/styles";
|
||||
import { depths, s, borderRadius } from "@shared/styles";
|
||||
import type { Props as ButtonProps } from "~/components/Button";
|
||||
import { fadeAndSlideDown, fadeAndSlideUp } from "~/styles/animations";
|
||||
import {
|
||||
@@ -145,7 +145,7 @@ const StyledContent = styled(InputSelectPrimitive.Content)`
|
||||
max-height: 350px;
|
||||
|
||||
padding: 4px;
|
||||
border-radius: 6px;
|
||||
${borderRadius(8)}
|
||||
background: ${s("menuBackground")};
|
||||
box-shadow: ${s("menuShadow")};
|
||||
transform-origin: 50% 0;
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as PopoverPrimitive from "@radix-ui/react-popover";
|
||||
import * as React from "react";
|
||||
import { mergeRefs } from "react-merge-refs";
|
||||
import styled from "styled-components";
|
||||
import { depths, s } from "@shared/styles";
|
||||
import { depths, s, borderRadius } from "@shared/styles";
|
||||
import { fadeAndScaleIn } from "~/styles/animations";
|
||||
import { usePortalContext } from "../Portal";
|
||||
|
||||
@@ -110,7 +110,7 @@ const StyledContent = styled(PopoverPrimitive.Content)<StyledContentProps>`
|
||||
|
||||
background: ${s("menuBackground")};
|
||||
box-shadow: ${s("menuShadow")};
|
||||
border-radius: 6px;
|
||||
${borderRadius(8)}
|
||||
outline: none;
|
||||
|
||||
padding: ${({ $shrink }) => ($shrink ? "6px 0" : "12px 24px")};
|
||||
|
||||
@@ -3,7 +3,7 @@ import { ellipsis } from "polished";
|
||||
import { Link } from "react-router-dom";
|
||||
import styled, { css } from "styled-components";
|
||||
import breakpoint from "styled-components-breakpoint";
|
||||
import { depths, s } from "@shared/styles";
|
||||
import { depths, s, borderRadius } from "@shared/styles";
|
||||
import Scrollable from "~/components/Scrollable";
|
||||
import { fadeAndScaleIn } from "~/styles/animations";
|
||||
|
||||
@@ -202,7 +202,7 @@ export const MenuContent = styled(Scrollable).attrs<MenuContentProps>(
|
||||
|
||||
background: ${s("menuBackground")};
|
||||
box-shadow: ${s("menuShadow")};
|
||||
border-radius: 6px;
|
||||
${borderRadius(8)}
|
||||
// Vertical spacing comes from spacers rather than padding so that the bottom
|
||||
// fade, which is confined to the content box, can reach the menu's edge.
|
||||
padding: 0 6px;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { transparentize } from "polished";
|
||||
import { NodeSelection } from "prosemirror-state";
|
||||
import { selectedRect } from "prosemirror-tables";
|
||||
import * as React from "react";
|
||||
@@ -6,7 +7,7 @@ import styled, { css, keyframes } 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 { depths, s } from "@shared/styles";
|
||||
import { depths, hairline, s } from "@shared/styles";
|
||||
import { HEADER_HEIGHT } from "~/components/Header";
|
||||
import { Portal } from "~/components/Portal";
|
||||
import useEventListener from "~/hooks/useEventListener";
|
||||
@@ -246,6 +247,7 @@ const FloatingToolbar = React.forwardRef(function FloatingToolbar_(
|
||||
) {
|
||||
const menuRef = ref || React.createRef<HTMLDivElement>();
|
||||
const [isSelectingText, setSelectingText] = React.useState(false);
|
||||
const raisedClickAt = React.useRef(0);
|
||||
|
||||
let position = usePosition({
|
||||
menuRef,
|
||||
@@ -268,23 +270,61 @@ const FloatingToolbar = React.forwardRef(function FloatingToolbar_(
|
||||
});
|
||||
|
||||
const isMobile = useMobile();
|
||||
const isMobileToolbarVisible = isMobile && !!props.active && position.visible;
|
||||
const isMobileToolbarVisible = isMobile && !!props.active && !!props.children;
|
||||
|
||||
// Keep the mobile toolbar glued to the top of the on-screen keyboard. The
|
||||
// hook tracks the visual viewport directly — see its implementation for the
|
||||
// iOS specifics.
|
||||
useKeyboardStickyOffset(menuRef, isMobileToolbarVisible);
|
||||
|
||||
// Tapping the bar must not move focus out of the editor, that would dismiss
|
||||
// the on-screen keyboard and take the bar down with it. Mousedown is the
|
||||
// event that assigns focus, and a tap dispatches it only after pointerup.
|
||||
const handleMouseDown = (event: React.MouseEvent) => {
|
||||
if (
|
||||
event.target instanceof Element &&
|
||||
!event.target.closest("input, textarea, [contenteditable='true']")
|
||||
) {
|
||||
event.preventDefault();
|
||||
}
|
||||
};
|
||||
|
||||
// Canceling that mousedown cancels the tap's click with it, so the click is
|
||||
// raised here instead, from the pointerup that comes before both.
|
||||
const handlePointerUp = (event: React.PointerEvent) => {
|
||||
if (event.pointerType === "mouse") {
|
||||
return;
|
||||
}
|
||||
|
||||
const button =
|
||||
event.target instanceof Element ? event.target.closest("button") : null;
|
||||
if (button) {
|
||||
raisedClickAt.current = event.timeStamp;
|
||||
button.click();
|
||||
}
|
||||
};
|
||||
|
||||
// A browser that delivers the tap's click anyway must not act twice.
|
||||
const handleClickCapture = (event: React.MouseEvent) => {
|
||||
if (event.isTrusted && event.timeStamp - raisedClickAt.current < 500) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
};
|
||||
|
||||
if (isMobile) {
|
||||
if (isMobileToolbarVisible) {
|
||||
// Vertical position (above the keyboard) is owned entirely by
|
||||
// useKeyboardStickyOffset, which writes the transform directly.
|
||||
return (
|
||||
<ReactPortal>
|
||||
<MobileWrapper ref={menuRef}>
|
||||
{props.children && (
|
||||
<MobileBackground>{props.children}</MobileBackground>
|
||||
)}
|
||||
<MobileWrapper
|
||||
ref={menuRef}
|
||||
onMouseDown={handleMouseDown}
|
||||
onPointerUp={handlePointerUp}
|
||||
onClickCapture={handleClickCapture}
|
||||
>
|
||||
<MobileBackground>{props.children}</MobileBackground>
|
||||
</MobileWrapper>
|
||||
</ReactPortal>
|
||||
);
|
||||
@@ -351,6 +391,7 @@ const MobileWrapper = styled.div`
|
||||
right: 0;
|
||||
width: 100vw;
|
||||
box-sizing: border-box;
|
||||
padding: 0 16px 4px;
|
||||
z-index: ${depths.editorToolbar};
|
||||
will-change: transform;
|
||||
|
||||
@@ -359,19 +400,27 @@ const MobileWrapper = styled.div`
|
||||
}
|
||||
`;
|
||||
|
||||
// A rounded bar floating clear of the edges of the screen, with the buttons
|
||||
// inside clipped to its corners as they scroll.
|
||||
const MobileBackground = styled.div`
|
||||
padding: 10px 6px;
|
||||
height: 60px;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
padding: 4px;
|
||||
min-height: 48px;
|
||||
overflow: hidden;
|
||||
background-color: ${s("menuBackground")};
|
||||
border-top: 1px solid ${s("divider")};
|
||||
box-shadow: ${s("menuShadow")};
|
||||
border-radius: 24px;
|
||||
${(props) => hairline(props.theme.divider)}
|
||||
|
||||
&:after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 100px;
|
||||
background-color: ${s("menuBackground")};
|
||||
// The frosted glass of the iOS accessory bars.
|
||||
@supports (backdrop-filter: blur(20px)) or
|
||||
(-webkit-backdrop-filter: blur(20px)) {
|
||||
backdrop-filter: blur(20px) saturate(180%);
|
||||
background-color: ${(props) =>
|
||||
transparentize(0.2, props.theme.menuBackground)};
|
||||
}
|
||||
`;
|
||||
|
||||
|
||||
@@ -35,6 +35,8 @@ type Props = {
|
||||
isTemplate: boolean;
|
||||
/** Whether the toolbar is currently active/visible */
|
||||
isActive: boolean;
|
||||
/** Whether the editor currently holds focus */
|
||||
isEditorFocused: boolean;
|
||||
/** The current selection */
|
||||
selection?: Selection;
|
||||
/** Whether the editor is in read-only mode */
|
||||
@@ -66,11 +68,16 @@ enum Toolbar {
|
||||
}
|
||||
|
||||
export function SelectionToolbar(props: Props) {
|
||||
const { readOnly = false } = props;
|
||||
const { readOnly = false, isEditorFocused } = props;
|
||||
const { view, extensions, commands, selectionToolbarMenus } = useEditor();
|
||||
const menuRef = React.useRef<HTMLDivElement | null>(null);
|
||||
const isMobile = useMobile();
|
||||
const isActive = props.isActive || isMobile;
|
||||
|
||||
// On mobile the toolbar is docked above the on-screen keyboard, so it stays
|
||||
// visible for as long as the editor is being edited rather than only while
|
||||
// there is a selection.
|
||||
const isMobileEditing = isMobile && !readOnly && isEditorFocused;
|
||||
const { state } = view;
|
||||
const [autoFocusLinkInput, setAutoFocusLinkInput] = React.useState(false);
|
||||
const isDragging = useIsDragging(state);
|
||||
@@ -324,7 +331,8 @@ export function SelectionToolbar(props: Props) {
|
||||
onEscape={() => setActiveToolbar(Toolbar.Menu)}
|
||||
onClickOutside={handleClickOutsideLinkEditor}
|
||||
/>
|
||||
) : activeToolbar === Toolbar.Menu && items.length ? (
|
||||
) : (activeToolbar === Toolbar.Menu || isMobileEditing) &&
|
||||
items.length ? (
|
||||
<ToolbarMenu items={items} {...rest} />
|
||||
) : null}
|
||||
</FloatingToolbar>
|
||||
|
||||
@@ -419,7 +419,13 @@ function SuggestionsMenu<T extends MenuItem>(props: Props<T>) {
|
||||
|
||||
const close = React.useCallback(() => {
|
||||
props.onClose();
|
||||
view.focus();
|
||||
|
||||
// Don't steal focus back from a nested editor, such as the one inside a
|
||||
// math node, that took it while the menu was closing.
|
||||
const focused = view.dom.ownerDocument.activeElement;
|
||||
if (focused === view.dom || !view.dom.contains(focused)) {
|
||||
view.focus();
|
||||
}
|
||||
}, [props, view]);
|
||||
|
||||
const handleLinkInputKeydown = (
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import styled from "styled-components";
|
||||
import breakpoint from "styled-components-breakpoint";
|
||||
import * as Toolbar from "@radix-ui/react-toolbar";
|
||||
import { closeHistory } from "@shared/editor/lib/closeHistory";
|
||||
import type { MenuItem } from "@shared/editor/types";
|
||||
import { MenuItemGroup, type MenuItem } from "@shared/editor/types";
|
||||
import { hideScrollbars, s } from "@shared/styles";
|
||||
import { TooltipProvider } from "~/components/TooltipContext";
|
||||
import useMobile from "~/hooks/useMobile";
|
||||
import type { MenuItem as TMenuItem } from "~/types";
|
||||
import { mapMenuItems } from "../menus/mapMenuItems";
|
||||
import { useEditor } from "./EditorContext";
|
||||
@@ -70,6 +71,7 @@ function ToolbarDropdown(props: ToolbarDropdownProps) {
|
||||
<Menu open={isOpen} onOpenChange={handleOpenChange}>
|
||||
<MenuTrigger>
|
||||
<ToolbarButton
|
||||
data-group={item.group}
|
||||
aria-label={item.label ? undefined : item.tooltip}
|
||||
disabled={item.disabled}
|
||||
>
|
||||
@@ -94,6 +96,31 @@ function ToolbarMenu(props: Props) {
|
||||
const { commands, view } = useEditor();
|
||||
const { items } = props;
|
||||
const { state } = view;
|
||||
const isMobile = useMobile();
|
||||
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||
const hasSelection = !state.selection.empty;
|
||||
|
||||
// On mobile the toolbar is a single bar holding both the text and the block
|
||||
// controls, wider than the screen. It scrolls to the group that suits the
|
||||
// selection – text controls once there is a selection, block controls for a
|
||||
// bare cursor – leaving the other group one swipe away.
|
||||
const didScroll = useRef(false);
|
||||
useEffect(() => {
|
||||
const wrapper = wrapperRef.current;
|
||||
if (!isMobile || !wrapper) {
|
||||
return;
|
||||
}
|
||||
|
||||
const target = wrapper.querySelector(
|
||||
`[data-group="${hasSelection ? MenuItemGroup.inline : MenuItemGroup.block}"]`
|
||||
);
|
||||
target?.scrollIntoView({
|
||||
block: "nearest",
|
||||
inline: "start",
|
||||
behavior: didScroll.current ? "smooth" : "auto",
|
||||
});
|
||||
didScroll.current = true;
|
||||
}, [isMobile, hasSelection]);
|
||||
|
||||
const handleClick = (item: MenuItem) => () => {
|
||||
if (!item.name) {
|
||||
@@ -117,10 +144,12 @@ function ToolbarMenu(props: Props) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Toolbar.Root asChild>
|
||||
<FlexibleWrapper>
|
||||
<FlexibleWrapper ref={wrapperRef}>
|
||||
{items.map((item, index) => {
|
||||
if (item.name === "separator" && item.visible !== false) {
|
||||
return <ToolbarSeparator key={index} />;
|
||||
// The mobile bar spaces its buttons evenly instead, as dividers
|
||||
// would eat into the room for them.
|
||||
return isMobile ? null : <ToolbarSeparator key={index} />;
|
||||
}
|
||||
if (item.visible === false || (!item.skipIcon && !item.icon)) {
|
||||
return null;
|
||||
@@ -152,6 +181,7 @@ function ToolbarMenu(props: Props) {
|
||||
) : (
|
||||
<Toolbar.Button asChild>
|
||||
<ToolbarButton
|
||||
data-group={item.group}
|
||||
onClick={handleClick(item)}
|
||||
active={isActive && !item.label}
|
||||
aria-label={item.label ? undefined : item.tooltip}
|
||||
@@ -182,7 +212,28 @@ const FlexibleWrapper = styled.div`
|
||||
justify-content: space-evenly;
|
||||
align-items: center;
|
||||
overflow-x: auto;
|
||||
gap: 10px;
|
||||
scroll-padding-inline-start: 4px;
|
||||
padding: 0;
|
||||
|
||||
// Six buttons and half of the seventh fill the width – the half button is
|
||||
// what tells the user that the bar scrolls. Whatever is left over becomes
|
||||
// the space between them, so the first and last sit hard against the ends
|
||||
// and the bar keeps an even margin all round.
|
||||
gap: 0 calc((100% - 20px) / 6 - 40px);
|
||||
|
||||
> * {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
flex: 0 0 auto;
|
||||
min-width: 40px;
|
||||
}
|
||||
|
||||
> * > button {
|
||||
min-width: 40px;
|
||||
height: 40px;
|
||||
justify-content: center;
|
||||
border-radius: 20px;
|
||||
}
|
||||
|
||||
${hideScrollbars()}
|
||||
`}
|
||||
|
||||
@@ -72,7 +72,11 @@ export default class CommentGutter extends Extension {
|
||||
}
|
||||
|
||||
return {
|
||||
decorations: mapDecorations(pluginState.decorations, tr),
|
||||
decorations: mapDecorations(
|
||||
pluginState.decorations,
|
||||
tr,
|
||||
newState
|
||||
),
|
||||
};
|
||||
},
|
||||
},
|
||||
|
||||
@@ -111,11 +111,7 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
// have changed underneath us since the last search.
|
||||
this.search(state.doc);
|
||||
|
||||
if (this.currentResultIndex >= this.results.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const result = this.results[this.currentResultIndex];
|
||||
const result = this.currentResult;
|
||||
|
||||
if (!result) {
|
||||
return false;
|
||||
@@ -190,6 +186,16 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The result at the current index, checking the length first so that an index
|
||||
* beyond the end of the results is not read.
|
||||
*/
|
||||
private get currentResult() {
|
||||
return this.currentResultIndex < this.results.length
|
||||
? this.results[this.currentResultIndex]
|
||||
: undefined;
|
||||
}
|
||||
|
||||
private get findRegExp() {
|
||||
return RegExp(
|
||||
this.searchTerm.replace(/\\+$/, ""),
|
||||
@@ -199,6 +205,10 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
|
||||
private goToMatch(direction: number): Command {
|
||||
return (state, dispatch) => {
|
||||
if (!this.results.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (direction > 0) {
|
||||
if (this.currentResultIndex >= this.results.length - 1) {
|
||||
this.currentResultIndex = 0;
|
||||
@@ -248,11 +258,7 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
* Expand any folded toggle blocks that contain the current match.
|
||||
*/
|
||||
private expandFoldedTogglesForCurrentMatch() {
|
||||
if (this.currentResultIndex >= this.results.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = this.results[this.currentResultIndex];
|
||||
const result = this.currentResult;
|
||||
if (!result) {
|
||||
return;
|
||||
}
|
||||
@@ -305,7 +311,7 @@ export default class FindAndReplaceExtension extends Extension<FindAndReplaceOpt
|
||||
* Expand a collapsed code block if it contains the current match.
|
||||
*/
|
||||
private expandCollapsedCodeBlockForCurrentMatch() {
|
||||
const result = this.results[this.currentResultIndex];
|
||||
const result = this.currentResult;
|
||||
if (!result) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3,8 +3,10 @@ import { isEqual } from "es-toolkit/compat";
|
||||
import { Plugin } from "prosemirror-state";
|
||||
import {
|
||||
ySyncPlugin,
|
||||
ySyncPluginKey,
|
||||
yCursorPlugin,
|
||||
yUndoPlugin,
|
||||
yUndoPluginKey,
|
||||
undo,
|
||||
redo,
|
||||
undoCommand,
|
||||
@@ -12,7 +14,11 @@ import {
|
||||
} from "y-prosemirror";
|
||||
import * as Y from "yjs";
|
||||
import Extension from "@shared/editor/lib/Extension";
|
||||
import { isRemoteTransaction } from "@shared/editor/lib/multiplayer";
|
||||
import type { MultiplayerOperations } from "@shared/editor/lib/multiplayer";
|
||||
import {
|
||||
isRemoteTransaction,
|
||||
multiplayerPluginKey,
|
||||
} from "@shared/editor/lib/multiplayer";
|
||||
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
|
||||
import { Second } from "@shared/utils/time";
|
||||
|
||||
@@ -118,6 +124,18 @@ export default class Multiplayer extends Extension<MultiplayerOptions> {
|
||||
// mapping, this avoids stored mappings for clients that never made a change
|
||||
doc.on("afterTransaction", assignUser);
|
||||
|
||||
const multiplayer: MultiplayerOperations = {
|
||||
isRemoteTransaction: (tr) => {
|
||||
const meta = tr.getMeta(ySyncPluginKey);
|
||||
|
||||
// This logic seems to be flipped? But it's correct.
|
||||
return !!meta?.isChangeOrigin;
|
||||
},
|
||||
stopCapturing: (state) => {
|
||||
yUndoPluginKey.getState(state)?.undoManager?.stopCapturing();
|
||||
},
|
||||
};
|
||||
|
||||
return [
|
||||
ySyncPlugin(type),
|
||||
yCursorPlugin(provider.awareness, {
|
||||
@@ -125,9 +143,14 @@ export default class Multiplayer extends Extension<MultiplayerOptions> {
|
||||
selectionBuilder,
|
||||
}),
|
||||
yUndoPlugin(),
|
||||
// Facade plugin that exposes the collaboration operations to shared
|
||||
// code without a static dependency on the collaboration libraries.
|
||||
new Plugin({
|
||||
key: multiplayerPluginKey,
|
||||
multiplayer,
|
||||
props: {
|
||||
handleScrollToSelection: (view) => isRemoteTransaction(view.state.tr),
|
||||
handleScrollToSelection: (view) =>
|
||||
isRemoteTransaction(view.state.tr, view.state),
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
@@ -326,7 +326,7 @@ export default class PasteHandler extends Extension {
|
||||
},
|
||||
state: {
|
||||
init: () => DecorationSet.empty,
|
||||
apply: (tr, set) => {
|
||||
apply: (tr, set, _oldState, newState) => {
|
||||
let mapping = tr.mapping;
|
||||
|
||||
// See if the transaction adds or removes any placeholders
|
||||
@@ -352,7 +352,7 @@ export default class PasteHandler extends Extension {
|
||||
return DecorationSet.create(tr.doc, decorations);
|
||||
}
|
||||
|
||||
if (hasDecorations && (isRemoteTransaction(tr) || meta)) {
|
||||
if (hasDecorations && (isRemoteTransaction(tr, newState) || meta)) {
|
||||
try {
|
||||
mapping = recreateTransform(tr.before, tr.doc, {
|
||||
complexSteps: true,
|
||||
|
||||
+76
-2
@@ -9,7 +9,11 @@ import { gapCursor } from "prosemirror-gapcursor";
|
||||
import type { InputRule } from "prosemirror-inputrules";
|
||||
import { keymap } from "prosemirror-keymap";
|
||||
import type { NodeSpec, MarkSpec } from "prosemirror-model";
|
||||
import { Schema, Node as ProsemirrorNode } from "prosemirror-model";
|
||||
import {
|
||||
Schema,
|
||||
Node as ProsemirrorNode,
|
||||
DOMParser as ProsemirrorDOMParser,
|
||||
} from "prosemirror-model";
|
||||
import type { Plugin, Transaction } from "prosemirror-state";
|
||||
import { EditorState, Selection, TextSelection } from "prosemirror-state";
|
||||
import type { MarkdownParser } from "prosemirror-markdown";
|
||||
@@ -36,6 +40,7 @@ import { inputRules } from "@shared/editor/lib/inputRules";
|
||||
import type { MarkdownSerializer } from "@shared/editor/lib/markdown/serializer";
|
||||
import { isRemoteTransaction } from "@shared/editor/lib/multiplayer";
|
||||
import textBetween from "@shared/editor/lib/textBetween";
|
||||
import { findNearestPos } from "@shared/editor/queries/findNearestPos";
|
||||
import { basicExtensions as extensions } from "@shared/editor/nodes";
|
||||
import type ReactNode from "@shared/editor/nodes/ReactNode";
|
||||
import type {
|
||||
@@ -48,8 +53,12 @@ import type {
|
||||
ProsemirrorMark,
|
||||
UserPreferences,
|
||||
} from "@shared/types";
|
||||
import { HeadingPrefixStyle } from "@shared/types";
|
||||
import { headingPrefixPluginKey } from "@shared/editor/extensions/HeadingPrefix";
|
||||
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
|
||||
import EventEmitter from "@shared/utils/events";
|
||||
import { getDataTransferFiles } from "@shared/utils/files";
|
||||
import { AttachmentValidation } from "@shared/validations";
|
||||
import type Document from "~/models/Document";
|
||||
import Flex from "~/components/Flex";
|
||||
import { PortalContext } from "~/components/Portal";
|
||||
@@ -175,6 +184,8 @@ export type Props = {
|
||||
embeds: EmbedDescriptor[];
|
||||
/** Display preferences for the logged in user, if any. */
|
||||
userPreferences?: UserPreferences | null;
|
||||
/** The style of prefix displayed before headings in the document. */
|
||||
headingPrefix?: HeadingPrefixStyle;
|
||||
/** Whether embeds should be rendered without an iframe */
|
||||
embedsDisabled?: boolean;
|
||||
className?: string;
|
||||
@@ -313,6 +324,16 @@ export class Editor extends React.PureComponent<
|
||||
void this.scrollToAnchor(this.props.scrollTo);
|
||||
}
|
||||
|
||||
// Recompute heading prefix decorations when the display preference changes
|
||||
if (this.props.headingPrefix !== prevProps.headingPrefix) {
|
||||
this.view.dispatch(
|
||||
this.view.state.tr.setMeta(
|
||||
headingPrefixPluginKey,
|
||||
this.props.headingPrefix ?? HeadingPrefixStyle.None
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Focus at the end of the document if switching from readOnly and autoFocus
|
||||
// is set to true
|
||||
if (prevProps.readOnly && !this.props.readOnly && this.props.autoFocus) {
|
||||
@@ -560,7 +581,7 @@ export class Editor extends React.PureComponent<
|
||||
) {
|
||||
self.handleChange({
|
||||
remote: transactions.some(
|
||||
(tr) => tr.docChanged && isRemoteTransaction(tr)
|
||||
(tr) => tr.docChanged && isRemoteTransaction(tr, state)
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -731,6 +752,57 @@ export class Editor extends React.PureComponent<
|
||||
this.props
|
||||
);
|
||||
|
||||
/**
|
||||
* Insert the content of a drop event at the position nearest to where it
|
||||
* occurred. Intended for drops that land outside of the editor itself.
|
||||
*
|
||||
* @param event The drop event.
|
||||
*/
|
||||
public insertDroppedContent = (event: React.DragEvent<HTMLElement>) => {
|
||||
const { view } = this;
|
||||
if (!view.editable) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
const pos = findNearestPos(view, {
|
||||
left: event.clientX,
|
||||
top: event.clientY,
|
||||
});
|
||||
const files = getDataTransferFiles(event);
|
||||
|
||||
// Without files, attempt to parse the payload as an HTML fragment.
|
||||
if (files.length === 0) {
|
||||
const text =
|
||||
event.dataTransfer.getData("text/html") ||
|
||||
event.dataTransfer.getData("text/plain");
|
||||
if (!text) {
|
||||
return;
|
||||
}
|
||||
|
||||
const dom = new DOMParser().parseFromString(text, "text/html");
|
||||
view.dispatch(
|
||||
view.state.tr.insert(
|
||||
pos,
|
||||
ProsemirrorDOMParser.fromSchema(view.state.schema).parse(dom)
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Insert all files as attachments if any of the files are not images.
|
||||
const isAttachment = files.some(
|
||||
(file) => !AttachmentValidation.imageContentTypes.includes(file.type)
|
||||
);
|
||||
|
||||
return insertFiles(view, event, pos, files, {
|
||||
...this.props,
|
||||
isAttachment,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns true if the trimmed content of the editor is an empty string.
|
||||
*
|
||||
@@ -1017,6 +1089,8 @@ export class Editor extends React.PureComponent<
|
||||
rtl={isRTL}
|
||||
readOnly={readOnly}
|
||||
selection={this.view.state.selection}
|
||||
storedMarks={this.view.state.storedMarks}
|
||||
isEditorFocused={this.state.isEditorFocused}
|
||||
/>
|
||||
))}
|
||||
<Observer>
|
||||
|
||||
+191
-163
@@ -32,7 +32,11 @@ import { isInList } from "@shared/editor/queries/isInList";
|
||||
import { isListActive } from "@shared/editor/queries/isListActive";
|
||||
import { isMarkActive } from "@shared/editor/queries/isMarkActive";
|
||||
import { isNodeActive } from "@shared/editor/queries/isNodeActive";
|
||||
import type { MenuItem, SelectionContext } from "@shared/editor/types";
|
||||
import {
|
||||
MenuItemGroup,
|
||||
type MenuItem,
|
||||
type SelectionContext,
|
||||
} from "@shared/editor/types";
|
||||
import { metaDisplay } from "@shared/utils/keyboard";
|
||||
import { t } from "i18next";
|
||||
import CircleIcon from "~/components/Icons/CircleIcon";
|
||||
@@ -65,15 +69,18 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
isEmpty,
|
||||
isInCode,
|
||||
isInCodeBlock,
|
||||
isInList: isList,
|
||||
isTableCell,
|
||||
} = ctx;
|
||||
|
||||
const highlight = getMarksBetween(
|
||||
state.selection.from,
|
||||
state.selection.to,
|
||||
state
|
||||
).find(({ mark }) => mark.type === state.schema.marks.highlight);
|
||||
// With a cursor rather than a range the highlight that matters is the one
|
||||
// that will be applied to the text typed next, which is not in the document.
|
||||
const highlight = isEmpty
|
||||
? (state.storedMarks || state.selection.$from.marks()).find(
|
||||
(mark) => mark.type === schema.marks.highlight
|
||||
)
|
||||
: getMarksBetween(state.selection.from, state.selection.to, state).find(
|
||||
({ mark }) => mark.type === schema.marks.highlight
|
||||
)?.mark;
|
||||
|
||||
const cellSelectionHasBackground = isTableCell
|
||||
? hasNodeAttrMarkCellSelection(
|
||||
@@ -83,47 +90,191 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
: false;
|
||||
|
||||
const selectedCellsColorSet = getColorSetForSelectedCells(state.selection);
|
||||
const canFormat = !isInCodeBlock;
|
||||
|
||||
const canFormatInline = !isInCodeBlock && (!isMobile || !isEmpty);
|
||||
const canFormatBlock = !isInCodeBlock && (!isMobile || isEmpty);
|
||||
|
||||
// The block controls come first, so they are the ones on screen with a bare
|
||||
// cursor and the bar scrolls right to the text controls for a selection.
|
||||
return [
|
||||
{
|
||||
name: "placeholder",
|
||||
tooltip: t("Placeholder"),
|
||||
icon: <InputIcon />,
|
||||
active: isMarkActive(schema.marks.placeholder),
|
||||
visible: isTemplate && (!isMobile || !isEmpty),
|
||||
name: "heading",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Heading"),
|
||||
shortcut: `⇧+Ctrl+1`,
|
||||
icon: <Heading1Icon />,
|
||||
active: isNodeActive(schema.nodes.heading, { level: 1 }),
|
||||
attrs: { level: 1 },
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
name: "heading",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Subheading"),
|
||||
shortcut: `⇧+Ctrl+2`,
|
||||
icon: <Heading2Icon />,
|
||||
active: isNodeActive(schema.nodes.heading, { level: 2 }),
|
||||
attrs: { level: 2 },
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
name: "heading",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Subheading"),
|
||||
shortcut: `⇧+Ctrl+3`,
|
||||
icon: <Heading3Icon />,
|
||||
active: isNodeActive(schema.nodes.heading, { level: 3 }),
|
||||
attrs: { level: 3 },
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
name: "blockquote",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Quote"),
|
||||
shortcut: `${metaDisplay}+]`,
|
||||
icon: <BlockQuoteIcon />,
|
||||
active: isNodeActive(schema.nodes.blockquote),
|
||||
attrs: { level: 2 },
|
||||
visible: !isInCodeBlock && !isTableCell,
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
visible: isTemplate && (!isMobile || !isEmpty),
|
||||
},
|
||||
{
|
||||
name: "mergeCells",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Merge cells"),
|
||||
icon: <TableMergeCellsIcon />,
|
||||
visible: isMultipleCellSelection(state),
|
||||
},
|
||||
{
|
||||
name: "splitCell",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Split cell"),
|
||||
icon: <TableSplitCellsIcon />,
|
||||
visible: isMergedCellSelection(state),
|
||||
},
|
||||
{
|
||||
name: "container_toggle",
|
||||
group: MenuItemGroup.block,
|
||||
icon: <CollapseIcon />,
|
||||
tooltip: t("Toggle block"),
|
||||
active: isNodeActive(schema.nodes.container_toggle),
|
||||
attrs: { id: uuidv4() },
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
},
|
||||
{
|
||||
name: "checkbox_list",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Todo list"),
|
||||
shortcut: `⇧+Ctrl+7`,
|
||||
icon: <TodoListIcon />,
|
||||
keywords: "checklist checkbox task",
|
||||
active: isListActive(schema.nodes.checkbox_list),
|
||||
visible: !isInCodeBlock && !isTableCell,
|
||||
},
|
||||
{
|
||||
name: "bullet_list",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Bulleted list"),
|
||||
shortcut: `⇧+Ctrl+8`,
|
||||
icon: <BulletedListIcon />,
|
||||
active: isListActive(schema.nodes.bullet_list),
|
||||
visible: !isInCodeBlock && !isTableCell,
|
||||
},
|
||||
{
|
||||
name: "ordered_list",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Ordered list"),
|
||||
shortcut: `⇧+Ctrl+9`,
|
||||
icon: <OrderedListIcon />,
|
||||
active: isListActive(schema.nodes.ordered_list),
|
||||
visible: !isInCodeBlock && !isTableCell,
|
||||
},
|
||||
{
|
||||
name: "outdentList",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Outdent"),
|
||||
shortcut: `⇧+Tab`,
|
||||
icon: <OutdentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) &&
|
||||
isInList(state, { types: ["ordered_list", "bullet_list"] }),
|
||||
},
|
||||
{
|
||||
name: "indentList",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Indent"),
|
||||
shortcut: `Tab`,
|
||||
icon: <IndentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) &&
|
||||
isInList(state, { types: ["ordered_list", "bullet_list"] }),
|
||||
},
|
||||
{
|
||||
name: "outdentCheckboxList",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Outdent"),
|
||||
shortcut: `⇧+Tab`,
|
||||
icon: <OutdentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) && isInList(state, { types: ["checkbox_list"] }),
|
||||
},
|
||||
{
|
||||
name: "indentCheckboxList",
|
||||
group: MenuItemGroup.block,
|
||||
tooltip: t("Indent"),
|
||||
shortcut: `Tab`,
|
||||
icon: <IndentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) && isInList(state, { types: ["checkbox_list"] }),
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
visible: !isInCodeBlock,
|
||||
},
|
||||
{
|
||||
name: "placeholder",
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Placeholder"),
|
||||
icon: <InputIcon />,
|
||||
active: isMarkActive(schema.marks.placeholder),
|
||||
visible: isTemplate,
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
visible: isTemplate,
|
||||
},
|
||||
{
|
||||
name: "strong",
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Bold"),
|
||||
shortcut: `${metaDisplay}+B`,
|
||||
icon: <BoldIcon />,
|
||||
active: isMarkActive(schema.marks.strong),
|
||||
visible: canFormatInline,
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
name: "em",
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Italic"),
|
||||
shortcut: `${metaDisplay}+I`,
|
||||
icon: <ItalicIcon />,
|
||||
active: isMarkActive(schema.marks.em),
|
||||
visible: canFormatInline,
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
name: "strikethrough",
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Strikethrough"),
|
||||
shortcut: `${metaDisplay}+D`,
|
||||
icon: <StrikethroughIcon />,
|
||||
active: isMarkActive(schema.marks.strikethrough),
|
||||
visible: canFormatInline,
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Background color"),
|
||||
icon:
|
||||
getColorSetForSelectedCells(state.selection).size > 1 ? (
|
||||
@@ -137,7 +288,7 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
) : (
|
||||
<PaletteIcon />
|
||||
),
|
||||
visible: !isInCode && (!isMobile || !isEmpty) && isTableCell,
|
||||
visible: !isInCode && isTableCell,
|
||||
children: (): MenuItem[] => {
|
||||
const documentTableColors = getDocumentTableBackgroundColors(state);
|
||||
|
||||
@@ -216,21 +367,22 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
},
|
||||
},
|
||||
{
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Highlight"),
|
||||
shortcut: `${metaDisplay}+⇧+H`,
|
||||
icon: highlight ? (
|
||||
<CircleIcon
|
||||
color={highlight.mark.attrs.color || Highlight.presetColors[0].hex}
|
||||
color={highlight.attrs.color || Highlight.presetColors[0].hex}
|
||||
/>
|
||||
) : (
|
||||
<HighlightIcon />
|
||||
),
|
||||
active: () => !!highlight,
|
||||
visible: !isInCode && (!isMobile || !isEmpty) && !isTableCell,
|
||||
visible: !isInCode && !isTableCell,
|
||||
children: (): MenuItem[] => {
|
||||
const documentHighlightColors = getDocumentHighlightColors(state);
|
||||
|
||||
const currentHighlightColor = highlight?.mark.attrs.color;
|
||||
const currentHighlightColor = highlight?.attrs.color;
|
||||
const nonPresetDocumentColors = documentHighlightColors.filter(
|
||||
(color: string) =>
|
||||
!Highlight.isPresetColor(color) && color !== currentHighlightColor
|
||||
@@ -244,7 +396,7 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
label: t("None"),
|
||||
icon: <DottedCircleIcon retainColor color="transparent" />,
|
||||
active: () => false,
|
||||
attrs: { color: highlight.mark.attrs.color },
|
||||
attrs: { color: highlight.attrs.color },
|
||||
},
|
||||
]
|
||||
: []),
|
||||
@@ -256,22 +408,19 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
attrs: { color: preset.hex },
|
||||
})),
|
||||
...(highlight &&
|
||||
highlight.mark.attrs.color &&
|
||||
!Highlight.isPresetColor(highlight.mark.attrs.color)
|
||||
highlight.attrs.color &&
|
||||
!Highlight.isPresetColor(highlight.attrs.color)
|
||||
? [
|
||||
{
|
||||
name: "highlight",
|
||||
label: highlight.mark.attrs.color,
|
||||
label: highlight.attrs.color,
|
||||
icon: (
|
||||
<CircleIcon
|
||||
retainColor
|
||||
color={highlight.mark.attrs.color}
|
||||
/>
|
||||
<CircleIcon retainColor color={highlight.attrs.color} />
|
||||
),
|
||||
active: isMarkActive(schema.marks.highlight, {
|
||||
color: highlight.mark.attrs.color,
|
||||
color: highlight.attrs.color,
|
||||
}),
|
||||
attrs: { color: highlight.mark.attrs.color },
|
||||
attrs: { color: highlight.attrs.color },
|
||||
},
|
||||
]
|
||||
: []),
|
||||
@@ -290,8 +439,7 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
content: (
|
||||
<HighlightColorPicker
|
||||
activeColor={
|
||||
highlight?.mark.attrs.color ||
|
||||
Highlight.presetColors[0].hex
|
||||
highlight?.attrs.color || Highlight.presetColors[0].hex
|
||||
}
|
||||
/>
|
||||
),
|
||||
@@ -307,136 +455,12 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
},
|
||||
{
|
||||
name: "code_inline",
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Code"),
|
||||
shortcut: `${metaDisplay}+E`,
|
||||
icon: <CodeIcon />,
|
||||
active: isMarkActive(schema.marks.code_inline),
|
||||
visible: canFormatInline,
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
visible: !isInCodeBlock,
|
||||
},
|
||||
{
|
||||
name: "heading",
|
||||
tooltip: t("Heading"),
|
||||
shortcut: `⇧+Ctrl+1`,
|
||||
icon: <Heading1Icon />,
|
||||
active: isNodeActive(schema.nodes.heading, { level: 1 }),
|
||||
attrs: { level: 1 },
|
||||
visible: canFormatBlock,
|
||||
},
|
||||
{
|
||||
name: "heading",
|
||||
tooltip: t("Subheading"),
|
||||
shortcut: `⇧+Ctrl+2`,
|
||||
icon: <Heading2Icon />,
|
||||
active: isNodeActive(schema.nodes.heading, { level: 2 }),
|
||||
attrs: { level: 2 },
|
||||
visible: canFormatBlock,
|
||||
},
|
||||
{
|
||||
name: "heading",
|
||||
tooltip: t("Subheading"),
|
||||
shortcut: `⇧+Ctrl+3`,
|
||||
icon: <Heading3Icon />,
|
||||
active: isNodeActive(schema.nodes.heading, { level: 3 }),
|
||||
attrs: { level: 3 },
|
||||
visible: canFormatBlock,
|
||||
},
|
||||
{
|
||||
name: "blockquote",
|
||||
tooltip: t("Quote"),
|
||||
shortcut: `${metaDisplay}+]`,
|
||||
icon: <BlockQuoteIcon />,
|
||||
active: isNodeActive(schema.nodes.blockquote),
|
||||
attrs: { level: 2 },
|
||||
visible: !isInCodeBlock && !isTableCell && (!isMobile || isEmpty),
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
},
|
||||
{
|
||||
name: "mergeCells",
|
||||
tooltip: t("Merge cells"),
|
||||
icon: <TableMergeCellsIcon />,
|
||||
visible: isMultipleCellSelection(state),
|
||||
},
|
||||
{
|
||||
name: "splitCell",
|
||||
tooltip: t("Split cell"),
|
||||
icon: <TableSplitCellsIcon />,
|
||||
visible: isMergedCellSelection(state),
|
||||
},
|
||||
{
|
||||
name: "container_toggle",
|
||||
icon: <CollapseIcon />,
|
||||
tooltip: t("Toggle block"),
|
||||
active: isNodeActive(schema.nodes.container_toggle),
|
||||
attrs: { id: uuidv4() },
|
||||
visible: canFormatBlock,
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
},
|
||||
{
|
||||
name: "checkbox_list",
|
||||
tooltip: t("Todo list"),
|
||||
shortcut: `⇧+Ctrl+7`,
|
||||
icon: <TodoListIcon />,
|
||||
keywords: "checklist checkbox task",
|
||||
active: isListActive(schema.nodes.checkbox_list),
|
||||
visible: !isInCodeBlock && !isTableCell && (!isList || !isTouch),
|
||||
},
|
||||
{
|
||||
name: "bullet_list",
|
||||
tooltip: t("Bulleted list"),
|
||||
shortcut: `⇧+Ctrl+8`,
|
||||
icon: <BulletedListIcon />,
|
||||
active: isListActive(schema.nodes.bullet_list),
|
||||
visible: !isInCodeBlock && !isTableCell && (!isList || !isTouch),
|
||||
},
|
||||
{
|
||||
name: "ordered_list",
|
||||
tooltip: t("Ordered list"),
|
||||
shortcut: `⇧+Ctrl+9`,
|
||||
icon: <OrderedListIcon />,
|
||||
active: isListActive(schema.nodes.ordered_list),
|
||||
visible: !isInCodeBlock && !isTableCell && (!isList || !isTouch),
|
||||
},
|
||||
{
|
||||
name: "outdentList",
|
||||
tooltip: t("Outdent"),
|
||||
shortcut: `⇧+Tab`,
|
||||
icon: <OutdentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) &&
|
||||
isInList(state, { types: ["ordered_list", "bullet_list"] }),
|
||||
},
|
||||
{
|
||||
name: "indentList",
|
||||
tooltip: t("Indent"),
|
||||
shortcut: `Tab`,
|
||||
icon: <IndentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) &&
|
||||
isInList(state, { types: ["ordered_list", "bullet_list"] }),
|
||||
},
|
||||
{
|
||||
name: "outdentCheckboxList",
|
||||
tooltip: t("Outdent"),
|
||||
shortcut: `⇧+Tab`,
|
||||
icon: <OutdentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) && isInList(state, { types: ["checkbox_list"] }),
|
||||
},
|
||||
{
|
||||
name: "indentCheckboxList",
|
||||
tooltip: t("Indent"),
|
||||
shortcut: `Tab`,
|
||||
icon: <IndentIcon />,
|
||||
visible:
|
||||
(isTouch || isMobile) && isInList(state, { types: ["checkbox_list"] }),
|
||||
visible: canFormat,
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
@@ -444,15 +468,18 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
},
|
||||
{
|
||||
name: "addLink",
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Create link"),
|
||||
shortcut: `${metaDisplay}+K`,
|
||||
icon: <LinkIcon />,
|
||||
attrs: { href: "" },
|
||||
active: isMarkActive(schema.marks.link, undefined, { exact: true }),
|
||||
visible: canFormatInline,
|
||||
// A link cannot be made without text to attach it to.
|
||||
visible: canFormat && !isEmpty,
|
||||
},
|
||||
{
|
||||
name: "comment",
|
||||
group: MenuItemGroup.inline,
|
||||
tooltip: t("Comment"),
|
||||
shortcut: `${metaDisplay}+⌥+M`,
|
||||
icon: <CommentIcon />,
|
||||
@@ -462,7 +489,6 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
{ resolved: false },
|
||||
{ exact: true }
|
||||
),
|
||||
visible: !isMobile || !isEmpty,
|
||||
},
|
||||
{
|
||||
name: "separator",
|
||||
@@ -470,9 +496,11 @@ export default function formattingMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
},
|
||||
{
|
||||
name: "copyToClipboard",
|
||||
group: MenuItemGroup.inline,
|
||||
icon: <CopyIcon />,
|
||||
tooltip: t("Copy"),
|
||||
shortcut: `${metaDisplay}+C`,
|
||||
// Copy acts on the selected text, so it has nothing to do without one.
|
||||
visible: isInCode && !isInCodeBlock && (!isMobile || !isEmpty),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -67,7 +67,7 @@ export const ActionContextProvider = observer(function ActionContextProvider_({
|
||||
// navigation does not invalidate the context value. Action perform/visible
|
||||
// callbacks see the current location at call time via history.location,
|
||||
// which react-router updates on every navigation.
|
||||
const history = useHistory();
|
||||
const history = useHistory<{ sidebarContext?: SidebarContextType }>();
|
||||
|
||||
const {
|
||||
activeModels: valueModels,
|
||||
@@ -174,7 +174,6 @@ export const ActionContextProvider = observer(function ActionContextProvider_({
|
||||
...(isMenu !== undefined ? { isMenu } : {}),
|
||||
...(isCommandBar !== undefined ? { isCommandBar } : {}),
|
||||
...(isButton !== undefined ? { isButton } : {}),
|
||||
...(sidebarContext !== undefined ? { sidebarContext } : {}),
|
||||
...(event !== undefined ? { event } : {}),
|
||||
activeCollectionId,
|
||||
activeDocumentId,
|
||||
@@ -193,6 +192,18 @@ export const ActionContextProvider = observer(function ActionContextProvider_({
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
// The sidebar context is carried in location state, so fall back to the
|
||||
// current location when no ancestor provider supplies one. A getter for the
|
||||
// same reason as `location` above.
|
||||
Object.defineProperty(result, "sidebarContext", {
|
||||
get: () =>
|
||||
sidebarContext ??
|
||||
parentContext?.sidebarContext ??
|
||||
history.location.state?.sidebarContext,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
return result;
|
||||
}, [
|
||||
parentContext,
|
||||
|
||||
@@ -1,88 +1,83 @@
|
||||
import { useMemo } from "react";
|
||||
import type { NavigationNode } from "@shared/types";
|
||||
import type { CollectionSort, NavigationNode } from "@shared/types";
|
||||
import { NavigationNodeType } from "@shared/types";
|
||||
import { sortNavigationNodes } from "@shared/utils/collections";
|
||||
import type Collection from "~/models/Collection";
|
||||
import { useComputed } from "~/hooks/useComputed";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import type Collection from "~/models/Collection";
|
||||
|
||||
/**
|
||||
* React hook that modifies the document structure
|
||||
* of all collections present in store. Adds extra attributes
|
||||
* like type, depth and parent to each of the nodes in document
|
||||
* structure.
|
||||
* React hook that returns the document structure of all collections in the
|
||||
* store as navigation trees. Each node is a copy of the node in the store with
|
||||
* extra attributes added – type, collectionId, depth, and parent.
|
||||
*
|
||||
* @return {NavigationNode[]} collectionTrees root collection nodes of modified trees
|
||||
* @returns the root node of each collection tree.
|
||||
*/
|
||||
export default function useCollectionTrees(): NavigationNode[] {
|
||||
const { collections } = useStores();
|
||||
|
||||
const getCollectionTree = (collection: Collection): NavigationNode => {
|
||||
const addType = (node: NavigationNode): NavigationNode => {
|
||||
if (node.children.length > 0) {
|
||||
node.children = node.children.map(addType);
|
||||
}
|
||||
return useComputed(
|
||||
() => collections.orderedData.map(getCollectionTree),
|
||||
[collections]
|
||||
);
|
||||
}
|
||||
|
||||
node.type = node.type ? node.type : NavigationNodeType.Document;
|
||||
return node;
|
||||
};
|
||||
|
||||
const addParent = (
|
||||
node: NavigationNode,
|
||||
parent: NavigationNode | null = null
|
||||
): NavigationNode => {
|
||||
if (node.children.length > 0) {
|
||||
node.children = node.children.map((child) => addParent(child, node));
|
||||
}
|
||||
|
||||
node.parent = parent;
|
||||
return node;
|
||||
};
|
||||
|
||||
const addDepth = (node: NavigationNode, depth = 0): NavigationNode => {
|
||||
if (node.children.length > 0) {
|
||||
node.children = node.children.map((child) =>
|
||||
addDepth(child, depth + 1)
|
||||
);
|
||||
}
|
||||
|
||||
node.depth = depth;
|
||||
return node;
|
||||
};
|
||||
|
||||
const addCollectionId = (
|
||||
node: NavigationNode,
|
||||
collectionId = collection.id
|
||||
): NavigationNode => {
|
||||
if (node.children.length > 0) {
|
||||
node.children = node.children.map((child) =>
|
||||
addCollectionId(child, collectionId)
|
||||
);
|
||||
}
|
||||
|
||||
node.collectionId = collectionId;
|
||||
return node;
|
||||
};
|
||||
|
||||
const collectionNode: NavigationNode = {
|
||||
id: collection.id,
|
||||
title: collection.name,
|
||||
url: collection.path,
|
||||
type: NavigationNodeType.Collection,
|
||||
children: collection.documents
|
||||
? sortNavigationNodes(collection.documents, collection.sort, true)
|
||||
: [],
|
||||
parent: null,
|
||||
};
|
||||
|
||||
return addParent(addCollectionId(addDepth(addType(collectionNode), 1)));
|
||||
/**
|
||||
* Builds the navigation tree for a collection.
|
||||
*
|
||||
* @param collection The collection to build the tree for.
|
||||
* @returns the root node of the collection tree.
|
||||
*/
|
||||
function getCollectionTree(collection: Collection): NavigationNode {
|
||||
const root: NavigationNode = {
|
||||
id: collection.id,
|
||||
title: collection.name,
|
||||
url: collection.path,
|
||||
type: NavigationNodeType.Collection,
|
||||
collectionId: collection.id,
|
||||
depth: 1,
|
||||
parent: null,
|
||||
children: [],
|
||||
};
|
||||
|
||||
const key = collections.orderedData.map((o) => o.documents?.length).join("-");
|
||||
const collectionTrees = useMemo(
|
||||
() => collections.orderedData.map(getCollectionTree),
|
||||
// oxlint-disable-next-line react-hooks/exhaustive-deps
|
||||
[collections.orderedData, key]
|
||||
root.children = annotateNodes(
|
||||
collection.documents ?? [],
|
||||
collection.sort,
|
||||
root
|
||||
);
|
||||
|
||||
return collectionTrees;
|
||||
return root;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the given nodes and their descendants in sorted order, adding the
|
||||
* attributes needed to traverse and render the tree.
|
||||
*
|
||||
* @param nodes The nodes to copy.
|
||||
* @param sort The sort of the collection the nodes belong to.
|
||||
* @param parent The node that the given nodes are children of.
|
||||
* @returns the copied nodes.
|
||||
*/
|
||||
function annotateNodes(
|
||||
nodes: NavigationNode[],
|
||||
sort: CollectionSort,
|
||||
parent: NavigationNode
|
||||
): NavigationNode[] {
|
||||
if (!nodes.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return sortNavigationNodes(nodes, sort, false).map((node) => {
|
||||
const annotated: NavigationNode = {
|
||||
...node,
|
||||
type: node.type ?? NavigationNodeType.Document,
|
||||
collectionId: parent.collectionId,
|
||||
depth: (parent.depth ?? 0) + 1,
|
||||
parent,
|
||||
children: [],
|
||||
};
|
||||
|
||||
annotated.children = annotateNodes(node.children ?? [], sort, annotated);
|
||||
|
||||
return annotated;
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useHistory } from "react-router-dom";
|
||||
import { patchLocation } from "~/utils/history";
|
||||
import useQuery from "./useQuery";
|
||||
|
||||
/**
|
||||
@@ -20,13 +21,13 @@ export default function useConsumeQueryParam(name: string): string | null {
|
||||
if (value && !consumedRef.current) {
|
||||
consumedRef.current = true;
|
||||
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const location = history.location;
|
||||
const params = new URLSearchParams(location.search);
|
||||
params.delete(name);
|
||||
const search = params.toString();
|
||||
history.replace({
|
||||
pathname: window.location.pathname,
|
||||
search: search ? `?${search}` : "",
|
||||
});
|
||||
history.replace(
|
||||
patchLocation(location, { search: search ? `?${search}` : "" })
|
||||
);
|
||||
}
|
||||
}, [value, name, history]);
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import type Document from "~/models/Document";
|
||||
import type Model from "~/models/base/Model";
|
||||
import useStores from "~/hooks/useStores";
|
||||
|
||||
/**
|
||||
* Returns the models that document actions should operate on – the document
|
||||
* itself, and its collection unless the document is only reachable through a
|
||||
* direct share with the user.
|
||||
*
|
||||
* @param document the document the actions will be performed on.
|
||||
* @returns the active models to provide to the action context.
|
||||
*/
|
||||
export function useDocumentActiveModels(document: Document): Model[] {
|
||||
const { userMemberships, groupMemberships } = useStores();
|
||||
|
||||
const isShared = !!(
|
||||
userMemberships.getByDocumentId(document.id) ||
|
||||
groupMemberships.getByDocumentId(document.id)
|
||||
);
|
||||
|
||||
return [
|
||||
document,
|
||||
...(!isShared && document.collection ? [document.collection] : []),
|
||||
];
|
||||
}
|
||||
@@ -45,6 +45,8 @@ import { useTemplateMenuActions } from "./useTemplateMenuActions";
|
||||
type Props = {
|
||||
/** Document ID for which the actions are generated */
|
||||
documentId: string;
|
||||
/** Whether the document is currently being viewed */
|
||||
isViewing?: boolean;
|
||||
/** Invoked when the "Find and replace" menu item is clicked */
|
||||
onFindAndReplace?: () => void;
|
||||
/** Invoked when the "Rename" menu item is clicked */
|
||||
@@ -55,6 +57,7 @@ type Props = {
|
||||
|
||||
export function useDocumentMenuAction({
|
||||
documentId,
|
||||
isViewing = false,
|
||||
onFindAndReplace,
|
||||
onRename,
|
||||
onSelectTemplate,
|
||||
@@ -106,7 +109,7 @@ export function useDocumentMenuAction({
|
||||
openDocumentComments,
|
||||
openDocumentHistory,
|
||||
openDocumentInsights,
|
||||
toggleDocumentStats,
|
||||
...(isViewing ? [toggleDocumentStats] : []),
|
||||
openDocumentInSplit,
|
||||
openDocumentInDesktop,
|
||||
presentDocument,
|
||||
@@ -118,6 +121,14 @@ export function useDocumentMenuAction({
|
||||
permanentlyDeleteDocument,
|
||||
leaveDocument,
|
||||
]),
|
||||
[t, isMobile, templateMenuActions, documentId, onFindAndReplace, onRename]
|
||||
[
|
||||
t,
|
||||
isMobile,
|
||||
isViewing,
|
||||
templateMenuActions,
|
||||
documentId,
|
||||
onFindAndReplace,
|
||||
onRename,
|
||||
]
|
||||
);
|
||||
}
|
||||
+11
-3
@@ -38,10 +38,18 @@ const useHover = ({ ref, duration }: Props): boolean => {
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
if (ref.current) {
|
||||
ref.current.onmouseenter = onMouseEnter;
|
||||
ref.current.onmouseleave = onMouseLeave;
|
||||
const element = ref.current;
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
|
||||
element.addEventListener("mouseenter", onMouseEnter);
|
||||
element.addEventListener("mouseleave", onMouseLeave);
|
||||
|
||||
return () => {
|
||||
element.removeEventListener("mouseenter", onMouseEnter);
|
||||
element.removeEventListener("mouseleave", onMouseLeave);
|
||||
};
|
||||
}, [ref, onMouseEnter, onMouseLeave]);
|
||||
|
||||
return hovered;
|
||||
|
||||
@@ -13,12 +13,13 @@ import { getSafeAreaInsets } from "@shared/utils/browser";
|
||||
* translates the element upwards by that amount so it always rests on top of
|
||||
* the keyboard.
|
||||
*
|
||||
* The transform is re-applied after every render (so a parent re-render cannot
|
||||
* clobber it) and on visual viewport `resize`/`scroll` events. A short-lived
|
||||
* `requestAnimationFrame` loop tracks the keyboard's open/close animation so
|
||||
* the element glides with it rather than snapping into place once the
|
||||
* transition settles. Writes go directly to the node's style to avoid React
|
||||
* re-render latency during the animation.
|
||||
* The measurement is repeated every frame while enabled. A keyboard changes
|
||||
* height without warning – a predictive text strip or an accessory bar comes
|
||||
* and goes, one keyboard type replaces another – and not every change is
|
||||
* announced by a viewport event, so an element positioned once from an event
|
||||
* can be left behind the keyboard. Writes go straight to the node's style, and
|
||||
* only when the offset changes, so a frame that measures the same keyboard
|
||||
* costs a handful of property reads.
|
||||
*
|
||||
* @param ref A ref to the fixed-position element to keep pinned.
|
||||
* @param enabled Whether the behavior should be active.
|
||||
@@ -27,6 +28,13 @@ export default function useKeyboardStickyOffset(
|
||||
ref: React.RefObject<HTMLElement>,
|
||||
enabled: boolean
|
||||
) {
|
||||
const applied = React.useRef<number | null>(null);
|
||||
|
||||
// Reading the layout viewport height can force a layout, so it is measured
|
||||
// when it changes rather than on every frame.
|
||||
const safeAreaBottom = React.useRef(0);
|
||||
const layoutHeight = React.useRef(0);
|
||||
|
||||
const apply = React.useCallback(() => {
|
||||
const viewport = window.visualViewport;
|
||||
const node = ref.current;
|
||||
@@ -41,55 +49,46 @@ export default function useKeyboardStickyOffset(
|
||||
// clears the home indicator.
|
||||
const keyboardInset = Math.max(
|
||||
0,
|
||||
window.innerHeight - (viewport.offsetTop + viewport.height)
|
||||
);
|
||||
const offset = Math.round(
|
||||
Math.max(keyboardInset, getSafeAreaInsets().bottom)
|
||||
layoutHeight.current - (viewport.offsetTop + viewport.height)
|
||||
);
|
||||
const offset = Math.round(Math.max(keyboardInset, safeAreaBottom.current));
|
||||
|
||||
node.style.transform = `translate3d(0, ${-offset}px, 0)`;
|
||||
if (offset !== applied.current) {
|
||||
applied.current = offset;
|
||||
node.style.transform = `translate3d(0, ${-offset}px, 0)`;
|
||||
}
|
||||
}, [ref, enabled]);
|
||||
|
||||
// Re-apply after every render, before paint, so the keyboard-aware transform
|
||||
// survives parent re-renders and there is no flash on first mount.
|
||||
React.useLayoutEffect(apply);
|
||||
// Re-apply after every render, before paint, so the transform survives a
|
||||
// parent re-render and there is no flash on first mount.
|
||||
React.useLayoutEffect(() => {
|
||||
safeAreaBottom.current = getSafeAreaInsets().bottom;
|
||||
layoutHeight.current = window.innerHeight;
|
||||
applied.current = null;
|
||||
apply();
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
const viewport = window.visualViewport;
|
||||
if (!enabled || !viewport) {
|
||||
if (!enabled || !window.visualViewport) {
|
||||
return;
|
||||
}
|
||||
|
||||
let frame = 0;
|
||||
let trackUntil = 0;
|
||||
const handleResize = () => {
|
||||
layoutHeight.current = window.innerHeight;
|
||||
safeAreaBottom.current = getSafeAreaInsets().bottom;
|
||||
};
|
||||
window.addEventListener("resize", handleResize);
|
||||
window.addEventListener("orientationchange", handleResize);
|
||||
|
||||
const tick = (now: number) => {
|
||||
let frame = requestAnimationFrame(function tick() {
|
||||
apply();
|
||||
frame = now < trackUntil ? requestAnimationFrame(tick) : 0;
|
||||
};
|
||||
|
||||
const schedule = () => {
|
||||
// Keep re-measuring for a short window so the element follows the
|
||||
// keyboard animation rather than jumping once it settles.
|
||||
trackUntil = performance.now() + 350;
|
||||
if (!frame) {
|
||||
frame = requestAnimationFrame(tick);
|
||||
}
|
||||
};
|
||||
|
||||
viewport.addEventListener("resize", schedule);
|
||||
viewport.addEventListener("scroll", schedule);
|
||||
window.addEventListener("focusin", schedule);
|
||||
window.addEventListener("orientationchange", schedule);
|
||||
frame = requestAnimationFrame(tick);
|
||||
});
|
||||
|
||||
return () => {
|
||||
if (frame) {
|
||||
cancelAnimationFrame(frame);
|
||||
}
|
||||
viewport.removeEventListener("resize", schedule);
|
||||
viewport.removeEventListener("scroll", schedule);
|
||||
window.removeEventListener("focusin", schedule);
|
||||
window.removeEventListener("orientationchange", schedule);
|
||||
cancelAnimationFrame(frame);
|
||||
window.removeEventListener("resize", handleResize);
|
||||
window.removeEventListener("orientationchange", handleResize);
|
||||
};
|
||||
}, [enabled, apply]);
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import { isNumber } from "es-toolkit/compat";
|
||||
import { useRef } from "react";
|
||||
|
||||
/** Minimum distance in pixels that a touch must travel to count as a swipe. */
|
||||
const MinSwipeDistance = 40;
|
||||
|
||||
type Props = {
|
||||
onSwipeRight: () => void;
|
||||
onSwipeLeft: () => void;
|
||||
@@ -47,6 +50,12 @@ export default function useSwipe({
|
||||
const dx = touchXEnd.current - touchXStart.current;
|
||||
const dy = touchYEnd.current - touchYStart.current;
|
||||
|
||||
// Ignore small movements so that a tap, or the start of a gesture, is not
|
||||
// mistaken for a swipe.
|
||||
if (Math.max(Math.abs(dx), Math.abs(dy)) < MinSwipeDistance) {
|
||||
return;
|
||||
}
|
||||
|
||||
const swipeRight = dx > 0 && Math.abs(dy) < Math.abs(dx);
|
||||
if (swipeRight) {
|
||||
resetTouchPoints();
|
||||
|
||||
@@ -27,4 +27,9 @@ describe("getTextStats", () => {
|
||||
it("rounds reading time up to a minute for short text", () => {
|
||||
expect(getTextStats("Hello world").readingTime).toBe(1);
|
||||
});
|
||||
|
||||
it("rounds reading time up to the next minute for long text", () => {
|
||||
expect(getTextStats("word ".repeat(500)).readingTime).toBe(3);
|
||||
expect(getTextStats("word ".repeat(400)).readingTime).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -13,7 +13,7 @@ export function getTextStats(text: string) {
|
||||
words,
|
||||
characters: text.length,
|
||||
paragraphs: countParagraphs(text),
|
||||
readingTime: words ? Math.max(1, Math.floor(words / 200)) : 0,
|
||||
readingTime: Math.ceil(words / 200),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+7
-1
@@ -114,7 +114,13 @@ window.addEventListener("load", async () => {
|
||||
});
|
||||
});
|
||||
|
||||
if ("serviceWorker" in navigator && env.ENVIRONMENT !== "development") {
|
||||
// Skip registration on public share views, anonymous visitors gain nothing
|
||||
// from having the app precached.
|
||||
if (
|
||||
"serviceWorker" in navigator &&
|
||||
env.ENVIRONMENT !== "development" &&
|
||||
!env.isShare
|
||||
) {
|
||||
window.addEventListener("load", () => {
|
||||
// see: https://bugs.chromium.org/p/chromium/issues/detail?id=1097616
|
||||
// In some rare (<0.1% of cases) this call can return `undefined`
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { observer } from "mobx-react";
|
||||
import type * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type Document from "~/models/Document";
|
||||
import { ContextMenu } from "~/components/Menu/ContextMenu";
|
||||
import { ActionContextProvider } from "~/hooks/useActionContext";
|
||||
import { useDocumentActiveModels } from "~/hooks/useDocumentActiveModels";
|
||||
import { useDocumentMenuAction } from "~/hooks/useDocumentMenuAction";
|
||||
|
||||
type Props = {
|
||||
/** Document for which the menu is to be shown */
|
||||
document: Document;
|
||||
/** The element that opens the menu when right clicked */
|
||||
children: React.ReactNode;
|
||||
/** Invoked when menu is opened */
|
||||
onOpen?: () => void;
|
||||
/** Invoked when menu is closed */
|
||||
onClose?: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Wraps its children in a right click context menu offering the standard
|
||||
* document actions.
|
||||
*/
|
||||
export const DocumentContextMenu = observer(function DocumentContextMenu_({
|
||||
document,
|
||||
children,
|
||||
onOpen,
|
||||
onClose,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const action = useDocumentMenuAction({ documentId: document.id });
|
||||
const activeModels = useDocumentActiveModels(document);
|
||||
|
||||
return (
|
||||
<ActionContextProvider value={{ activeModels }}>
|
||||
<ContextMenu
|
||||
action={action}
|
||||
ariaLabel={t("Document options")}
|
||||
onOpen={onOpen}
|
||||
onClose={onClose}
|
||||
>
|
||||
{children}
|
||||
</ContextMenu>
|
||||
</ActionContextProvider>
|
||||
);
|
||||
});
|
||||
+51
-16
@@ -10,9 +10,15 @@ import type Document from "~/models/Document";
|
||||
import type Template from "~/models/Template";
|
||||
import { DropdownMenu } from "~/components/Menu/DropdownMenu";
|
||||
import { OverflowMenuButton } from "~/components/Menu/OverflowMenuButton";
|
||||
import { toMenuItems, toMobileMenuItems } from "~/components/Menu/transformer";
|
||||
import Switch from "~/components/Switch";
|
||||
import { ActionContextProvider } from "~/hooks/useActionContext";
|
||||
import { actionToMenuItem } from "~/actions";
|
||||
import { changeHeadingPrefix } from "~/actions/definitions/documents";
|
||||
import useActionContext, {
|
||||
ActionContextProvider,
|
||||
} from "~/hooks/useActionContext";
|
||||
import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
import { useDocumentActiveModels } from "~/hooks/useDocumentActiveModels";
|
||||
import useMobile from "~/hooks/useMobile";
|
||||
import usePolicy from "~/hooks/usePolicy";
|
||||
import useRequest from "~/hooks/useRequest";
|
||||
@@ -60,13 +66,8 @@ function DocumentMenu({
|
||||
const isMobile = useMobile();
|
||||
const can = usePolicy(document);
|
||||
|
||||
const { userMemberships, groupMemberships, subscriptions, pins } =
|
||||
useStores();
|
||||
|
||||
const isShared = !!(
|
||||
userMemberships.getByDocumentId(document.id) ||
|
||||
groupMemberships.getByDocumentId(document.id)
|
||||
);
|
||||
const { subscriptions, pins } = useStores();
|
||||
const activeModels = useDocumentActiveModels(document);
|
||||
|
||||
const {
|
||||
loading: auxDataLoading,
|
||||
@@ -128,6 +129,7 @@ function DocumentMenu({
|
||||
|
||||
const rootAction = useDocumentMenuAction({
|
||||
documentId: document.id,
|
||||
isViewing: showDisplayOptions,
|
||||
onFindAndReplace,
|
||||
onRename,
|
||||
onSelectTemplate,
|
||||
@@ -141,6 +143,7 @@ function DocumentMenu({
|
||||
return (
|
||||
<>
|
||||
<MenuSeparator />
|
||||
{showDisplayOptions && <HeadingPrefixMenuItem />}
|
||||
<DisplayOptions>
|
||||
{can.updateInsights && (
|
||||
<Style>
|
||||
@@ -197,14 +200,7 @@ function DocumentMenu({
|
||||
]);
|
||||
|
||||
return (
|
||||
<ActionContextProvider
|
||||
value={{
|
||||
activeModels: [
|
||||
document,
|
||||
...(!isShared && document.collection ? [document.collection] : []),
|
||||
],
|
||||
}}
|
||||
>
|
||||
<ActionContextProvider value={{ activeModels }}>
|
||||
<DropdownMenu
|
||||
action={rootAction}
|
||||
align={align}
|
||||
@@ -222,6 +218,45 @@ function DocumentMenu({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the heading numbering submenu as part of the display options block.
|
||||
* A separate component so the action context is read inside the provider.
|
||||
*/
|
||||
const HeadingPrefixMenuItem = observer(function HeadingPrefixMenuItem_() {
|
||||
const context = useActionContext({ isMenu: true });
|
||||
const isMobile = useMobile();
|
||||
const item = actionToMenuItem(changeHeadingPrefix, context);
|
||||
|
||||
// On mobile the display options are appended to a drawer rather than to menu
|
||||
// content, so there is no menu root for the submenu primitives to attach to.
|
||||
// Flatten the submenu into an inline group of options instead, which also
|
||||
// matches the toggles it sits alongside — picking one leaves the drawer open.
|
||||
if (isMobile) {
|
||||
if (item.type !== "submenu") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{toMobileMenuItems(
|
||||
[
|
||||
{
|
||||
type: "group",
|
||||
title: item.title,
|
||||
visible: item.visible,
|
||||
items: item.items,
|
||||
},
|
||||
],
|
||||
noop,
|
||||
noop
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{toMenuItems([item])}</>;
|
||||
});
|
||||
|
||||
const ToggleMenuItem = styled(Switch)`
|
||||
* {
|
||||
font-weight: normal;
|
||||
|
||||
@@ -4,6 +4,9 @@ import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import styled from "styled-components";
|
||||
import { EmojiText } from "@shared/components/EmojiText";
|
||||
import { HeadingPrefixHelper } from "@shared/editor/extensions/HeadingPrefix";
|
||||
import { s } from "@shared/styles";
|
||||
import { DocumentPreference, HeadingPrefixStyle } from "@shared/types";
|
||||
import { createAction, createActionGroup } from "~/actions";
|
||||
import { ActiveDocumentSection } from "~/actions/sections";
|
||||
import Button from "~/components/Button";
|
||||
@@ -13,39 +16,58 @@ import { useMenuAction } from "~/hooks/useMenuAction";
|
||||
import history, { patchLocation } from "~/utils/history";
|
||||
|
||||
function TableOfContentsMenu() {
|
||||
const { headings } = useDocumentContext();
|
||||
const documentContext = useDocumentContext();
|
||||
// Headings inside tables carry no number and are not listed.
|
||||
const headings = useMemo(
|
||||
() => documentContext.headings.filter((heading) => !heading.inTable),
|
||||
[documentContext.headings]
|
||||
);
|
||||
const { t } = useTranslation();
|
||||
const minHeading = headings.reduce(
|
||||
(memo, heading) => (heading.level < memo ? heading.level : memo),
|
||||
Infinity
|
||||
);
|
||||
const headingPrefix =
|
||||
documentContext.document?.getPreference(DocumentPreference.HeadingPrefix) ??
|
||||
HeadingPrefixStyle.None;
|
||||
|
||||
const headingActions = useMemo(
|
||||
() =>
|
||||
headings
|
||||
.filter((heading) => heading.level < 4)
|
||||
.map((heading) =>
|
||||
createAction({
|
||||
name: (
|
||||
<HeadingWrapper $level={heading.level - minHeading}>
|
||||
<EmojiText>{heading.title}</EmojiText>
|
||||
</HeadingWrapper>
|
||||
),
|
||||
section: ActiveDocumentSection,
|
||||
perform: () =>
|
||||
const headingActions = useMemo(() => {
|
||||
// Compute prefix labels over all headings so they match the numbering
|
||||
// shown in the document, then attach them before headings are filtered.
|
||||
const labels =
|
||||
headingPrefix === HeadingPrefixStyle.None
|
||||
? undefined
|
||||
: HeadingPrefixHelper.labels(
|
||||
headings.map((heading) => heading.level),
|
||||
headingPrefix,
|
||||
{ indented: true }
|
||||
);
|
||||
|
||||
return headings
|
||||
.map((heading, index) => ({ heading, label: labels?.[index] }))
|
||||
.filter(({ heading }) => heading.level <= 4)
|
||||
.map(({ heading, label }) =>
|
||||
createAction({
|
||||
name: (
|
||||
<HeadingWrapper $level={heading.level - minHeading}>
|
||||
{label && <Prefix>{label}</Prefix>}
|
||||
<EmojiText>{heading.title}</EmojiText>
|
||||
</HeadingWrapper>
|
||||
),
|
||||
section: ActiveDocumentSection,
|
||||
perform: () =>
|
||||
requestAnimationFrame(() =>
|
||||
requestAnimationFrame(() =>
|
||||
requestAnimationFrame(() =>
|
||||
// Navigate via history so the location state (active sidebar
|
||||
// context) is retained when scrolling to the heading.
|
||||
history.push(
|
||||
patchLocation(history.location, { hash: `#${heading.id}` })
|
||||
)
|
||||
// Navigate via history so the location state (active sidebar
|
||||
// context) is retained when scrolling to the heading.
|
||||
history.push(
|
||||
patchLocation(history.location, { hash: `#${heading.id}` })
|
||||
)
|
||||
),
|
||||
})
|
||||
),
|
||||
[headings, minHeading]
|
||||
);
|
||||
)
|
||||
),
|
||||
})
|
||||
);
|
||||
}, [headings, minHeading, headingPrefix]);
|
||||
|
||||
const actions = useMemo(() => {
|
||||
let childActions = headingActions;
|
||||
@@ -87,6 +109,12 @@ function TableOfContentsMenu() {
|
||||
);
|
||||
}
|
||||
|
||||
const Prefix = styled.span`
|
||||
color: ${s("textSecondary")};
|
||||
margin-inline-end: 0.25em;
|
||||
user-select: none;
|
||||
`;
|
||||
|
||||
const HeadingWrapper = styled.div<{ $level?: number }>`
|
||||
max-width: 100%;
|
||||
white-space: normal;
|
||||
|
||||
@@ -8,11 +8,14 @@ import type {
|
||||
ProsemirrorData,
|
||||
} from "@shared/types";
|
||||
import {
|
||||
type DocumentPreference,
|
||||
type DocumentPreferences,
|
||||
type ExportContentType,
|
||||
FileOperationFormat,
|
||||
NavigationNodeType,
|
||||
NotificationEventType,
|
||||
} from "@shared/types";
|
||||
import { DocumentPreferenceDefaults } from "@shared/constants";
|
||||
import Storage from "@shared/utils/Storage";
|
||||
import { isRTL } from "@shared/utils/rtl";
|
||||
import slugify from "@shared/utils/slugify";
|
||||
@@ -155,6 +158,13 @@ export default class Document extends ArchivableModel implements Searchable {
|
||||
@observable
|
||||
fullWidth: boolean;
|
||||
|
||||
/**
|
||||
* Display preferences for the document.
|
||||
*/
|
||||
@Field
|
||||
@observable
|
||||
preferences: DocumentPreferences | null;
|
||||
|
||||
/**
|
||||
* Whether team members can see who has viewed this document.
|
||||
*/
|
||||
@@ -194,6 +204,14 @@ export default class Document extends ArchivableModel implements Searchable {
|
||||
@observable
|
||||
updatedBy: User | undefined;
|
||||
|
||||
/**
|
||||
* The user that deleted this document, only set while the document is in the
|
||||
* trash.
|
||||
*/
|
||||
@Relation(() => User)
|
||||
@observable
|
||||
deletedBy: User | undefined;
|
||||
|
||||
@observable
|
||||
publishedAt: string | undefined;
|
||||
|
||||
@@ -477,6 +495,34 @@ export default class Document extends ArchivableModel implements Searchable {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the value for a specific display preference key, or the default if
|
||||
* none is set.
|
||||
*
|
||||
* @param key The DocumentPreference key to retrieve
|
||||
* @returns The value
|
||||
*/
|
||||
getPreference<K extends DocumentPreference>(key: K): DocumentPreferences[K] {
|
||||
return this.preferences?.[key] ?? DocumentPreferenceDefaults[key];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the value for a specific display preference key.
|
||||
*
|
||||
* @param key The DocumentPreference key to set
|
||||
* @param value The value to set
|
||||
*/
|
||||
@action
|
||||
setPreference<K extends DocumentPreference>(
|
||||
key: K,
|
||||
value: NonNullable<DocumentPreferences[K]>
|
||||
) {
|
||||
this.preferences = {
|
||||
...this.preferences,
|
||||
[key]: value,
|
||||
};
|
||||
}
|
||||
|
||||
archive = () => this.store.archive(this);
|
||||
|
||||
restore = (options?: { revisionId?: string; collectionId?: string }) =>
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { observer } from "mobx-react";
|
||||
import { GlobeIcon, PadlockIcon, TeamIcon } from "outline-icons";
|
||||
import { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import styled from "styled-components";
|
||||
import breakpoint from "styled-components-breakpoint";
|
||||
import { flattenTree } from "@shared/utils/tree";
|
||||
import type Collection from "~/models/Collection";
|
||||
import Flex from "~/components/Flex";
|
||||
import { HeaderMeta, Separator } from "~/components/HeaderMeta";
|
||||
import Tooltip from "~/components/Tooltip";
|
||||
import useCurrentTeam from "~/hooks/useCurrentTeam";
|
||||
import useStores from "~/hooks/useStores";
|
||||
|
||||
type Props = {
|
||||
/** The collection to display meta information for */
|
||||
collection: Collection;
|
||||
};
|
||||
|
||||
/**
|
||||
* A line of meta information about a collection, rendered directly beneath its
|
||||
* title to match the equivalent display for documents.
|
||||
*/
|
||||
export const CollectionMeta = observer(function CollectionMeta_({
|
||||
collection,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { shares } = useStores();
|
||||
const team = useCurrentTeam();
|
||||
|
||||
const share = shares.getByCollectionId(collection.id);
|
||||
const isPubliclyShared =
|
||||
team.sharing !== false &&
|
||||
collection.sharing !== false &&
|
||||
!!share?.published;
|
||||
|
||||
// The document structure is cached on the collection once loaded, so this is
|
||||
// a no-op when the sidebar or another tab has already requested it.
|
||||
useEffect(() => {
|
||||
void collection.fetchDocuments();
|
||||
}, [collection]);
|
||||
|
||||
const documentCount = collection.documents
|
||||
? flattenTree(collection.asNavigationNode).length - 1
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<Meta align="center" dir="ltr">
|
||||
<Tooltip
|
||||
content={
|
||||
collection.isPrivate
|
||||
? t("Only members with access can view")
|
||||
: t("All members in the workspace can view")
|
||||
}
|
||||
placement="bottom"
|
||||
>
|
||||
<IconLabel align="center">
|
||||
{collection.isPrivate ? (
|
||||
<PadlockIcon size={18} />
|
||||
) : (
|
||||
<TeamIcon size={18} />
|
||||
)}
|
||||
{collection.isPrivate ? t("Private") : t("Workspace")}
|
||||
</IconLabel>
|
||||
</Tooltip>
|
||||
{isPubliclyShared && (
|
||||
<>
|
||||
<Separator />
|
||||
<Tooltip
|
||||
content={t("Anyone with the link can view")}
|
||||
placement="bottom"
|
||||
>
|
||||
<IconLabel align="center">
|
||||
<GlobeIcon size={18} />
|
||||
{t("Publicly shared")}
|
||||
</IconLabel>
|
||||
</Tooltip>
|
||||
</>
|
||||
)}
|
||||
{documentCount !== undefined && (
|
||||
<span>
|
||||
<Separator />
|
||||
{t("{{ count }} document", { count: documentCount })}
|
||||
</span>
|
||||
)}
|
||||
</Meta>
|
||||
);
|
||||
});
|
||||
|
||||
const IconLabel = styled(Flex)`
|
||||
gap: 2px;
|
||||
cursor: default;
|
||||
`;
|
||||
|
||||
const Meta = styled(HeaderMeta)`
|
||||
// Aligns with the collection title, which is indented on mobile.
|
||||
margin-inline-start: 16px;
|
||||
|
||||
${breakpoint("tablet")`
|
||||
margin-inline-start: 0;
|
||||
`}
|
||||
`;
|
||||
@@ -48,6 +48,7 @@ import MembershipPreview from "./components/MembershipPreview";
|
||||
import Navigation, { CollectionTab } from "./components/Navigation";
|
||||
import Notices from "./components/Notices";
|
||||
import Overview from "./components/Overview";
|
||||
import { CollectionMeta } from "./components/CollectionMeta";
|
||||
import { Header } from "./components/Header";
|
||||
import usePersistedState from "~/hooks/usePersistedState";
|
||||
import useCurrentUser from "~/hooks/useCurrentUser";
|
||||
@@ -185,8 +186,13 @@ const CollectionScene = observer(function CollectionScene_() {
|
||||
collection={collection}
|
||||
isEditing={isEditRoute || !user?.separateEditMode}
|
||||
/>
|
||||
<CollectionMeta collection={collection} />
|
||||
|
||||
<PinnedDocuments pins={pins} placeholderCount={count} />
|
||||
<PinnedDocuments
|
||||
pins={pins}
|
||||
placeholderCount={count}
|
||||
collapseKey={collection.id}
|
||||
/>
|
||||
|
||||
<Content>
|
||||
<Navigation
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { observer } from "mobx-react";
|
||||
import { transparentize } from "polished";
|
||||
import { useState, useEffect, useRef, useCallback } from "react";
|
||||
import { useState, useEffect, useMemo, useRef, useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useHistory } from "react-router-dom";
|
||||
import styled from "styled-components";
|
||||
import breakpoint from "styled-components-breakpoint";
|
||||
import { EmojiText } from "@shared/components/EmojiText";
|
||||
import { HeadingPrefixHelper } from "@shared/editor/extensions/HeadingPrefix";
|
||||
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
|
||||
import { DocumentPreference, HeadingPrefixStyle } from "@shared/types";
|
||||
import { depths, hideScrollbars, s } from "@shared/styles";
|
||||
import { supportsPassiveListener } from "@shared/utils/browser";
|
||||
import { useDocumentContext } from "~/components/DocumentContext";
|
||||
@@ -16,6 +18,9 @@ import { decodeURIComponentSafe } from "~/utils/urls";
|
||||
|
||||
const HEADING_OFFSET = 20;
|
||||
|
||||
/** Headings deeper than this level are not listed in the contents. */
|
||||
const MAX_HEADING_LEVEL = 4;
|
||||
|
||||
function Contents() {
|
||||
const history = useHistory();
|
||||
const [scrolledSlug, setScrolledSlug] = useState<string>();
|
||||
@@ -24,14 +29,42 @@ function Contents() {
|
||||
throttle: 100,
|
||||
});
|
||||
const documentContext = useDocumentContext();
|
||||
const { headings } = documentContext;
|
||||
// Headings inside tables carry no number and are not listed.
|
||||
const headings = useMemo(
|
||||
() => documentContext.headings.filter((heading) => !heading.inTable),
|
||||
[documentContext.headings]
|
||||
);
|
||||
const itemRefs = useRef<Record<string, HTMLLIElement | null>>({});
|
||||
|
||||
const headingPrefix =
|
||||
documentContext.document?.getPreference(DocumentPreference.HeadingPrefix) ??
|
||||
HeadingPrefixStyle.None;
|
||||
|
||||
// Prefix labels are computed over every heading so that they match the
|
||||
// numbering shown in the document, and attached before the deeper headings
|
||||
// are dropped. Those headings are not listed, so they also take no part in
|
||||
// tracking the active one — a reader inside a deep section keeps the nearest
|
||||
// listed heading highlighted rather than losing the highlight entirely.
|
||||
const items = useMemo(() => {
|
||||
const labels =
|
||||
headingPrefix === HeadingPrefixStyle.None
|
||||
? undefined
|
||||
: HeadingPrefixHelper.labels(
|
||||
headings.map((heading) => heading.level),
|
||||
headingPrefix,
|
||||
{ indented: true }
|
||||
);
|
||||
|
||||
return headings
|
||||
.map((heading, index) => ({ heading, label: labels?.[index] }))
|
||||
.filter(({ heading }) => heading.level <= MAX_HEADING_LEVEL);
|
||||
}, [headings, headingPrefix]);
|
||||
|
||||
// A heading chosen from the contents stays highlighted until the reader
|
||||
// scrolls themselves. Headings near the end of a document cannot reach the
|
||||
// top of the viewport, so the scroll position alone would never select them.
|
||||
const activeSlug =
|
||||
selectedSlug && headings.some((heading) => heading.id === selectedSlug)
|
||||
selectedSlug && items.some(({ heading }) => heading.id === selectedSlug)
|
||||
? selectedSlug
|
||||
: scrolledSlug;
|
||||
|
||||
@@ -87,10 +120,9 @@ function Contents() {
|
||||
}, [selectedSlug]);
|
||||
|
||||
useEffect(() => {
|
||||
let activeId = headings.length > 0 ? headings[0].id : undefined;
|
||||
let activeId = items.length > 0 ? items[0].heading.id : undefined;
|
||||
|
||||
for (let key = 0; key < headings.length; key++) {
|
||||
const heading = headings[key];
|
||||
for (const { heading } of items) {
|
||||
const element = window.document.getElementById(
|
||||
decodeURIComponentSafe(heading.id)
|
||||
);
|
||||
@@ -107,7 +139,7 @@ function Contents() {
|
||||
if (scrolledSlug !== activeId) {
|
||||
setScrolledSlug(activeId);
|
||||
}
|
||||
}, [scrollPosition, headings, scrolledSlug]);
|
||||
}, [scrollPosition, items, scrolledSlug]);
|
||||
|
||||
useEffect(() => {
|
||||
const activeItem = activeSlug ? itemRefs.current[activeSlug] : undefined;
|
||||
@@ -122,14 +154,14 @@ function Contents() {
|
||||
// calculate the minimum heading level and adjust all the headings to make
|
||||
// that the top-most. This prevents the contents from being weirdly indented
|
||||
// if all of the headings in the document start at level 3, for example.
|
||||
const minHeading = headings.reduce(
|
||||
(memo, heading) => (heading.level < memo ? heading.level : memo),
|
||||
const minHeading = items.reduce(
|
||||
(memo, { heading }) => (heading.level < memo ? heading.level : memo),
|
||||
Infinity
|
||||
);
|
||||
const headingAdjustment = minHeading - 1;
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (headings.length === 0) {
|
||||
if (items.length === 0) {
|
||||
return <StickyWrapper />;
|
||||
}
|
||||
|
||||
@@ -137,23 +169,22 @@ function Contents() {
|
||||
<StickyWrapper>
|
||||
<Heading>{t("Contents")}</Heading>
|
||||
<List>
|
||||
{headings
|
||||
.filter((heading) => heading.level < 4)
|
||||
.map((heading) => (
|
||||
<ListItem
|
||||
key={heading.id}
|
||||
ref={(el) => (itemRefs.current[heading.id] = el)}
|
||||
level={heading.level - headingAdjustment}
|
||||
active={activeSlug === heading.id}
|
||||
{items.map(({ heading, label }) => (
|
||||
<ListItem
|
||||
key={heading.id}
|
||||
ref={(el) => (itemRefs.current[heading.id] = el)}
|
||||
level={heading.level - headingAdjustment}
|
||||
active={activeSlug === heading.id}
|
||||
>
|
||||
<Link
|
||||
href={`#${heading.id}`}
|
||||
onClick={(event) => handleClick(event, heading.id)}
|
||||
>
|
||||
<Link
|
||||
href={`#${heading.id}`}
|
||||
onClick={(event) => handleClick(event, heading.id)}
|
||||
>
|
||||
<EmojiText>{heading.title}</EmojiText>
|
||||
</Link>
|
||||
</ListItem>
|
||||
))}
|
||||
{label && <Prefix>{label}</Prefix>}
|
||||
<EmojiText>{heading.title}</EmojiText>
|
||||
</Link>
|
||||
</ListItem>
|
||||
))}
|
||||
</List>
|
||||
</StickyWrapper>
|
||||
);
|
||||
@@ -192,6 +223,12 @@ const Heading = styled.h3`
|
||||
margin-top: 10px;
|
||||
`;
|
||||
|
||||
const Prefix = styled.span`
|
||||
color: ${s("textSecondary")};
|
||||
margin-inline-end: 0.25em;
|
||||
user-select: none;
|
||||
`;
|
||||
|
||||
const ListItem = styled.li<{ level: number; active?: boolean }>`
|
||||
margin-left: ${(props) => (props.level - 1) * 10}px;
|
||||
margin-bottom: 8px;
|
||||
@@ -201,6 +238,11 @@ const ListItem = styled.li<{ level: number; active?: boolean }>`
|
||||
a {
|
||||
font-weight: ${(props) => (props.active ? "600" : "inherit")};
|
||||
color: ${(props) => (props.active ? props.theme.accent : props.theme.text)};
|
||||
|
||||
${Prefix} {
|
||||
color: ${(props) =>
|
||||
props.active ? props.theme.accent : props.theme.textSecondary};
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
|
||||
@@ -206,6 +206,37 @@ function DocumentScene({
|
||||
[readOnly, abilities.update, history, document, sidebarContext]
|
||||
);
|
||||
|
||||
// Files dropped in the margins around the document are inserted at the
|
||||
// closest point in the editor, rather than being ignored by the browser.
|
||||
const isFileDrag = useCallback(
|
||||
(event: React.DragEvent<HTMLElement>) =>
|
||||
!readOnly && !revision && event.dataTransfer.types.includes("Files"),
|
||||
[readOnly, revision]
|
||||
);
|
||||
|
||||
const handleDragOver = useCallback(
|
||||
(event: React.DragEvent<HTMLElement>) => {
|
||||
if (isFileDrag(event)) {
|
||||
event.dataTransfer.dropEffect = "copy";
|
||||
event.preventDefault();
|
||||
}
|
||||
},
|
||||
[isFileDrag]
|
||||
);
|
||||
|
||||
const handleDrop = useCallback(
|
||||
(event: React.DragEvent<HTMLElement>) => {
|
||||
// A drop that landed inside the editor has already been handled.
|
||||
if (event.defaultPrevented || !isFileDrag(event)) {
|
||||
return;
|
||||
}
|
||||
// Prevent the browser from navigating to the file if it cannot be added.
|
||||
event.preventDefault();
|
||||
void editorRef.current?.insertDroppedContent(event);
|
||||
},
|
||||
[isFileDrag]
|
||||
);
|
||||
|
||||
const goToHistory = useCallback(
|
||||
(ev: KeyboardEvent) => {
|
||||
if (!readOnly) {
|
||||
@@ -315,6 +346,9 @@ function DocumentScene({
|
||||
key={revision ? revision.id : document.id}
|
||||
column
|
||||
auto
|
||||
onDragOver={handleDragOver}
|
||||
onDrop={handleDrop}
|
||||
data-drop-area
|
||||
>
|
||||
<PageTitle title={pageTitle} favicon={favicon} />
|
||||
{(isUploading || isSaving) && <LoadingIndicator />}
|
||||
|
||||
@@ -9,14 +9,18 @@ import type Document from "~/models/Document";
|
||||
import type Revision from "~/models/Revision";
|
||||
import type Template from "~/models/Template";
|
||||
import { openDocumentInsights } from "~/actions/definitions/documents";
|
||||
import DocumentMeta, { MetaButton, Separator } from "~/components/DocumentMeta";
|
||||
import DocumentMeta from "~/components/DocumentMeta";
|
||||
import {
|
||||
MetaButton,
|
||||
Separator,
|
||||
headerMetaStyles,
|
||||
} from "~/components/HeaderMeta";
|
||||
import Fade from "~/components/Fade";
|
||||
import { useSplitView } from "~/components/SplitView/context";
|
||||
import useCurrentTeam from "~/hooks/useCurrentTeam";
|
||||
import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext";
|
||||
import usePolicy from "~/hooks/usePolicy";
|
||||
import useStores from "~/hooks/useStores";
|
||||
import breakpoint from "styled-components-breakpoint";
|
||||
import { documentPath } from "~/utils/routeHelpers";
|
||||
|
||||
type Props = {
|
||||
@@ -97,35 +101,7 @@ function TitleDocumentMeta({ to, document, revision, rtl, ...rest }: Props) {
|
||||
}
|
||||
|
||||
export const Meta = styled(DocumentMeta)<{ $rtl?: boolean }>`
|
||||
justify-content: ${(props) => (props.$rtl ? "flex-end" : "flex-start")};
|
||||
margin: -12px 0 2em 0;
|
||||
font-size: 14px;
|
||||
position: relative;
|
||||
user-select: none;
|
||||
z-index: 1;
|
||||
|
||||
${breakpoint("mobile", "tablet")`
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
line-height: 1.6;
|
||||
|
||||
${Separator} {
|
||||
display: none;
|
||||
}
|
||||
`}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
cursor: var(--pointer);
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
@media print {
|
||||
display: none;
|
||||
}
|
||||
${headerMetaStyles}
|
||||
`;
|
||||
|
||||
export default observer(TitleDocumentMeta);
|
||||
@@ -7,6 +7,7 @@ import styled from "styled-components";
|
||||
import Text from "@shared/components/Text";
|
||||
import type { CommentAnchor } from "@shared/editor/commands/comment";
|
||||
import { richExtensions, withComments } from "@shared/editor/nodes";
|
||||
import { DocumentPreference } from "@shared/types";
|
||||
import { colorPalette } from "@shared/constants";
|
||||
import Comment from "~/models/Comment";
|
||||
import type Document from "~/models/Document";
|
||||
@@ -280,6 +281,11 @@ function DocumentEditor(props: Props, ref: React.ForwardedRef<SharedEditor>) {
|
||||
onInit={handleInit}
|
||||
onDestroy={handleDestroy}
|
||||
onChange={updateDocState}
|
||||
headingPrefix={
|
||||
"preferences" in document
|
||||
? document.getPreference(DocumentPreference.HeadingPrefix)
|
||||
: undefined
|
||||
}
|
||||
extensions={extensions}
|
||||
editorStyle={editorStyle}
|
||||
{...rest}
|
||||
|
||||
@@ -342,6 +342,7 @@ function MultiplayerEditor(
|
||||
defaultValue={props.defaultValue}
|
||||
extensions={props.extensions}
|
||||
scrollTo={props.scrollTo}
|
||||
headingPrefix={props.headingPrefix}
|
||||
cacheOnly
|
||||
readOnly
|
||||
ref={ref}
|
||||
|
||||
@@ -65,7 +65,7 @@ export default function Notices({ document }: Props) {
|
||||
description={permanentlyDeletedDescription()}
|
||||
>
|
||||
{t("Deleted by {{userName}}", {
|
||||
userName: document.updatedBy?.name ?? t("Unknown"),
|
||||
userName: document.deletedBy?.name ?? t("Unknown"),
|
||||
})}
|
||||
|
||||
<Time dateTime={document.deletedAt} addSuffix />
|
||||
|
||||
@@ -119,13 +119,17 @@ export default function useDocumentSidebar() {
|
||||
? documents.get(slugMatch.params.documentSlug)
|
||||
: undefined;
|
||||
if (document) {
|
||||
paneHistory.push(documentPath(document));
|
||||
paneHistory.push({
|
||||
pathname: documentPath(document),
|
||||
state: location.state,
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [
|
||||
panel,
|
||||
isHistoryRoute,
|
||||
location.pathname,
|
||||
location.state,
|
||||
documents,
|
||||
paneHistory,
|
||||
ui,
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Trans, useTranslation } from "react-i18next";
|
||||
import { useHistory, useLocation } from "react-router-dom";
|
||||
import { toast } from "sonner";
|
||||
import styled from "styled-components";
|
||||
import type { Filter } from "@shared/helpers/FilterHelper";
|
||||
import type UsersStore from "~/stores/UsersStore";
|
||||
import { queriedUsers } from "~/stores/UsersStore";
|
||||
import { Action } from "~/components/Actions";
|
||||
@@ -40,17 +41,19 @@ function Users() {
|
||||
const can = usePolicy(team);
|
||||
const [query, setQuery] = useState("");
|
||||
|
||||
const status = params.get("filter") || "active";
|
||||
const role = params.get("role") || undefined;
|
||||
|
||||
const reqParams = useMemo(
|
||||
() => ({
|
||||
query: params.get("query") || undefined,
|
||||
filter: params.get("filter") || "active",
|
||||
role: params.get("role") || undefined,
|
||||
filters: getUserFilters({ status, role }),
|
||||
sort: params.get("sort") || "name",
|
||||
direction: (params.get("direction") || "asc").toUpperCase() as
|
||||
| "ASC"
|
||||
| "DESC",
|
||||
}),
|
||||
[params]
|
||||
[params, status, role]
|
||||
);
|
||||
|
||||
const sort: ColumnSort = useMemo(
|
||||
@@ -65,8 +68,8 @@ function Users() {
|
||||
data: getFilteredUsers({
|
||||
users,
|
||||
query: reqParams.query,
|
||||
filter: reqParams.filter,
|
||||
role: reqParams.role,
|
||||
filter: status,
|
||||
role,
|
||||
}),
|
||||
sort,
|
||||
reqFn: users.fetchPage,
|
||||
@@ -156,11 +159,11 @@ function Users() {
|
||||
onChange={handleSearch}
|
||||
/>
|
||||
<LargeUserStatusFilter
|
||||
activeKey={reqParams.filter ?? ""}
|
||||
activeKey={status}
|
||||
onSelect={handleStatusFilter}
|
||||
/>
|
||||
<LargeUserRoleFilter
|
||||
activeKey={reqParams.role ?? ""}
|
||||
activeKey={role ?? ""}
|
||||
onSelect={handleRoleFilter}
|
||||
/>
|
||||
</HStack>
|
||||
@@ -182,6 +185,47 @@ function Users() {
|
||||
);
|
||||
}
|
||||
|
||||
function getUserFilters({
|
||||
status,
|
||||
role,
|
||||
}: {
|
||||
status: string;
|
||||
role?: string;
|
||||
}): Filter[] {
|
||||
const filters: Filter[] = [];
|
||||
|
||||
if (role) {
|
||||
filters.push({ field: "role", operator: "eq", value: role });
|
||||
}
|
||||
|
||||
switch (status) {
|
||||
case "all":
|
||||
// Suspended users are excluded unless the expression references
|
||||
// suspendedAt, so match on either state.
|
||||
filters.push({
|
||||
operator: "OR",
|
||||
filters: [
|
||||
{ field: "suspendedAt", operator: "isNull" },
|
||||
{ field: "suspendedAt", operator: "isNotNull" },
|
||||
],
|
||||
});
|
||||
break;
|
||||
case "suspended":
|
||||
filters.push({ field: "suspendedAt", operator: "isNotNull" });
|
||||
break;
|
||||
case "invited":
|
||||
filters.push({ field: "lastActiveAt", operator: "isNull" });
|
||||
break;
|
||||
default:
|
||||
filters.push(
|
||||
{ field: "lastActiveAt", operator: "isNotNull" },
|
||||
{ field: "suspendedAt", operator: "isNull" }
|
||||
);
|
||||
}
|
||||
|
||||
return filters;
|
||||
}
|
||||
|
||||
function getFilteredUsers({
|
||||
users,
|
||||
query,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useCallback, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import Button from "~/components/Button";
|
||||
import type { Filter } from "@shared/helpers/FilterHelper";
|
||||
import { CSVHelper } from "@shared/utils/csv";
|
||||
import { download } from "~/utils/download";
|
||||
import useStores from "~/hooks/useStores";
|
||||
@@ -12,8 +13,7 @@ type Props = {
|
||||
/** Request parameters for filtering users */
|
||||
reqParams: {
|
||||
query?: string;
|
||||
filter?: string;
|
||||
role?: string;
|
||||
filters?: Filter[];
|
||||
sort?: string;
|
||||
direction?: "ASC" | "DESC";
|
||||
};
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import invariant from "invariant";
|
||||
import { isEmpty, orderBy, sortBy } from "es-toolkit/compat";
|
||||
import { computed, action, runInAction } from "mobx";
|
||||
import type { Filter } from "@shared/helpers/FilterHelper";
|
||||
import {
|
||||
CollectionPermission,
|
||||
CollectionStatusFilter,
|
||||
type FileOperationFormat,
|
||||
SubscriptionType,
|
||||
} from "@shared/types";
|
||||
@@ -166,9 +166,7 @@ export default class CollectionsStore extends Store<Collection> {
|
||||
@action
|
||||
fetchNamedPage = async (
|
||||
request = "list",
|
||||
options:
|
||||
| (PaginationParams & { statusFilter: CollectionStatusFilter[] })
|
||||
| undefined
|
||||
options: (PaginationParams & { filters?: Filter[] }) | undefined
|
||||
): Promise<Collection[]> => {
|
||||
this.isFetching = true;
|
||||
|
||||
@@ -190,7 +188,7 @@ export default class CollectionsStore extends Store<Collection> {
|
||||
fetchArchived = async (options?: PaginationParams): Promise<Collection[]> =>
|
||||
this.fetchNamedPage("list", {
|
||||
...options,
|
||||
statusFilter: [CollectionStatusFilter.Archived],
|
||||
filters: [{ field: "archivedAt", operator: "isNotNull" }],
|
||||
});
|
||||
|
||||
get(id: string = ""): Collection | undefined {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
/* oxlint-disable */
|
||||
import stores from "~/stores";
|
||||
|
||||
describe("DocumentsStore", () => {
|
||||
describe("deleted", () => {
|
||||
test("should filter by the user that deleted the document", () => {
|
||||
const deleter = stores.users.add({
|
||||
id: "22222222-2222-2222-2222-222222222222",
|
||||
name: "Deleter",
|
||||
});
|
||||
const other = stores.users.add({
|
||||
id: "33333333-3333-3333-3333-333333333333",
|
||||
name: "Other",
|
||||
});
|
||||
|
||||
const mine = stores.documents.add({
|
||||
id: "11111111-1111-1111-1111-111111111111",
|
||||
title: "Deleted by me",
|
||||
deletedAt: "2026-08-18T00:00:00.000Z",
|
||||
deletedBy: deleter,
|
||||
});
|
||||
stores.documents.add({
|
||||
id: "44444444-4444-4444-4444-444444444444",
|
||||
title: "Deleted by someone else",
|
||||
deletedAt: "2026-08-18T00:00:00.000Z",
|
||||
deletedBy: other,
|
||||
});
|
||||
|
||||
const results = stores.documents.deleted({ userId: deleter.id });
|
||||
expect(results.map((doc) => doc.id)).toEqual([mine.id]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,6 @@ import { adjustIndexForMove } from "@shared/utils/collections";
|
||||
import { subtractDate } from "@shared/utils/date";
|
||||
import { bytesToHumanReadable } from "@shared/utils/files";
|
||||
import naturalSort from "@shared/utils/naturalSort";
|
||||
import type { JSONObject } from "@shared/types";
|
||||
import type RootStore from "~/stores/RootStore";
|
||||
import Store from "~/stores/base/Store";
|
||||
import Document from "~/models/Document";
|
||||
@@ -249,11 +248,10 @@ export default class DocumentsStore extends Store<Document> {
|
||||
(d) => d.deletedAt
|
||||
);
|
||||
|
||||
// The deleting user is recorded as the last to modify the document.
|
||||
if (options.userId) {
|
||||
deleted = filter(
|
||||
deleted,
|
||||
(document) => document.updatedBy?.id === options.userId
|
||||
(document) => document.deletedBy?.id === options.userId
|
||||
);
|
||||
}
|
||||
|
||||
@@ -456,7 +454,7 @@ export default class DocumentsStore extends Store<Document> {
|
||||
|
||||
@action
|
||||
searchTitles = async (options?: SearchParams): Promise<SearchResult[]> => {
|
||||
const compactedOptions = omitBy(options, (o) => !o) as JSONObject;
|
||||
const compactedOptions = omitBy(options, (o) => !o);
|
||||
const res = await client.post("/documents.search_titles", {
|
||||
...compactedOptions,
|
||||
});
|
||||
@@ -487,7 +485,7 @@ export default class DocumentsStore extends Store<Document> {
|
||||
|
||||
@action
|
||||
search = async (options: SearchParams): Promise<SearchResult[]> => {
|
||||
const compactedOptions = omitBy(options, (o) => !o) as JSONObject;
|
||||
const compactedOptions = omitBy(options, (o) => !o);
|
||||
const res = await client.post("/documents.search", {
|
||||
...compactedOptions,
|
||||
});
|
||||
@@ -680,11 +678,11 @@ export default class DocumentsStore extends Store<Document> {
|
||||
// acting user against the document and its descendants. The trash relies
|
||||
// on this to filter by who deleted an item before the next fetch.
|
||||
const user = this.rootStore.auth.user ?? undefined;
|
||||
const setUpdatedBy = (doc: Document) => {
|
||||
doc.updatedBy = user;
|
||||
doc.childDocuments.forEach(setUpdatedBy);
|
||||
const setDeletedBy = (doc: Document) => {
|
||||
doc.deletedBy = user;
|
||||
doc.childDocuments.forEach(setDeletedBy);
|
||||
};
|
||||
setUpdatedBy(document);
|
||||
setDeletedBy(document);
|
||||
}
|
||||
|
||||
// check to see if we have any shares related to this document already
|
||||
|
||||
@@ -137,6 +137,18 @@ export default class RootStore {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable IndexedDB persistence for all stores, closing any open connections
|
||||
* so that the databases can be deleted or upgraded.
|
||||
*/
|
||||
public disablePersistence() {
|
||||
Object.values(this).forEach((store) => {
|
||||
if (store instanceof Store) {
|
||||
store.disablePersistence();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a store by model name.
|
||||
*
|
||||
|
||||
@@ -132,6 +132,16 @@ export default abstract class Store<T extends Model> {
|
||||
await this.persistence.hydrate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables persistence of this store's data, closing the connection to the
|
||||
* database without removing anything that was already persisted. Safe to call
|
||||
* whether or not persistence is currently enabled.
|
||||
*/
|
||||
disablePersistence(): void {
|
||||
this.persistence?.disable();
|
||||
this.persistence = undefined;
|
||||
}
|
||||
|
||||
addPolicies = (policies: Policy[]) => {
|
||||
policies?.forEach((policy) => this.rootStore.policies.add(policy));
|
||||
};
|
||||
|
||||
@@ -141,6 +141,89 @@ describe("StorePersistence", () => {
|
||||
expect(other.policies.get("doc-1")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("reopens the database after the connection is closed underneath it", async () => {
|
||||
const teamId = "team-8";
|
||||
const source = new RootStore();
|
||||
const persistence = new StorePersistence(source.policies, teamId);
|
||||
const opened: IDBDatabase[] = [];
|
||||
const open = indexedDB.open.bind(indexedDB);
|
||||
vi.spyOn(indexedDB, "open").mockImplementation((...args) => {
|
||||
const request = open(...args);
|
||||
request.addEventListener("success", () => opened.push(request.result));
|
||||
return request;
|
||||
});
|
||||
|
||||
source.policies.add({ id: "doc-1", abilities: { read: true } });
|
||||
persistence.persist("doc-1");
|
||||
await persistence.flush();
|
||||
|
||||
// Closing the connection directly leaves a stale one cached, as the browser
|
||||
// does when it reclaims storage – no close event is fired.
|
||||
opened.forEach((database) => database.close());
|
||||
|
||||
source.policies.add({ id: "doc-2", abilities: { read: true } });
|
||||
persistence.persist("doc-2");
|
||||
await persistence.flush();
|
||||
|
||||
expect(
|
||||
await readAll(
|
||||
StorePersistence.databaseName(source.policies.apiEndpoint, teamId)
|
||||
)
|
||||
).toHaveLength(2);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("does not recreate the database from a pending flush once disabled", async () => {
|
||||
const teamId = "team-10";
|
||||
const source = new RootStore();
|
||||
const persistence = new StorePersistence(source.policies, teamId);
|
||||
const databaseName = StorePersistence.databaseName(
|
||||
source.policies.apiEndpoint,
|
||||
teamId
|
||||
);
|
||||
|
||||
source.policies.add({ id: "doc-1", abilities: { read: true } });
|
||||
persistence.persist("doc-1");
|
||||
|
||||
// Disabling while a debounced write is still scheduled, as logout does.
|
||||
persistence.disable();
|
||||
await new Promise((resolve) => setTimeout(resolve, 1100));
|
||||
|
||||
const databases = await indexedDB.databases();
|
||||
expect(databases.map((database) => database.name)).not.toContain(
|
||||
databaseName
|
||||
);
|
||||
});
|
||||
|
||||
it("does not block another tab from deleting the database", async () => {
|
||||
const teamId = "team-9";
|
||||
const source = new RootStore();
|
||||
const persistence = new StorePersistence(source.policies, teamId);
|
||||
const databaseName = StorePersistence.databaseName(
|
||||
source.policies.apiEndpoint,
|
||||
teamId
|
||||
);
|
||||
|
||||
source.policies.add({ id: "doc-1", abilities: { read: true } });
|
||||
persistence.persist("doc-1");
|
||||
await persistence.flush();
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
const request = indexedDB.deleteDatabase(databaseName);
|
||||
request.onsuccess = () => resolve(undefined);
|
||||
request.onerror = () => reject(request.error);
|
||||
request.onblocked = () => reject(new Error("Deletion was blocked"));
|
||||
});
|
||||
|
||||
source.policies.add({ id: "doc-2", abilities: { read: true } });
|
||||
persistence.persist("doc-2");
|
||||
await persistence.flush();
|
||||
|
||||
expect(await readAll(databaseName)).toEqual([
|
||||
{ id: "doc-2", abilities: { read: true } },
|
||||
]);
|
||||
});
|
||||
|
||||
it("clear removes all persisted records", async () => {
|
||||
const teamId = "team-4";
|
||||
const source = new RootStore();
|
||||
@@ -160,6 +243,27 @@ describe("StorePersistence", () => {
|
||||
|
||||
expect(target.policies.orderedData).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("clear leaves no database behind for a closed connection to fail against", async () => {
|
||||
const teamId = "team-11";
|
||||
const source = new RootStore();
|
||||
const persistence = new StorePersistence(source.policies, teamId);
|
||||
const databaseName = StorePersistence.databaseName(
|
||||
source.policies.apiEndpoint,
|
||||
teamId
|
||||
);
|
||||
|
||||
source.policies.add({ id: "doc-1", abilities: { read: true } });
|
||||
persistence.persist("doc-1");
|
||||
await persistence.flush();
|
||||
|
||||
await persistence.clear();
|
||||
|
||||
const databases = await indexedDB.databases();
|
||||
expect(databases.map((database) => database.name)).not.toContain(
|
||||
databaseName
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
/** Writes raw records into a database, bypassing the store. */
|
||||
|
||||
@@ -49,12 +49,8 @@ export default class StorePersistence<T extends Model> {
|
||||
*/
|
||||
public hydrate = async (): Promise<void> => {
|
||||
try {
|
||||
const database = await this.open();
|
||||
const records = await promisifyRequest<Record<string, unknown>[]>(
|
||||
database
|
||||
.transaction(OBJECT_STORE_NAME, "readonly")
|
||||
.objectStore(OBJECT_STORE_NAME)
|
||||
.getAll()
|
||||
const records = await this.transaction("readonly", (objectStore) =>
|
||||
promisifyRequest<Record<string, unknown>[]>(objectStore.getAll())
|
||||
);
|
||||
|
||||
this.hydrating = true;
|
||||
@@ -66,11 +62,11 @@ export default class StorePersistence<T extends Model> {
|
||||
this.store.add(this.store.model.fromPersisted<T>(record));
|
||||
}
|
||||
} catch (err) {
|
||||
this.disabled = true;
|
||||
Logger.warn("Failed to hydrate store from IndexedDB", {
|
||||
database: this.name,
|
||||
error: err,
|
||||
});
|
||||
// A closed connection is transient, a later write reopens the database.
|
||||
if (!isConnectionClosedError(err)) {
|
||||
this.disabled = true;
|
||||
}
|
||||
this.report("Failed to hydrate store from IndexedDB", err);
|
||||
} finally {
|
||||
this.hydrating = false;
|
||||
}
|
||||
@@ -106,25 +102,20 @@ export default class StorePersistence<T extends Model> {
|
||||
this.dirty.clear();
|
||||
|
||||
try {
|
||||
const database = await this.open();
|
||||
const transaction = database.transaction(OBJECT_STORE_NAME, "readwrite");
|
||||
const objectStore = transaction.objectStore(OBJECT_STORE_NAME);
|
||||
|
||||
for (const id of ids) {
|
||||
const model = this.store.get(id);
|
||||
if (model) {
|
||||
objectStore.put(model.toPersisted());
|
||||
} else {
|
||||
objectStore.delete(id);
|
||||
await this.transaction("readwrite", (objectStore) => {
|
||||
for (const id of ids) {
|
||||
const model = this.store.get(id);
|
||||
if (model) {
|
||||
objectStore.put(model.toPersisted());
|
||||
} else {
|
||||
objectStore.delete(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await promisifyTransaction(transaction);
|
||||
} catch (err) {
|
||||
Logger.warn("Failed to write store to IndexedDB", {
|
||||
database: this.name,
|
||||
error: err,
|
||||
return promisifyTransaction(objectStore.transaction);
|
||||
});
|
||||
} catch (err) {
|
||||
this.report("Failed to write store to IndexedDB", err);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -135,21 +126,87 @@ export default class StorePersistence<T extends Model> {
|
||||
*/
|
||||
public clear = async (): Promise<void> => {
|
||||
this.dirty.clear();
|
||||
this.scheduleFlush.cancel();
|
||||
|
||||
if (this.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
// The database is deleted rather than emptied through a transaction, as a
|
||||
// deletion cannot fail against a connection the browser has closed.
|
||||
this.close();
|
||||
|
||||
try {
|
||||
const database = await this.open();
|
||||
const transaction = database.transaction(OBJECT_STORE_NAME, "readwrite");
|
||||
transaction.objectStore(OBJECT_STORE_NAME).clear();
|
||||
await promisifyTransaction(transaction);
|
||||
} catch (err) {
|
||||
Logger.warn("Failed to clear persisted store in IndexedDB", {
|
||||
database: this.name,
|
||||
error: err,
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const request = window.indexedDB.deleteDatabase(this.name);
|
||||
request.onsuccess = () => resolve();
|
||||
request.onerror = () => reject(request.error);
|
||||
// Another tab holds a connection, which it closes in response to the
|
||||
// versionchange event, and the deletion completes without us.
|
||||
request.onblocked = () => resolve();
|
||||
});
|
||||
} catch (err) {
|
||||
this.report("Failed to clear persisted store in IndexedDB", err);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Stops persisting the store's data and closes the connection to the
|
||||
* database, discarding any writes that have not yet been made. Records that
|
||||
* were already persisted are left untouched.
|
||||
*/
|
||||
public disable = () => {
|
||||
this.disabled = true;
|
||||
this.dirty.clear();
|
||||
this.scheduleFlush.cancel();
|
||||
this.close();
|
||||
};
|
||||
|
||||
/**
|
||||
* Closes the connection to the database, if one is open. Safe to call at any
|
||||
* time; a later read or write opens a fresh connection.
|
||||
*/
|
||||
private close = () => {
|
||||
this.connection?.close();
|
||||
this.forget();
|
||||
};
|
||||
|
||||
/**
|
||||
* Runs an operation against the object store. The connection is opened once
|
||||
* and reused, but it may be closed at any time by the browser or by another
|
||||
* tab deleting the database, so a closed connection is reopened for a single
|
||||
* retry.
|
||||
*
|
||||
* @param mode the mode the transaction should run in.
|
||||
* @param run the operation to run against the object store.
|
||||
* @returns a promise that resolves with the result of the operation.
|
||||
*/
|
||||
private transaction = async <R>(
|
||||
mode: IDBTransactionMode,
|
||||
run: (objectStore: IDBObjectStore) => Promise<R>
|
||||
): Promise<R> => {
|
||||
try {
|
||||
return await run(await this.objectStore(mode));
|
||||
} catch (err) {
|
||||
if (!isConnectionClosedError(err)) {
|
||||
throw err;
|
||||
}
|
||||
this.close();
|
||||
return run(await this.objectStore(mode));
|
||||
}
|
||||
};
|
||||
|
||||
private objectStore = async (
|
||||
mode: IDBTransactionMode
|
||||
): Promise<IDBObjectStore> => {
|
||||
const database = await this.open();
|
||||
try {
|
||||
return database
|
||||
.transaction(OBJECT_STORE_NAME, mode)
|
||||
.objectStore(OBJECT_STORE_NAME);
|
||||
} catch (err) {
|
||||
this.forget();
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -165,13 +222,64 @@ export default class StorePersistence<T extends Model> {
|
||||
}
|
||||
database.createObjectStore(OBJECT_STORE_NAME, { keyPath: "id" });
|
||||
};
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
request.onsuccess = () => {
|
||||
const database = request.result;
|
||||
this.connection = database;
|
||||
|
||||
// Another tab is deleting or upgrading the database – get out of the
|
||||
// way, rather than blocking it, and reopen when next needed.
|
||||
database.onversionchange = () => {
|
||||
database.close();
|
||||
this.forget(database);
|
||||
};
|
||||
database.onclose = () => this.forget(database);
|
||||
|
||||
resolve(database);
|
||||
};
|
||||
request.onerror = () => {
|
||||
this.forget();
|
||||
reject(request.error);
|
||||
};
|
||||
request.onblocked = () => {
|
||||
this.forget();
|
||||
reject(new Error(`Opening ${this.name} was blocked`));
|
||||
};
|
||||
});
|
||||
}
|
||||
return this.database;
|
||||
};
|
||||
|
||||
/**
|
||||
* Discards the cached connection so that the next operation opens a new one,
|
||||
* unless it has already been replaced.
|
||||
*/
|
||||
private forget = (database?: IDBDatabase) => {
|
||||
if (database && this.connection !== database) {
|
||||
return;
|
||||
}
|
||||
this.connection = undefined;
|
||||
this.database = undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* Logs an operation that failed against the database. The browser closes
|
||||
* connections at times the page does not control, such as when the tab is
|
||||
* frozen or discarded, so those failures are expected and are not reported.
|
||||
*
|
||||
* @param message a description of the operation that failed.
|
||||
* @param err the error that was thrown.
|
||||
*/
|
||||
private report = (message: string, err: unknown) => {
|
||||
const extra = { database: this.name, error: err };
|
||||
|
||||
if (isConnectionClosedError(err)) {
|
||||
Logger.debug("store", message, extra);
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.warn(message, extra);
|
||||
};
|
||||
|
||||
private scheduleFlush = debounce(() => void this.flush(), FLUSH_DELAY_MS);
|
||||
|
||||
private store: Store<T>;
|
||||
@@ -180,6 +288,8 @@ export default class StorePersistence<T extends Model> {
|
||||
|
||||
private database?: Promise<IDBDatabase>;
|
||||
|
||||
private connection?: IDBDatabase;
|
||||
|
||||
private dirty = new Set<string>();
|
||||
|
||||
private disabled = false;
|
||||
@@ -187,6 +297,20 @@ export default class StorePersistence<T extends Model> {
|
||||
private hydrating = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an error was caused by the connection to the database closing, in
|
||||
* which case the operation did not run and can safely be retried.
|
||||
*
|
||||
* @param err the error to check.
|
||||
* @returns true if the connection was closed.
|
||||
*/
|
||||
function isConnectionClosedError(err: unknown): boolean {
|
||||
return (
|
||||
err instanceof DOMException &&
|
||||
(err.name === "InvalidStateError" || err.name === "AbortError")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an IndexedDB request into a promise.
|
||||
*
|
||||
@@ -210,6 +334,10 @@ function promisifyTransaction(transaction: IDBTransaction): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
transaction.oncomplete = () => resolve();
|
||||
transaction.onerror = () => reject(transaction.error);
|
||||
transaction.onabort = () => reject(transaction.error);
|
||||
transaction.onabort = () =>
|
||||
reject(
|
||||
transaction.error ??
|
||||
new DOMException("The transaction was aborted", "AbortError")
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -133,6 +133,23 @@ export const bounceIn = keyframes`
|
||||
}
|
||||
`;
|
||||
|
||||
export const popIn = keyframes`
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: scale(0.6);
|
||||
}
|
||||
|
||||
60% {
|
||||
opacity: 1;
|
||||
transform: scale(1.15);
|
||||
}
|
||||
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
`;
|
||||
|
||||
export const pulsate = keyframes`
|
||||
0% { opacity: 1; }
|
||||
50% { opacity: 0.5; }
|
||||
|
||||
+1
-1
@@ -142,7 +142,7 @@ type BaseAction = {
|
||||
name: ((context: ActionContext) => React.ReactNode) | React.ReactNode;
|
||||
section: ((context: ActionContext) => string) | string;
|
||||
description?: ((context: ActionContext) => string) | string;
|
||||
shortcut?: string[];
|
||||
shortcut?: ((context: ActionContext) => string[] | undefined) | string[];
|
||||
keywords?: string;
|
||||
/** Higher number is higher in results, default is 0. */
|
||||
priority?: number;
|
||||
|
||||
@@ -14,6 +14,10 @@ export async function deleteAllDatabases() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Close any connections this tab holds open, otherwise the deletions below
|
||||
// are blocked until they are, and in-flight reads and writes are aborted.
|
||||
stores.disablePersistence();
|
||||
|
||||
const teamId = stores.auth.currentTeamId;
|
||||
if (teamId) {
|
||||
Object.values(stores).forEach((store) => {
|
||||
|
||||
+11
-11
@@ -52,12 +52,12 @@
|
||||
"> 0.25%, not dead"
|
||||
],
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.1111.0",
|
||||
"@aws-sdk/client-s3": "^3.1115.0",
|
||||
"@aws-sdk/cloudfront-signer": "^3.1111.0",
|
||||
"@aws-sdk/lib-storage": "^3.1111.0",
|
||||
"@aws-sdk/s3-presigned-post": "^3.1111.0",
|
||||
"@aws-sdk/s3-request-presigner": "^3.1111.0",
|
||||
"@aws-sdk/signature-v4-crt": "^3.1111.0",
|
||||
"@aws-sdk/lib-storage": "^3.1115.0",
|
||||
"@aws-sdk/s3-presigned-post": "^3.1115.0",
|
||||
"@aws-sdk/s3-request-presigner": "^3.1115.0",
|
||||
"@aws-sdk/signature-v4-crt": "^3.1115.0",
|
||||
"@benrbray/prosemirror-math": "^0.2.2",
|
||||
"@bull-board/api": "^6.21.3",
|
||||
"@bull-board/koa": "^6.21.3",
|
||||
@@ -82,11 +82,11 @@
|
||||
"@hocuspocus/server": "1.1.3",
|
||||
"@juggle/resize-observer": "^3.4.0",
|
||||
"@linear/sdk": "^58.1.0",
|
||||
"@mermaid-js/layout-elk": "^0.2.2",
|
||||
"@mermaid-js/layout-elk": "0.2.2",
|
||||
"@modelcontextprotocol/sdk": "^1.25.3",
|
||||
"@node-oauth/oauth2-server": "^5.3.0",
|
||||
"@notionhq/client": "^2.3.0",
|
||||
"@octokit/auth-app": "^8.2.0",
|
||||
"@octokit/auth-app": "^8.3.0",
|
||||
"@octokit/webhooks-types": "^7.6.1",
|
||||
"@outlinewiki/koa-passport": "^4.2.1",
|
||||
"@outlinewiki/passport-azure-ad-oauth2": "^0.1.0",
|
||||
@@ -129,7 +129,7 @@
|
||||
"core-js": "^3.49.0",
|
||||
"crypto-js": "^4.2.0",
|
||||
"date-fns": "^3.6.0",
|
||||
"dd-trace": "^5.117.0",
|
||||
"dd-trace": "^5.123.0",
|
||||
"diff": "^5.2.2",
|
||||
"email-providers": "^1.14.0",
|
||||
"emoji-mart": "^5.6.0",
|
||||
@@ -177,7 +177,7 @@
|
||||
"markdown-it": "^14.3.0",
|
||||
"markdown-it-container": "^3.0.0",
|
||||
"markdown-it-emoji": "^3.0.0",
|
||||
"mermaid": "11.16.1",
|
||||
"mermaid": "11.17.1",
|
||||
"mime-types": "^3.0.2",
|
||||
"mobx": "^4.15.7",
|
||||
"mobx-react": "^6.3.1",
|
||||
@@ -202,7 +202,7 @@
|
||||
"prosemirror-changeset": "2.4.1",
|
||||
"prosemirror-codemark": "^0.4.2",
|
||||
"prosemirror-commands": "^1.7.1",
|
||||
"prosemirror-dropcursor": "^1.8.2",
|
||||
"prosemirror-dropcursor": "^1.8.3",
|
||||
"prosemirror-gapcursor": "^1.4.1",
|
||||
"prosemirror-history": "^1.5.0",
|
||||
"prosemirror-inputrules": "^1.5.1",
|
||||
@@ -226,7 +226,7 @@
|
||||
"react-dom": "^17.0.2",
|
||||
"react-dropzone": "^11.7.1",
|
||||
"react-helmet-async": "^2.0.5",
|
||||
"react-hook-form": "^7.76.0",
|
||||
"react-hook-form": "^7.85.0",
|
||||
"react-i18next": "^12.3.1",
|
||||
"react-is": "^17.0.2",
|
||||
"react-merge-refs": "^2.1.1",
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Gitlab } from "@gitbeaker/rest";
|
||||
import type {
|
||||
EpicSchema,
|
||||
IssueSchemaWithExpandedLabels,
|
||||
MergeRequestSchema,
|
||||
ProjectSchema,
|
||||
SimpleLabelSchema,
|
||||
StatisticsSchema,
|
||||
} from "@gitbeaker/rest";
|
||||
import z from "zod";
|
||||
@@ -106,6 +108,25 @@ export class GitLab {
|
||||
return issues[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches an epic from a GitLab group.
|
||||
*
|
||||
* @param accessToken - The access token for authentication.
|
||||
* @param groupPath - The full path of the group.
|
||||
* @param epicIid - The epic IID (internal ID within the group).
|
||||
* @param customUrl - Optional custom GitLab URL from integration settings.
|
||||
* @returns The epic data.
|
||||
*/
|
||||
public static async getEpic(
|
||||
accessToken: string,
|
||||
groupPath: string,
|
||||
epicIid: number,
|
||||
customUrl?: string
|
||||
) {
|
||||
const client = await this.createClient(accessToken, customUrl);
|
||||
return client.Epics.show(groupPath, epicIid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches a merge request from a GitLab project.
|
||||
*
|
||||
@@ -228,7 +249,6 @@ export class GitLab {
|
||||
|
||||
try {
|
||||
const customUrl = matchedIntegration.settings?.gitlab?.url;
|
||||
const projectPath = `${resource.owner}/${resource.repo}`;
|
||||
const { authentication } = matchedIntegration;
|
||||
const token = await authentication.refreshTokenIfNeeded(
|
||||
async (refreshToken: string) =>
|
||||
@@ -240,6 +260,23 @@ export class GitLab {
|
||||
})
|
||||
);
|
||||
|
||||
// Epics are group-scoped, so they have no project path.
|
||||
if (
|
||||
resource.type === UnfurlResourceType.Issue &&
|
||||
resource.scope === "group"
|
||||
) {
|
||||
const epic = await this.getEpic(
|
||||
token,
|
||||
resource.owner,
|
||||
resource.id,
|
||||
customUrl
|
||||
);
|
||||
|
||||
return this.transformIssue(epic);
|
||||
}
|
||||
|
||||
const projectPath = `${resource.owner}/${resource.repo}`;
|
||||
|
||||
if (resource.type === UnfurlResourceType.Issue) {
|
||||
const issue = await this.getIssue(
|
||||
token,
|
||||
@@ -359,7 +396,11 @@ export class GitLab {
|
||||
return AccessTokenResponseSchema.parse(resJson);
|
||||
}
|
||||
|
||||
private static transformIssue(issue: IssueSchemaWithExpandedLabels) {
|
||||
private static transformIssue(
|
||||
issue: IssueSchemaWithExpandedLabels | EpicSchema
|
||||
) {
|
||||
const labels: (string | SimpleLabelSchema)[] = issue.labels;
|
||||
|
||||
return {
|
||||
type: UnfurlResourceType.Issue,
|
||||
url: issue.web_url,
|
||||
@@ -370,10 +411,12 @@ export class GitLab {
|
||||
name: issue.author?.username ?? "",
|
||||
avatarUrl: issue.author?.avatar_url ?? "",
|
||||
},
|
||||
labels: issue.labels.map((label) => ({
|
||||
name: label.name,
|
||||
color: label.color,
|
||||
})),
|
||||
// Epics are returned without label color details.
|
||||
labels: labels.map((label) =>
|
||||
typeof label === "string"
|
||||
? { name: label, color: GitLabUtils.defaultLabelColor }
|
||||
: { name: label.name, color: label.color }
|
||||
),
|
||||
state: {
|
||||
name: issue.state,
|
||||
color: GitLabUtils.getColorForStatus(issue.state),
|
||||
@@ -436,7 +479,7 @@ export class GitLab {
|
||||
},
|
||||
labels: (project.topics ?? []).map((topic: string) => ({
|
||||
name: topic,
|
||||
color: "#6B7280",
|
||||
color: GitLabUtils.defaultLabelColor,
|
||||
})),
|
||||
progress,
|
||||
createdAt: project.created_at,
|
||||
|
||||
@@ -394,6 +394,77 @@ describe("GitLabUtils.parseUrl", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("group URLs", () => {
|
||||
it("should parse a group work_items URL", () => {
|
||||
const result = GitLabUtils.parseUrl(
|
||||
"https://gitlab.com/groups/gitlab-org/-/work_items/1234"
|
||||
);
|
||||
expect(result).toEqual({
|
||||
owner: "gitlab-org",
|
||||
type: UnfurlResourceType.Issue,
|
||||
scope: "group",
|
||||
id: 1234,
|
||||
url: "https://gitlab.com/groups/gitlab-org/-/work_items/1234",
|
||||
});
|
||||
});
|
||||
|
||||
it("should parse a nested group work_items URL", () => {
|
||||
const result = GitLabUtils.parseUrl(
|
||||
"https://gitlab.com/groups/gitlab-org/subgroup/-/work_items/5"
|
||||
);
|
||||
expect(result).toEqual({
|
||||
owner: "gitlab-org/subgroup",
|
||||
type: UnfurlResourceType.Issue,
|
||||
scope: "group",
|
||||
id: 5,
|
||||
url: "https://gitlab.com/groups/gitlab-org/subgroup/-/work_items/5",
|
||||
});
|
||||
});
|
||||
|
||||
it("should parse a legacy group epics URL", () => {
|
||||
const result = GitLabUtils.parseUrl(
|
||||
"https://gitlab.com/groups/gitlab-org/-/epics/1234"
|
||||
);
|
||||
expect(result).toEqual({
|
||||
owner: "gitlab-org",
|
||||
type: UnfurlResourceType.Issue,
|
||||
scope: "group",
|
||||
id: 1234,
|
||||
url: "https://gitlab.com/groups/gitlab-org/-/epics/1234",
|
||||
});
|
||||
});
|
||||
|
||||
it("should parse a group work_items URL with show parameter", () => {
|
||||
const show = btoa(
|
||||
JSON.stringify({ iid: "39", full_path: "gitlab-org", id: 1215135 })
|
||||
);
|
||||
const result = GitLabUtils.parseUrl(
|
||||
`https://gitlab.com/groups/gitlab-org/-/work_items?show=${show}`
|
||||
);
|
||||
expect(result).toEqual({
|
||||
owner: "gitlab-org",
|
||||
type: UnfurlResourceType.Issue,
|
||||
scope: "group",
|
||||
id: 39,
|
||||
url: `https://gitlab.com/groups/gitlab-org/-/work_items?show=${show}`,
|
||||
});
|
||||
});
|
||||
|
||||
it("should return undefined for an unsupported group resource", () => {
|
||||
const result = GitLabUtils.parseUrl(
|
||||
"https://gitlab.com/groups/gitlab-org/-/milestones/3"
|
||||
);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return undefined for a subgroup URL", () => {
|
||||
const result = GitLabUtils.parseUrl(
|
||||
"https://gitlab.com/groups/gitlab-org/subgroup"
|
||||
);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("custom GitLab URL", () => {
|
||||
it("should parse with a custom URL", () => {
|
||||
const result = GitLabUtils.parseUrl(
|
||||
|
||||
@@ -9,14 +9,34 @@ export type OAuthState = {
|
||||
nonce: string;
|
||||
};
|
||||
|
||||
/** The kind of namespace a resource belongs to. */
|
||||
export type GitLabScope = "project" | "group";
|
||||
|
||||
export class GitLabUtils {
|
||||
public static defaultGitlabUrl = "https://gitlab.com";
|
||||
|
||||
private static supportedResources = [
|
||||
UnfurlResourceType.Issue,
|
||||
UnfurlResourceType.PR,
|
||||
UnfurlResourceType.Project,
|
||||
];
|
||||
/** Fallback color for labels returned without color details. */
|
||||
public static defaultLabelColor = "#6B7280";
|
||||
|
||||
/** The separator GitLab puts between a namespace and the resource path. */
|
||||
private static separator = "/-/";
|
||||
|
||||
/** Maps the resource segment of a URL to a resource type, per scope. */
|
||||
private static resourceTypes: Record<
|
||||
string,
|
||||
Partial<
|
||||
Record<GitLabScope, UnfurlResourceType.Issue | UnfurlResourceType.PR>
|
||||
>
|
||||
> = {
|
||||
issues: { project: UnfurlResourceType.Issue },
|
||||
merge_requests: { project: UnfurlResourceType.PR },
|
||||
// Group-scoped work items are epics, which are shown as issues.
|
||||
work_items: {
|
||||
project: UnfurlResourceType.Issue,
|
||||
group: UnfurlResourceType.Issue,
|
||||
},
|
||||
epics: { group: UnfurlResourceType.Issue },
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the GitLab URL, preferring the provided custom URL over the default.
|
||||
@@ -132,6 +152,7 @@ export class GitLabUtils {
|
||||
| {
|
||||
owner: string;
|
||||
repo: string | undefined;
|
||||
scope?: "group";
|
||||
type: UnfurlResourceType.Issue | UnfurlResourceType.PR;
|
||||
id: number;
|
||||
url: string;
|
||||
@@ -143,96 +164,84 @@ export class GitLabUtils {
|
||||
url: string;
|
||||
}
|
||||
| undefined {
|
||||
let parsed: URL;
|
||||
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const urlHostname = new URL(this.getGitlabUrl(customUrl)).hostname;
|
||||
|
||||
if (parsed.hostname !== urlHostname) {
|
||||
parsed = new URL(url);
|
||||
if (parsed.hostname !== new URL(this.getGitlabUrl(customUrl)).hostname) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parts = parsed.pathname.split("/").filter(Boolean);
|
||||
|
||||
// Try base64-encoded `show` query parameter first
|
||||
// e.g. /owner/repo/-/issues?show=eyJ...
|
||||
const showParam = parsed.searchParams.get("show");
|
||||
if (showParam && parts.length >= 4) {
|
||||
const resourceType = parts.pop();
|
||||
parts.pop(); // separator ("-")
|
||||
const repo = parts.pop();
|
||||
const owner = parts.join("/");
|
||||
|
||||
const type =
|
||||
resourceType === "issues" || resourceType === "work_items"
|
||||
? UnfurlResourceType.Issue
|
||||
: resourceType === "merge_requests"
|
||||
? UnfurlResourceType.PR
|
||||
: undefined;
|
||||
|
||||
if (!type || !this.supportedResources.includes(type)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = JSON.parse(atob(decodeURIComponent(showParam)));
|
||||
const iid = Number(decoded.iid);
|
||||
if (!iid) {
|
||||
return;
|
||||
}
|
||||
return { owner, repo, type, id: iid, url };
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if it's a project URL (no -/ separator pattern in path)
|
||||
if (!parsed.pathname.includes("/-/")) {
|
||||
if (parts.length >= 2 && !this.isSystemPath(parts[0])) {
|
||||
const repo = parts[parts.length - 1];
|
||||
const owner = parts.slice(0, -1).join("/");
|
||||
return {
|
||||
owner,
|
||||
repo,
|
||||
type: UnfurlResourceType.Project,
|
||||
url,
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (parts.length < 5) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Direct URL: /owner/repo/-/issues/123 or /owner/repo/-/merge_requests/123
|
||||
const resourceId = parts.pop();
|
||||
const resourceType = parts.pop();
|
||||
parts.pop(); // separator ("-")
|
||||
|
||||
const repo = parts.pop();
|
||||
const owner = parts.join("/");
|
||||
|
||||
const type =
|
||||
resourceType === "issues" || resourceType === "work_items"
|
||||
? UnfurlResourceType.Issue
|
||||
: resourceType === "merge_requests"
|
||||
? UnfurlResourceType.PR
|
||||
: undefined;
|
||||
|
||||
if (!type || !this.supportedResources.includes(type)) {
|
||||
return;
|
||||
}
|
||||
|
||||
return {
|
||||
owner,
|
||||
repo,
|
||||
type,
|
||||
id: Number(resourceId),
|
||||
url,
|
||||
};
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const { pathname } = parsed;
|
||||
const separatorIndex = pathname.indexOf(this.separator);
|
||||
|
||||
// Project URL, e.g. /owner/repo
|
||||
if (separatorIndex === -1) {
|
||||
const parts = pathname.split("/").filter(Boolean);
|
||||
if (parts.length < 2 || this.isSystemPath(parts[0])) {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
owner: parts.slice(0, -1).join("/"),
|
||||
repo: parts[parts.length - 1],
|
||||
type: UnfurlResourceType.Project,
|
||||
url,
|
||||
};
|
||||
}
|
||||
|
||||
// e.g. /owner/repo/-/issues/123 or /groups/owner/-/work_items/123
|
||||
const namespace = pathname
|
||||
.slice(0, separatorIndex)
|
||||
.split("/")
|
||||
.filter(Boolean);
|
||||
const [segment, resourceId] = pathname
|
||||
.slice(separatorIndex + this.separator.length)
|
||||
.split("/");
|
||||
|
||||
// Epics are group-scoped, and so carry no repo.
|
||||
const scope: GitLabScope = namespace[0] === "groups" ? "group" : "project";
|
||||
if (scope === "group") {
|
||||
namespace.shift();
|
||||
}
|
||||
|
||||
const type = this.resourceTypes[segment]?.[scope];
|
||||
if (!type) {
|
||||
return;
|
||||
}
|
||||
|
||||
// List views carry the id in a base64-encoded `show` parameter instead.
|
||||
const showParam = parsed.searchParams.get("show");
|
||||
const id = showParam ? this.parseShowParam(showParam) : Number(resourceId);
|
||||
if (!id) {
|
||||
return;
|
||||
}
|
||||
|
||||
const repo = scope === "group" ? undefined : namespace.pop();
|
||||
const owner = namespace.join("/");
|
||||
if (!owner) {
|
||||
return;
|
||||
}
|
||||
|
||||
const resource = { owner, repo, type, id, url };
|
||||
return scope === "group" ? { ...resource, scope } : resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the base64-encoded `show` query parameter used by GitLab list views.
|
||||
*
|
||||
* @param showParam - the raw query parameter value.
|
||||
* @returns the resource IID, or undefined when it cannot be parsed.
|
||||
*/
|
||||
private static parseShowParam(showParam: string): number | undefined {
|
||||
try {
|
||||
const decoded = JSON.parse(atob(decodeURIComponent(showParam)));
|
||||
return Number(decoded.iid) || undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -164,9 +164,25 @@ export function createOIDCRouter(
|
||||
|
||||
// Derive a providerId from the OIDC location if there is no existing provider.
|
||||
const oidcURL = new URL(endpoints.authorizationURL);
|
||||
const providerId =
|
||||
let providerId =
|
||||
authenticationProvider?.providerId ?? oidcURL.hostname;
|
||||
|
||||
// The provider can move to a different domain, in which case the
|
||||
// stored identifier must follow the configured location.
|
||||
if (authenticationProvider && providerId !== oidcURL.hostname) {
|
||||
try {
|
||||
await authenticationProvider.update({
|
||||
providerId: oidcURL.hostname,
|
||||
});
|
||||
providerId = oidcURL.hostname;
|
||||
} catch (error) {
|
||||
Logger.warn(
|
||||
"Could not update OIDC authentication provider identifier",
|
||||
{ providerId, hostname: oidcURL.hostname, error }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!domain) {
|
||||
throw OIDCMalformedUserInfoError();
|
||||
}
|
||||
|
||||
@@ -773,6 +773,53 @@ describe("PostgresSearchProvider", () => {
|
||||
expect(total).toBe(1);
|
||||
});
|
||||
|
||||
it("should return context that is not shifted by earlier highlights", async () => {
|
||||
const team = await buildTeam();
|
||||
const user = await buildUser({ teamId: team.id });
|
||||
const collection = await buildCollection({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
});
|
||||
await buildDocument({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
collectionId: collection.id,
|
||||
title: "change",
|
||||
text: "world war two was a very large conflict that involved many nations over six years. Later on, hello world became the canonical first program.",
|
||||
});
|
||||
const { results } = await provider.searchForUser(user, {
|
||||
query: "hello world",
|
||||
});
|
||||
expect(results.length).toBe(1);
|
||||
// The earlier "world" is highlighted too, which must not move the start
|
||||
// of the slice into the middle of a word.
|
||||
expect(results[0].context).toBe(
|
||||
" conflict that involved many nations over six years. Later on, <b>hello world</b> became the canonical first program"
|
||||
);
|
||||
});
|
||||
|
||||
it("should return context for text with no word boundaries", async () => {
|
||||
const team = await buildTeam();
|
||||
const user = await buildUser({ teamId: team.id });
|
||||
const collection = await buildCollection({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
});
|
||||
const text = "abcdefghij".repeat(40);
|
||||
await buildDocument({
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
collectionId: collection.id,
|
||||
title: "hello world",
|
||||
text,
|
||||
});
|
||||
const { results } = await provider.searchForUser(user, {
|
||||
query: "hello world",
|
||||
});
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0].context).toBe(text.slice(0, 250));
|
||||
});
|
||||
|
||||
it("should correctly handle removal of trailing spaces", async () => {
|
||||
const team = await buildTeam();
|
||||
const user = await buildUser({ teamId: team.id });
|
||||
|
||||
@@ -591,14 +591,17 @@ export default class PostgresSearchProvider extends BaseSearchProvider {
|
||||
? 0
|
||||
: regexIndexOf(text, breakCharsRegex, offsetStartIndex)
|
||||
);
|
||||
const context = text.replace(highlightRegex, "<b>$&</b>");
|
||||
const endIndex = regexLastIndexOf(
|
||||
context,
|
||||
breakCharsRegex,
|
||||
startIndex + 250
|
||||
);
|
||||
// Ends on the last word boundary within the window, or at the window
|
||||
// itself when the text has none.
|
||||
const maxEndIndex = Math.min(text.length, startIndex + 250);
|
||||
const breakIndex = regexLastIndexOf(text, breakCharsRegex, maxEndIndex);
|
||||
const endIndex = breakIndex > startIndex ? breakIndex : maxEndIndex;
|
||||
|
||||
return context.slice(startIndex, endIndex);
|
||||
// Highlight after slicing, as the inserted tags shift every index that
|
||||
// follows an earlier match.
|
||||
return text
|
||||
.slice(startIndex, endIndex)
|
||||
.replace(highlightRegex, "<b>$&</b>");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -169,6 +169,7 @@ export default class DeliverWebhookTask extends BaseTask<Props> {
|
||||
case "authenticationProviders.update":
|
||||
case "notifications.create":
|
||||
case "notifications.update":
|
||||
case "notifications.delete":
|
||||
case "access_requests.create":
|
||||
// Ignored
|
||||
return;
|
||||
|
||||
@@ -1,37 +1,27 @@
|
||||
import type {
|
||||
onChangePayload,
|
||||
onDisconnectPayload,
|
||||
onLoadDocumentPayload,
|
||||
Extension,
|
||||
connectedPayload,
|
||||
onLoadDocumentPayload,
|
||||
} from "@hocuspocus/server";
|
||||
import Metrics from "@server/logging/Metrics";
|
||||
import type { withContext } from "./types";
|
||||
|
||||
export default class MetricsExtension implements Extension {
|
||||
async onLoadDocument({
|
||||
documentName,
|
||||
instance,
|
||||
}: withContext<onLoadDocumentPayload>) {
|
||||
Metrics.increment("collaboration.load_document", {
|
||||
documentName,
|
||||
});
|
||||
async onLoadDocument({ instance }: withContext<onLoadDocumentPayload>) {
|
||||
Metrics.increment("collaboration.load_document");
|
||||
Metrics.gaugePerInstance(
|
||||
"collaboration.documents_count",
|
||||
instance.getDocumentsCount()
|
||||
);
|
||||
}
|
||||
|
||||
onAuthenticationFailed({ documentName }: { documentName: string }) {
|
||||
Metrics.increment("collaboration.authentication_failed", {
|
||||
documentName,
|
||||
});
|
||||
onAuthenticationFailed() {
|
||||
Metrics.increment("collaboration.authentication_failed");
|
||||
}
|
||||
|
||||
async connected({ documentName, instance }: withContext<connectedPayload>) {
|
||||
Metrics.increment("collaboration.connect", {
|
||||
documentName,
|
||||
});
|
||||
async connected({ instance }: withContext<connectedPayload>) {
|
||||
Metrics.increment("collaboration.connect");
|
||||
Metrics.gaugePerInstance(
|
||||
"collaboration.connections_count",
|
||||
instance.getConnectionsCount() + 1
|
||||
@@ -42,13 +32,8 @@ export default class MetricsExtension implements Extension {
|
||||
);
|
||||
}
|
||||
|
||||
async onDisconnect({
|
||||
documentName,
|
||||
instance,
|
||||
}: withContext<onDisconnectPayload>) {
|
||||
Metrics.increment("collaboration.disconnect", {
|
||||
documentName,
|
||||
});
|
||||
async onDisconnect({ instance }: withContext<onDisconnectPayload>) {
|
||||
Metrics.increment("collaboration.disconnect");
|
||||
Metrics.gaugePerInstance(
|
||||
"collaboration.connections_count",
|
||||
instance.getConnectionsCount()
|
||||
@@ -59,10 +44,8 @@ export default class MetricsExtension implements Extension {
|
||||
);
|
||||
}
|
||||
|
||||
async onStoreDocument({ documentName }: withContext<onChangePayload>) {
|
||||
Metrics.increment("collaboration.change", {
|
||||
documentName,
|
||||
});
|
||||
async onStoreDocument() {
|
||||
Metrics.increment("collaboration.change");
|
||||
}
|
||||
|
||||
async onDestroy() {
|
||||
|
||||
@@ -22,6 +22,7 @@ type Props = Optional<
|
||||
| "importId"
|
||||
| "apiImportId"
|
||||
| "fullWidth"
|
||||
| "preferences"
|
||||
| "sourceMetadata"
|
||||
| "editorVersion"
|
||||
| "publishedAt"
|
||||
@@ -161,6 +162,7 @@ export default async function documentCreator(
|
||||
content,
|
||||
template,
|
||||
fullWidth,
|
||||
preferences,
|
||||
importId,
|
||||
apiImportId,
|
||||
createdAt,
|
||||
@@ -231,6 +233,7 @@ export default async function documentCreator(
|
||||
apiImportId,
|
||||
sourceMetadata,
|
||||
fullWidth: fullWidth ?? template?.fullWidth,
|
||||
preferences,
|
||||
icon: icon ?? template?.icon,
|
||||
color: color ?? template?.color,
|
||||
title: titleWithReplacements,
|
||||
|
||||
@@ -216,6 +216,7 @@ async function duplicateRoots(
|
||||
icon: original.icon,
|
||||
color: original.color,
|
||||
fullWidth: original.fullWidth,
|
||||
preferences: original.preferences,
|
||||
title: item.title,
|
||||
content: ProsemirrorHelper.replaceDocumentReferences(
|
||||
ProsemirrorHelper.removeMarks(DocumentHelper.toProsemirror(original), [
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { TextEditMode } from "@shared/types";
|
||||
import type { DocumentPreferences, TextEditMode } from "@shared/types";
|
||||
import { DocumentConflictError } from "@server/errors";
|
||||
import { Event, Document } from "@server/models";
|
||||
import { DocumentHelper } from "@server/models/helpers/DocumentHelper";
|
||||
@@ -24,6 +24,8 @@ type Props = {
|
||||
templateId?: string | null;
|
||||
/** If the document should be displayed full-width on the screen */
|
||||
fullWidth?: boolean;
|
||||
/** Display preferences for the document, merged with existing values */
|
||||
preferences?: DocumentPreferences | null;
|
||||
/** Whether insights should be visible on the document */
|
||||
insightsEnabled?: boolean;
|
||||
/** The edit mode: "replace", "append", "prepend", or "patch" */
|
||||
@@ -56,6 +58,7 @@ export default async function documentUpdater(
|
||||
editorVersion,
|
||||
templateId,
|
||||
fullWidth,
|
||||
preferences,
|
||||
insightsEnabled,
|
||||
editMode,
|
||||
findText,
|
||||
@@ -87,6 +90,12 @@ export default async function documentUpdater(
|
||||
if (fullWidth !== undefined) {
|
||||
document.fullWidth = fullWidth;
|
||||
}
|
||||
if (preferences) {
|
||||
document.preferences = {
|
||||
...document.preferences,
|
||||
...preferences,
|
||||
};
|
||||
}
|
||||
if (insightsEnabled !== undefined) {
|
||||
document.insightsEnabled = insightsEnabled;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import fractionalIndex from "fractional-index";
|
||||
import type { WhereOptions } from "sequelize";
|
||||
import { Sequelize, Op } from "sequelize";
|
||||
import { PinValidation } from "@shared/validations";
|
||||
import { ValidationError } from "@server/errors";
|
||||
import type { User } from "@server/models";
|
||||
import { Pin } from "@server/models";
|
||||
import type { APIContext } from "@server/types";
|
||||
@@ -35,22 +33,17 @@ export default async function pinCreator({
|
||||
...rest
|
||||
}: Props): Promise<Pin> {
|
||||
let { index } = rest;
|
||||
const { transaction } = ctx.context;
|
||||
const where: WhereOptions<Pin> = {
|
||||
teamId: user.teamId,
|
||||
...(collectionId ? { collectionId } : { collectionId: { [Op.is]: null } }),
|
||||
};
|
||||
|
||||
const count = await Pin.count({ where });
|
||||
if (count >= PinValidation.max) {
|
||||
throw ValidationError(
|
||||
`You cannot pin more than ${PinValidation.max} documents`
|
||||
);
|
||||
}
|
||||
|
||||
if (!index) {
|
||||
const pins = await Pin.findAll({
|
||||
where,
|
||||
attributes: ["id", "index", "updatedAt"],
|
||||
transaction,
|
||||
limit: 1,
|
||||
order: [
|
||||
// using LC_COLLATE:"C" because we need byte order to drive the sorting
|
||||
|
||||
@@ -50,17 +50,17 @@ const teamUpdater = async (ctx: APIContext, { params, user, team }: Props) => {
|
||||
const newDomains = allowedDomains.filter(
|
||||
(newDomain) => newDomain !== "" && !existingDomains.includes(newDomain)
|
||||
);
|
||||
await Promise.all(
|
||||
newDomains.map(async (newDomain) => {
|
||||
newAllowedDomains.push(
|
||||
await TeamDomain.createWithCtx(ctx, {
|
||||
name: newDomain,
|
||||
teamId: team.id,
|
||||
createdById: user.id,
|
||||
})
|
||||
);
|
||||
})
|
||||
);
|
||||
// Created one at a time so that the limit check on each create counts the
|
||||
// domains added earlier in the same request.
|
||||
for (const newDomain of newDomains) {
|
||||
newAllowedDomains.push(
|
||||
await TeamDomain.createWithCtx(ctx, {
|
||||
name: newDomain,
|
||||
teamId: team.id,
|
||||
createdById: user.id,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// Destroy the existing TeamDomains that were removed
|
||||
const deletedDomains = existingAllowedDomains.filter(
|
||||
|
||||
@@ -10,6 +10,8 @@ interface MockContextOptions {
|
||||
path?: string;
|
||||
mountPath?: string;
|
||||
ip?: string;
|
||||
/** Records the response headers the middleware writes. */
|
||||
set?: ReturnType<typeof vi.fn>;
|
||||
/** When set, presented as a bearer token in the authorization header. */
|
||||
token?: string;
|
||||
}
|
||||
@@ -18,13 +20,15 @@ const createContext = ({
|
||||
path = "/some/path",
|
||||
mountPath,
|
||||
ip = "192.168.1.1",
|
||||
set,
|
||||
token,
|
||||
}: MockContextOptions = {}) =>
|
||||
({
|
||||
path,
|
||||
mountPath,
|
||||
ip,
|
||||
set: vi.fn(),
|
||||
state: {},
|
||||
set: set ?? vi.fn(),
|
||||
request: {
|
||||
get: () => (token ? `Bearer ${token}` : undefined),
|
||||
body: {},
|
||||
@@ -118,6 +122,70 @@ describe("rateLimiter middleware", () => {
|
||||
expect(limiter.points).toBe(1);
|
||||
});
|
||||
|
||||
it("registers one limiter for case and trailing slash variants of a path", async () => {
|
||||
const registerMiddleware = rateLimiter({ duration: 60, requests: 5 });
|
||||
|
||||
await registerMiddleware(
|
||||
createContext({ path: "/documents.export", mountPath: "/api" }),
|
||||
vi.fn()
|
||||
);
|
||||
await registerMiddleware(
|
||||
createContext({ path: "/Documents.Export", mountPath: "/API" }),
|
||||
vi.fn()
|
||||
);
|
||||
await registerMiddleware(
|
||||
createContext({ path: "/documents.export/", mountPath: "/api" }),
|
||||
vi.fn()
|
||||
);
|
||||
|
||||
expect(RateLimiter.rateLimiterMap.size).toBe(1);
|
||||
|
||||
const limiter = RateLimiter.getRateLimiter("/api/documents.export");
|
||||
for (const variant of [
|
||||
"/API/Documents.Export",
|
||||
"/api/documents.export/",
|
||||
"/API/Documents.Export/",
|
||||
]) {
|
||||
expect(RateLimiter.hasRateLimiter(variant)).toBe(true);
|
||||
expect(RateLimiter.getRateLimiter(variant)).toBe(limiter);
|
||||
}
|
||||
});
|
||||
|
||||
it("consumes one bucket for case and trailing slash variants of a path", async () => {
|
||||
const registerMiddleware = rateLimiter({ duration: 60, requests: 5 });
|
||||
await registerMiddleware(
|
||||
createContext({ path: "/documents.export", mountPath: "/api" }),
|
||||
vi.fn()
|
||||
);
|
||||
|
||||
const customLimiter = RateLimiter.getRateLimiter("/api/documents.export");
|
||||
const consumeSpy = vi
|
||||
.spyOn(customLimiter, "consume")
|
||||
.mockResolvedValue({} as never);
|
||||
|
||||
const middleware = defaultRateLimiter();
|
||||
for (const path of [
|
||||
"/documents.export",
|
||||
"/Documents.Export",
|
||||
"/documents.export/",
|
||||
]) {
|
||||
await middleware(
|
||||
createContext({ path, mountPath: "/api", ip: "127.0.0.1" }),
|
||||
vi.fn()
|
||||
);
|
||||
}
|
||||
|
||||
expect(consumeSpy.mock.calls.map(([key]) => key)).toEqual([
|
||||
"/api/documents.export:127.0.0.1",
|
||||
"/api/documents.export:127.0.0.1",
|
||||
"/api/documents.export:127.0.0.1",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the root path when normalizing", () => {
|
||||
expect(RateLimiter.normalizePath("/")).toBe("/");
|
||||
});
|
||||
|
||||
it("should use default rate limiter when no custom rate limiter is registered", async () => {
|
||||
const fullPath = "/some/random/path";
|
||||
expect(RateLimiter.hasRateLimiter(fullPath)).toBe(false);
|
||||
@@ -348,4 +416,83 @@ describe("rateLimiter middleware", () => {
|
||||
expect(consumeSpy).toHaveBeenCalledWith("/api/documents.export:user-abc");
|
||||
});
|
||||
});
|
||||
|
||||
describe("first request accounting", () => {
|
||||
it("charges the request that registers a route limiter", async () => {
|
||||
const path = "/auth/registers";
|
||||
const register = rateLimiter({ duration: 3600, requests: 1 });
|
||||
|
||||
// Registration happens downstream of the point where quota is consumed,
|
||||
// so this request has to be charged here or it goes uncounted.
|
||||
const next = vi.fn();
|
||||
await register(createContext({ path }), next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
|
||||
// The single point is now spent, so the next request is rejected by the
|
||||
// default middleware.
|
||||
await expect(
|
||||
defaultRateLimiter()(createContext({ path }), vi.fn())
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("reuses the identifiers the default middleware resolved", async () => {
|
||||
const path = "/auth/reuses";
|
||||
const ctx = createContext({ path, token: "verified-token" });
|
||||
const cacheSpy = vi
|
||||
.spyOn(RateLimiter, "getCachedUserIdForToken")
|
||||
.mockResolvedValue("user-abc");
|
||||
|
||||
await defaultRateLimiter()(ctx, vi.fn());
|
||||
cacheSpy.mockClear();
|
||||
|
||||
await rateLimiter({ duration: 3600, requests: 5 })(ctx, vi.fn());
|
||||
|
||||
expect(cacheSpy).not.toHaveBeenCalled();
|
||||
const limiter = RateLimiter.getRateLimiter(path);
|
||||
await expect(limiter.get(`${path}:user-abc`)).resolves.toMatchObject({
|
||||
consumedPoints: 1,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("rejection headers", () => {
|
||||
/** Trips a route limiter and returns the headers it wrote. */
|
||||
const tripLimiter = async (path: string, msBeforeNext: number) => {
|
||||
await rateLimiter({ duration: 3600, requests: 5 })(
|
||||
createContext({ path }),
|
||||
vi.fn()
|
||||
);
|
||||
|
||||
vi.spyOn(RateLimiter.getRateLimiter(path), "consume").mockRejectedValue(
|
||||
new RateLimiterRes(0, msBeforeNext, 6)
|
||||
);
|
||||
|
||||
const set = vi.fn();
|
||||
await expect(
|
||||
defaultRateLimiter()(createContext({ path, set }), vi.fn())
|
||||
).rejects.toThrow();
|
||||
return set;
|
||||
};
|
||||
|
||||
it("reports the wait as a whole number of seconds", async () => {
|
||||
const set = await tripLimiter("/auth/whole", 59986);
|
||||
|
||||
expect(set).toHaveBeenCalledWith("Retry-After", "60");
|
||||
expect(set).toHaveBeenCalledWith("RateLimit-Reset", "60");
|
||||
});
|
||||
|
||||
it("rounds up so a client that waits is not rejected again", async () => {
|
||||
const set = await tripLimiter("/auth/rounds", 1);
|
||||
|
||||
expect(set).toHaveBeenCalledWith("Retry-After", "1");
|
||||
expect(set).toHaveBeenCalledWith("RateLimit-Reset", "1");
|
||||
});
|
||||
|
||||
it("reports the limit and the remaining quota", async () => {
|
||||
const set = await tripLimiter("/auth/quota", 30000);
|
||||
|
||||
expect(set).toHaveBeenCalledWith("RateLimit-Limit", "5");
|
||||
expect(set).toHaveBeenCalledWith("RateLimit-Remaining", "0");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -52,6 +52,56 @@ async function getRateLimiterIdentifiers(ctx: AppContext): Promise<string[]> {
|
||||
return [ctx.ip];
|
||||
}
|
||||
|
||||
/**
|
||||
* Consumes a point from a limiter for every identifier on the request. A
|
||||
* limiter that is unreachable is logged and skipped, so an outage of the store
|
||||
* does not take the endpoint down with it.
|
||||
*
|
||||
* @param ctx The application context.
|
||||
* @param fullPath The path the limiter is registered against.
|
||||
* @param identifiers The identifiers to consume for this request.
|
||||
* @throws RateLimitExceededError when an identifier is out of quota.
|
||||
*/
|
||||
async function consume(
|
||||
ctx: AppContext,
|
||||
fullPath: string,
|
||||
identifiers: string[]
|
||||
): Promise<void> {
|
||||
const isPathScoped = RateLimiter.hasRateLimiter(fullPath);
|
||||
const limiter = RateLimiter.getRateLimiter(fullPath);
|
||||
|
||||
try {
|
||||
for (const identifier of identifiers) {
|
||||
await limiter.consume(
|
||||
isPathScoped ? `${fullPath}:${identifier}` : identifier
|
||||
);
|
||||
}
|
||||
} catch (rateLimiterRes) {
|
||||
if (
|
||||
rateLimiterRes instanceof Error ||
|
||||
!(rateLimiterRes instanceof RateLimiterRes)
|
||||
) {
|
||||
Logger.error("Rate limiter error", toError(rateLimiterRes));
|
||||
return;
|
||||
}
|
||||
|
||||
// Both headers are defined as a whole number of seconds, rounded up so that
|
||||
// a client waiting exactly this long is not turned away a second time.
|
||||
const resetSeconds = Math.ceil(rateLimiterRes.msBeforeNext / 1000);
|
||||
|
||||
ctx.set("Retry-After", `${resetSeconds}`);
|
||||
ctx.set("RateLimit-Limit", `${limiter.points}`);
|
||||
ctx.set("RateLimit-Remaining", `${rateLimiterRes.remainingPoints}`);
|
||||
ctx.set("RateLimit-Reset", `${resetSeconds}`);
|
||||
|
||||
Metrics.increment("rate_limit.exceeded", {
|
||||
path: isPathScoped ? "path" : "default",
|
||||
});
|
||||
|
||||
throw RateLimitExceededError();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware that limits the number of requests that are allowed within a given
|
||||
* window. Should only be applied once to a server – do not use on individual
|
||||
@@ -65,40 +115,16 @@ export function defaultRateLimiter() {
|
||||
return next();
|
||||
}
|
||||
|
||||
const fullPath = `${ctx.mountPath ?? ""}${ctx.path}`;
|
||||
const fullPath = RateLimiter.normalizePath(
|
||||
`${ctx.mountPath ?? ""}${ctx.path}`
|
||||
);
|
||||
const identifiers = await getRateLimiterIdentifiers(ctx);
|
||||
const isPathScoped = RateLimiter.hasRateLimiter(fullPath);
|
||||
const limiter = RateLimiter.getRateLimiter(fullPath);
|
||||
|
||||
try {
|
||||
for (const identifier of identifiers) {
|
||||
await limiter.consume(
|
||||
isPathScoped ? `${fullPath}:${identifier}` : identifier
|
||||
);
|
||||
}
|
||||
} catch (rateLimiterRes) {
|
||||
if (
|
||||
rateLimiterRes instanceof Error ||
|
||||
!(rateLimiterRes instanceof RateLimiterRes)
|
||||
) {
|
||||
Logger.error("Rate limiter error", toError(rateLimiterRes));
|
||||
return next();
|
||||
}
|
||||
// Kept for a route that registers its own limiter further down the chain,
|
||||
// so that it can charge this request without resolving them again.
|
||||
ctx.state.rateLimiterIdentifiers = identifiers;
|
||||
|
||||
ctx.set("Retry-After", `${rateLimiterRes.msBeforeNext / 1000}`);
|
||||
ctx.set("RateLimit-Limit", `${limiter.points}`);
|
||||
ctx.set("RateLimit-Remaining", `${rateLimiterRes.remainingPoints}`);
|
||||
ctx.set(
|
||||
"RateLimit-Reset",
|
||||
new Date(Date.now() + rateLimiterRes.msBeforeNext).toString()
|
||||
);
|
||||
|
||||
Metrics.increment("rate_limit.exceeded", {
|
||||
path: fullPath,
|
||||
});
|
||||
|
||||
throw RateLimitExceededError();
|
||||
}
|
||||
await consume(ctx, fullPath, identifiers);
|
||||
|
||||
return next();
|
||||
};
|
||||
@@ -127,7 +153,9 @@ export function rateLimiter(config: RateLimiterConfig) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const fullPath = `${ctx.mountPath ?? ""}${ctx.path}`;
|
||||
const fullPath = RateLimiter.normalizePath(
|
||||
`${ctx.mountPath ?? ""}${ctx.path}`
|
||||
);
|
||||
|
||||
if (!RateLimiter.hasRateLimiter(fullPath)) {
|
||||
const points = Math.max(
|
||||
@@ -150,6 +178,15 @@ export function rateLimiter(config: RateLimiterConfig) {
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
// The limiter did not exist when the request entered the default
|
||||
// middleware, so this request has not been charged against it yet.
|
||||
await consume(
|
||||
ctx,
|
||||
fullPath,
|
||||
ctx.state.rateLimiterIdentifiers ??
|
||||
(await getRateLimiterIdentifiers(ctx))
|
||||
);
|
||||
}
|
||||
|
||||
return next();
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"use strict";
|
||||
|
||||
const BATCH_SIZE = 1000;
|
||||
|
||||
/** @type {import('sequelize-cli').Migration} */
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
// Every statement is idempotent because the migration cannot run inside a
|
||||
// transaction, so a failure part way through has to be resumable.
|
||||
await queryInterface.sequelize.query(
|
||||
'ALTER TABLE "documents" ADD COLUMN IF NOT EXISTS "deletedById" uuid;'
|
||||
);
|
||||
|
||||
// NOT VALID adds the constraint without scanning the existing rows, which
|
||||
// would hold an exclusive lock for the length of that scan. VALIDATE then
|
||||
// checks them under a lock that still allows reads and writes.
|
||||
const [constraints] = await queryInterface.sequelize.query(
|
||||
`SELECT 1 FROM pg_constraint WHERE conname = 'documents_deletedById_fkey';`
|
||||
);
|
||||
if (!constraints.length) {
|
||||
await queryInterface.sequelize.query(`
|
||||
ALTER TABLE "documents"
|
||||
ADD CONSTRAINT "documents_deletedById_fkey"
|
||||
FOREIGN KEY ("deletedById") REFERENCES "users" ("id")
|
||||
NOT VALID;
|
||||
`);
|
||||
}
|
||||
await queryInterface.sequelize.query(
|
||||
'ALTER TABLE "documents" VALIDATE CONSTRAINT "documents_deletedById_fkey";'
|
||||
);
|
||||
|
||||
// Serves the trash query. Partial so that it only covers deleted documents
|
||||
// rather than the whole table.
|
||||
await queryInterface.sequelize.query(
|
||||
'CREATE INDEX CONCURRENTLY IF NOT EXISTS "documents_deleted_by_id" ON "documents" ("deletedById") WHERE "deletedAt" IS NOT NULL;'
|
||||
);
|
||||
|
||||
// Indexes only the rows the backfill has left to do, so it shrinks as the
|
||||
// loop runs and each batch reads its own rows and nothing else. Without it
|
||||
// every batch re-reads the rows already written, which turns the loop
|
||||
// quadratic on a large table.
|
||||
await queryInterface.sequelize.query(
|
||||
'CREATE INDEX CONCURRENTLY IF NOT EXISTS "documents_deleted_by_backfill" ON "documents" ("id") WHERE "deletedAt" IS NOT NULL AND "deletedById" IS NULL;'
|
||||
);
|
||||
|
||||
// Written in batches, each its own transaction, so that no single statement
|
||||
// locks a large number of rows.
|
||||
let rowCount = 1;
|
||||
let total = 0;
|
||||
|
||||
while (rowCount) {
|
||||
const [, metadata] = await queryInterface.sequelize.query(`
|
||||
WITH rows AS (
|
||||
SELECT "id" FROM "documents"
|
||||
WHERE "deletedAt" IS NOT NULL AND "deletedById" IS NULL
|
||||
ORDER BY "id"
|
||||
LIMIT ${BATCH_SIZE}
|
||||
)
|
||||
UPDATE "documents"
|
||||
SET "deletedById" = "lastModifiedById"
|
||||
WHERE EXISTS (SELECT 1 FROM rows WHERE "documents"."id" = rows."id")
|
||||
`);
|
||||
|
||||
rowCount = metadata.rowCount;
|
||||
total += rowCount;
|
||||
if (rowCount) {
|
||||
console.log(`Backfilling documents.deletedById… ${total}`);
|
||||
}
|
||||
}
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
'DROP INDEX CONCURRENTLY IF EXISTS "documents_deleted_by_backfill";'
|
||||
);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
// Dropping the column takes the index and the foreign key with it.
|
||||
await queryInterface.sequelize.query(
|
||||
'ALTER TABLE "documents" DROP COLUMN IF EXISTS "deletedById";'
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
|
||||
/** @type {import('sequelize-cli').Migration} */
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn("documents", "preferences", {
|
||||
type: Sequelize.JSONB,
|
||||
allowNull: true,
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeColumn("documents", "preferences");
|
||||
},
|
||||
};
|
||||
@@ -1,6 +1,7 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { randomString } from "@shared/random";
|
||||
import slugify from "@shared/utils/slugify";
|
||||
import { createContext } from "@server/context";
|
||||
import {
|
||||
buildUser,
|
||||
buildGroup,
|
||||
@@ -9,7 +10,6 @@ import {
|
||||
buildDocument,
|
||||
} from "@server/test/factories";
|
||||
import { withAPIContext } from "@server/test/support";
|
||||
import { createContext } from "@server/context";
|
||||
import Collection from "./Collection";
|
||||
import Document from "./Document";
|
||||
|
||||
|
||||
+16
-13
@@ -4,6 +4,7 @@ import { find, findIndex, isNil, keyBy, remove, uniq } from "es-toolkit/compat";
|
||||
import type {
|
||||
Identifier,
|
||||
Transaction,
|
||||
DestroyOptions,
|
||||
FindOptions,
|
||||
NonNullFindOptions,
|
||||
InferAttributes,
|
||||
@@ -58,6 +59,7 @@ import { CollectionValidation } from "@shared/validations";
|
||||
import { parser } from "@server/editor";
|
||||
import { ValidationError } from "@server/errors";
|
||||
import type { APIContext } from "@server/types";
|
||||
import { LockHelper } from "@server/storage/LockHelper";
|
||||
import { CacheHelper } from "@server/utils/CacheHelper";
|
||||
import { RedisPrefixHelper } from "@server/utils/RedisPrefixHelper";
|
||||
import removeIndexCollision from "@server/utils/removeIndexCollision";
|
||||
@@ -431,7 +433,13 @@ class Collection extends ParanoidModel<
|
||||
}
|
||||
|
||||
@BeforeDestroy
|
||||
static async checkLastCollection(model: Collection) {
|
||||
static async checkLastCollection(model: Collection, options: DestroyOptions) {
|
||||
await LockHelper.acquire(
|
||||
model.sequelize,
|
||||
`collections:${model.teamId}`,
|
||||
options.transaction
|
||||
);
|
||||
|
||||
const total = await this.count({
|
||||
where: {
|
||||
teamId: model.teamId,
|
||||
@@ -444,9 +452,12 @@ class Collection extends ParanoidModel<
|
||||
|
||||
@BeforeDestroy
|
||||
static async deleteDocuments(model: Collection, ctx: APIContext["context"]) {
|
||||
// A bulk update rather than a destroy per document, so `deletedById` is
|
||||
// written here instead of by the hook on ParanoidModel.
|
||||
await Document.update(
|
||||
{
|
||||
lastModifiedById: ctx.auth.user.id,
|
||||
deletedById: ctx.auth.user.id,
|
||||
deletedAt: new Date(),
|
||||
},
|
||||
{
|
||||
@@ -883,12 +894,11 @@ class Collection extends ParanoidModel<
|
||||
* Removes a document from this collection's structure and soft deletes it
|
||||
* along with all of its descendants.
|
||||
*
|
||||
* @param ctx the API context, providing the acting user and transaction.
|
||||
* @param ctx the API context, which attributes the deletion to the acting user.
|
||||
* @param document the document to delete.
|
||||
*/
|
||||
deleteDocument = async (ctx: APIContext, document: Document) => {
|
||||
const { user } = ctx.state.auth;
|
||||
const { transaction } = ctx.state;
|
||||
const { transaction } = ctx.context;
|
||||
|
||||
await this.removeDocumentInStructure(ctx, document);
|
||||
|
||||
@@ -909,18 +919,11 @@ class Collection extends ParanoidModel<
|
||||
|
||||
// Destroyed one at a time to ensure model hooks run for each document.
|
||||
for (const childDocumentId of childDocumentIds) {
|
||||
const childDocument = childDocumentsById[childDocumentId];
|
||||
if (childDocument) {
|
||||
// Attributes the deletion of the whole tree to the acting user, which
|
||||
// the trash relies on to show a person their own deletions.
|
||||
childDocument.lastModifiedById = user.id;
|
||||
childDocument.updatedBy = user;
|
||||
await childDocument.destroy({ transaction });
|
||||
}
|
||||
await childDocumentsById[childDocumentId]?.destroy(ctx.context);
|
||||
}
|
||||
}
|
||||
|
||||
await document.destroy({ transaction });
|
||||
await document.destroy(ctx.context);
|
||||
};
|
||||
|
||||
removeDocumentInStructure = async (
|
||||
|
||||
@@ -46,11 +46,14 @@ import { MaxLength } from "class-validator";
|
||||
import isUUID from "validator/lib/isUUID";
|
||||
import type {
|
||||
DocumentPermission,
|
||||
DocumentPreference,
|
||||
DocumentPreferences,
|
||||
ImportableIntegrationService,
|
||||
NavigationNode,
|
||||
ProsemirrorData,
|
||||
SourceMetadata,
|
||||
} from "@shared/types";
|
||||
import { DocumentPreferenceDefaults } from "@shared/constants";
|
||||
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
|
||||
import { UrlHelper } from "@shared/utils/UrlHelper";
|
||||
import slugify from "@shared/utils/slugify";
|
||||
@@ -340,6 +343,11 @@ class Document extends ArchivableModel<
|
||||
@Column(DataType.BOOLEAN)
|
||||
fullWidth: boolean;
|
||||
|
||||
/** Display preferences for the document. */
|
||||
@AllowNull
|
||||
@Column(DataType.JSONB)
|
||||
preferences: DocumentPreferences | null;
|
||||
|
||||
@Default(false)
|
||||
@Column(DataType.BOOLEAN)
|
||||
template: boolean;
|
||||
@@ -691,6 +699,14 @@ class Document extends ArchivableModel<
|
||||
@Column(DataType.UUID)
|
||||
createdById: string;
|
||||
|
||||
@BelongsTo(() => User, "deletedById")
|
||||
deletedBy: User | null;
|
||||
|
||||
/** The user that deleted this document, set automatically on delete. */
|
||||
@ForeignKey(() => User)
|
||||
@Column(DataType.UUID)
|
||||
deletedById: string | null;
|
||||
|
||||
@ForeignKey(() => Template)
|
||||
@Column(DataType.UUID)
|
||||
templateId: string;
|
||||
@@ -1055,6 +1071,34 @@ class Document extends ArchivableModel<
|
||||
return !this.archivedAt && !this.deletedAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the given display preference.
|
||||
*
|
||||
* @param preference The document preference to set
|
||||
* @param value Sets the preference value
|
||||
* @returns The current document preferences
|
||||
*/
|
||||
public setPreference = <T extends keyof DocumentPreferences>(
|
||||
preference: T,
|
||||
value: DocumentPreferences[T]
|
||||
) => {
|
||||
this.preferences = {
|
||||
...this.preferences,
|
||||
[preference]: value,
|
||||
};
|
||||
|
||||
return this.preferences;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the value of the given display preference.
|
||||
*
|
||||
* @param preference The document preference to retrieve
|
||||
* @returns The preference value if set, else the default value
|
||||
*/
|
||||
public getPreference = <T extends DocumentPreference>(preference: T) =>
|
||||
this.preferences?.[preference] ?? DocumentPreferenceDefaults[preference];
|
||||
|
||||
/**
|
||||
* Convenience method that returns whether this document is a draft.
|
||||
*
|
||||
@@ -1445,7 +1489,7 @@ class Document extends ArchivableModel<
|
||||
}
|
||||
|
||||
if (!deleted) {
|
||||
await this.destroy({ transaction });
|
||||
await this.destroy(ctx.context);
|
||||
}
|
||||
|
||||
this.lastModifiedById = user.id;
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
import type { DocumentPermission } from "@shared/types";
|
||||
import { CollectionPermission } from "@shared/types";
|
||||
import { ValidationError } from "@server/errors";
|
||||
import { LockHelper } from "@server/storage/LockHelper";
|
||||
import type { APIContext } from "@server/types";
|
||||
import Collection from "./Collection";
|
||||
import Document from "./Document";
|
||||
@@ -441,6 +442,15 @@ class GroupMembership extends ParanoidModel<
|
||||
model: GroupMembership,
|
||||
{ transaction }: APIContext["context"]
|
||||
) {
|
||||
// Both models guard the same invariant, so they share one lock name,
|
||||
// otherwise the last user manager and the last group manager can be
|
||||
// removed at the same time.
|
||||
await LockHelper.acquire(
|
||||
model.sequelize,
|
||||
`collectionAdmins:${model.collectionId}`,
|
||||
transaction
|
||||
);
|
||||
|
||||
const [userMemberships, groupMemberships] = await Promise.all([
|
||||
UserMembership.count({
|
||||
where: {
|
||||
|
||||
Loaded 100 of 225 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user