From 62ef10d6296e35b87fa013597f53c48dcfa713df Mon Sep 17 00:00:00 2001 From: Tahsin Ahmed Refat Date: Fri, 9 Oct 2026 03:59:34 +0600 Subject: [PATCH 001/467] fix: Allow private-use URI schemes for OAuth redirect URIs (#13945) * fix: Allow private-use URI schemes for OAuth redirect URIs Native apps receive OAuth redirects on a private-use URI scheme (RFC 8252 section 7.1), e.g. com.example.app:/oauth2redirect or myapp://callback. These were rejected when registering a client because IsUrlList only accepted http, https and ftp, and the recommended com.example.app:/path form was also rejected at authorize time because it has no host. Add isPrivateUseSchemeUrl, which accepts private-use schemes while excluding web schemes and schemes that can execute or embed content, and use it in both places. Co-Authored-By: Claude Opus 5.5 * fix: Require a protocol for OAuth redirect URIs isURL treats a bare word such as "callback" as a hostname, so a client could be saved with a redirect URI that validateRedirectUri would always reject at authorize time. Require a protocol when validating the list. Co-Authored-By: Claude Opus 5.5 * fix: Accept one-character private-use URI destinations The destination check compared the pathname length, so a valid opaque URI such as myapp:a was rejected along with the empty myapp: and myapp:/. Reject only those empty forms. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- server/models/validators/IsUrlList.test.ts | 46 +++++++++++++++++++++ server/models/validators/IsUrlList.ts | 15 ++++--- server/routes/oauth/oauth.test.ts | 42 +++++++++++++++++++ server/utils/oauth/OAuthInterface.test.ts | 38 +++++++++++++++++ server/utils/oauth/OAuthInterface.ts | 9 ++++- shared/utils/urls.test.ts | 43 ++++++++++++++++++++ shared/utils/urls.ts | 47 ++++++++++++++++++++++ 7 files changed, 234 insertions(+), 6 deletions(-) create mode 100644 server/models/validators/IsUrlList.test.ts diff --git a/server/models/validators/IsUrlList.test.ts b/server/models/validators/IsUrlList.test.ts new file mode 100644 index 0000000000..bd778e62ff --- /dev/null +++ b/server/models/validators/IsUrlList.test.ts @@ -0,0 +1,46 @@ +import { OAuthClient } from "@server/models"; + +describe("IsUrlList", () => { + const validateUrls = (redirectUris: string[]) => + OAuthClient.build({ redirectUris }).validate({ fields: ["redirectUris"] }); + + it("should allow http and https urls", async () => { + await expect( + validateUrls(["https://example.com/callback", "http://localhost:8080"]) + ).resolves.toBeTruthy(); + }); + + it("should allow urls without a top-level domain", async () => { + await expect( + validateUrls(["https://internal/callback"]) + ).resolves.toBeTruthy(); + }); + + it("should allow private-use schemes for native apps", async () => { + await expect( + validateUrls(["com.example.app:/oauth2redirect", "myapp://callback"]) + ).resolves.toBeTruthy(); + }); + + it("should reject schemes that can execute or embed content", async () => { + await expect(validateUrls(["javascript:alert(1)"])).rejects.toThrow(); + await expect(validateUrls(["data:text/html,hi"])).rejects.toThrow(); + await expect(validateUrls(["file:///etc/passwd"])).rejects.toThrow(); + }); + + it("should reject urls without a protocol", async () => { + await expect(validateUrls(["callback"])).rejects.toThrow(); + await expect(validateUrls(["example.com/callback"])).rejects.toThrow(); + }); + + it("should reject a private-use scheme without a destination", async () => { + await expect(validateUrls(["myapp:"])).rejects.toThrow(); + await expect(validateUrls(["myapp:/"])).rejects.toThrow(); + }); + + it("should reject duplicate urls", async () => { + await expect( + validateUrls(["myapp://callback", "myapp://callback"]) + ).rejects.toThrow(); + }); +}); diff --git a/server/models/validators/IsUrlList.ts b/server/models/validators/IsUrlList.ts index ac916f1a34..3b922701ee 100644 --- a/server/models/validators/IsUrlList.ts +++ b/server/models/validators/IsUrlList.ts @@ -1,10 +1,12 @@ import { addAttributeOptions } from "sequelize-typescript"; import isURL from "validator/lib/isURL"; +import { isPrivateUseSchemeUrl } from "@shared/utils/urls"; /** * A decorator that validates that a value is an array of unique, well-formed * URLs with a length within the given bounds. A top-level domain is not - * required, allowing local and internal hostnames. + * required, allowing local and internal hostnames. Private-use schemes such + * as `com.example.app:/callback` are allowed for native apps (RFC 8252). */ export default function IsUrlList({ min = 1, @@ -29,10 +31,13 @@ export default function IsUrlList({ for (const url of value) { if ( typeof url !== "string" || - !isURL(url, { - require_tld: false, - allow_underscores: true, - }) + !( + isURL(url, { + require_tld: false, + require_protocol: true, + allow_underscores: true, + }) || isPrivateUseSchemeUrl(url) + ) ) { throw new Error("Must be a valid url"); } diff --git a/server/routes/oauth/oauth.test.ts b/server/routes/oauth/oauth.test.ts index f4475d4047..aa1a71ad00 100644 --- a/server/routes/oauth/oauth.test.ts +++ b/server/routes/oauth/oauth.test.ts @@ -59,6 +59,22 @@ describe("#oauth.register", () => { expect(client!.published).toEqual(false); }); + it("should register a native app client with a private-use scheme redirect URI", async () => { + const res = await server.post("/oauth/register", { + body: { + client_name: "Native App", + redirect_uris: ["com.example.app:/oauth2redirect"], + }, + headers: { + host: `${subdomain}.outline.dev`, + }, + }); + + expect(res.status).toEqual(201); + const body = await res.json(); + expect(body.redirect_uris).toEqual(["com.example.app:/oauth2redirect"]); + }); + it("should register a confidential client", async () => { const res = await server.post("/oauth/register", { body: { @@ -671,4 +687,30 @@ describe("POST /oauth/authorize", () => { expect(res.status).toEqual(302); expect(res.headers.get("location")).toContain("code="); }); + + it("should redirect to a private-use scheme redirect URI", async () => { + const team = await buildTeam(); + const user = await buildUser({ teamId: team.id }); + const client = await buildOAuthClient({ + teamId: team.id, + redirectUris: ["com.example.app:/oauth2redirect"], + }); + + const res = await server.post("/oauth/authorize", user, { + redirect: "manual", + body: { + client_id: client.clientId, + response_type: "code", + redirect_uri: "com.example.app:/oauth2redirect", + state: "state", + scope: "read", + }, + }); + + expect(res.status).toEqual(302); + const location = res.headers.get("location"); + expect(location).toMatch(/^com\.example\.app:\/oauth2redirect\?/); + expect(location).toContain("code="); + expect(location).toContain("state=state"); + }); }); diff --git a/server/utils/oauth/OAuthInterface.test.ts b/server/utils/oauth/OAuthInterface.test.ts index 2f109b5f47..b40e1ef24c 100644 --- a/server/utils/oauth/OAuthInterface.test.ts +++ b/server/utils/oauth/OAuthInterface.test.ts @@ -279,6 +279,44 @@ describe("OAuthInterface", () => { ); expect(result).toBe(false); // Fragment check happens first }); + + it("should allow private-use scheme redirect URIs per RFC 8252", async () => { + const nativeClient = { + ...client, + redirectUris: ["com.example.app:/oauth2redirect", "myapp://callback"], + }; + for (const redirectUri of nativeClient.redirectUris) { + const result = await OAuthInterface.validateRedirectUri( + redirectUri, + nativeClient + ); + expect(result).toBe(true); + } + }); + + it("should reject private-use scheme redirect URIs that are not registered", async () => { + const nativeClient = { + ...client, + redirectUris: ["com.example.app:/oauth2redirect"], + }; + const result = await OAuthInterface.validateRedirectUri( + "com.attacker.app:/oauth2redirect", + nativeClient + ); + expect(result).toBe(false); + }); + + it("should reject private-use scheme redirect URI with fragment", async () => { + const nativeClient = { + ...client, + redirectUris: ["com.example.app:/oauth2redirect#fragment"], + }; + const result = await OAuthInterface.validateRedirectUri( + "com.example.app:/oauth2redirect#fragment", + nativeClient + ); + expect(result).toBe(false); + }); }); describe("#saveAuthorizationCode", () => { diff --git a/server/utils/oauth/OAuthInterface.ts b/server/utils/oauth/OAuthInterface.ts index dd63ac375a..cc7ff6fbbe 100644 --- a/server/utils/oauth/OAuthInterface.ts +++ b/server/utils/oauth/OAuthInterface.ts @@ -7,7 +7,7 @@ import type { } from "@node-oauth/oauth2-server"; import type { Required } from "utility-types"; import AuthenticationHelper from "@shared/helpers/AuthenticationHelper"; -import { isUrl } from "@shared/utils/urls"; +import { isPrivateUseSchemeUrl, isUrl } from "@shared/utils/urls"; import { OAuthClient, OAuthAuthentication, @@ -383,6 +383,13 @@ export const OAuthInterface: RefreshTokenModel & // Invalid URL, will be caught by isUrl check below } + // Allow private-use URI schemes for native apps (RFC 8252 §7.1). The + // recommended form, e.g. com.example.app:/oauth2redirect, has no host so + // isUrl would reject it. + if (isPrivateUseSchemeUrl(uri)) { + return true; + } + if (!isUrl(uri, { requireHttps: true })) { return false; } diff --git a/shared/utils/urls.test.ts b/shared/utils/urls.test.ts index e339307e89..a0fac0800e 100644 --- a/shared/utils/urls.test.ts +++ b/shared/utils/urls.test.ts @@ -69,6 +69,49 @@ describe("isUrl", () => { }); }); +describe("isPrivateUseSchemeUrl", () => { + it("should return true for private-use schemes", () => { + expect( + urlsUtils.isPrivateUseSchemeUrl("com.example.app:/oauth2redirect") + ).toBe(true); + expect(urlsUtils.isPrivateUseSchemeUrl("myapp://callback")).toBe(true); + expect(urlsUtils.isPrivateUseSchemeUrl("myapp://callback?x=1")).toBe(true); + expect(urlsUtils.isPrivateUseSchemeUrl("MyApp://callback")).toBe(true); + expect(urlsUtils.isPrivateUseSchemeUrl("myapp:a")).toBe(true); + expect(urlsUtils.isPrivateUseSchemeUrl("myapp:/a")).toBe(true); + }); + + it("should return false for web schemes", () => { + expect(urlsUtils.isPrivateUseSchemeUrl("http://example.com")).toBe(false); + expect(urlsUtils.isPrivateUseSchemeUrl("https://example.com")).toBe(false); + expect(urlsUtils.isPrivateUseSchemeUrl("ftp://example.com")).toBe(false); + expect(urlsUtils.isPrivateUseSchemeUrl("wss://example.com")).toBe(false); + }); + + it("should return false for schemes that can execute or embed content", () => { + expect(urlsUtils.isPrivateUseSchemeUrl("javascript:alert(1)")).toBe(false); + expect(urlsUtils.isPrivateUseSchemeUrl("JavaScript:alert(1)")).toBe(false); + expect(urlsUtils.isPrivateUseSchemeUrl("data:text/html,hi")).toBe(false); + expect(urlsUtils.isPrivateUseSchemeUrl("vbscript:msgbox")).toBe(false); + expect(urlsUtils.isPrivateUseSchemeUrl("file:///etc/passwd")).toBe(false); + expect(urlsUtils.isPrivateUseSchemeUrl("blob:https://example.com/x")).toBe( + false + ); + expect(urlsUtils.isPrivateUseSchemeUrl("about:blank")).toBe(false); + }); + + it("should return false for malformed or empty values", () => { + expect(urlsUtils.isPrivateUseSchemeUrl("")).toBe(false); + expect(urlsUtils.isPrivateUseSchemeUrl("myapp:")).toBe(false); + expect(urlsUtils.isPrivateUseSchemeUrl("myapp:/")).toBe(false); + expect(urlsUtils.isPrivateUseSchemeUrl("myapp://")).toBe(false); + expect(urlsUtils.isPrivateUseSchemeUrl("callback")).toBe(false); + expect(urlsUtils.isPrivateUseSchemeUrl("/relative/path")).toBe(false); + expect(urlsUtils.isPrivateUseSchemeUrl(" myapp://callback")).toBe(false); + expect(urlsUtils.isPrivateUseSchemeUrl("myapp://call back")).toBe(false); + }); +}); + describe("isBase64Url", () => { it("should return false for invalid url", () => { expect(urlsUtils.isBase64Url("")).toBe(false); diff --git a/shared/utils/urls.ts b/shared/utils/urls.ts index 40911bfb44..f3f31888aa 100644 --- a/shared/utils/urls.ts +++ b/shared/utils/urls.ts @@ -148,6 +148,53 @@ export function isUrl( } } +/** + * Schemes that are never treated as private-use, either because they are web + * schemes validated elsewhere or because they can execute or embed content. + */ +const nonPrivateUseSchemes = new Set([ + "http", + "https", + "ftp", + "ws", + "wss", + "file", + "data", + "javascript", + "vbscript", + "blob", + "about", +]); + +/** + * Returns true if the given url uses a private-use URI scheme, as registered + * by native apps to receive OAuth redirects (RFC 8252 section 7.1), for + * example `com.example.app:/oauth2redirect` or `myapp://callback`. + * + * @param text The url to check. + * @returns True if the url uses a private-use URI scheme, false otherwise. + */ +export function isPrivateUseSchemeUrl(text: string) { + if (/\s/.test(text)) { + return false; + } + + let url: URL; + try { + url = new URL(text); + } catch (_err) { + return false; + } + + const scheme = url.protocol.slice(0, -1).toLowerCase(); + if (nonPrivateUseSchemes.has(scheme)) { + return false; + } + + // Require a destination after the scheme, e.g. reject a bare "myapp:". + return !!url.host || (url.pathname !== "" && url.pathname !== "/"); +} + /** * Temporary prefix applied to links in document that are not yet persisted. */ From d6e555bb19d86bf85a8a075abac6a267c46a1b85 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 8 Oct 2026 20:42:57 -0400 Subject: [PATCH 002/467] perf: Virtualize sidebar document trees (#13993) * perf: Virtualize sidebar document trees * fix: Hide empty state while adding a doc and scroll the active row on tree mount * fix: Track scroll margin for sidebar trees that start empty --- .../Sidebar/components/CollectionLink.tsx | 16 +- .../components/CollectionLinkChildren.tsx | 41 +-- .../Sidebar/components/CollectionRow.tsx | 46 ++-- .../Sidebar/components/DocumentLink.tsx | 191 ++----------- .../Sidebar/components/DocumentTree.tsx | 251 ++++++++++++++++++ .../Sidebar/components/DragActiveContext.tsx | 32 ++- .../Sidebar/components/DropToImport.tsx | 83 ++++-- .../Sidebar/components/SharedWithMeLink.tsx | 22 +- .../Sidebar/components/StarredLink.tsx | 36 ++- .../Sidebar/hooks/useDragAndDrop.tsx | 9 +- .../Sidebar/hooks/useScrollMargin.ts | 56 ++++ shared/utils/tree.test.ts | 98 ++++++- shared/utils/tree.ts | 76 ++++++ 13 files changed, 645 insertions(+), 312 deletions(-) create mode 100644 app/components/Sidebar/components/DocumentTree.tsx create mode 100644 app/components/Sidebar/hooks/useScrollMargin.ts diff --git a/app/components/Sidebar/components/CollectionLink.tsx b/app/components/Sidebar/components/CollectionLink.tsx index 8f553745e7..b64d3f0f2a 100644 --- a/app/components/Sidebar/components/CollectionLink.tsx +++ b/app/components/Sidebar/components/CollectionLink.tsx @@ -131,12 +131,16 @@ const CollectionLink: React.FC = ({ dropRef={dropRef} isActiveDropTarget={isOver && canDrop} > - + {(newChild) => ( + + {newChild} + + )} ); }; diff --git a/app/components/Sidebar/components/CollectionLinkChildren.tsx b/app/components/Sidebar/components/CollectionLinkChildren.tsx index d897513fff..799a78913d 100644 --- a/app/components/Sidebar/components/CollectionLinkChildren.tsx +++ b/app/components/Sidebar/components/CollectionLinkChildren.tsx @@ -1,8 +1,7 @@ import { noop } from "es-toolkit/compat"; import { observer } from "mobx-react"; -import { useState, useRef, useEffect, useCallback } from "react"; +import { useRef, useCallback } from "react"; import { useTranslation } from "react-i18next"; -import { Waypoint } from "react-waypoint"; import styled from "styled-components"; import type Collection from "~/models/Collection"; import type Document from "~/models/Document"; @@ -16,16 +15,13 @@ import { useDropToChangeCollection } from "../hooks/useDragAndDrop"; import SidebarExpansionContext, { useSidebarExpansionState, } from "./SidebarExpansionContext"; -import DocumentLink from "./DocumentLink"; +import { DocumentTree } from "./DocumentTree"; import DropCursor from "./DropCursor"; import Folder from "./Folder"; import PlaceholderCollections from "./PlaceholderCollections"; import { useSidebarDisclosure } from "./SidebarDisclosureContext"; import SidebarLink from "./SidebarLink"; -// The number of child documents to initially render -const DEFAULT_PAGE_SIZE = 50; - type Props = { /** The collection to render the children of. */ collection: Collection; @@ -49,24 +45,10 @@ function CollectionLinkChildren({ // Documents sit one level below the collection, with a minimum that leaves // room for their own disclosure to the left of the label. const childDepth = Math.max(depth + 1, 2); - const pageSize = DEFAULT_PAGE_SIZE; const { documents, ui } = useStores(); const { t } = useTranslation(); const activeDocument = documents.active; const childDocuments = useCollectionDocuments(collection, activeDocument); - const [showing, setShowing] = useState(pageSize); - - useEffect(() => { - if (!expanded) { - setShowing(pageSize); - } - }, [expanded, pageSize]); - - const showMore = useCallback(() => { - if (childDocuments && childDocuments.length > showing) { - setShowing((value) => value + pageSize); - } - }, [childDocuments, showing, pageSize]); const expansion = useSidebarExpansionState( childDocuments, @@ -97,18 +79,14 @@ function CollectionLinkChildren({ )} - {childDocuments?.slice(0, showing).map((node, index) => ( - - ))} + )} {childDocuments?.length === 0 && !children && ( )} - {childDocuments && ( - - )} diff --git a/app/components/Sidebar/components/CollectionRow.tsx b/app/components/Sidebar/components/CollectionRow.tsx index 19f05789ac..9a5d5258da 100644 --- a/app/components/Sidebar/components/CollectionRow.tsx +++ b/app/components/Sidebar/components/CollectionRow.tsx @@ -81,8 +81,11 @@ export type CollectionRowProps = { /** Whether the row is an active drop target (visual highlight). */ isActiveDropTarget?: boolean; - /** Content rendered after the row (e.g. CollectionLinkChildren). */ - children?: React.ReactNode; + /** + * Renders the content after the row (e.g. CollectionLinkChildren), given the + * inline new document input to show above the child documents. + */ + children: (newChild: React.ReactNode) => React.ReactNode; }; function CollectionRow({ @@ -234,26 +237,27 @@ function CollectionRow({ {sidebarLinkElement} - {isAddingNewChild && onCreateChild && ( - true} - depth={newChildDepth ?? Math.max(depth + 1, 2)} - ellipsis={false} - label={ - - } - /> + {children( + isAddingNewChild && onCreateChild ? ( + true} + depth={newChildDepth ?? Math.max(depth + 1, 2)} + ellipsis={false} + label={ + + } + /> + ) : undefined )} - {children} ); } diff --git a/app/components/Sidebar/components/DocumentLink.tsx b/app/components/Sidebar/components/DocumentLink.tsx index 34e2660dde..4cf48b3fb8 100644 --- a/app/components/Sidebar/components/DocumentLink.tsx +++ b/app/components/Sidebar/components/DocumentLink.tsx @@ -1,27 +1,23 @@ import type { Location } from "history"; import { observer } from "mobx-react"; import * as React from "react"; -import { useMergeRefs } from "react-merge-refs"; import { useTranslation } from "react-i18next"; import type { match } from "react-router"; import { useHistory } from "react-router-dom"; -import scrollIntoView from "scroll-into-view-if-needed"; import Icon from "@shared/components/Icon"; import type { NavigationNode } from "@shared/types"; import { DocumentPermission, UserPreference } from "@shared/types"; import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper"; -import { sortNavigationNodes } from "@shared/utils/collections"; +import type { FlattenedTreeNode } from "@shared/utils/tree"; import type Collection from "~/models/Collection"; import type Document from "~/models/Document"; import type GroupMembership from "~/models/GroupMembership"; import type UserMembership from "~/models/UserMembership"; import type { RefHandle } from "~/components/EditableTitle"; -import { useActiveSidebarContext } from "~/hooks/useActiveSidebarContext"; import useBoolean from "~/hooks/useBoolean"; import { useComputed } from "~/hooks/useComputed"; import useCurrentUser from "~/hooks/useCurrentUser"; import { useDocumentMenuAction } from "~/hooks/useDocumentMenuAction"; -import useOnScreen from "~/hooks/useOnScreen"; import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; import DocumentMenu from "~/menus/DocumentMenu"; @@ -32,11 +28,9 @@ import { useDropToReorderDocument, useDropToReparentDocument, } from "../hooks/useDragAndDrop"; -import { useIsDragActive, useSidebarScrollElement } from "./DragActiveContext"; import { useSidebarExpansion } from "./SidebarExpansionContext"; import DocumentRow from "./DocumentRow"; import DropCursor from "./DropCursor"; -import Folder from "./Folder"; import { indentForDepth } from "./SidebarLink"; import type { SidebarContextType } from "./SidebarContext"; import { useSidebarContext } from "./SidebarContext"; @@ -45,18 +39,17 @@ type Props = { node: NavigationNode; collection?: Collection; membership?: UserMembership | GroupMembership; - activeDocument: Document | null | undefined; prefetchDocument?: (documentId: string) => Promise; isDraft?: boolean; depth: number; index: number; parentId?: string; + hasChildren: boolean; /** - * Positions directly after each ancestor whose subtree ends with this node, - * nearest first. They let a drop at the end of an expanded subtree land - * beside an ancestor instead of inside it. + * Ancestors whose subtree ends with this node, nearest first. A drop at the + * end of an expanded subtree can land beside one of them instead of inside. */ - ancestorDropTargets?: DropTarget[]; + trailingAncestors: FlattenedTreeNode[]; }; /** A position in the document tree that a dragged document can be dropped at. */ @@ -66,166 +59,7 @@ type DropTarget = { depth: number; }; -// Approximate rendered row height; used to reserve space for unmounted rows so -// the scroll container stays the right height and IntersectionObserver triggers -// correctly as the user scrolls. -const ROW_HEIGHT = 30; - -// Pre-mount rows just outside the viewport so scrolling stays smooth and drop -// targets exist a screen ahead when a drag starts. -const ROOT_MARGIN = "300px 0px"; - -const DocumentLink = observer(function DocumentLink(props: Props) { - const { node, collection, activeDocument } = props; - const { documents } = useStores(); - const expansion = useSidebarExpansion(); - const expanded = expansion.isExpanded(node.id); - const isActiveDocument = activeDocument && activeDocument.id === node.id; - const hasChildDocuments = - !!node.children.length || activeDocument?.parentDocumentId === node.id; - const sidebarContext = useSidebarContext(); - const activeSidebarContext = useActiveSidebarContext(); - const { fetchChildDocuments } = documents; - - // Keep expansion/data effects on the outer so they run regardless of whether - // the heavy row content is currently mounted. - React.useEffect(() => { - if (expanded && !hasChildDocuments) { - expansion.collapse(node.id); - } - }, [expansion, expanded, hasChildDocuments, node.id]); - - React.useEffect(() => { - if ( - isActiveDocument && - (hasChildDocuments || sidebarContext !== "collections") - ) { - void fetchChildDocuments(node.id); - } - }, [ - fetchChildDocuments, - node.id, - hasChildDocuments, - sidebarContext, - isActiveDocument, - ]); - - const insertDraftChild = !!( - activeDocument?.isDraft && - activeDocument?.isActive && - activeDocument?.parentDocumentId === node.id - ); - - const draftNavNode = insertDraftChild - ? activeDocument?.asNavigationNode - : undefined; - - const nodeChildren = React.useMemo( - () => - collection && draftNavNode - ? sortNavigationNodes( - [draftNavNode, ...node.children], - collection.sort, - false - ) - : node.children, - [draftNavNode, collection, node.children] - ); - - // The last child shares its bottom edge with this node's subtree, so a drop - // there may also target the position after this node or its ancestors. - const lastChildDropTargets = React.useMemo( - () => [ - { - parentDocumentId: props.parentId, - index: props.index + 1, - depth: props.depth, - }, - ...(props.ancestorDropTargets ?? []), - ], - [props.parentId, props.index, props.depth, props.ancestorDropTargets] - ); - - // Visibility gate: only mount the heavy inner content when scrolled near the - // viewport, but keep it mounted while a drag is in progress so the dragged - // source (or a drop target the user is heading toward) isn't yanked. - const scrollRoot = useSidebarScrollElement(); - const placeholderRef = React.useRef(null); - const observerOptions = React.useMemo( - () => ({ root: scrollRoot, rootMargin: ROOT_MARGIN }), - [scrollRoot] - ); - const [onScreenRef, isOnScreen] = useOnScreen(observerOptions); - const mergedRef = useMergeRefs([placeholderRef, onScreenRef]); - const isDragActive = useIsDragActive(); - const [mounted, setMounted] = React.useState(false); - - // Flip mount state during render (not in an effect) so the first paint - // already contains the row content when the placeholder is on screen, - // avoiding a blank frame. - if (isOnScreen && !mounted) { - setMounted(true); - } else if (!isOnScreen && !isDragActive && mounted) { - setMounted(false); - } - - // The inner row's own scrollIntoView only fires while it is mounted, which - // skips active documents that are virtualized off-screen. Only scroll the tree - // that matches the navigation context so a document rendered in multiple - // contexts (collections/starred/shared) doesn't jump to an unexpected section; - // when no context is set, fall back to the collections tree alone. - React.useLayoutEffect(() => { - if ( - isActiveDocument && - (activeSidebarContext === sidebarContext || - (!activeSidebarContext && sidebarContext === "collections")) && - placeholderRef.current - ) { - scrollIntoView(placeholderRef.current, { - scrollMode: "if-needed", - behavior: "auto", - boundary: (parent) => parent.id !== "sidebar", - }); - } - }, [isActiveDocument, sidebarContext, activeSidebarContext]); - - return ( - <> -
- {mounted ? ( - 0} /> - ) : null} -
- - {nodeChildren.map((childNode, childIndex) => ( - - ))} - - - ); -}); - -type InnerProps = Props & { - hasChildren: boolean; -}; - -const DocumentLinkInner = observer(function DocumentLinkInner({ +const DocumentLink = observer(function DocumentLink({ node, collection, membership, @@ -235,8 +69,8 @@ const DocumentLinkInner = observer(function DocumentLinkInner({ index, parentId, hasChildren, - ancestorDropTargets, -}: InnerProps) { + trailingAncestors, +}: Props) { const { documents } = useStores(); const { t } = useTranslation(); const history = useHistory(); @@ -377,7 +211,12 @@ const DocumentLinkInner = observer(function DocumentLinkInner({ const afterSelf = isDragging ? [] : [{ parentDocumentId: parentId, index: index + 1, depth }]; - return [...afterSelf, ...(ancestorDropTargets ?? [])]; + const afterAncestors = trailingAncestors.map((ancestor) => ({ + parentDocumentId: ancestor.parentId, + index: ancestor.index + 1, + depth: ancestor.depth, + })); + return [...afterSelf, ...afterAncestors]; }, [ expanded, hasChildren, @@ -386,7 +225,7 @@ const DocumentLinkInner = observer(function DocumentLinkInner({ parentId, index, depth, - ancestorDropTargets, + trailingAncestors, ]); const title = document?.title || node.title || t("Untitled"); diff --git a/app/components/Sidebar/components/DocumentTree.tsx b/app/components/Sidebar/components/DocumentTree.tsx new file mode 100644 index 0000000000..9f8c343f5e --- /dev/null +++ b/app/components/Sidebar/components/DocumentTree.tsx @@ -0,0 +1,251 @@ +import type { Range } from "@tanstack/react-virtual"; +import { defaultRangeExtractor, useVirtualizer } from "@tanstack/react-virtual"; +import { noop } from "es-toolkit/compat"; +import { observer } from "mobx-react"; +import * as React from "react"; +import scrollIntoView from "scroll-into-view-if-needed"; +import type { NavigationNode } from "@shared/types"; +import { sortNavigationNodes } from "@shared/utils/collections"; +import { flattenExpandedTree } from "@shared/utils/tree"; +import type Collection from "~/models/Collection"; +import type Document from "~/models/Document"; +import type GroupMembership from "~/models/GroupMembership"; +import type UserMembership from "~/models/UserMembership"; +import { useActiveSidebarContext } from "~/hooks/useActiveSidebarContext"; +import { useComputed } from "~/hooks/useComputed"; +import useStores from "~/hooks/useStores"; +import { useScrollMargin } from "../hooks/useScrollMargin"; +import DocumentLink from "./DocumentLink"; +import { useDraggedItemId, useSidebarScrollElement } from "./DragActiveContext"; +import { useSidebarContext } from "./SidebarContext"; +import { useSidebarExpansion } from "./SidebarExpansionContext"; + +// Approximate rendered row height, rows are measured once mounted. +const ROW_HEIGHT = 30; + +// Mount rows just outside the visible area so that scrolling stays smooth. +const OVERSCAN = 10; + +const estimateSize = () => ROW_HEIGHT; + +const noAdjustment = () => false; + +interface Props { + /** The documents at the root of the tree. */ + nodes: NavigationNode[]; + /** Indentation depth of the root documents. */ + depth: number; + /** Id of the document that contains the root documents, if any. */ + parentId?: string; + /** The collection that the documents belong to, if loaded. */ + collection?: Collection; + /** The membership that grants access to the documents, if any. */ + membership?: UserMembership | GroupMembership; + /** Function to prefetch a document by ID. */ + prefetchDocument?: (documentId: string) => Promise; +} + +/** + * Renders the expanded part of a sidebar document tree as a flat list, and + * mounts only the rows that are near the visible area of the sidebar. + */ +export const DocumentTree = observer(function DocumentTree({ + nodes, + depth, + parentId, + collection, + membership, + prefetchDocument, +}: Props) { + const { documents } = useStores(); + const expansion = useSidebarExpansion(); + const sidebarContext = useSidebarContext(); + const activeSidebarContext = useActiveSidebarContext(); + const scrollElement = useSidebarScrollElement(); + const draggedItemId = useDraggedItemId(); + const containerRef = React.useRef(null); + const scrollMargin = useScrollMargin(containerRef, scrollElement); + const activeDocument = documents.active; + + const rows = useComputed( + () => + flattenExpandedTree({ + nodes, + depth, + parentId, + isExpanded: (nodeId) => expansion.isExpanded(nodeId), + getChildren: (node) => { + // Show an unpublished draft below its parent while it is open. + const active = documents.active; + if ( + collection && + active?.isDraft && + active.isActive && + active.parentDocumentId === node.id + ) { + return sortNavigationNodes( + [active.asNavigationNode, ...node.children], + collection.sort, + false + ); + } + return node.children; + }, + }), + [nodes, depth, parentId, collection, expansion, documents] + ); + + const activeIndex = React.useMemo( + () => rows.findIndex((row) => row.node.id === activeDocument?.id), + [rows, activeDocument?.id] + ); + const draggedIndex = React.useMemo( + () => rows.findIndex((row) => row.node.id === draggedItemId), + [rows, draggedItemId] + ); + + // Keep the active row mounted so that it can scroll into view, and the + // dragged row so that the drag does not end when it scrolls away. + const rangeExtractor = React.useCallback( + (range: Range) => { + const indexes = new Set(defaultRangeExtractor(range)); + for (const index of [activeIndex, draggedIndex]) { + if (index !== -1) { + indexes.add(index); + } + } + return [...indexes].sort((a, b) => a - b); + }, + [activeIndex, draggedIndex] + ); + + const getScrollElement = React.useCallback( + () => scrollElement, + [scrollElement] + ); + const getScrollOffset = React.useCallback( + () => scrollElement?.scrollTop ?? 0, + [scrollElement] + ); + const getItemKey = React.useCallback( + (index: number) => rows[index].node.id, + [rows] + ); + + const virtualizer = useVirtualizer({ + count: rows.length, + getScrollElement, + getItemKey, + estimateSize, + overscan: OVERSCAN, + scrollMargin, + rangeExtractor, + // The virtualizer only learns the offset from scroll events, and scrolls + // to its initial offset when it mounts. Start from the current position + // and never scroll, as the browser and scrollIntoView own the position. + initialOffset: getScrollOffset, + scrollToFn: noop, + }); + + // Rows stay in the normal flow, so the browser's scroll anchoring already + // compensates when a row above the visible area changes size. + virtualizer.shouldAdjustScrollPositionOnItemSizeChange = noAdjustment; + + const virtualItems = virtualizer.getVirtualItems(); + // The virtualizer renders no rows until it has measured the scroll element, + // so the active row can appear a render after the tree mounts. + const isActiveRowRendered = virtualItems.some( + (item) => item.index === activeIndex + ); + const activeNodeId = + activeIndex === -1 ? undefined : rows[activeIndex].node.id; + const activeHasChildren = + activeIndex !== -1 && rows[activeIndex].node.children.length > 0; + const activeParentId = activeDocument?.parentDocumentId; + + // Only scroll the tree that matches the navigation context so a document + // rendered in multiple contexts (collections/starred/shared) doesn't jump to + // an unexpected section; when no context is set, fall back to the collections + // tree alone. + const isScrollContext = + activeSidebarContext === sidebarContext || + (!activeSidebarContext && sidebarContext === "collections"); + + React.useLayoutEffect(() => { + const element = containerRef.current?.querySelector( + `[data-index="${activeIndex}"]` + ); + if (isActiveRowRendered && isScrollContext && element) { + scrollIntoView(element, { + scrollMode: "if-needed", + behavior: "auto", + boundary: (parent) => parent.id !== "sidebar", + }); + } + // Scroll when the active row appears, not when rows above it change. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [activeNodeId, isActiveRowRendered, isScrollContext]); + + React.useEffect(() => { + if ( + activeNodeId && + (activeHasChildren || sidebarContext !== "collections") + ) { + void documents.fetchChildDocuments(activeNodeId); + } + }, [documents, activeNodeId, activeHasChildren, sidebarContext]); + + // Collapse documents that no longer have children, so that they do not show + // as expanded when a child is added again. + React.useEffect(() => { + for (const row of rows) { + if ( + !row.node.children.length && + row.node.id !== activeParentId && + expansion.isExpanded(row.node.id) + ) { + expansion.collapse(row.node.id); + } + } + }, [rows, expansion, activeParentId]); + + // Rows outside of the rendered range are replaced by spacers of the same + // height, so that the rows keep their place in the normal document flow. + let offset = 0; + const items = virtualItems.map((item) => { + const row = rows[item.index]; + const start = item.start - virtualizer.options.scrollMargin; + const gap = start - offset; + offset = start + item.size; + + return ( + + {gap > 0 &&
} +
+ +
+ + ); + }); + const remainder = virtualizer.getTotalSize() - offset; + + // The container stays mounted while the tree is empty, so that its scroll + // margin is already tracked when the first rows are added. + return ( +
+ {items} + {remainder > 0 &&
} +
+ ); +}); diff --git a/app/components/Sidebar/components/DragActiveContext.tsx b/app/components/Sidebar/components/DragActiveContext.tsx index a4de11d3d3..1cd5ef9c06 100644 --- a/app/components/Sidebar/components/DragActiveContext.tsx +++ b/app/components/Sidebar/components/DragActiveContext.tsx @@ -1,13 +1,13 @@ import * as React from "react"; import { useDragLayer } from "react-dnd"; -const DragActiveContext = React.createContext(false); +const DraggedItemContext = React.createContext(undefined); const SidebarScrollContext = React.createContext(null); /** - * Provides the sidebar's scroll container so descendants can use it as the - * IntersectionObserver root when deciding whether to render heavy content. + * Provides the sidebar's scroll container so descendants can virtualize their + * content against it. */ export const SidebarScrollProvider = SidebarScrollContext.Provider; @@ -20,18 +20,23 @@ export function useSidebarScrollElement(): HTMLElement | null { } /** - * Subscribes once to react-dnd's drag state and exposes a boolean via context. + * Subscribes once to react-dnd's drag state and exposes the id of the dragged + * item via context. * - * Visibility-gated sidebar rows read this to keep their inner content mounted - * for the duration of a drag, so that scrolling away from the dragged source - * (or a drop target the user is heading toward) does not unmount it mid-drag. + * Virtualized sidebar trees read this to keep the dragged row mounted for the + * duration of a drag, as react-dnd ends a drag whose source leaves the DOM. */ export function DragActiveProvider({ children, }: { children: React.ReactNode; }) { - const isDragging = useDragLayer((monitor) => monitor.isDragging()); + const { isDragging, itemId } = useDragLayer((monitor) => ({ + isDragging: monitor.isDragging(), + itemId: monitor.isDragging() + ? monitor.getItem<{ id?: string } | null>()?.id + : undefined, + })); // Expose drag state to CSS so per-row UI (e.g. the hover actions slot) can // be hidden for the duration of a drag without re-rendering @@ -41,15 +46,16 @@ export function DragActiveProvider({ }, [isDragging]); return ( - + {children} - + ); } /** - * Returns whether any react-dnd drag is currently active. + * Returns the id of the item being dragged, or undefined when no drag is in + * progress. */ -export function useIsDragActive(): boolean { - return React.useContext(DragActiveContext); +export function useDraggedItemId(): string | undefined { + return React.useContext(DraggedItemContext); } diff --git a/app/components/Sidebar/components/DropToImport.tsx b/app/components/Sidebar/components/DropToImport.tsx index 31cdb89852..b6e04d1c89 100644 --- a/app/components/Sidebar/components/DropToImport.tsx +++ b/app/components/Sidebar/components/DropToImport.tsx @@ -1,13 +1,12 @@ import { VisuallyHidden } from "@radix-ui/react-visually-hidden"; import invariant from "invariant"; import { observer } from "mobx-react"; -import { useCallback, useState } from "react"; +import { useCallback, useSyncExternalStore } from "react"; import Dropzone from "react-dropzone"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import styled, { css } from "styled-components"; import LoadingIndicator from "~/components/LoadingIndicator"; -import useEventListener from "~/hooks/useEventListener"; import useImportDocument from "~/hooks/useImportDocument"; import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; @@ -20,30 +19,38 @@ type Props = { activeClassName?: string; }; -function DropToImport({ disabled, children, collectionId, documentId }: Props) { +/** + * Wraps sidebar content in a dropzone that imports the files dropped on it. + * The dropzone is only prepared once files are dragged into the window. + */ +function DropToImport(props: Props) { + const hasDraggedFiles = useSyncExternalStore( + subscribeToFileDrag, + getHasDraggedFiles + ); + invariant( + props.collectionId || props.documentId, + "Must provide either collectionId or documentId" + ); + + if (props.disabled || !hasDraggedFiles) { + return props.children; + } + + return ; +} + +const ImportDropzone = observer(function ImportDropzone({ + children, + collectionId, + documentId, +}: Props) { const { t } = useTranslation(); const { documents } = useStores(); - const [prerender, setPreRendered] = useState(false); const { handleFiles, isImporting } = useImportDocument( collectionId, documentId ); - invariant( - collectionId || documentId, - "Must provide either collectionId or documentId" - ); - - // Only prepare the dropzone for OS file drags, internal react-dnd drags - // fire native dragenter too - useEventListener("dragenter", (event: Event) => { - if ( - typeof DragEvent !== "undefined" && - event instanceof DragEvent && - Array.from(event.dataTransfer?.types ?? []).includes("Files") - ) { - setPreRendered(true); - } - }); const canCollection = usePolicy(collectionId); const canDocument = usePolicy(documentId); @@ -53,8 +60,6 @@ function DropToImport({ disabled, children, collectionId, documentId }: Props) { }, [t]); if ( - disabled || - !prerender || (collectionId && !canCollection.createDocument) || (documentId && !canDocument.createChildDocument) ) { @@ -87,7 +92,37 @@ function DropToImport({ disabled, children, collectionId, documentId }: Props) { )} ); -} +}); + +let hasDraggedFiles = false; +const fileDragListeners = new Set<() => void>(); + +// Only prepare dropzones for OS file drags, internal react-dnd drags fire +// native dragenter too. +const handleDragEnter = (event: DragEvent) => { + if (!Array.from(event.dataTransfer?.types ?? []).includes("Files")) { + return; + } + hasDraggedFiles = true; + window.removeEventListener("dragenter", handleDragEnter); + fileDragListeners.forEach((listener) => listener()); +}; + +const subscribeToFileDrag = (listener: () => void) => { + if (!hasDraggedFiles && !fileDragListeners.size) { + window.addEventListener("dragenter", handleDragEnter); + } + fileDragListeners.add(listener); + + return () => { + fileDragListeners.delete(listener); + if (!fileDragListeners.size) { + window.removeEventListener("dragenter", handleDragEnter); + } + }; +}; + +const getHasDraggedFiles = () => hasDraggedFiles; const DropzoneContainer = styled.div<{ $isDragActive: boolean }>` border-radius: 4px; @@ -106,4 +141,4 @@ const DropzoneContainer = styled.div<{ $isDragActive: boolean }>` `} `; -export default observer(DropToImport); +export default DropToImport; diff --git a/app/components/Sidebar/components/SharedWithMeLink.tsx b/app/components/Sidebar/components/SharedWithMeLink.tsx index 116268e784..8040127caa 100644 --- a/app/components/Sidebar/components/SharedWithMeLink.tsx +++ b/app/components/Sidebar/components/SharedWithMeLink.tsx @@ -21,7 +21,7 @@ import SidebarExpansionContext, { useSidebarExpansionState, } from "./SidebarExpansionContext"; import { useSidebarLabelAndIcon } from "../hooks/useSidebarLabelAndIcon"; -import DocumentLink from "./DocumentLink"; +import { DocumentTree } from "./DocumentTree"; import DocumentRow from "./DocumentRow"; import DropCursor from "./DropCursor"; import Folder from "./Folder"; @@ -208,19 +208,13 @@ function SharedWithMeLink({ membership, depth = 0 }: Props) { - {childDocuments.map((childNode, index) => ( - - ))} + diff --git a/app/components/Sidebar/components/StarredLink.tsx b/app/components/Sidebar/components/StarredLink.tsx index 5eb2ca58ca..368b74106e 100644 --- a/app/components/Sidebar/components/StarredLink.tsx +++ b/app/components/Sidebar/components/StarredLink.tsx @@ -35,7 +35,7 @@ import SidebarExpansionContext, { } from "./SidebarExpansionContext"; import CollectionLinkChildren from "./CollectionLinkChildren"; import CollectionRow from "./CollectionRow"; -import DocumentLink from "./DocumentLink"; +import { DocumentTree } from "./DocumentTree"; import DocumentRow from "./DocumentRow"; import DropCursor from "./DropCursor"; import Folder from "./Folder"; @@ -229,19 +229,13 @@ const StarredDocumentLink = observer(function StarredDocumentLink({ - {childDocuments.map((node, index) => ( - - ))} + {cursor} @@ -356,11 +350,15 @@ const StarredCollectionLink = observer(function StarredCollectionLink({ dropRef={dropRef} isActiveDropTarget={isOver && canDrop} > - + {(newChild) => ( + + {newChild} + + )} {cursor} diff --git a/app/components/Sidebar/hooks/useDragAndDrop.tsx b/app/components/Sidebar/hooks/useDragAndDrop.tsx index 0a880d48a5..1362ca3453 100644 --- a/app/components/Sidebar/hooks/useDragAndDrop.tsx +++ b/app/components/Sidebar/hooks/useDragAndDrop.tsx @@ -437,10 +437,6 @@ export function useDropToReparentDocument( const { documents, collections, dialogs, policies } = useStores(); const hasChildDocuments = !!node?.children.length; const document = node ? documents.get(node.id) : undefined; - const pathToNode = React.useMemo( - () => document?.pathTo.map((item) => item.id), - [document] - ); const startHover = useHover(parentRef, setExpanded); @@ -504,7 +500,10 @@ export function useDropToReparentDocument( return true; // optimistic, in case the document is not loaded yet; server will check for permissions before performing the move. } - return document.isActive && !!pathToNode && !pathToNode.includes(item.id); + return ( + document.isActive && + !document.pathTo.some((ancestor) => ancestor.id === item.id) + ); }, hover: (_item, monitor) => { // Enables expansion of document children when hovering over the document diff --git a/app/components/Sidebar/hooks/useScrollMargin.ts b/app/components/Sidebar/hooks/useScrollMargin.ts new file mode 100644 index 0000000000..36ce759081 --- /dev/null +++ b/app/components/Sidebar/hooks/useScrollMargin.ts @@ -0,0 +1,56 @@ +import type { RefObject } from "react"; +import { useLayoutEffect, useState } from "react"; + +/** + * Tracks the offset of an element from the top of the content of a scroll + * container, for use as the scroll margin of a virtualized list. The offset is + * measured again when a direct child of the scroll container is resized, added + * or removed, as these move the element without a scroll event. + * + * @param ref a ref to the element to measure. + * @param scrollElement the scroll container that holds the element. + * @returns the offset in pixels. + */ +export function useScrollMargin( + ref: RefObject, + scrollElement: HTMLElement | null +): number { + const [scrollMargin, setScrollMargin] = useState(0); + + useLayoutEffect(() => { + const element = ref.current; + if (!element || !scrollElement) { + return; + } + + const measure = () => { + setScrollMargin( + element.getBoundingClientRect().top - + scrollElement.getBoundingClientRect().top + + scrollElement.scrollTop + ); + }; + + const resizeObserver = new ResizeObserver(measure); + const observeChildren = () => { + for (const child of scrollElement.children) { + resizeObserver.observe(child); + } + }; + const mutationObserver = new MutationObserver(() => { + observeChildren(); + measure(); + }); + + measure(); + observeChildren(); + mutationObserver.observe(scrollElement, { childList: true }); + + return () => { + resizeObserver.disconnect(); + mutationObserver.disconnect(); + }; + }, [ref, scrollElement]); + + return scrollMargin; +} diff --git a/shared/utils/tree.test.ts b/shared/utils/tree.test.ts index effe513195..99e70f6ddc 100644 --- a/shared/utils/tree.test.ts +++ b/shared/utils/tree.test.ts @@ -1,5 +1,10 @@ import type { NavigationNode } from "../types"; -import { ancestors, descendants, flattenTree } from "./tree"; +import { + ancestors, + descendants, + flattenExpandedTree, + flattenTree, +} from "./tree"; const buildNode = ( id: string, @@ -140,3 +145,94 @@ describe("#descendants", () => { expect(descendants(buildNode("leaf"))).toEqual([]); }); }); + +describe("#flattenExpandedTree", () => { + // a + // ├── b + // │ ├── c + // │ └── d + // └── e + // f + const nodes = [ + buildNode("a", [ + buildNode("b", [buildNode("c"), buildNode("d")]), + buildNode("e"), + ]), + buildNode("f"), + ]; + + const flatten = ( + expandedIds: string[], + getChildren?: (node: NavigationNode) => NavigationNode[] + ) => + flattenExpandedTree({ + nodes, + depth: 2, + parentId: "root", + isExpanded: (id) => expandedIds.includes(id), + getChildren, + }); + + it("should return only the root nodes when nothing is expanded", () => { + const flattened = flatten([]); + + expect(flattened.map((item) => item.node.id)).toEqual(["a", "f"]); + expect(flattened[0]).toMatchObject({ + depth: 2, + index: 0, + parentId: "root", + hasChildren: true, + }); + expect(flattened[1]).toMatchObject({ index: 1, hasChildren: false }); + }); + + it("should include the children of expanded nodes in display order", () => { + const flattened = flatten(["a", "b"]); + + expect( + flattened.map((item) => [item.node.id, item.depth, item.parentId]) + ).toEqual([ + ["a", 2, "root"], + ["b", 3, "a"], + ["c", 4, "b"], + ["d", 4, "b"], + ["e", 3, "a"], + ["f", 2, "root"], + ]); + }); + + it("should skip the children of a collapsed node", () => { + const flattened = flatten(["b"]); + + expect(flattened.map((item) => item.node.id)).toEqual(["a", "f"]); + }); + + it("should give the last child the ancestors that end with it", () => { + const flattened = flatten(["a", "b"]); + const trailing = Object.fromEntries( + flattened.map((item) => [ + item.node.id, + item.trailingAncestors.map((ancestor) => ancestor.node.id), + ]) + ); + + expect(trailing).toEqual({ + a: [], + b: [], + c: [], + d: ["b"], + e: ["a"], + f: [], + }); + }); + + it("should use the children returned by getChildren", () => { + const draft = buildNode("draft"); + const flattened = flatten(["f"], (node) => + node.id === "f" ? [draft] : node.children + ); + + expect(flattened.map((item) => item.node.id)).toEqual(["a", "f", "draft"]); + expect(flattened[1].hasChildren).toBe(true); + }); +}); diff --git a/shared/utils/tree.ts b/shared/utils/tree.ts index cb3428a2cc..30a4a0d584 100644 --- a/shared/utils/tree.ts +++ b/shared/utils/tree.ts @@ -79,3 +79,79 @@ export const descendants = ( return found; }; + +/** A node of a flattened tree, with its position in the tree. */ +export interface FlattenedTreeNode { + /** The node itself. */ + node: NavigationNode; + /** Depth of the node in the tree. */ + depth: number; + /** Index of the node among its siblings. */ + index: number; + /** Id of the parent node, if any. */ + parentId?: string; + /** Whether the node has children. */ + hasChildren: boolean; + /** + * Ancestors whose subtree ends with the subtree of this node, nearest first. + * Empty unless the node is the last child of its parent. + */ + trailingAncestors: FlattenedTreeNode[]; +} + +/** + * Flattens the expanded part of a navigation tree into a list of nodes in + * display order. The children of a node are included only when it is expanded. + * + * @param options.nodes The nodes at the root of the tree. + * @param options.isExpanded Returns whether the node with the given id is expanded. + * @param options.getChildren Returns the children to show for a node, defaults + * to the children of the node. + * @param options.depth Depth of the root nodes, defaults to 0. + * @param options.parentId Id of the node that contains the root nodes, if any. + * @returns the visible nodes in display order. + */ +export const flattenExpandedTree = ({ + nodes, + isExpanded, + getChildren = (node) => node.children, + depth = 0, + parentId, +}: { + nodes: NavigationNode[]; + isExpanded: (nodeId: string) => boolean; + getChildren?: (node: NavigationNode) => NavigationNode[]; + depth?: number; + parentId?: string; +}): FlattenedTreeNode[] => { + const flattened: FlattenedTreeNode[] = []; + + const visit = ( + siblings: NavigationNode[], + siblingDepth: number, + parent: FlattenedTreeNode | undefined + ) => { + siblings.forEach((node, index) => { + const children = getChildren(node); + const item: FlattenedTreeNode = { + node, + depth: siblingDepth, + index, + parentId: parent ? parent.node.id : parentId, + hasChildren: children.length > 0, + trailingAncestors: + parent && index === siblings.length - 1 + ? [parent, ...parent.trailingAncestors] + : [], + }; + flattened.push(item); + + if (children.length && isExpanded(node.id)) { + visit(children, siblingDepth + 1, item); + } + }); + }; + + visit(nodes, depth, undefined); + return flattened; +}; From 3749b78f629cd251c7c1aef66dc24f48cb9290aa Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 8 Oct 2026 20:50:55 -0400 Subject: [PATCH 003/467] fix: Log a warning instead of prompting when leaving a document with unsynced changes (#13994) --- app/scenes/Document/components/Document.tsx | 25 +++++++++++---------- shared/i18n/locales/en_US/translation.json | 2 -- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/app/scenes/Document/components/Document.tsx b/app/scenes/Document/components/Document.tsx index a4dea7a5d9..35d9e996a3 100644 --- a/app/scenes/Document/components/Document.tsx +++ b/app/scenes/Document/components/Document.tsx @@ -30,6 +30,7 @@ import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext"; import useMobile from "~/hooks/useMobile"; import useStores from "~/hooks/useStores"; import isTextInput from "~/utils/isTextInput"; +import Logger from "~/utils/Logger"; import { client } from "~/utils/ApiClient"; import { emojiToUrl } from "~/utils/emoji"; import { documentHistoryPath, documentEditPath } from "~/utils/routeHelpers"; @@ -324,28 +325,28 @@ function DocumentScene({ const hasUnsyncedChanges = !readOnly && documentContext.hasUnsyncedChanges; + const warnUnsyncedChanges = () => { + Logger.warn("Leaving document with unsynced changes", { + documentId: document.id, + hasLocalPersistence: documentContext.hasLocalPersistence, + }); + }; + const handleBlockNavigation = () => { - if (hasUnsyncedChanges) { - return documentContext.hasLocalPersistence - ? t( - `Your changes haven’t synced yet, they are saved on this device.\nAre you sure you want to leave?` - ) - : t( - `Your changes haven’t synced yet and will be lost.\nAre you sure you want to leave?` - ); - } if (isUploading && !isEditorDirty) { return t( `Images are still uploading.\nAre you sure you want to discard them?` ); } + if (hasUnsyncedChanges) { + warnUnsyncedChanges(); + } return true; }; - const handleUnload = (event: BeforeUnloadEvent) => { + const handleUnload = () => { if (hasUnsyncedChanges) { - event.preventDefault(); - event.returnValue = ""; + warnUnsyncedChanges(); } }; diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 88c246f8ce..156d3a3942 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -928,8 +928,6 @@ "Edits you make will sync once you’re online": "Edits you make will sync once you’re online", "Offline": "Offline", "Document restored": "Document restored", - "Your changes haven’t synced yet, they are saved on this device.\nAre you sure you want to leave?": "Your changes haven’t synced yet, they are saved on this device.\nAre you sure you want to leave?", - "Your changes haven’t synced yet and will be lost.\nAre you sure you want to leave?": "Your changes haven’t synced yet and will be lost.\nAre you sure you want to leave?", "Images are still uploading.\nAre you sure you want to discard them?": "Images are still uploading.\nAre you sure you want to discard them?", "{{ count }} comment": "{{ count }} comment", "{{ count }} comment_plural": "{{ count }} comments", From 8cd9d49d757559d59abe34ad8b33bd7c5a98a576 Mon Sep 17 00:00:00 2001 From: hcker2000 Date: Thu, 8 Oct 2026 20:52:14 -0400 Subject: [PATCH 004/467] feat: Added link breadcrumbs (#13876) * Added link breadcrumbs * Adjusted to use the DocumentBreadcrumb component --- app/components/HoverPreview/Components.tsx | 19 +++++++++++ .../HoverPreview/HoverPreviewDocument.tsx | 32 ++++++++++++++++--- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/app/components/HoverPreview/Components.tsx b/app/components/HoverPreview/Components.tsx index 3701d0271a..74dacb47b6 100644 --- a/app/components/HoverPreview/Components.tsx +++ b/app/components/HoverPreview/Components.tsx @@ -133,3 +133,22 @@ export const Card = styled.div<{ fadeOut?: boolean; $borderRadius?: string }>` }` : ""} `; + +export const BreadcrumbContainer = styled.div` + font-size: 12px; + font-weight: 500; + color: ${(props) => props.theme.textTertiary}; + margin-bottom: 4px; + display: flex; + align-items: center; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + + /* Adds a subtle separator between path items */ + span:not(:last-child)::after { + content: "/"; + margin: 0 4px; + color: ${(props) => props.theme.divider}; + } +`; \ No newline at end of file diff --git a/app/components/HoverPreview/HoverPreviewDocument.tsx b/app/components/HoverPreview/HoverPreviewDocument.tsx index 2979d3187d..71ec6d2a16 100644 --- a/app/components/HoverPreview/HoverPreviewDocument.tsx +++ b/app/components/HoverPreview/HoverPreviewDocument.tsx @@ -4,6 +4,9 @@ import type { UnfurlResourceType, UnfurlResponse } from "@shared/types"; import Editor from "~/components/Editor"; import Flex from "~/components/Flex"; import ErrorBoundary from "../ErrorBoundary"; +import useStores from "~/hooks/useStores"; +import { observer } from "mobx-react"; +import DocumentBreadcrumb from "~/components/DocumentBreadcrumb"; import { Preview, Title, @@ -11,26 +14,47 @@ import { Card, CardContent, Description, + BreadcrumbContainer, } from "./Components"; type Props = Omit & { ref?: React.Ref; }; -function HoverPreviewDocument({ +const HoverPreviewDocument = observer(({ url, id, title, summary, lastActivityByViewer, ref, -}: Props) { +}: Props) => { const parsedUrl = new URL(url, window.location.href); + + const { documents } = useStores(); + const document = documents.get(id); + + // We only need to fetch the document. + // DocumentBreadcrumb handles loading the collection and relations internally. + React.useEffect(() => { + if (!document) { + void documents.fetch(id); + } + }, [id, document, documents]); + const content = ( + + {/* Wrap the built-in breadcrumb in your container for CSS spacing */} + {document && ( + + + + )} + {title} {lastActivityByViewer && {lastActivityByViewer}} @@ -63,6 +87,6 @@ function HoverPreviewDocument({ {content} ); -} +}); -export default HoverPreviewDocument; +export default HoverPreviewDocument; \ No newline at end of file From f6f27d51296978b3f5d7305c556c2bd4f81a666f Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Thu, 8 Oct 2026 21:13:31 -0400 Subject: [PATCH 005/467] fix: reveal search results in paginated sidebar collections (#13786) --- app/components/PaginatedList.tsx | 15 +++++++++++++++ app/components/Sidebar/components/Collections.tsx | 9 ++++++++- .../components/DraggableCollectionLink.tsx | 3 ++- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/app/components/PaginatedList.tsx b/app/components/PaginatedList.tsx index e0c9258910..2dd854cae2 100644 --- a/app/components/PaginatedList.tsx +++ b/app/components/PaginatedList.tsx @@ -56,6 +56,9 @@ interface Props< /** Array of items to display in the list */ items?: T[]; + /** ID of an item that must be included in the rendered page. */ + activeItemId?: string; + /** CSS class name to apply to the list container */ className?: string; @@ -112,6 +115,7 @@ const PaginatedList = ({ empty = null, loading = null, items = [], + activeItemId, className, renderItem, renderError, @@ -135,6 +139,17 @@ const PaginatedList = ({ const [offset, setOffset] = React.useState(0); const [allowLoadMore, setAllowLoadMore] = React.useState(true); + React.useEffect(() => { + if (!activeItemId) { + return; + } + + const activeIndex = items.findIndex((item) => item.id === activeItemId); + if (activeIndex >= 0) { + setRenderCount((count) => Math.max(count, activeIndex + 1)); + } + }, [items, activeItemId]); + const reset = React.useCallback(() => { setOffset(0); setAllowLoadMore(true); diff --git a/app/components/Sidebar/components/Collections.tsx b/app/components/Sidebar/components/Collections.tsx index e6adbeadcd..4b269b694b 100644 --- a/app/components/Sidebar/components/Collections.tsx +++ b/app/components/Sidebar/components/Collections.tsx @@ -8,6 +8,7 @@ import Flex from "~/components/Flex"; import Error from "~/components/List/Error"; import PaginatedList from "~/components/PaginatedList"; import { createCollection } from "~/actions/definitions/collections"; +import { useActiveSidebarContext } from "~/hooks/useActiveSidebarContext"; import useStores from "~/hooks/useStores"; import { type DragObject, useDropRef } from "../hooks/useDragAndDrop"; import DraggableCollectionLink from "./DraggableCollectionLink"; @@ -24,7 +25,8 @@ import usePolicy from "~/hooks/usePolicy"; const headerActions = [createCollection]; function Collections() { - const { documents, auth, collections, policies } = useStores(); + const { documents, auth, collections, policies, ui } = useStores(); + const activeSidebarContext = useActiveSidebarContext() ?? "collections"; const { t } = useTranslation(); const can = usePolicy(auth.team?.id); const orderedCollections = collections.allActive; @@ -70,6 +72,11 @@ function Collections() { options={params} aria-label={t("Collections")} items={orderedCollections} + activeItemId={ + activeSidebarContext === "collections" + ? ui.activeCollectionId + : undefined + } loading={} heading={ isDraggingAnyCollection ? ( diff --git a/app/components/Sidebar/components/DraggableCollectionLink.tsx b/app/components/Sidebar/components/DraggableCollectionLink.tsx index c6f53bc14b..e5d3b32ba9 100644 --- a/app/components/Sidebar/components/DraggableCollectionLink.tsx +++ b/app/components/Sidebar/components/DraggableCollectionLink.tsx @@ -35,7 +35,7 @@ function DraggableCollectionLink({ activeDocument, belowCollection, }: Props) { - const activeSidebarContext = useActiveSidebarContext(); + const activeSidebarContext = useActiveSidebarContext() ?? "collections"; const sidebarContext = useSidebarContext(); const { ui, policies, collections } = useStores(); const [expanded, setExpanded] = useState( @@ -103,6 +103,7 @@ function DraggableCollectionLink({ }, [ collection.id, ui.activeCollectionId, + activeDocument?.id, sidebarContext, activeSidebarContext, ]); From fe9758300756cee39a31086ada664f5f5f033af9 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 9 Oct 2026 17:26:58 -0400 Subject: [PATCH 006/467] fix: Emit events when deleting synced groups (#13998) --- server/routes/api/groups/groups.test.ts | 53 +++++++++++++++++++++++++ server/routes/api/groups/groups.ts | 11 ++++- 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/server/routes/api/groups/groups.test.ts b/server/routes/api/groups/groups.test.ts index 87de3cb6a9..ef9f940caf 100644 --- a/server/routes/api/groups/groups.test.ts +++ b/server/routes/api/groups/groups.test.ts @@ -607,6 +607,59 @@ describe("#groups.delete", () => { }); }); +describe("#groups.deleteAll", () => { + it("should require admin", async () => { + const user = await buildUser(); + const authProvider = (await AuthenticationProvider.findOne({ + where: { teamId: user.teamId }, + }))!; + const res = await server.post("/api/groups.deleteAll", user, { + body: { + authenticationProviderId: authProvider.id, + }, + }); + expect(res.status).toEqual(403); + }); + + it("deletes synced groups and emits a delete event for each", async () => { + const user = await buildAdmin(); + const authProvider = (await AuthenticationProvider.findOne({ + where: { teamId: user.teamId }, + }))!; + const synced = await buildGroup({ teamId: user.teamId }); + const unsynced = await buildGroup({ teamId: user.teamId }); + await ExternalGroup.create({ + externalId: "ext-1", + name: synced.name, + groupId: synced.id, + authenticationProviderId: authProvider.id, + teamId: user.teamId, + }); + + const res = await server.post("/api/groups.deleteAll", user, { + body: { + authenticationProviderId: authProvider.id, + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.success).toEqual(true); + + await synced.reload({ paranoid: false }); + await unsynced.reload(); + expect(synced.deletedAt).toBeTruthy(); + expect(unsynced.deletedAt).toBeNull(); + + const events = await Event.findAll({ + where: { + name: "groups.delete", + teamId: user.teamId, + }, + }); + expect(events.map((event) => event.modelId)).toEqual([synced.id]); + }); +}); + describe("#groups.memberships", () => { it("should return members in a group", async () => { const user = await buildUser(); diff --git a/server/routes/api/groups/groups.ts b/server/routes/api/groups/groups.ts index dea9bedfc8..c66a4fc5eb 100644 --- a/server/routes/api/groups/groups.ts +++ b/server/routes/api/groups/groups.ts @@ -371,10 +371,17 @@ router.post( ); if (groupIds.length) { - await Group.destroy({ - where: { id: groupIds }, + const groups = await Group.findAll({ + where: { id: groupIds, teamId: user.teamId }, transaction, + lock: transaction.LOCK.UPDATE, }); + + // Each group is destroyed individually so that a delete event is + // emitted, which revokes the access that its members were granted. + for (const group of groups) { + await group.destroyWithCtx(ctx); + } } ctx.body = { From bd1d4e518a177b89402a431c8b953a40646f1413 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 9 Oct 2026 17:29:05 -0400 Subject: [PATCH 007/467] fix: Ignore CSP eval errors from injected scripts in Sentry (#14001) Fixes OUTLINE-CLOUD-ADG --- app/utils/sentry.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/utils/sentry.ts b/app/utils/sentry.ts index 507cc0db88..5a8daf4871 100644 --- a/app/utils/sentry.ts +++ b/app/utils/sentry.ts @@ -57,6 +57,8 @@ export function initSentry(history: History) { "Object Not Found Matching Id", // Telegram's Android in-app browser calls a missing native bridge method /Error invoking post\w*: Method not found/, + // Injected scripts calling eval are blocked by our CSP, the app never uses eval + /evaluate a string as JavaScript/, "file://", "chrome-extension://", ], From 8433475ef6ad07bd57efa3095ff88aba5d40a219 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Fri, 9 Oct 2026 17:29:51 -0400 Subject: [PATCH 008/467] feat: Show who added a member in the group members table (#14000) * feat: Show who added a member in the group members table * fix: Make timestamps with tooltip detail keyboard accessible --- app/components/LocaleTime.tsx | 28 +++++++++++++++-- app/models/GroupUser.ts | 7 +++++ .../Settings/components/GroupMembersTable.tsx | 30 +++++++++++++++++++ server/presenters/groupUser.ts | 2 ++ server/routes/api/groups/groups.test.ts | 26 ++++++++++++++++ server/routes/api/groups/groups.ts | 18 ++++++++++- shared/i18n/locales/en_US/translation.json | 2 ++ 7 files changed, 109 insertions(+), 4 deletions(-) diff --git a/app/components/LocaleTime.tsx b/app/components/LocaleTime.tsx index d1bd6a09d6..802a798eab 100644 --- a/app/components/LocaleTime.tsx +++ b/app/components/LocaleTime.tsx @@ -10,15 +10,24 @@ export type Props = { shorten?: boolean; relative?: boolean; format?: Partial>; + /** Additional content shown below the date in the tooltip. */ + tooltipDetail?: React.ReactNode; }; -const LocaleTime: React.FC = ({ children, ...rest }: Props) => { +const LocaleTime: React.FC = ({ + children, + tooltipDetail, + ...rest +}: Props) => { const { tooltipContent, content } = useLocaleTime(rest); const [isInteractive, setIsInteractive] = React.useState(false); + // Detail is only available in the tooltip, so it must be reachable by keyboard. + const hasDetail = !!tooltipDetail; const time = ( ); - return isInteractive ? ( - + return isInteractive || hasDetail ? ( + + {tooltipContent} +
+ {tooltipDetail} + + ) : ( + tooltipContent + ) + } + placement="bottom" + > {time}
) : ( diff --git a/app/models/GroupUser.ts b/app/models/GroupUser.ts index 43fc93589b..12f0a9bfa8 100644 --- a/app/models/GroupUser.ts +++ b/app/models/GroupUser.ts @@ -31,6 +31,13 @@ class GroupUser extends Model { @Relation(() => Group, { onDelete: "cascade" }) group: Group; + /** The ID of the user that added the user to the group. */ + createdById: string; + + /** The user that added the user to the group. */ + @Relation(() => User, { onDelete: "null" }) + createdBy?: User; + /** The permission of the user in the group. */ @Field @observable diff --git a/app/scenes/Settings/components/GroupMembersTable.tsx b/app/scenes/Settings/components/GroupMembersTable.tsx index 4c08d7ed89..9360c0c62e 100644 --- a/app/scenes/Settings/components/GroupMembersTable.tsx +++ b/app/scenes/Settings/components/GroupMembersTable.tsx @@ -117,6 +117,36 @@ export const GroupMembersTable = observer(function GroupMembersTable({ ), width: "1fr", }, + { + type: "data", + id: "addedAt", + header: t("Added"), + sortable: false, + accessor: (user) => + groupUsers.membership(group.id, user.id)?.createdAt ?? "", + component: (user) => { + const membership = groupUsers.membership(group.id, user.id); + if (!membership?.createdAt) { + return null; + } + return ( +