From 2295c44eb6caabbe4c49739a1010de6e930c77c9 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 19 Aug 2026 10:13:49 -0400 Subject: [PATCH 01/55] Animate drafts count in sidebar (#13490) * Animate drafts count in sidebar Adds a subtle pop animation when the drafts count appears or changes. * Key drafts count animation on the displayed value --- .../Sidebar/components/DraftsLink.tsx | 9 +++++++-- app/styles/animations.ts | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/app/components/Sidebar/components/DraftsLink.tsx b/app/components/Sidebar/components/DraftsLink.tsx index 701597a17d..7ac37fe2fc 100644 --- a/app/components/Sidebar/components/DraftsLink.tsx +++ b/app/components/Sidebar/components/DraftsLink.tsx @@ -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 (
@@ -25,8 +28,8 @@ export const DraftsLink = observer(() => { {t("Drafts")} {documents.totalDrafts > 0 ? ( - - {documents.totalDrafts > 25 ? "25+" : documents.totalDrafts} + + {totalDrafts} ) : null} @@ -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; `; diff --git a/app/styles/animations.ts b/app/styles/animations.ts index 107ac5cad9..fc0a5603a0 100644 --- a/app/styles/animations.ts +++ b/app/styles/animations.ts @@ -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; } From 46e47024067362dc801572d49bf47cda5053e411 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 19 Aug 2026 16:56:11 -0400 Subject: [PATCH 02/55] fix: Ctrl+Left jumping to the start of a heading (#13494) The heading node bound its caret-sync handler to Mod-ArrowLeft, which Prosemirror maps to Ctrl on Linux and Windows. The handler moved the selection to the start of the heading, replacing the word-left movement that Ctrl+Left performs everywhere else. Bind Cmd rather than Mod, so the handler only runs for the shortcut it was written for. Co-authored-by: Claude Opus 5 (1M context) --- shared/editor/nodes/Heading.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/shared/editor/nodes/Heading.ts b/shared/editor/nodes/Heading.ts index 89ddf8d0d0..b7304c1d57 100644 --- a/shared/editor/nodes/Heading.ts +++ b/shared/editor/nodes/Heading.ts @@ -209,8 +209,9 @@ export default class Heading extends Node { // widget (contentEditable=false, ignoreSelection: true), so Prosemirror // does not update its model. Subsequent commands like Enter then operate // on the stale position. Move the model selection explicitly to keep it - // in sync with the visual caret. - "Mod-ArrowLeft": ((state, dispatch) => { + // in sync with the visual caret. Note this is Cmd rather than Mod, as + // Ctrl+Left moves by word on other platforms. + "Cmd-ArrowLeft": ((state, dispatch) => { const { $from, empty } = state.selection; if (!empty || $from.parent.type !== type) { return false; From e7249cb138b9bf1561e87721f1ea7a72751a2d84 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 19 Aug 2026 16:57:45 -0400 Subject: [PATCH 03/55] fix: RangeError rendering a diff with sibling node modifications (#13496) The modification loop advanced its cursor with node sizes read from the slice, which describes the content before the change. When one step replaces several sibling nodes the changeset emits a change per node, each carrying the whole slice, so the later changes walked past the end of the document and decoration building threw. Measure each decorated node in the document being decorated instead. Fixes OUTLINE-CLOUD-D19 Co-authored-by: Claude Opus 5 (1M context) --- shared/editor/extensions/Diff.test.ts | 103 ++++++++++++++++++++++++++ shared/editor/extensions/Diff.ts | 14 +++- 2 files changed, 114 insertions(+), 3 deletions(-) create mode 100644 shared/editor/extensions/Diff.test.ts diff --git a/shared/editor/extensions/Diff.test.ts b/shared/editor/extensions/Diff.test.ts new file mode 100644 index 0000000000..1b39947b86 --- /dev/null +++ b/shared/editor/extensions/Diff.test.ts @@ -0,0 +1,103 @@ +import { EditorState } from "prosemirror-state"; +import type { DecorationSet } from "prosemirror-view"; +import Diff from "./Diff"; +import { ChangesetHelper } from "../lib/ChangesetHelper"; +import type { ProsemirrorData } from "../../types"; + +/** + * Builds a document with a single checkbox list, one item per given state. + */ +function checkboxDoc(...checked: boolean[]): ProsemirrorData { + return { + type: "doc", + content: [ + { + type: "checkbox_list", + content: checked.map((isChecked, index) => ({ + type: "checkbox_item", + attrs: { checked: isChecked }, + content: [ + { + type: "paragraph", + content: [{ type: "text", text: `Task number ${index}` }], + }, + ], + })), + }, + ], + } as ProsemirrorData; +} + +/** + * Builds a document with a single table row, one cell per given node type. + */ +function tableDoc(...cellTypes: string[]): ProsemirrorData { + return { + type: "doc", + content: [ + { + type: "table", + content: [ + { + type: "tr", + content: cellTypes.map((type, index) => ({ + type, + content: [ + { + type: "paragraph", + content: [{ type: "text", text: `Cell ${index}` }], + }, + ], + })), + }, + ], + }, + ], + } as ProsemirrorData; +} + +/** + * Builds the diff decorations for the changeset between two documents. + */ +function decorationsFor(after: ProsemirrorData, before: ProsemirrorData) { + const changeset = ChangesetHelper.getChangeset(after, before); + expect(changeset).not.toBeNull(); + + const state = EditorState.create({ + doc: changeset!.doc, + plugins: new Diff({ changes: changeset!.changes }).plugins, + }); + + const decorations = state.plugins[0].getState(state) as DecorationSet; + return { decorations, doc: changeset!.doc }; +} + +describe("Diff", () => { + it("decorates the modified node", () => { + const { decorations, doc } = decorationsFor( + checkboxDoc(true, false), + checkboxDoc(false, false) + ); + + const firstItem = doc.child(0).child(0); + expect(decorations.find()).toEqual([ + expect.objectContaining({ from: 1, to: 1 + firstItem.nodeSize }), + ]); + }); + + it("keeps modification decorations within the document", () => { + const cases: Array<[ProsemirrorData, ProsemirrorData]> = [ + [checkboxDoc(true, true, true), checkboxDoc(false, false, false)], + [tableDoc("th", "th", "th"), tableDoc("td", "td", "td")], + ]; + + for (const [after, before] of cases) { + const { decorations, doc } = decorationsFor(after, before); + expect(decorations.find().length).toBeGreaterThan(0); + for (const decoration of decorations.find()) { + expect(decoration.from).toBeLessThanOrEqual(doc.content.size); + expect(decoration.to).toBeLessThanOrEqual(doc.content.size); + } + } + }); +}); diff --git a/shared/editor/extensions/Diff.ts b/shared/editor/extensions/Diff.ts index 68455a41fe..73701d6d2f 100644 --- a/shared/editor/extensions/Diff.ts +++ b/shared/editor/extensions/Diff.ts @@ -349,9 +349,17 @@ export default class Diff extends Extension { return; } - modification.data.slice.content.forEach((node: Node) => { - const nodeSize = node.nodeSize; - const end = pos + nodeSize; + modification.data.slice.content.forEach(() => { + // The slice describes the content before the change, and may cover + // more nodes than remain at this position, so the node being + // decorated is measured in the document itself. + const node = + pos <= doc.content.size ? doc.resolve(pos).nodeAfter : null; + if (!node) { + return; + } + + const end = pos + node.nodeSize; // Check if this specific node should use node decoration const useNodeDecoration = From 54ccfc76bb2a645c2a898e16ea9ad0add3edc45d Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 19 Aug 2026 16:58:01 -0400 Subject: [PATCH 04/55] fix: Crash inserting a math block from the suggestions menu (#13495) Opening the nested math editor moves focus, which dismisses the suggestions menu. Restoring focus to the outer view re-entered the node view's selection handling before it had finished, throwing "inner view should not exist!". Fixes OUTLINE-CLOUD-BZA Co-authored-by: Claude Opus 5 (1M context) --- app/editor/components/SuggestionsMenu.tsx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/app/editor/components/SuggestionsMenu.tsx b/app/editor/components/SuggestionsMenu.tsx index 13378cf2f5..051098d575 100644 --- a/app/editor/components/SuggestionsMenu.tsx +++ b/app/editor/components/SuggestionsMenu.tsx @@ -419,7 +419,13 @@ function SuggestionsMenu(props: Props) { 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 = ( From d2c11b9298942b324c30a0f881f3d21965a59dbc Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 19 Aug 2026 17:05:44 -0400 Subject: [PATCH 05/55] fix: MobX out of bounds warning searching an empty document (#13493) * fix: MobX out of bounds warning searching an empty document * Avoid negative match index when navigating with no results --- app/editor/extensions/FindAndReplace.tsx | 28 ++++++++++++++---------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/app/editor/extensions/FindAndReplace.tsx b/app/editor/extensions/FindAndReplace.tsx index 5de496ff60..edb4f3dcf0 100644 --- a/app/editor/extensions/FindAndReplace.tsx +++ b/app/editor/extensions/FindAndReplace.tsx @@ -111,11 +111,7 @@ export default class FindAndReplaceExtension extends Extension= 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 { + 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= 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 Date: Wed, 19 Aug 2026 19:55:26 -0400 Subject: [PATCH 06/55] fix: Unfurl GitLab epics (#13497) * wip: Epic support * fix: Unfurl GitLab epics and group work items Group-scoped work items are parsed as project issues, producing a project path of `groups/` and a 404 from the issues API. Parse the namespace around the `/-/` separator instead, and fetch group-scoped resources via the epics API. Co-Authored-By: Claude Opus 5 (1M context) * Truncate long mention labels instead of wrapping A mention with a long unfurled title wrapped the pill onto several lines. Cap it to a single line and elide the label, keeping icons and the trailing identifier intact. Co-Authored-By: Claude Opus 5 (1M context) * Build the project path only for project-scoped resources Co-Authored-By: Claude Opus 5 (1M context) --------- Co-authored-by: Claude Opus 5 (1M context) --- plugins/gitlab/server/gitlab.ts | 57 ++++++- plugins/gitlab/shared/GitLabUtils.test.ts | 71 ++++++++ plugins/gitlab/shared/GitLabUtils.ts | 187 ++++++++++++---------- shared/editor/components/Mentions.tsx | 8 +- shared/editor/components/Styles.ts | 21 +++ 5 files changed, 244 insertions(+), 100 deletions(-) diff --git a/plugins/gitlab/server/gitlab.ts b/plugins/gitlab/server/gitlab.ts index ae3528cebb..63edcaac72 100644 --- a/plugins/gitlab/server/gitlab.ts +++ b/plugins/gitlab/server/gitlab.ts @@ -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, diff --git a/plugins/gitlab/shared/GitLabUtils.test.ts b/plugins/gitlab/shared/GitLabUtils.test.ts index 5af9d766be..f9e0f5b875 100644 --- a/plugins/gitlab/shared/GitLabUtils.test.ts +++ b/plugins/gitlab/shared/GitLabUtils.test.ts @@ -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( diff --git a/plugins/gitlab/shared/GitLabUtils.ts b/plugins/gitlab/shared/GitLabUtils.ts index dde4bb6c99..4834960652 100644 --- a/plugins/gitlab/shared/GitLabUtils.ts +++ b/plugins/gitlab/shared/GitLabUtils.ts @@ -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 + > + > = { + 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; + } } /** diff --git a/shared/editor/components/Mentions.tsx b/shared/editor/components/Mentions.tsx index 272ed62dbb..22949e6963 100644 --- a/shared/editor/components/Mentions.tsx +++ b/shared/editor/components/Mentions.tsx @@ -73,7 +73,7 @@ export const MentionUser = observer(function MentionUser_( })} > - {user?.name || node.attrs.label} + {user?.name || node.attrs.label} ); }); @@ -94,7 +94,7 @@ export const MentionGroup = observer(function MentionGroup_( })} > - {group?.name || node.attrs.label} + {group?.name || node.attrs.label} ); }); @@ -135,7 +135,7 @@ export const MentionDocument = observer(function MentionDocument_( ) : ( )} - {doc?.title || node.attrs.label} + {doc?.title || node.attrs.label} ); }); @@ -173,7 +173,7 @@ export const MentionCollection = observer(function MentionCollection_( ) : ( )} - {collection?.title || node.attrs.label} + {collection?.title || node.attrs.label} ); }); diff --git a/shared/editor/components/Styles.ts b/shared/editor/components/Styles.ts index 5dde5def4f..ad036976f2 100644 --- a/shared/editor/components/Styles.ts +++ b/shared/editor/components/Styles.ts @@ -560,6 +560,27 @@ width: 100%; gap: 4px; vertical-align: bottom; + /* Long labels are truncated so a mention never wraps onto a second line. */ + max-width: 100%; + white-space: nowrap; + overflow: hidden; + + span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + /* Text sets white-space: normal, so nowrap cannot simply be inherited. */ + white-space: nowrap; + } + + /* Only the label truncates; icons and trailing identifiers stay whole. */ + &::before, + svg, + img, + span ~ span { + flex-shrink: 0; + } + &:${hover} { cursor: default; background: ${props.theme.mentionHoverBackground}; From 0f8f69de42a98488606a5251070cf534bdd14174 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Wed, 19 Aug 2026 23:38:09 -0400 Subject: [PATCH 07/55] Unpin and context menu controls on pinned documents (#13498) * feat: Unpin and context menu controls on pinned documents - Adds an unpin control to document chips in the collapsed pinned view - Adds the collapse toggle to collections, matching home - Makes the Pin menu items toggles with a selected state - Adds a document context menu to pinned cards and chips - Stops the drag sensor swallowing clicks on the card unpin button Co-Authored-By: Claude Opus 5 (1M context) * fix: Hide the collection pin toggle for a mixed selection Co-Authored-By: Claude Opus 5 (1M context) --------- Co-authored-by: Claude Opus 5 (1M context) --- app/actions/definitions/documents.tsx | 110 ++++++++++++++---- app/components/DocumentCard.tsx | 155 ++++++++++++++------------ app/components/DocumentChip.tsx | 96 ++++++++++++---- app/components/DocumentListItem.tsx | 17 +-- app/components/Menu/ContextMenu.tsx | 2 +- app/components/PinnedDocuments.tsx | 4 +- app/hooks/useDocumentActiveModels.ts | 25 +++++ app/menus/DocumentContextMenu.tsx | 47 ++++++++ app/menus/DocumentMenu.tsx | 19 +--- app/scenes/Collection/index.tsx | 6 +- 10 files changed, 337 insertions(+), 144 deletions(-) create mode 100644 app/hooks/useDocumentActiveModels.ts create mode 100644 app/menus/DocumentContextMenu.tsx diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index 7972f7d6a9..8539a47247 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -928,23 +928,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: , @@ -1006,14 +1008,6 @@ export const pinDocumentToHome = createAction({ }, }); -export const pinDocument = createActionWithChildren({ - name: ({ t }) => t("Pin"), - analyticsName: "Pin document", - section: ActiveDocumentSection, - icon: , - children: [pinDocumentToCollection, pinDocumentToHome], -}); - export const unpinDocument = createAction({ name: ({ t }) => t("Unpin"), analyticsName: "Unpin document", @@ -1039,6 +1033,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: , + 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: , + 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: , + children: [togglePinDocumentToCollection, togglePinDocumentToHome], +}); + export const searchInDocument = createInternalLinkAction({ name: ({ t }) => t("Search in document"), analyticsName: "Search document", diff --git a/app/components/DocumentCard.tsx b/app/components/DocumentCard.tsx index 0ffbc4a869..f67c2f9bd5 100644 --- a/app/components/DocumentCard.tsx +++ b/app/components/DocumentCard.tsx @@ -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 }} > - - - - - - - - {document.icon ? ( - - ) : ( - + + + - {collection?.icon && - collection?.icon !== "letter" && - collection?.icon !== "collection" && - pinnedToHome ? ( - - ) : ( - - )} - + + + + + {document.icon ? ( + + ) : ( + + {collection?.icon && + collection?.icon !== "letter" && + collection?.icon !== "collection" && + pinnedToHome ? ( + + ) : ( + + )} + + )} +
+ + {hasEmojiInTitle + ? document.titleWithDefault.replace(document.icon!, "") + : document.titleWithDefault} + + + {isRecentlyUpdated ? ( + updatedAt + ) : ( + + + + )} + +
+
+ {canUnpin && !isDragging && pin && ( + + + + + + + )} -
- - {hasEmojiInTitle - ? document.titleWithDefault.replace(document.icon!, "") - : document.titleWithDefault} - - - {isRecentlyUpdated ? ( - updatedAt - ) : ( - - - - )} - -
- - {canUnpin && !isDragging && pin && ( - - - - - - - - )} -
+ + ); diff --git a/app/components/DocumentChip.tsx b/app/components/DocumentChip.tsx index 64409bac76..5c45fb46ae 100644 --- a/app/components/DocumentChip.tsx +++ b/app/components/DocumentChip.tsx @@ -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 ( - - {icon ? ( - - ) : ( - - )} - {isEmoji ? title.replace(icon!, "") : title} - + + + {icon ? ( + + ) : ( + + )} + {isEmoji ? title.replace(icon!, "") : title} + {pin && canUnpin && ( + + + + + + )} + + ); }); @@ -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; + } `; diff --git a/app/components/DocumentListItem.tsx b/app/components/DocumentListItem.tsx index c5243ff9b6..eb20ccc727 100644 --- a/app/components/DocumentListItem.tsx +++ b/app/components/DocumentListItem.tsx @@ -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 ( - + - {children} + {children} {items.map((documentId) => { const document = documents.get(documentId); + const pin = pins.find((p) => p.documentId === documentId); + return document ? ( - + ) : null; })} diff --git a/app/hooks/useDocumentActiveModels.ts b/app/hooks/useDocumentActiveModels.ts new file mode 100644 index 0000000000..5383af2306 --- /dev/null +++ b/app/hooks/useDocumentActiveModels.ts @@ -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] : []), + ]; +} diff --git a/app/menus/DocumentContextMenu.tsx b/app/menus/DocumentContextMenu.tsx new file mode 100644 index 0000000000..00bae9abd2 --- /dev/null +++ b/app/menus/DocumentContextMenu.tsx @@ -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 ( + + + {children} + + + ); +}); diff --git a/app/menus/DocumentMenu.tsx b/app/menus/DocumentMenu.tsx index 894e480de4..d418777b62 100644 --- a/app/menus/DocumentMenu.tsx +++ b/app/menus/DocumentMenu.tsx @@ -13,6 +13,7 @@ import { OverflowMenuButton } from "~/components/Menu/OverflowMenuButton"; import Switch from "~/components/Switch"; import { 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 +61,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, @@ -197,14 +193,7 @@ function DocumentMenu({ ]); return ( - + - + Date: Fri, 21 Aug 2026 19:36:11 -0400 Subject: [PATCH 08/55] Superellipse corners for menus, dialogs, and floating surfaces (#13520) * Superellipse corner-shape utility for elevated surfaces * Rename squircle helper to borderRadius, use block comment in CSS string --- app/components/DocumentCard.tsx | 4 ++-- app/components/Modal.tsx | 4 ++-- app/components/ModelSelectionToolbar.tsx | 4 ++-- app/components/UserHoverCard.tsx | 4 ++-- app/components/primitives/Drawer.tsx | 4 ++-- app/components/primitives/InputSelect.tsx | 4 ++-- app/components/primitives/Popover.tsx | 4 ++-- app/components/primitives/components/Menu.tsx | 4 ++-- shared/components/Calendar.tsx | 4 ++-- shared/editor/components/ColorHoverCard.tsx | 4 ++-- shared/editor/components/DateMentionPicker.tsx | 4 ++-- shared/editor/components/Styles.ts | 10 ++++++++++ shared/styles/index.ts | 18 ++++++++++++++++++ 13 files changed, 50 insertions(+), 22 deletions(-) diff --git a/app/components/DocumentCard.tsx b/app/components/DocumentCard.tsx index f67c2f9bd5..6f9ded7570 100644 --- a/app/components/DocumentCard.tsx +++ b/app/components/DocumentCard.tsx @@ -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"; @@ -305,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; diff --git a/app/components/Modal.tsx b/app/components/Modal.tsx index 1f21e0b655..5d75f32f34 100644 --- a/app/components/Modal.tsx +++ b/app/components/Modal.tsx @@ -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} { diff --git a/app/components/ModelSelectionToolbar.tsx b/app/components/ModelSelectionToolbar.tsx index 6d2000afcb..4af641c6a1 100644 --- a/app/components/ModelSelectionToolbar.tsx +++ b/app/components/ModelSelectionToolbar.tsx @@ -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; `; diff --git a/app/components/UserHoverCard.tsx b/app/components/UserHoverCard.tsx index 9fe83bcd22..2392f83ae0 100644 --- a/app/components/UserHoverCard.tsx +++ b/app/components/UserHoverCard.tsx @@ -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; diff --git a/app/components/primitives/Drawer.tsx b/app/components/primitives/Drawer.tsx index d556d400d3..8df6c76142 100644 --- a/app/components/primitives/Drawer.tsx +++ b/app/components/primitives/Drawer.tsx @@ -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")}; `; diff --git a/app/components/primitives/InputSelect.tsx b/app/components/primitives/InputSelect.tsx index dbafe63786..0cb5f1bb40 100644 --- a/app/components/primitives/InputSelect.tsx +++ b/app/components/primitives/InputSelect.tsx @@ -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; diff --git a/app/components/primitives/Popover.tsx b/app/components/primitives/Popover.tsx index c1b4510127..634998ef02 100644 --- a/app/components/primitives/Popover.tsx +++ b/app/components/primitives/Popover.tsx @@ -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)` background: ${s("menuBackground")}; box-shadow: ${s("menuShadow")}; - border-radius: 6px; + ${borderRadius(8)} outline: none; padding: ${({ $shrink }) => ($shrink ? "6px 0" : "12px 24px")}; diff --git a/app/components/primitives/components/Menu.tsx b/app/components/primitives/components/Menu.tsx index 5337b06731..412178d5fb 100644 --- a/app/components/primitives/components/Menu.tsx +++ b/app/components/primitives/components/Menu.tsx @@ -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( 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; diff --git a/shared/components/Calendar.tsx b/shared/components/Calendar.tsx index efbce7e2eb..03dd8bbe6b 100644 --- a/shared/components/Calendar.tsx +++ b/shared/components/Calendar.tsx @@ -79,7 +79,7 @@ const Wrapper = styled.div` background: none; border-radius: 4px; color: ${s("textSecondary")}; - cursor: pointer; + cursor: var(--pointer); transition: background 100ms ease; &:hover { @@ -124,7 +124,7 @@ const Wrapper = styled.div` font-size: 13px; font-variant-numeric: tabular-nums; color: ${s("text")}; - cursor: pointer; + cursor: var(--pointer); transition: background 100ms ease; &:hover:not([disabled]):not(.rdp-day_selected) { diff --git a/shared/editor/components/ColorHoverCard.tsx b/shared/editor/components/ColorHoverCard.tsx index e9db45a690..a40f536d2d 100644 --- a/shared/editor/components/ColorHoverCard.tsx +++ b/shared/editor/components/ColorHoverCard.tsx @@ -1,7 +1,7 @@ import * as PopoverPrimitive from "@radix-ui/react-popover"; import type { ReactNode } from "react"; import styled from "styled-components"; -import { depths, s } from "../../styles"; +import { depths, s, borderRadius } from "../../styles"; import type { EditorNotice } from "../types"; import { ColorPreview } from "./ColorPreview"; @@ -67,7 +67,7 @@ const Card = styled.div` z-index: ${depths.modal}; background: ${s("menuBackground")}; box-shadow: ${s("menuShadow")}; - border-radius: 8px; + ${borderRadius(8)} outline: none; &[data-state="open"] { diff --git a/shared/editor/components/DateMentionPicker.tsx b/shared/editor/components/DateMentionPicker.tsx index e4a397e655..fb36dc0c7a 100644 --- a/shared/editor/components/DateMentionPicker.tsx +++ b/shared/editor/components/DateMentionPicker.tsx @@ -6,7 +6,7 @@ import { useTranslation } from "react-i18next"; import { RemoveScroll } from "react-remove-scroll"; import styled from "styled-components"; import { Calendar } from "../../components/Calendar"; -import { depths, s } from "../../styles"; +import { depths, s, borderRadius } from "../../styles"; import { dateLocale, toISODate, toISODateTime } from "../../utils/date"; type Props = { @@ -100,7 +100,7 @@ const DatePopoverContent = styled.div` z-index: ${depths.modal}; background: ${s("menuBackground")}; box-shadow: ${s("menuShadow")}; - border-radius: 8px; + ${borderRadius(8)} outline: none; &[data-state="open"] { diff --git a/shared/editor/components/Styles.ts b/shared/editor/components/Styles.ts index ad036976f2..8e35a98ec7 100644 --- a/shared/editor/components/Styles.ts +++ b/shared/editor/components/Styles.ts @@ -586,6 +586,16 @@ width: 100%; background: ${props.theme.mentionHoverBackground}; } + /* Date mentions only open the picker when editable, so no hover affordance + in read-only mode. */ + ${ + props.readOnly + ? `&[data-type="date"]:${hover} { + background: ${props.theme.mentionBackground}; + }` + : "" + } + &[data-type="user"], &[data-type="group"] { gap: 0; diff --git a/shared/styles/index.ts b/shared/styles/index.ts index 6c15bcd136..4341f564c4 100644 --- a/shared/styles/index.ts +++ b/shared/styles/index.ts @@ -46,6 +46,24 @@ export const hideScrollbars = () => ` } `; +/** + * Mixin to give an element superellipse ("squircle") corners in browsers that + * support `corner-shape`, with a standard border radius elsewhere. + * + * @param radius the border radius in pixels. + * @param exponent the superellipse exponent, where 2 is a squircle. + * @returns string of CSS + */ +export const borderRadius = (radius: number, exponent = 2) => ` + border-radius: ${radius}px; + + @supports (corner-shape: superellipse(2)) { + /* A superellipse is tighter than a circular arc, so increase the radius to compensate. */ + border-radius: ${Math.round(radius * 1.8)}px; + corner-shape: superellipse(${exponent}); + } +`; + /** * Mixin on any component with relative positioning to add additional hidden clickable/hoverable area * From e88b6ad28c1adef64c0b76182925c185a1bc9766 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 21 Aug 2026 19:36:23 -0400 Subject: [PATCH 09/55] Exclude archived documents from MCP document search by default (#13518) --- server/tools/documents.test.ts | 87 ++++++++++++++++++++++++++++++++++ server/tools/documents.ts | 40 ++++++++++++---- 2 files changed, 117 insertions(+), 10 deletions(-) diff --git a/server/tools/documents.test.ts b/server/tools/documents.test.ts index 098905ae08..ae82fd9f53 100644 --- a/server/tools/documents.test.ts +++ b/server/tools/documents.test.ts @@ -251,6 +251,93 @@ describe("list_documents", () => { expect(ids).toContain(document.id); }); + it("excludes archived documents from search by default", async () => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + title: "Blackberry", + }); + const archived = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + title: "Blackberry", + archivedAt: new Date(), + }); + + const res = await callMcpTool(server, accessToken, "list_documents", { + query: "Blackberry", + }); + const data = parseMcpListContent<{ document: { id: string } }>( + res?.result?.content + ); + const ids = data.map((d) => d.document.id); + + expect(ids).toContain(document.id); + expect(ids).not.toContain(archived.id); + }); + + it("includes archived documents in search when requested", async () => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const archived = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + title: "Blackberry", + archivedAt: new Date(), + }); + + const res = await callMcpTool(server, accessToken, "list_documents", { + query: "Blackberry", + includeArchived: true, + }); + const data = parseMcpListContent<{ document: { id: string } }>( + res?.result?.content + ); + const ids = data.map((d) => d.document.id); + + expect(ids).toContain(archived.id); + }); + + it("includes archived documents in recent documents when requested", async () => { + const { user, accessToken } = await buildOAuthUser(); + const collection = await buildCollection({ + teamId: user.teamId, + userId: user.id, + }); + const archived = await buildDocument({ + teamId: user.teamId, + userId: user.id, + collectionId: collection.id, + archivedAt: new Date(), + }); + + const excluded = parseMcpListContent<{ document: { id: string } }>( + (await callMcpTool(server, accessToken, "list_documents"))?.result + ?.content + ).map((d) => d.document.id); + expect(excluded).not.toContain(archived.id); + + const included = parseMcpListContent<{ document: { id: string } }>( + ( + await callMcpTool(server, accessToken, "list_documents", { + includeArchived: true, + }) + )?.result?.content + ).map((d) => d.document.id); + expect(included).toContain(archived.id); + }); + it("records the search query with an mcp source", async () => { const { user, accessToken } = await buildOAuthUser(); const collection = await buildCollection({ diff --git a/server/tools/documents.ts b/server/tools/documents.ts index 626872a3c1..8bae887be0 100644 --- a/server/tools/documents.ts +++ b/server/tools/documents.ts @@ -10,6 +10,7 @@ import documentRestorer from "@server/commands/documentRestorer"; import documentUpdater from "@server/commands/documentUpdater"; import { Collection, Document, SearchQuery, Template } from "@server/models"; import { SearchQuerySource } from "@server/models/SearchQuery"; +import { combineFilters } from "@server/models/helpers/Filters"; import DocumentImportTask from "@server/queues/tasks/DocumentImportTask"; import { sequelize } from "@server/storage/database"; import { authorize, can } from "@server/policies"; @@ -72,7 +73,7 @@ export function documentTools(server: McpServer, scopes: string[]) { { title: "Search documents", description: - "Searches documents the user has access to. Performs full-text search across document content when a query is provided, or lists recent documents when no query is given. Optionally filter by collection. To retrieve the full contents or hierarchy of a specific collection, use list_collection_documents instead.", + "Searches documents the user has access to. Performs full-text search across document content when a query is provided, or lists recent documents when no query is given. Archived documents are excluded unless includeArchived is set. Optionally filter by collection. To retrieve the full contents or hierarchy of a specific collection, use list_collection_documents instead.", annotations: { idempotentHint: true, readOnlyHint: true, @@ -84,6 +85,12 @@ export function documentTools(server: McpServer, scopes: string[]) { collectionId: optionalString().describe( "A collection ID to filter documents by." ), + includeArchived: z + .boolean() + .optional() + .describe( + "Whether to include archived documents in the results. Defaults to false, as archived documents are usually outdated." + ), offset: z.coerce .number() .int() @@ -103,7 +110,10 @@ export function documentTools(server: McpServer, scopes: string[]) { }, withTracing( "list_documents", - async ({ query, collectionId, offset, limit }, extra) => { + async ( + { query, collectionId, includeArchived, offset, limit }, + extra + ) => { try { const user = getActorFromContext(extra); const effectiveOffset = offset ?? 0; @@ -146,17 +156,25 @@ export function documentTools(server: McpServer, scopes: string[]) { } const searchStartedAt = Date.now(); + const searchFilters: Filter[] = []; + if (!includeArchived) { + searchFilters.push({ + field: "archivedAt", + operator: "isNull", + }); + } + if (collectionId) { + searchFilters.push({ + field: "collectionId", + operator: "eq", + value: collectionId, + }); + } const { results, total } = await searchProvider.searchForUser( user, { query, - filter: collectionId - ? { - field: "collectionId", - operator: "eq", - value: collectionId, - } - : undefined, + filter: combineFilters(searchFilters), offset: effectiveOffset, limit: effectiveLimit, } @@ -241,9 +259,11 @@ export function documentTools(server: McpServer, scopes: string[]) { // access control matches the search path exactly. const searchProvider = SearchProviderManager.getProvider(); const filters: Filter[] = [ - { field: "archivedAt", operator: "isNull" }, { field: "publishedAt", operator: "isNotNull" }, ]; + if (!includeArchived) { + filters.push({ field: "archivedAt", operator: "isNull" }); + } if (collectionId) { filters.push({ field: "collectionId", From 5ee3f1a5d993f033def9b7804275937463608e40 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 21 Aug 2026 20:49:29 -0400 Subject: [PATCH 10/55] perf: Refactor `y-prosemirror` loading (#13521) * wip * perf: Refactor y-prosemirror loading --- app/editor/extensions/CommentGutter.tsx | 6 ++- app/editor/extensions/Multiplayer.ts | 30 ++++++++++-- app/editor/extensions/PasteHandler.tsx | 4 +- app/editor/index.tsx | 2 +- shared/editor/extensions/Mermaid.ts | 10 ++-- shared/editor/lib/closeHistory.ts | 5 +- shared/editor/lib/multiplayer.ts | 46 ++++++++++++++++--- shared/editor/lib/uploadPlaceholder.tsx | 4 +- shared/editor/nodes/CodeFence.ts | 2 +- shared/editor/nodes/ToggleBlock.ts | 2 +- shared/editor/plugins/AnchorPlugin.ts | 5 +- .../editor/plugins/CodeHighlightingPlugin.ts | 2 +- .../plugins/CodeWordDecorationsPlugin.ts | 5 +- shared/editor/plugins/CommentedImagePlugin.ts | 2 +- .../plugins/DraftCommentAnchorPlugin.ts | 8 +++- .../editor/plugins/SuggestionsMenuPlugin.ts | 8 +++- 16 files changed, 109 insertions(+), 32 deletions(-) diff --git a/app/editor/extensions/CommentGutter.tsx b/app/editor/extensions/CommentGutter.tsx index bbe9db2b1e..049634834e 100644 --- a/app/editor/extensions/CommentGutter.tsx +++ b/app/editor/extensions/CommentGutter.tsx @@ -72,7 +72,11 @@ export default class CommentGutter extends Extension { } return { - decorations: mapDecorations(pluginState.decorations, tr), + decorations: mapDecorations( + pluginState.decorations, + tr, + newState + ), }; }, }, diff --git a/app/editor/extensions/Multiplayer.ts b/app/editor/extensions/Multiplayer.ts index 8bfe608f0f..ff8b2dfea0 100644 --- a/app/editor/extensions/Multiplayer.ts +++ b/app/editor/extensions/Multiplayer.ts @@ -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 { MultiplayerState } 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"; @@ -125,9 +131,27 @@ export default class Multiplayer extends Extension { selectionBuilder, }), yUndoPlugin(), - new Plugin({ + // Facade plugin that exposes the collaboration operations to shared + // code without a static dependency on the collaboration libraries. + new Plugin({ + key: multiplayerPluginKey, + state: { + init: (): MultiplayerState => ({ + 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(); + }, + }), + apply: (_tr, value) => value, + }, props: { - handleScrollToSelection: (view) => isRemoteTransaction(view.state.tr), + handleScrollToSelection: (view) => + isRemoteTransaction(view.state.tr, view.state), }, }), ]; diff --git a/app/editor/extensions/PasteHandler.tsx b/app/editor/extensions/PasteHandler.tsx index e9e58ff7ee..4e147bee92 100644 --- a/app/editor/extensions/PasteHandler.tsx +++ b/app/editor/extensions/PasteHandler.tsx @@ -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, diff --git a/app/editor/index.tsx b/app/editor/index.tsx index d7042b2dd5..7e41854ea8 100644 --- a/app/editor/index.tsx +++ b/app/editor/index.tsx @@ -560,7 +560,7 @@ export class Editor extends React.PureComponent< ) { self.handleChange({ remote: transactions.some( - (tr) => tr.docChanged && isRemoteTransaction(tr) + (tr) => tr.docChanged && isRemoteTransaction(tr, state) ), }); } diff --git a/shared/editor/extensions/Mermaid.ts b/shared/editor/extensions/Mermaid.ts index b750562e6c..88d26b4b3f 100644 --- a/shared/editor/extensions/Mermaid.ts +++ b/shared/editor/extensions/Mermaid.ts @@ -384,7 +384,11 @@ export default function Mermaid({ mermaidMeta && "editingId" in mermaidMeta ? mermaidMeta.editingId : pluginState.editingId, - decorationSet: mapDecorations(pluginState.decorationSet, transaction), + decorationSet: mapDecorations( + pluginState.decorationSet, + transaction, + state + ), }; if ( @@ -427,7 +431,7 @@ export default function Mermaid({ mermaidMeta || themeToggled || codeBlockChanged || - isRemoteTransaction(transaction) + isRemoteTransaction(transaction, state) ) { return getNewState({ doc: transaction.doc, @@ -437,7 +441,7 @@ export default function Mermaid({ codeBlockChanged && transaction.docChanged && !isPaste && - !isRemoteTransaction(transaction), + !isRemoteTransaction(transaction, state), }); } diff --git a/shared/editor/lib/closeHistory.ts b/shared/editor/lib/closeHistory.ts index 14a6f4afa1..d9cffcc737 100644 --- a/shared/editor/lib/closeHistory.ts +++ b/shared/editor/lib/closeHistory.ts @@ -4,7 +4,7 @@ import { undoDepth, } from "prosemirror-history"; import type { EditorView } from "prosemirror-view"; -import { yUndoPluginKey } from "y-prosemirror"; +import { stopCapturingUndo } from "./multiplayer"; /** * Closes the current history item so that subsequent changes start a new undo @@ -19,6 +19,5 @@ export function closeHistory(view: EditorView): void { view.dispatch(pmCloseHistory(view.state.tr)); } - const yUndoState = yUndoPluginKey.getState(view.state); - yUndoState?.undoManager?.stopCapturing(); + stopCapturingUndo(view.state); } diff --git a/shared/editor/lib/multiplayer.ts b/shared/editor/lib/multiplayer.ts index 3a374c302c..6e172925a9 100644 --- a/shared/editor/lib/multiplayer.ts +++ b/shared/editor/lib/multiplayer.ts @@ -1,19 +1,49 @@ -import type { Transaction } from "prosemirror-state"; +import type { EditorState, Transaction } from "prosemirror-state"; +import { PluginKey } from "prosemirror-state"; import type { DecorationSet } from "prosemirror-view"; -import { ySyncPluginKey } from "y-prosemirror"; import { recreateTransform } from "./prosemirror-recreate-transform"; +/** + * State of the facade plugin mounted by the multiplayer extension. It exposes + * the collaboration operations to shared code without a static dependency on + * the collaboration libraries. + */ +export interface MultiplayerState { + /** Returns true if the transaction originated from a remote client. */ + isRemoteTransaction: (tr: Transaction) => boolean; + /** Stops the collaborative undo manager from capturing further changes. */ + stopCapturing: (state: EditorState) => void; +} + +/** + * Key of the facade plugin mounted by the multiplayer extension. + */ +export const multiplayerPluginKey = new PluginKey( + "multiplayer-facade" +); + /** * Checks if a transaction is a remote transaction * * @param tr The Prosemirror transaction + * @param state The editor state * @returns true if the transaction is a remote transaction */ -export function isRemoteTransaction(tr: Transaction): boolean { - const meta = tr.getMeta(ySyncPluginKey); +export function isRemoteTransaction( + tr: Transaction, + state: EditorState +): boolean { + return multiplayerPluginKey.getState(state)?.isRemoteTransaction(tr) ?? false; +} - // This logic seems to be flipped? But it's correct. - return !!meta?.isChangeOrigin; +/** + * Stops the collaborative undo manager from capturing further changes, if + * the multiplayer extension is mounted in the editor. + * + * @param state The editor state + */ +export function stopCapturingUndo(state: EditorState): void { + multiplayerPluginKey.getState(state)?.stopCapturing(state); } /** @@ -21,18 +51,20 @@ export function isRemoteTransaction(tr: Transaction): boolean { * * @param set The current set of decorations * @param tr The Prosemirror transaction + * @param state The editor state * @param force Whether to force recalculation for map even for local transactions * @returns The mapped set of decorations */ export function mapDecorations( set: DecorationSet, tr: Transaction, + state: EditorState, force: boolean = false ): DecorationSet { let mapping = tr.mapping; const hasDecorations = set.find().length; - if (hasDecorations && (isRemoteTransaction(tr) || force)) { + if (hasDecorations && (isRemoteTransaction(tr, state) || force)) { try { mapping = recreateTransform(tr.before, tr.doc, { complexSteps: true, diff --git a/shared/editor/lib/uploadPlaceholder.tsx b/shared/editor/lib/uploadPlaceholder.tsx index b8f7738924..328c982745 100644 --- a/shared/editor/lib/uploadPlaceholder.tsx +++ b/shared/editor/lib/uploadPlaceholder.tsx @@ -11,11 +11,11 @@ const uploadPlaceholder = new Plugin({ init() { return DecorationSet.empty; }, - apply(this: Plugin, tr, set: DecorationSet) { + apply(this: Plugin, tr, set: DecorationSet, _oldState, newState) { // See if the transaction adds or removes any placeholders – the placeholder display is // different depending on if we're uploading an image, video or plain file const action = tr.getMeta(this); - set = mapDecorations(set, tr, !!action); + set = mapDecorations(set, tr, newState, !!action); if (action?.add) { if (action.add.replaceExisting) { diff --git a/shared/editor/nodes/CodeFence.ts b/shared/editor/nodes/CodeFence.ts index e6bc406451..792caf529f 100644 --- a/shared/editor/nodes/CodeFence.ts +++ b/shared/editor/nodes/CodeFence.ts @@ -476,7 +476,7 @@ export default class CodeFence extends Node { if (tr.docChanged) { const tallBlocks = findTallBlocks(newState.doc); const collapsedBlocks = new Set(); - const isRemote = isRemoteTransaction(tr); + const isRemote = isRemoteTransaction(tr, newState); const inverse = tr.mapping.invert(); for (const pos of tallBlocks) { diff --git a/shared/editor/nodes/ToggleBlock.ts b/shared/editor/nodes/ToggleBlock.ts index 7c0c8c78eb..a5ab44be52 100644 --- a/shared/editor/nodes/ToggleBlock.ts +++ b/shared/editor/nodes/ToggleBlock.ts @@ -164,7 +164,7 @@ export default class ToggleBlock extends Node { }, apply: (tr, pluginState, _oldState, newState) => { - if (isRemoteTransaction(tr)) { + if (isRemoteTransaction(tr, newState)) { const foldedIds = this.initFoldedIds(newState); return { foldedIds, diff --git a/shared/editor/plugins/AnchorPlugin.ts b/shared/editor/plugins/AnchorPlugin.ts index cba28f57d3..977c2470c9 100644 --- a/shared/editor/plugins/AnchorPlugin.ts +++ b/shared/editor/plugins/AnchorPlugin.ts @@ -19,7 +19,10 @@ export class AnchorPlugin extends Plugin { return pluginState; } - if (isRemoteTransaction(tr) || this.hasAnchorableChange(tr)) { + if ( + isRemoteTransaction(tr, newState) || + this.hasAnchorableChange(tr) + ) { return { decorations: this.createDecorations(newState) }; } diff --git a/shared/editor/plugins/CodeHighlightingPlugin.ts b/shared/editor/plugins/CodeHighlightingPlugin.ts index a721489c73..a6f701a68e 100644 --- a/shared/editor/plugins/CodeHighlightingPlugin.ts +++ b/shared/editor/plugins/CodeHighlightingPlugin.ts @@ -218,7 +218,7 @@ export function CodeHighlighting({ codeBlockChanged || isPaste || langLoaded || - isRemoteTransaction(transaction) + isRemoteTransaction(transaction, state) ) { // Invalidate cached entries for blocks whose language just loaded // so getDecorations rebuilds them with syntax highlighting applied. diff --git a/shared/editor/plugins/CodeWordDecorationsPlugin.ts b/shared/editor/plugins/CodeWordDecorationsPlugin.ts index 365f6a2bf2..0475e7f40b 100644 --- a/shared/editor/plugins/CodeWordDecorationsPlugin.ts +++ b/shared/editor/plugins/CodeWordDecorationsPlugin.ts @@ -32,7 +32,10 @@ class CodeWordDecorationsPlugin extends Plugin { return pluginState; } - if (isRemoteTransaction(tr) || this.hasCodeInlineChange(tr)) { + if ( + isRemoteTransaction(tr, newState) || + this.hasCodeInlineChange(tr) + ) { return { decorations: this.createDecorations(newState, finalConfig), }; diff --git a/shared/editor/plugins/CommentedImagePlugin.ts b/shared/editor/plugins/CommentedImagePlugin.ts index 8351309481..76987afdf1 100644 --- a/shared/editor/plugins/CommentedImagePlugin.ts +++ b/shared/editor/plugins/CommentedImagePlugin.ts @@ -22,7 +22,7 @@ export class CommentedImagePlugin extends Plugin { return pluginState; } - if (isRemoteTransaction(tr) || this.hasImageChange(tr)) { + if (isRemoteTransaction(tr, newState) || this.hasImageChange(tr)) { return { decorations: this.createDecorations(newState) }; } diff --git a/shared/editor/plugins/DraftCommentAnchorPlugin.ts b/shared/editor/plugins/DraftCommentAnchorPlugin.ts index 4a95e550b8..108916b070 100644 --- a/shared/editor/plugins/DraftCommentAnchorPlugin.ts +++ b/shared/editor/plugins/DraftCommentAnchorPlugin.ts @@ -52,7 +52,11 @@ export class DraftCommentAnchorPlugin extends Plugin { return pluginState; } - let decorations = mapDecorations(pluginState.decorations, tr); + let decorations = mapDecorations( + pluginState.decorations, + tr, + newState + ); if (meta?.add) { const { id, from, to, isNode, userId } = meta.add; @@ -88,7 +92,7 @@ export class DraftCommentAnchorPlugin extends Plugin { // local decoration in favor of the real mark. if ( tr.docChanged && - isRemoteTransaction(tr) && + isRemoteTransaction(tr, newState) && decorations.find().length > 0 ) { const markIds = new Set( diff --git a/shared/editor/plugins/SuggestionsMenuPlugin.ts b/shared/editor/plugins/SuggestionsMenuPlugin.ts index c3b12a0d5f..6742c31254 100644 --- a/shared/editor/plugins/SuggestionsMenuPlugin.ts +++ b/shared/editor/plugins/SuggestionsMenuPlugin.ts @@ -100,7 +100,7 @@ export class SuggestionsMenuPlugin extends Plugin { // changes to the document, including those made by other users. state: { init: (): PluginState => ({ decorations: DecorationSet.empty }), - apply: (tr, pluginState): PluginState => { + apply: (tr, pluginState, _oldState, newState): PluginState => { const range: TriggerRange | undefined | null = tr.getMeta(key); if (range !== undefined) { @@ -127,7 +127,11 @@ export class SuggestionsMenuPlugin extends Plugin { return pluginState; } - const decorations = mapDecorations(pluginState.decorations, tr); + const decorations = mapDecorations( + pluginState.decorations, + tr, + newState + ); const [decoration] = decorations.find(); const { trigger } = extensionState; From 67b53220ceb587d040b78bea723134184c5438e7 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 21 Aug 2026 20:54:30 -0400 Subject: [PATCH 11/55] perf: Limit PWA precache and skip service worker on share views (#13519) * perf: Cache JS chunks on first use instead of precaching entire build The service worker precached every JS chunk (~590 files) in the background for every visitor. Chunks are content-hashed and immutable, so a CacheFirst runtime route provides the same repeat-visit behavior while only fetching chunks that are actually used. Co-Authored-By: Claude Fable 5 * perf: Do not register service worker on public share views Anonymous share visitors gain nothing from the worker or the PWA cache, shares always require the API. The server now exposes an isShare flag in window.env and the client skips registration when it is set. Co-Authored-By: Claude Fable 5 --------- Co-authored-by: Claude Fable 5 --- app/index.tsx | 8 +++++++- server/presenters/env.ts | 2 ++ shared/types.ts | 3 +++ vite.config.ts | 20 +++++++++++++++++++- 4 files changed, 31 insertions(+), 2 deletions(-) diff --git a/app/index.tsx b/app/index.tsx index 6dd18656b3..3b5fc4a48a 100644 --- a/app/index.tsx +++ b/app/index.tsx @@ -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` diff --git a/server/presenters/env.ts b/server/presenters/env.ts index 3523f3cf68..d1dc601a99 100644 --- a/server/presenters/env.ts +++ b/server/presenters/env.ts @@ -9,10 +9,12 @@ export default function present( options: { analytics?: Integration[]; rootShareId?: string | null; + isShare?: boolean; } = {} ): PublicEnv { return { ROOT_SHARE_ID: options.rootShareId || undefined, + isShare: options.isShare || undefined, analytics: (options.analytics ?? []).map((integration) => ({ service: integration?.service, settings: integration?.settings, diff --git a/shared/types.ts b/shared/types.ts index 3d21f4734a..af2e6b1947 100644 --- a/shared/types.ts +++ b/shared/types.ts @@ -135,7 +135,10 @@ export enum MentionType { } export type PublicEnv = { + /** ID of the share mounted at the root of a custom domain, if any. */ ROOT_SHARE_ID?: string; + /** Whether the page is a publicly shared view. */ + isShare?: boolean; analytics: { service: IntegrationService; settings: IntegrationSettings; diff --git a/vite.config.ts b/vite.config.ts index 40e3f92191..70ef306888 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -61,7 +61,7 @@ export default ({ mode }: ConfigEnv) => registerType: "autoUpdate", workbox: { maximumFileSizeToCacheInBytes: 5 * 1024 * 1024, - globPatterns: ["**/*.{js,css,ico,png,svg}"], + globPatterns: ["**/*.{css,ico,png,svg}"], navigateFallback: null, modifyURLPrefix: { "": `${environment.CDN_URL ?? ""}/static/`, @@ -70,6 +70,24 @@ export default ({ mode }: ConfigEnv) => clientsClaim: true, cleanupOutdatedCaches: true, runtimeCaching: [ + { + // Chunks are content-hashed and immutable, so cache them on + // first use rather than precaching the entire build. + urlPattern: ({ url }) => + url.pathname.startsWith("/static/assets/") && + url.pathname.endsWith(".js"), + handler: "CacheFirst", + options: { + cacheName: "js-cache", + expiration: { + maxEntries: 200, + maxAgeSeconds: 2592000, // 30 days + }, + cacheableResponse: { + statuses: [200], + }, + }, + }, { urlPattern: /api\/urls\.unfurl$/, handler: "CacheOnly", From 2beacf9d56fb41331191c272fc445ef81286f1cb Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 21 Aug 2026 20:54:57 -0400 Subject: [PATCH 12/55] fix: Rate limit response headers and first-request accounting (#13506) * fix: Rate limit response headers and first-request accounting Retry-After and RateLimit-Reset are both defined as a whole number of seconds. Retry-After was sent as a fraction and RateLimit-Reset as a full date string, neither of which a client can act on. A route limiter is registered by middleware that runs after the point where quota is consumed, so the first request to reach a path in each process was never charged against it. Charge it at registration time instead. Co-Authored-By: Claude Opus 5 (1M context) * test: Cover rate limit headers and first request accounting Co-Authored-By: Claude Opus 5 (1M context) --------- Co-authored-by: Claude Opus 5 (1M context) --- server/middlewares/rateLimiter.test.ts | 85 ++++++++++++++++++++++- server/middlewares/rateLimiter.ts | 93 +++++++++++++++++--------- server/types.ts | 2 + 3 files changed, 149 insertions(+), 31 deletions(-) diff --git a/server/middlewares/rateLimiter.test.ts b/server/middlewares/rateLimiter.test.ts index 7ff403be54..c57f5e7274 100644 --- a/server/middlewares/rateLimiter.test.ts +++ b/server/middlewares/rateLimiter.test.ts @@ -10,6 +10,8 @@ interface MockContextOptions { path?: string; mountPath?: string; ip?: string; + /** Records the response headers the middleware writes. */ + set?: ReturnType; /** 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: {}, @@ -348,4 +352,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"); + }); + }); }); diff --git a/server/middlewares/rateLimiter.ts b/server/middlewares/rateLimiter.ts index 56bbee00b3..c0a645487a 100644 --- a/server/middlewares/rateLimiter.ts +++ b/server/middlewares/rateLimiter.ts @@ -52,6 +52,56 @@ async function getRateLimiterIdentifiers(ctx: AppContext): Promise { 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 { + 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: fullPath, + }); + + 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 @@ -67,38 +117,12 @@ export function defaultRateLimiter() { const fullPath = `${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(); }; @@ -150,6 +174,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(); diff --git a/server/types.ts b/server/types.ts index a0cdec7cc8..119613ecbb 100644 --- a/server/types.ts +++ b/server/types.ts @@ -76,6 +76,8 @@ export type AppState = { oauthClient?: OAuthClient; oauthIntent?: OAuthIntent; oauthState?: OAuthState; + /** The identifiers this request is rate limited against. */ + rateLimiterIdentifiers?: string[]; }; export type AppContext = ParameterizedContext; From 7652d26d07307df2ab1ef3377df2bc1dd8a3da0c Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 21 Aug 2026 20:59:21 -0400 Subject: [PATCH 13/55] fix: Consistent rate limiter keys across path variants (#13504) * fix: Normalize path when keying rate limiters The router matches paths case-insensitively and with an optional trailing slash, so those variants each received their own quota. Collapse them onto a single key at both registration and consumption. Co-Authored-By: Claude Opus 5 (1M context) * feedback --------- Co-authored-by: Claude Opus 5 (1M context) --- server/middlewares/rateLimiter.test.ts | 64 ++++++++++++++++++++++++++ server/middlewares/rateLimiter.ts | 8 +++- server/utils/RateLimiter.ts | 32 ++++++++++--- 3 files changed, 96 insertions(+), 8 deletions(-) diff --git a/server/middlewares/rateLimiter.test.ts b/server/middlewares/rateLimiter.test.ts index c57f5e7274..770f6af3bc 100644 --- a/server/middlewares/rateLimiter.test.ts +++ b/server/middlewares/rateLimiter.test.ts @@ -122,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); diff --git a/server/middlewares/rateLimiter.ts b/server/middlewares/rateLimiter.ts index c0a645487a..1ddfb8bc29 100644 --- a/server/middlewares/rateLimiter.ts +++ b/server/middlewares/rateLimiter.ts @@ -115,7 +115,9 @@ export function defaultRateLimiter() { return next(); } - const fullPath = `${ctx.mountPath ?? ""}${ctx.path}`; + const fullPath = RateLimiter.normalizePath( + `${ctx.mountPath ?? ""}${ctx.path}` + ); const identifiers = await getRateLimiterIdentifiers(ctx); // Kept for a route that registers its own limiter further down the chain, @@ -151,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( diff --git a/server/utils/RateLimiter.ts b/server/utils/RateLimiter.ts index 29a15a2359..e3b2c0a543 100644 --- a/server/utils/RateLimiter.ts +++ b/server/utils/RateLimiter.ts @@ -50,36 +50,56 @@ export default class RateLimiter { return this._defaultRateLimiter; } + /** + * Normalizes a request path into the key that identifies its rate limiter. + * The router matches paths case-insensitively and with an optional trailing + * slash, so every one of those variants must collapse onto a single key. + * + * @param path the request path to normalize. + * @returns the normalized path. + */ + static normalizePath(path: string): string { + const lowercased = path.toLowerCase(); + return lowercased.length > 1 && lowercased.endsWith("/") + ? lowercased.slice(0, -1) + : lowercased; + } + /** * Returns the rate limiter registered for a path, falling back to the - * default rate limiter. + * default rate limiter. The path is normalized before lookup. * * @param path the request path to look up. * @returns the rate limiter for the path. */ static getRateLimiter(path: string): RateLimiterRedis { - return this.rateLimiterMap.get(path) || this.defaultRateLimiter; + return ( + this.rateLimiterMap.get(this.normalizePath(path)) || + this.defaultRateLimiter + ); } /** - * Registers a rate limiter with a custom configuration for a path. + * Registers a rate limiter with a custom configuration for a path. The path + * is normalized before registration. * * @param path the request path to register the rate limiter for. * @param config the rate limiter configuration. */ static setRateLimiter(path: string, config: IRateLimiterStoreOptions): void { const rateLimiter = new RateLimiterRedis(config); - this.rateLimiterMap.set(path, rateLimiter); + this.rateLimiterMap.set(this.normalizePath(path), rateLimiter); } /** - * Checks whether a custom rate limiter is registered for a path. + * Checks whether a custom rate limiter is registered for a path. The path is + * normalized before lookup. * * @param path the request path to check. * @returns true if a custom rate limiter is registered. */ static hasRateLimiter(path: string): boolean { - return this.rateLimiterMap.has(path); + return this.rateLimiterMap.has(this.normalizePath(path)); } /** From fa1b529bef60b94fb506927d5963b8d5b4b24987 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 21 Aug 2026 21:09:13 -0400 Subject: [PATCH 14/55] Allow reordering sidebar sections by dragging their headers (#13505) * wip * Center reorder cursors between sections, detect empty sections with CSS * Deduplicate persisted sidebar section order * fix: Stricter zod type * Remove DraggableSection unit tests --- app/components/Sidebar/App.tsx | 28 ++- .../Sidebar/components/DraggableSection.tsx | 183 ++++++++++++++++++ .../Sidebar/components/DropCursor.tsx | 12 +- app/components/Sidebar/components/Header.tsx | 18 +- .../Sidebar/hooks/useDragAndDrop.tsx | 63 +++++- server/routes/api/users/schema.ts | 19 +- server/routes/api/users/users.test.ts | 42 ++++ server/routes/api/users/users.ts | 3 +- shared/i18n/locales/en_US/translation.json | 4 +- shared/types.ts | 12 ++ 10 files changed, 359 insertions(+), 25 deletions(-) create mode 100644 app/components/Sidebar/components/DraggableSection.tsx diff --git a/app/components/Sidebar/App.tsx b/app/components/Sidebar/App.tsx index 217d62e935..fb542f6fc8 100644 --- a/app/components/Sidebar/App.tsx +++ b/app/components/Sidebar/App.tsx @@ -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]: , + [SidebarSection.SharedWithMe]: , + [SidebarSection.Collections]: , + }; + return (