Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(docs): stop host re-renders from re-syncing the whole live doc (MUL-9751) (#11241)

Bohan Jiang52b22268cf8b
diff --git a/packages/views/docs/components/doc-outline.test.tsx b/packages/views/docs/components/doc-outline.test.tsx
index 93ab04d866..615eff6000 100644
--- a/packages/views/docs/components/doc-outline.test.tsx
+++ b/packages/views/docs/components/doc-outline.test.tsx
@@ -46,10 +46,18 @@ describe("DocOutline", () => {
const headings = readOutline(
renderedDoc("<h2>Goals</h2><h3>Scope</h3><h2>Plan</h2>"),
);
- const onSelect = vi.fn();
- render(<DocOutline headings={headings} activeIndex={1} onSelect={onSelect} />, {
- wrapper: I18nWrapper,
+ // The second heading is the last one above the active line.
+ headings.forEach((heading, i) => {
+ vi.spyOn(heading.element, "getBoundingClientRect").mockReturnValue({
+ top: [0, 50, 500][i],
+ } as DOMRect);
});
+ const scroller = document.createElement("div");
+ const onSelect = vi.fn();
+ render(
+ <DocOutline headings={headings} scrollRef={{ current: scroller }} onSelect={onSelect} />,
+ { wrapper: I18nWrapper },
+ );
expect(screen.getByRole("navigation", { name: "Outline" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Scope" })).toHaveAttribute(
"aria-current",
diff --git a/packages/views/docs/components/doc-outline.tsx b/packages/views/docs/components/doc-outline.tsx
index 2d2757906d..b48fb35700 100644
--- a/packages/views/docs/components/doc-outline.tsx
+++ b/packages/views/docs/components/doc-outline.tsx
@@ -47,9 +47,10 @@ function sameOutline(a: OutlineHeading[], b: OutlineHeading[]): boolean {
}
/**
- * Headings of the editor under `rootRef`, kept current as the user types, and
- * which one the scroll position of `scrollRef` is in. A new `bodyKey` reads
- * them again at once, for a host that swaps what the root shows.
+ * Headings of the editor under `rootRef`, kept current as the user types. A
+ * new `bodyKey` reads them again at once, for a host that swaps what the root
+ * shows. Which heading is current is tracked by `DocOutline` itself: scrolling
+ * then re-renders only the outline, never the page holding the editor.
*/
export function useDocOutline(
rootRef: RefObject<HTMLElement | null>,
@@ -57,7 +58,6 @@ export function useDocOutline(
bodyKey?: string | number,
) {
const [headings, setHeadings] = useState<OutlineHeading[]>([]);
- const [activeIndex, setActiveIndex] = useState(0);
useEffect(() => {
const root = rootRef.current;
@@ -70,6 +70,27 @@ export function useDocOutline(
});
}, [rootRef, bodyKey]);
+ const scrollTo = (heading: OutlineHeading) => {
+ const scroller = scrollRef.current;
+ if (!scroller) return;
+ const offset =
+ heading.element.getBoundingClientRect().top -
+ scroller.getBoundingClientRect().top;
+ scroller.scrollTo({
+ top: scroller.scrollTop + offset - SCROLL_MARGIN,
+ behavior: "smooth",
+ });
+ };
+
+ return { headings, scrollTo };
+}
+
+/** Which of `headings` the scroll position of `scrollRef` is in. */
+function useActiveHeading(
+ headings: OutlineHeading[],
+ scrollRef: RefObject<HTMLElement | null>,
+): number {
+ const [activeIndex, setActiveIndex] = useState(0);
useEffect(() => {
const scroller = scrollRef.current;
if (!scroller || headings.length === 0) return;
@@ -84,33 +105,21 @@ export function useDocOutline(
update();
scroller.addEventListener("scroll", update, { passive: true });
return () => scroller.removeEventListener("scroll", update);
- }, [headings, scrollRef, bodyKey]);
-
- const scrollTo = (heading: OutlineHeading) => {
- const scroller = scrollRef.current;
- if (!scroller) return;
- const offset =
- heading.element.getBoundingClientRect().top -
- scroller.getBoundingClientRect().top;
- scroller.scrollTo({
- top: scroller.scrollTop + offset - SCROLL_MARGIN,
- behavior: "smooth",
- });
- };
-
- return { headings, activeIndex, scrollTo };
+ }, [headings, scrollRef]);
+ return activeIndex;
}
export function DocOutline({
headings,
- activeIndex,
+ scrollRef,
onSelect,
}: {
headings: OutlineHeading[];
- activeIndex: number;
+ scrollRef: RefObject<HTMLElement | null>;
onSelect: (heading: OutlineHeading) => void;
}) {
const { t } = useT("docs");
+ const activeIndex = useActiveHeading(headings, scrollRef);
const minLevel = Math.min(...headings.map((heading) => heading.level));
return (
<nav
diff --git a/packages/views/docs/components/doc-page.tsx b/packages/views/docs/components/doc-page.tsx
index b35527b21d..778a759260 100644
--- a/packages/views/docs/components/doc-page.tsx
+++ b/packages/views/docs/components/doc-page.tsx
@@ -580,7 +580,7 @@ function DocEditor({ doc }: { doc: Doc }) {
<aside className="hidden w-56 shrink-0 py-8 pr-6 @5xl:block">
<DocOutline
headings={outline.headings}
- activeIndex={outline.activeIndex}
+ scrollRef={scrollRef}
onSelect={outline.scrollTo}
/>
</aside>
diff --git a/packages/views/docs/components/use-doc-comment-highlights.ts b/packages/views/docs/components/use-doc-comment-highlights.ts
index 50be58e6cf..5d35cefd54 100644
--- a/packages/views/docs/components/use-doc-comment-highlights.ts
+++ b/packages/views/docs/components/use-doc-comment-highlights.ts
@@ -43,11 +43,15 @@ export function useDocCommentHighlights(
if (!root) return;
const ranges = new Map<string, Range>();
const gone = new Set<string>();
- const index = indexCommentText(root, true);
- for (const thread of threadsRef.current) {
- const range = docAnchorRange(root, thread, index);
- if (range) ranges.set(thread.id, range);
- else gone.add(thread.id);
+ // A doc without discussions has nothing to find: skip the walk over its
+ // text, which otherwise runs on every batch of edits.
+ if (threadsRef.current.length > 0) {
+ const index = indexCommentText(root, true);
+ for (const thread of threadsRef.current) {
+ const range = docAnchorRange(root, thread, index);
+ if (range) ranges.set(thread.id, range);
+ else gone.add(thread.id);
+ }
}
rangesRef.current = ranges;
setMissing((prev) =>
diff --git a/packages/views/editor/content-editor-options.test.tsx b/packages/views/editor/content-editor-options.test.tsx
new file mode 100644
index 0000000000..a29233380a
--- /dev/null
+++ b/packages/views/editor/content-editor-options.test.tsx
@@ -0,0 +1,57 @@
+import { describe, expect, it, vi } from "vitest";
+import { waitFor } from "@testing-library/react";
+import { Editor } from "@tiptap/core";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { renderWithI18n } from "../test/i18n";
+import { NavigationProvider } from "../navigation/context";
+import type { NavigationAdapter } from "../navigation/types";
+import { ContentEditor } from "./content-editor";
+
+function adapter(): NavigationAdapter {
+ return {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/",
+ searchParams: new URLSearchParams(),
+ hash: "",
+ getShareableUrl: (path) => `https://app.example${path}`,
+ };
+}
+
+// MUL-9751: Tiptap calls `setOptions` after any render whose options differ
+// from the editor's, and that re-runs every plugin view — for a live doc, a
+// diff of the whole document against the shared one. A host re-render that
+// changes nothing must not reach it.
+describe("ContentEditor options", () => {
+ it("leaves the editor alone when the host re-renders with the same props", async () => {
+ const queryClient = new QueryClient();
+ const setOptions = vi.spyOn(Editor.prototype, "setOptions");
+ const onReady = vi.fn();
+ const ui = (className: string) => (
+ <NavigationProvider value={adapter()}>
+ <QueryClientProvider client={queryClient}>
+ <ContentEditor
+ defaultValue="Hello"
+ className={className}
+ showBubbleMenu={false}
+ // A fresh callback each render, as hosts pass them.
+ onReady={() => onReady()}
+ />
+ </QueryClientProvider>
+ </NavigationProvider>
+ );
+ const { rerender } = renderWithI18n(ui("a"));
+ await waitFor(() => expect(onReady).toHaveBeenCalled());
+ setOptions.mockClear();
+
+ rerender(ui("a"));
+ rerender(ui("a"));
+ expect(setOptions).not.toHaveBeenCalled();
+
+ // A prop the editor does read still reaches it.
+ rerender(ui("b"));
+ expect(setOptions).toHaveBeenCalledTimes(1);
+ setOptions.mockRestore();
+ });
+});
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 81f410508b..9048d3c806 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -41,6 +41,7 @@ import {
type MouseEvent as ReactMouseEvent,
} from "react";
import { useEditor, EditorContent, type Editor } from "@tiptap/react";
+import type { EditorProps } from "@tiptap/pm/view";
import { cn } from "@multica/ui/lib/utils";
import type { UploadResult } from "@multica/core/hooks/use-file-upload";
import { useWorkspaceSlug } from "@multica/core/paths";
@@ -620,46 +621,14 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
// parseMarkdownChunked). Small docs stay on the single-parse fast path.
const mountChunked = initialContent.length > MARKDOWN_CHUNK_THRESHOLD;
- const editor = useEditor({
- immediatelyRender: false,
- // Explicit for clarity — the real perf win is useEditorState in BubbleMenu.
- shouldRerenderOnTransaction: false,
- onCreate: ({ editor: ed }) => {
- // For large docs we mount empty (below) and parse in chunks here, so the
- // O(n²) marked tokenizer never sees the whole document at once.
- if (mountChunked) {
- const manager = (
- ed.storage as { markdown?: { manager?: MarkdownManagerLike } }
- ).markdown?.manager;
- if (manager) {
- ed.commands.setContent(
- parseMarkdownChunked(manager, initialContent),
- { emitUpdate: false },
- );
- } else {
- ed.commands.setContent(initialContent, {
- emitUpdate: false,
- contentType: "markdown",
- });
- }
- }
- // A markdown draft ending in an empty list item (e.g. `"1. \n\n"` left
- // after typing `1.`) parses into a caretless, schema-invalid item;
- // repair it so the mounted editor has a real cursor in the list.
- repairEmptyListItems(ed);
- lastEmittedRef.current = normalizeEditorMarkdown(ed);
- if (focusOnReadyRef.current) {
- focusOnReadyRef.current = false;
- ed.commands.focus("end");
- }
- },
- content: mountChunked ? "" : initialContent,
- contentType: mountChunked
- ? undefined
- : initialMarkdown
- ? "markdown"
- : undefined,
- extensions: createEditorExtensions({
+ // Tiptap compares these to the editor's options after every render and,
+ // when they differ, calls `setOptions`, which re-runs every plugin view.
+ // The collaboration plugin answers that by diffing the whole document
+ // against the shared one, so a fresh array or object on each render made
+ // every host re-render cost a pass over the doc (MUL-9751). Extensions are
+ // only read when the editor is created; editorProps follow their inputs.
+ const [extensions] = useState(() =>
+ createEditorExtensions({
placeholder: () => placeholderRef.current,
queryClient,
onSubmitRef,
@@ -685,31 +654,9 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
resolveIssueIdentifierRef,
collaboration,
}),
- onUpdate: ({ editor: ed }) => {
- if (!onUpdateRef.current) return;
- pendingBaseRef.current = documentBaseRef.current;
- if (flushPendingOnUnmountRef.current) {
- pendingFlushRef.current = normalizeEditorMarkdown(ed);
- }
- if (debounceRef.current) clearTimeout(debounceRef.current);
- debounceRef.current = setTimeout(() => {
- debounceRef.current = undefined;
- pendingFlushRef.current = null;
- const base = pendingBaseRef.current ?? documentBaseRef.current;
- pendingBaseRef.current = null;
- const md = normalizeEditorMarkdown(ed);
- if (md === lastEmittedRef.current) return;
- lastEmittedRef.current = md;
- onUpdateRef.current?.(md, base);
- }, debounceMs);
- },
- onFocus: () => {
- caretPlacedRef.current = true;
- },
- onBlur: () => {
- onBlurRef.current?.();
- },
- editorProps: {
+ );
+ const editorProps = useMemo<EditorProps>(
+ () => ({
handleDOMEvents: {
click(_view, event) {
const target = event.target as HTMLElement;
@@ -761,7 +708,76 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
"data-mc": "content",
...(ariaLabel ? { role: "textbox", "aria-label": ariaLabel, "aria-multiline": "true" } : {}),
},
+ }),
+ // The handlers read everything else through refs.
+ [className, ariaLabel],
+ );
+
+ const editor = useEditor({
+ immediatelyRender: false,
+ // Explicit for clarity — the real perf win is useEditorState in BubbleMenu.
+ shouldRerenderOnTransaction: false,
+ onCreate: ({ editor: ed }) => {
+ // For large docs we mount empty (below) and parse in chunks here, so the
+ // O(n²) marked tokenizer never sees the whole document at once.
+ if (mountChunked) {
+ const manager = (
+ ed.storage as { markdown?: { manager?: MarkdownManagerLike } }
+ ).markdown?.manager;
+ if (manager) {
+ ed.commands.setContent(
+ parseMarkdownChunked(manager, initialContent),
+ { emitUpdate: false },
+ );
+ } else {
+ ed.commands.setContent(initialContent, {
+ emitUpdate: false,
+ contentType: "markdown",
+ });
+ }
+ }
+ // A markdown draft ending in an empty list item (e.g. `"1. \n\n"` left
+ // after typing `1.`) parses into a caretless, schema-invalid item;
+ // repair it so the mounted editor has a real cursor in the list.
+ repairEmptyListItems(ed);
+ lastEmittedRef.current = normalizeEditorMarkdown(ed);
+ if (focusOnReadyRef.current) {
+ focusOnReadyRef.current = false;
+ ed.commands.focus("end");
+ }
+ },
+ content: mountChunked ? "" : initialContent,
+ contentType: mountChunked
+ ? undefined
+ : initialMarkdown
+ ? "markdown"
+ : undefined,
+ extensions,
+ onUpdate: ({ editor: ed }) => {
+ if (!onUpdateRef.current) return;
+ pendingBaseRef.current = documentBaseRef.current;
+ if (flushPendingOnUnmountRef.current) {
+ pendingFlushRef.current = normalizeEditorMarkdown(ed);
+ }
+ if (debounceRef.current) clearTimeout(debounceRef.current);
+ debounceRef.current = setTimeout(() => {
+ debounceRef.current = undefined;
+ pendingFlushRef.current = null;
+ const base = pendingBaseRef.current ?? documentBaseRef.current;
+ pendingBaseRef.current = null;
+ const md = normalizeEditorMarkdown(ed);
+ if (md === lastEmittedRef.current) return;
+ lastEmittedRef.current = md;
+ onUpdateRef.current?.(md, base);
+ }, debounceMs);
+ },
+ onFocus: () => {
+ caretPlacedRef.current = true;
+ },
+ onBlur: () => {
+ onBlurRef.current?.();
},
+ editorProps,
});
// Catalog queries can settle after the last keystroke. Refresh the active