From ad04aed6ef70ddacb152bfdc2364ee76945fa589 Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 20 Sep 2026 16:54:56 -0400 Subject: [PATCH] fix: Editor content delayed by React 19 Suspense reveal throttle (#13817) Lazy components now render synchronously once their chunk is loaded and share a preload promise, so the editor no longer commits a fallback and waits out the 300ms retry throttle. Editor chunks are preloaded from the document route, the sidebar hover, and the data loader. A lint rule blocks direct imports of the editor chunk. --- app/.oxlintrc.json | 7 +- app/components/AsyncEditor.ts | 13 ++++ app/components/Editor.tsx | 6 +- app/components/LazyLoad.ts | 10 +-- .../Sidebar/components/DocumentLink.tsx | 4 +- .../Sidebar/components/StarredLink.tsx | 2 +- app/routes/authenticated.tsx | 18 ++++- app/routes/scenes.ts | 6 +- app/scenes/Document/components/DataLoader.tsx | 5 ++ ...thRetry.test.ts => lazyWithRetry.test.tsx} | 0 .../{lazyWithRetry.ts => lazyWithRetry.tsx} | 67 ++++++++++++++++++- 11 files changed, 118 insertions(+), 20 deletions(-) create mode 100644 app/components/AsyncEditor.ts rename app/utils/{lazyWithRetry.test.ts => lazyWithRetry.test.tsx} (100%) rename app/utils/{lazyWithRetry.ts => lazyWithRetry.tsx} (60%) diff --git a/app/.oxlintrc.json b/app/.oxlintrc.json index 9857c6171f..ce3d9271bf 100644 --- a/app/.oxlintrc.json +++ b/app/.oxlintrc.json @@ -4,7 +4,7 @@ "plugins": ["oxc", "eslint", "typescript", "react"], "overrides": [ { - "files": ["**/*.{jsx,tsx}"], + "files": ["**/*.{js,jsx,ts,tsx}"], "rules": { "no-restricted-globals": [ "error", @@ -17,6 +17,11 @@ "error", { "paths": [ + { + "name": "~/editor", + "allowTypeImports": true, + "message": "Import AsyncEditor from ~/components/AsyncEditor instead. A direct import pulls the editor into the importing chunk and bypasses the shared preload." + }, { "name": "prosemirror-tables", "importNames": [ diff --git a/app/components/AsyncEditor.ts b/app/components/AsyncEditor.ts new file mode 100644 index 0000000000..916ab3808b --- /dev/null +++ b/app/components/AsyncEditor.ts @@ -0,0 +1,13 @@ +import lazyWithRetry from "~/utils/lazyWithRetry"; + +/** + * The editor core is the largest chunk in the app and is kept out of the + * initial bundle. This module stays light so routes can preload the chunk + * without pulling editor dependencies into their own chunk. + */ +const AsyncEditor = lazyWithRetry( + // oxlint-disable-next-line no-restricted-imports -- the one place the chunk is loaded + () => import("~/editor") +); + +export default AsyncEditor; diff --git a/app/components/Editor.tsx b/app/components/Editor.tsx index e0b0dcd73c..c801fbcb79 100644 --- a/app/components/Editor.tsx +++ b/app/components/Editor.tsx @@ -8,6 +8,7 @@ import type { Optional } from "utility-types"; import EditorContainer from "@shared/editor/components/Styles"; import { AttachmentPreset } from "@shared/types"; import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; +import AsyncEditor from "~/components/AsyncEditor"; import ClickablePadding from "~/components/ClickablePadding"; import ErrorBoundary from "~/components/ErrorBoundary"; import PlaceholderDocument from "~/components/PlaceholderDocument"; @@ -17,11 +18,8 @@ import useEditorClickHandlers from "~/hooks/useEditorClickHandlers"; import useEmbeds from "~/hooks/useEmbeds"; import useStores from "~/hooks/useStores"; import { uploadFile, uploadFileFromUrl } from "~/utils/files"; -import lazyWithRetry from "~/utils/lazyWithRetry"; import useShare from "@shared/hooks/useShare"; -const LazyLoadedEditor = lazyWithRetry(() => import("~/editor")); - export type Props = Optional< EditorProps, "placeholder" | "defaultValue" | "onClickLink" | "embeds" | "extensions" @@ -235,7 +233,7 @@ function Editor({ ref, ...props }: Props & { ref?: React.Ref }) { // React 18 would hide mounted ancestors and destroy their effects, // re-running provider setup and ref callbacks in a loop. }> - is the standard React pattern for generic component constraints export interface LazyComponent> { - Component: React.LazyExoticComponent; + Component: LazyComponentType; preload: () => Promise<{ default: T }>; } @@ -46,8 +47,7 @@ export function createLazyComponent>( })) : (factory as () => Promise<{ default: T }>); - return { - Component: lazyWithRetry(wrappedFactory, retries, interval), - preload: wrappedFactory, - }; + const Component = lazyWithRetry(wrappedFactory, retries, interval); + + return { Component, preload: Component.preload }; } diff --git a/app/components/Sidebar/components/DocumentLink.tsx b/app/components/Sidebar/components/DocumentLink.tsx index 1a5928ee59..ef5e0459d8 100644 --- a/app/components/Sidebar/components/DocumentLink.tsx +++ b/app/components/Sidebar/components/DocumentLink.tsx @@ -24,7 +24,7 @@ import useOnScreen from "~/hooks/useOnScreen"; import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; import DocumentMenu from "~/menus/DocumentMenu"; -import * as Scenes from "~/routes/scenes"; +import { preloadEditor } from "~/routes/scenes"; import { documentEditPath } from "~/utils/routeHelpers"; import { useDragDocument, @@ -276,7 +276,7 @@ const DocumentLinkInner = observer(function DocumentLinkInner({ }, [expansion, node.id]); const handlePrefetch = React.useCallback(() => { - void Scenes.Document.preload(); + preloadEditor(); void prefetchDocument?.(node.id); }, [prefetchDocument, node]); diff --git a/app/components/Sidebar/components/StarredLink.tsx b/app/components/Sidebar/components/StarredLink.tsx index d224b1d88f..5eb2ca58ca 100644 --- a/app/components/Sidebar/components/StarredLink.tsx +++ b/app/components/Sidebar/components/StarredLink.tsx @@ -438,7 +438,7 @@ function StarredLink({ star }: Props) { const handlePrefetch = React.useCallback(() => { if (documentId) { - void Scenes.Document.preload(); + Scenes.preloadEditor(); void documents.prefetchDocument(documentId); const document = documents.get(documentId); const documentCollection = document?.collectionId diff --git a/app/routes/authenticated.tsx b/app/routes/authenticated.tsx index f3b138bf99..1b38a9b27b 100644 --- a/app/routes/authenticated.tsx +++ b/app/routes/authenticated.tsx @@ -1,7 +1,7 @@ import { observer } from "mobx-react"; -import { Suspense } from "react"; +import { Suspense, useEffect } from "react"; import type { RouteComponentProps } from "react-router-dom"; -import { Switch, Redirect } from "react-router-dom"; +import { Switch, Redirect, matchPath, useLocation } from "react-router-dom"; import DocumentNew from "~/scenes/DocumentNew"; import Error404 from "~/scenes/Errors/Error404"; import AuthenticatedLayout from "~/components/AuthenticatedLayout"; @@ -54,6 +54,20 @@ function AuthenticatedRoutes() { useKeyboardShortcutsQuery(); const team = useCurrentTeam(); const can = usePolicy(team); + const location = useLocation(); + + // Warm the editor chunks alongside the scene chunk so a document can render + // as soon as its data arrives. + useEffect(() => { + if ( + matchPath(location.pathname, { + path: [`/doc/${documentSlug}`, `/d/${documentSlug}`], + }) + ) { + Scenes.preloadEditor(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); return ( diff --git a/app/routes/scenes.ts b/app/routes/scenes.ts index a2b2bf4b91..a86c06d540 100644 --- a/app/routes/scenes.ts +++ b/app/routes/scenes.ts @@ -1,4 +1,6 @@ +import AsyncEditor from "~/components/AsyncEditor"; import { createLazyComponent as lazy } from "~/components/LazyLoad"; +import AsyncMultiplayerEditor from "~/scenes/Document/components/AsyncMultiplayerEditor"; /** * Lazy-loaded scenes for the authenticated routes. Defined separately from the @@ -21,6 +23,6 @@ export const Trash = lazy(() => import("~/scenes/Trash")); */ export function preloadEditor() { void Document.preload(); - void import("~/scenes/Document/components/MultiplayerEditor"); - void import("~/editor"); + void AsyncMultiplayerEditor.preload(); + void AsyncEditor.preload(); } diff --git a/app/scenes/Document/components/DataLoader.tsx b/app/scenes/Document/components/DataLoader.tsx index 3cba266554..747c78677d 100644 --- a/app/scenes/Document/components/DataLoader.tsx +++ b/app/scenes/Document/components/DataLoader.tsx @@ -19,6 +19,7 @@ import useCurrentUser from "~/hooks/useCurrentUser"; import usePolicy from "~/hooks/usePolicy"; import useQuery from "~/hooks/useQuery"; import useStores from "~/hooks/useStores"; +import { preloadEditor } from "~/routes/scenes"; import type { Properties } from "~/types"; import Logger from "~/utils/Logger"; import { @@ -106,6 +107,10 @@ function DataLoader({ match, children }: Props) { useDocumentSidebar(); + React.useEffect(() => { + preloadEditor(); + }, []); + React.useEffect(() => { async function fetchDocument() { try { diff --git a/app/utils/lazyWithRetry.test.ts b/app/utils/lazyWithRetry.test.tsx similarity index 100% rename from app/utils/lazyWithRetry.test.ts rename to app/utils/lazyWithRetry.test.tsx diff --git a/app/utils/lazyWithRetry.ts b/app/utils/lazyWithRetry.tsx similarity index 60% rename from app/utils/lazyWithRetry.ts rename to app/utils/lazyWithRetry.tsx index 971e815d82..aca2d880ac 100644 --- a/app/utils/lazyWithRetry.ts +++ b/app/utils/lazyWithRetry.tsx @@ -24,20 +24,81 @@ export function isStaleChunkError(error: unknown): boolean { return staleChunkErrorPattern.test(message); } +/** + * A promise that carries the status fields React's `use` hook reads, so a + * fulfilled load can be unwrapped synchronously without suspending. + */ +type TrackedPromise = Promise & + ( + | React.PendingReactPromise + | React.FulfilledReactPromise + | React.RejectedReactPromise + ); + +export type LazyComponent> = React.FC< + React.ComponentPropsWithRef +> & { + /** + * Starts loading the chunk. Once the returned promise settles, rendering + * the component no longer suspends. + */ + preload: () => ComponentPromise; +}; + /** * Lazy load a component with automatic retry on failure. * + * Unlike `React.lazy`, a component whose chunk has already loaded renders + * synchronously instead of suspending. This matters because React throttles + * the reveal of a resolved Suspense boundary for up to 300ms after the fallback + * was shown, which delays content that is otherwise ready to paint. + * * @param component A function that returns a promise of a component. * @param retries The number of retries, defaults to 3. * @param interval The interval between retries in milliseconds, defaults to 1000. - * @returns A lazy component. + * @returns A lazy component with a `preload` method. */ export default function lazyWithRetry>( component: () => ComponentPromise, retries?: number, interval?: number -): React.LazyExoticComponent { - return React.lazy(() => retry(component, retries, interval)); +): LazyComponent { + let promise: TrackedPromise<{ default: T }> | undefined; + + const preload = () => { + if (!promise) { + const pending = retry(component, retries, interval) as TrackedPromise<{ + default: T; + }>; + pending.status = "pending"; + void pending.then( + (module) => { + const fulfilled = pending as React.FulfilledReactPromise<{ + default: T; + }>; + fulfilled.status = "fulfilled"; + fulfilled.value = module; + }, + (reason) => { + const rejected = pending as React.RejectedReactPromise<{ + default: T; + }>; + rejected.status = "rejected"; + rejected.reason = reason; + } + ); + promise = pending; + } + return promise; + }; + + const Lazy = (props: React.ComponentPropsWithRef) => { + const { default: Component } = React.use(preload()); + return ; + }; + Lazy.displayName = "Lazy"; + + return Object.assign(Lazy, { preload }); } function retry>(