@karimsa/mdxserve 0.5.1 → 0.6.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +3 -0
  2. package/client/DocView.tsx +26 -14
  3. package/client/ListingView.tsx +3 -3
  4. package/client/MdSection.tsx +14 -9
  5. package/client/RenderErrorBoundary.tsx +20 -5
  6. package/client/Settings.tsx +26 -21
  7. package/client/app.css +20 -0
  8. package/client/comments/CommentsPanel.tsx +194 -0
  9. package/client/comments/CommentsPopover.tsx +197 -0
  10. package/client/comments/CommentsSheet.tsx +63 -0
  11. package/client/comments/CommentsSidebar.tsx +24 -0
  12. package/client/comments/CtlButton.tsx +33 -0
  13. package/client/comments/DraftThread.tsx +86 -0
  14. package/client/comments/GutterCounters.tsx +121 -0
  15. package/client/comments/ReplyField.tsx +98 -0
  16. package/client/comments/SelectionButton.tsx +142 -0
  17. package/client/comments/Thread.tsx +308 -0
  18. package/client/comments/anchor.ts +204 -0
  19. package/client/comments/data.ts +98 -0
  20. package/client/comments/dom.ts +212 -0
  21. package/client/comments/drafts.ts +36 -0
  22. package/client/comments/highlights.ts +83 -0
  23. package/client/comments/model.ts +241 -0
  24. package/client/comments/motion.ts +44 -0
  25. package/client/comments/pins.ts +37 -0
  26. package/client/comments/self-writes.ts +22 -0
  27. package/client/comments/state.ts +67 -0
  28. package/client/comments/time.ts +21 -0
  29. package/client/entry.tsx +10 -0
  30. package/client/hooks.ts +19 -0
  31. package/client/platform.ts +8 -0
  32. package/client/router.ts +5 -0
  33. package/client/shell/AppShell.tsx +85 -15
  34. package/client/shell/StandaloneShell.tsx +3 -2
  35. package/client/shell/TopBar.tsx +25 -0
  36. package/client/ui/ConfirmDeleteDialog.tsx +1 -1
  37. package/client/ui/Toast.tsx +5 -1
  38. package/client/ui/icon-set.ts +10 -0
  39. package/dist/cli.js +872 -229
  40. package/package.json +1 -1
  41. package/skills/mdxserve/SKILL.md +86 -0
@@ -0,0 +1,98 @@
1
+ import { useQuery } from "@tanstack/react-query";
2
+ import { useMemo } from "react";
3
+ import type { CommentThread } from "../../src/comments/schema";
4
+ import { queryClient, trpc, trpcClient } from "../api";
5
+ import { pushToast } from "../ui/Toast";
6
+ import { markSelfWrite } from "./self-writes";
7
+
8
+ const NO_THREADS: CommentThread[] = [];
9
+
10
+ /** The doc's threads, from the same query the `mdxserve:doc-changed` handler invalidates. */
11
+ export function useDocThreads(path: string | null): { threads: CommentThread[]; loaded: boolean } {
12
+ const { data } = useQuery(
13
+ trpc.getDocComments.queryOptions({ path: path ?? "" }, { enabled: path !== null }),
14
+ );
15
+ return useMemo(
16
+ () => ({ threads: data?.threads ?? NO_THREADS, loaded: data !== undefined }),
17
+ [data],
18
+ );
19
+ }
20
+
21
+ function errorText(error: unknown): string {
22
+ return error instanceof Error && error.message ? error.message : "Could not save the comment";
23
+ }
24
+
25
+ export interface CommentActions {
26
+ /** Resolves to the id of the thread it created, or null when the write failed. */
27
+ addThread(anchor: CommentAnchorInput, body: string): Promise<string | null>;
28
+ reply(threadId: string, body: string): Promise<CommentThread[] | null>;
29
+ edit(threadId: string, messageId: string, body: string): Promise<CommentThread[] | null>;
30
+ setResolved(threadId: string, resolved: boolean): Promise<CommentThread[] | null>;
31
+ }
32
+
33
+ type CommentAnchorInput = { heading: string | null; block: string; quote: string };
34
+
35
+ /**
36
+ * Runs one comment mutation. The response carries the full thread list, which
37
+ * replaces the cached one at once. A failure becomes a danger toast with the
38
+ * server's message and resolves to null, so callers keep their draft text.
39
+ */
40
+ async function runWrite(
41
+ path: string,
42
+ call: () => Promise<{ threads: CommentThread[] }>,
43
+ ): Promise<CommentThread[] | null> {
44
+ markSelfWrite(path);
45
+ try {
46
+ const result = await call();
47
+ markSelfWrite(path);
48
+ queryClient.setQueryData(trpc.getDocComments.queryKey({ path }), (cached) => ({
49
+ diagnostics: cached?.diagnostics ?? [],
50
+ threads: result.threads,
51
+ }));
52
+ return result.threads;
53
+ } catch (error) {
54
+ pushToast({ tone: "danger", text: errorText(error), dedupeKey: "comment-error" });
55
+ return null;
56
+ }
57
+ }
58
+
59
+ // Each response is a snapshot of the whole thread list. Two writes in flight
60
+ // for one doc could land out of order and roll the cache back, so a doc's
61
+ // writes run one after another.
62
+ const writeQueues = new Map<string, Promise<unknown>>();
63
+
64
+ function write(
65
+ path: string,
66
+ call: () => Promise<{ threads: CommentThread[] }>,
67
+ ): Promise<CommentThread[] | null> {
68
+ const previous = writeQueues.get(path) ?? Promise.resolve();
69
+ // runWrite never rejects, so the chain cannot break.
70
+ const run = previous.then(() => runWrite(path, call));
71
+ writeQueues.set(path, run);
72
+ void run.then(() => {
73
+ if (writeQueues.get(path) === run) writeQueues.delete(path);
74
+ });
75
+ return run;
76
+ }
77
+
78
+ export function commentActions(path: string): CommentActions {
79
+ return {
80
+ addThread: async (anchor, body) => {
81
+ // The server names the thread it created; the returned list can also hold
82
+ // threads someone else added since this tab last fetched.
83
+ let created: string | null = null;
84
+ const threads = await write(path, async () => {
85
+ const result = await trpcClient.addCommentThread.mutate({ path, anchor, body });
86
+ created = result.threadId;
87
+ return result;
88
+ });
89
+ return threads ? created : null;
90
+ },
91
+ reply: (threadId, body) =>
92
+ write(path, () => trpcClient.addCommentReply.mutate({ path, threadId, body })),
93
+ edit: (threadId, messageId, body) =>
94
+ write(path, () => trpcClient.editComment.mutate({ path, threadId, messageId, body })),
95
+ setResolved: (threadId, resolved) =>
96
+ write(path, () => trpcClient.setCommentThreadResolved.mutate({ path, threadId, resolved })),
97
+ };
98
+ }
@@ -0,0 +1,212 @@
1
+ import {
2
+ captureAnchor,
3
+ headingKey,
4
+ mapNormalizedRange,
5
+ normalizeText,
6
+ resolveAnchor,
7
+ type AnchorFields,
8
+ type BlockDescription,
9
+ type NodePoint,
10
+ type Resolution,
11
+ type ResolveIndex,
12
+ } from "./anchor";
13
+
14
+ /** The innermost match of this selector inside the article is a block. */
15
+ export const BLOCK_SELECTOR =
16
+ "p, li, td, th, h1, h2, h3, h4, h5, h6, pre, dt, dd, figcaption, summary";
17
+ const HEADING_SELECTOR = "h1, h2, h3, h4, h5, h6";
18
+ /**
19
+ * Never part of a block or its text. `.mdx-anchor` is the hover "#" link
20
+ * Heading.tsx appends to a heading: it is chrome, not rendered text.
21
+ */
22
+ const EXCLUDED_SELECTOR = "[data-editing], svg, button, .mdx-anchor";
23
+ /** Content of an inactive tab: still mounted, but hidden from the page. */
24
+ const HIDDEN_SELECTOR = '[inert], [aria-hidden="true"]';
25
+
26
+ export interface DomBlock {
27
+ el: Element;
28
+ nodes: Text[];
29
+ /** Normalized text. */
30
+ text: string;
31
+ /** Index into `DomDoc.headings`, or -1 before the first heading. */
32
+ section: number;
33
+ }
34
+
35
+ export interface DomHeading {
36
+ /** `headingKey` of the text. */
37
+ key: string;
38
+ /** Index into `DomDoc.blocks`. */
39
+ block: number;
40
+ }
41
+
42
+ export interface DomDoc {
43
+ article: Element;
44
+ blocks: DomBlock[];
45
+ headings: DomHeading[];
46
+ }
47
+
48
+ function textNodesOf(block: Element): Text[] {
49
+ const nodes: Text[] = [];
50
+ const walker = block.ownerDocument.createTreeWalker(block, NodeFilter.SHOW_TEXT);
51
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
52
+ const parent = node.parentElement;
53
+ // The block itself is never inside an excluded element, so a match is within it.
54
+ if (parent?.closest(EXCLUDED_SELECTOR) || parent?.closest(HIDDEN_SELECTOR)) continue;
55
+ nodes.push(node as Text);
56
+ }
57
+ return nodes;
58
+ }
59
+
60
+ /** Headings and blocks of the article, in document order, per the plan's text model. */
61
+ export function collectDoc(article: Element): DomDoc {
62
+ const blocks: DomBlock[] = [];
63
+ const headings: DomHeading[] = [];
64
+ let section = -1;
65
+ for (const el of article.querySelectorAll(BLOCK_SELECTOR)) {
66
+ if (el.querySelector(BLOCK_SELECTOR)) continue;
67
+ if (el.closest(EXCLUDED_SELECTOR) || el.closest(HIDDEN_SELECTOR)) continue;
68
+ const nodes = textNodesOf(el);
69
+ const text = normalizeText(nodes.map((node) => node.data).join(""));
70
+ if (el.matches(HEADING_SELECTOR)) {
71
+ headings.push({ key: headingKey(text), block: blocks.length });
72
+ section = headings.length - 1;
73
+ }
74
+ blocks.push({ el, nodes, text, section });
75
+ }
76
+ return { article, blocks, headings };
77
+ }
78
+
79
+ export function findArticle(root: ParentNode = document): Element | null {
80
+ return root.querySelector("article.mdx-prose");
81
+ }
82
+
83
+ function describeBlocks(doc: DomDoc): BlockDescription[] {
84
+ return doc.blocks.map((block) => ({
85
+ heading: block.section === -1 ? null : doc.headings[block.section].key,
86
+ nodes: block.nodes.map((node) => node.data),
87
+ }));
88
+ }
89
+
90
+ /** Index of `node` within the block's text nodes for a range boundary; see `boundaryPoint`. */
91
+ function boundaryPoint(
92
+ block: DomBlock,
93
+ container: Node,
94
+ offset: number,
95
+ edge: "start" | "end",
96
+ ): NodePoint | null {
97
+ const direct = block.nodes.indexOf(container as Text);
98
+ if (direct !== -1) return { node: direct, offset };
99
+
100
+ const probe = block.el.ownerDocument.createRange();
101
+ probe.setStart(container, offset);
102
+ probe.collapse(true);
103
+ if (edge === "start") {
104
+ // First text node that begins at or after the boundary.
105
+ for (let node = 0; node < block.nodes.length; node++) {
106
+ if (probe.comparePoint(block.nodes[node], 0) >= 0) return { node, offset: 0 };
107
+ }
108
+ return null;
109
+ }
110
+ // Last text node that begins before the boundary, taken whole.
111
+ for (let node = block.nodes.length - 1; node >= 0; node--) {
112
+ if (probe.comparePoint(block.nodes[node], 0) < 0) {
113
+ return { node, offset: block.nodes[node].length };
114
+ }
115
+ }
116
+ return null;
117
+ }
118
+
119
+ /** The anchor for the live selection, or null when it cannot carry a comment. */
120
+ export function captureSelection(
121
+ selection: Selection | null,
122
+ article: Element | null = findArticle(),
123
+ ): AnchorFields | null {
124
+ if (!selection || selection.rangeCount === 0 || !article) return null;
125
+ const range = selection.getRangeAt(0);
126
+ if (range.collapsed) return null;
127
+ if (!article.contains(range.startContainer)) return null;
128
+
129
+ const startElement =
130
+ range.startContainer instanceof Element
131
+ ? range.startContainer
132
+ : range.startContainer.parentElement;
133
+ if (!startElement || startElement.closest("[data-editing]")) return null;
134
+ const blockElement = startElement.closest(BLOCK_SELECTOR);
135
+ if (!blockElement) return null;
136
+
137
+ const doc = collectDoc(article);
138
+ const blockIndex = doc.blocks.findIndex((block) => block.el === blockElement);
139
+ if (blockIndex === -1) return null;
140
+ const block = doc.blocks[blockIndex];
141
+
142
+ const start = boundaryPoint(block, range.startContainer, range.startOffset, "start");
143
+ if (!start) return null;
144
+ // An end beyond the block clips to the block's last text node.
145
+ const endsInside = blockElement.contains(range.endContainer);
146
+ const end = endsInside
147
+ ? boundaryPoint(block, range.endContainer, range.endOffset, "end")
148
+ : boundaryPoint(block, blockElement, blockElement.childNodes.length, "end");
149
+ if (!end) return null;
150
+ return captureAnchor(describeBlocks(doc), { blockIndex, start, end });
151
+ }
152
+
153
+ export function resolveIndexOf(doc: DomDoc): ResolveIndex {
154
+ return {
155
+ headings: doc.headings,
156
+ blocks: doc.blocks.map((block) => ({ text: block.text, section: block.section })),
157
+ };
158
+ }
159
+
160
+ export interface DomResolution {
161
+ resolution: Resolution;
162
+ /** The text to highlight; null for `section` and `detached`. */
163
+ range: Range | null;
164
+ /** What to scroll to when the thread is selected. */
165
+ scrollTarget: Element | null;
166
+ }
167
+
168
+ function blockRange(block: DomBlock): Range | null {
169
+ const first = block.nodes[0];
170
+ const last = block.nodes[block.nodes.length - 1];
171
+ if (!first || !last) return null;
172
+ const range = block.el.ownerDocument.createRange();
173
+ range.setStart(first, 0);
174
+ range.setEnd(last, last.length);
175
+ return range;
176
+ }
177
+
178
+ /** Resolves one anchor against the collected document and builds its DOM range. */
179
+ export function resolveInDom(
180
+ doc: DomDoc,
181
+ index: ResolveIndex,
182
+ anchor: AnchorFields,
183
+ ): DomResolution {
184
+ const resolution = resolveAnchor(anchor, index);
185
+ switch (resolution.state) {
186
+ case "exact": {
187
+ const block = doc.blocks[resolution.block];
188
+ const mapped = mapNormalizedRange(
189
+ block.nodes.map((node) => node.data),
190
+ resolution.start,
191
+ resolution.end,
192
+ );
193
+ if (!mapped) return { resolution, range: null, scrollTarget: block.el };
194
+ const range = block.el.ownerDocument.createRange();
195
+ range.setStart(block.nodes[mapped.start.node], mapped.start.offset);
196
+ range.setEnd(block.nodes[mapped.end.node], mapped.end.offset);
197
+ return { resolution, range, scrollTarget: block.el };
198
+ }
199
+ case "block": {
200
+ const block = doc.blocks[resolution.block];
201
+ return { resolution, range: blockRange(block), scrollTarget: block.el };
202
+ }
203
+ case "section":
204
+ return {
205
+ resolution,
206
+ range: null,
207
+ scrollTarget: resolution.block === -1 ? doc.article : doc.blocks[resolution.block].el,
208
+ };
209
+ case "detached":
210
+ return { resolution, range: null, scrollTarget: null };
211
+ }
212
+ }
@@ -0,0 +1,36 @@
1
+ /** Pure helpers for the reply field and the per-thread unsent text. */
2
+
3
+ export const FIELD_MIN_HEIGHT = 24;
4
+ export const FIELD_MAX_HEIGHT = 120;
5
+
6
+ /** Height of the one-line field for its content: grows to a cap, then scrolls. */
7
+ export function fieldHeight(scrollHeight: number): number {
8
+ return Math.min(FIELD_MAX_HEIGHT, Math.max(FIELD_MIN_HEIGHT, Math.ceil(scrollHeight)));
9
+ }
10
+
11
+ /** Unsent reply text by thread id. Empty text is not stored. */
12
+ export type ReplyDrafts = Readonly<Record<string, string>>;
13
+
14
+ /**
15
+ * The unsent text for a thread. Thread ids come from the file, so one can be
16
+ * "constructor" or "toString": only an own property counts as a draft.
17
+ */
18
+ export function replyDraftOf(drafts: ReplyDrafts, threadId: string): string {
19
+ return Object.hasOwn(drafts, threadId) ? drafts[threadId] : "";
20
+ }
21
+
22
+ export function withReplyDraft(drafts: ReplyDrafts, threadId: string, text: string): ReplyDrafts {
23
+ const stored = Object.hasOwn(drafts, threadId);
24
+ if (text === "") {
25
+ if (!stored) return drafts;
26
+ const { [threadId]: _removed, ...rest } = drafts;
27
+ return rest;
28
+ }
29
+ if (stored && drafts[threadId] === text) return drafts;
30
+ return { ...drafts, [threadId]: text };
31
+ }
32
+
33
+ /** Whether the send button is live: text with something other than whitespace, and no write in flight. */
34
+ export function canSend(text: string, disabled: boolean, pending: boolean): boolean {
35
+ return !disabled && !pending && text.trim() !== "";
36
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Highlights use the CSS Custom Highlight API, so React's DOM is never touched
3
+ * and a doc re-render cannot clash with the marks. Browsers without it show the
4
+ * panel and no marks. Styles live in client/app.css (`::highlight()`).
5
+ */
6
+ export const HIGHLIGHT_NAME = "mdxserve-comment";
7
+ export const ACTIVE_HIGHLIGHT_NAME = "mdxserve-comment-active";
8
+
9
+ export function supportsHighlights(): boolean {
10
+ return typeof CSS !== "undefined" && "highlights" in CSS && typeof Highlight !== "undefined";
11
+ }
12
+
13
+ export interface HighlightEntry {
14
+ threadId: string;
15
+ range: Range;
16
+ }
17
+
18
+ /** Entries currently drawn, for click hit-testing. */
19
+ let drawn: HighlightEntry[] = [];
20
+
21
+ export function setHighlights(entries: readonly HighlightEntry[], activeId: string | null): void {
22
+ drawn = [...entries];
23
+ if (!supportsHighlights()) return;
24
+ if (entries.length === 0) CSS.highlights.delete(HIGHLIGHT_NAME);
25
+ else CSS.highlights.set(HIGHLIGHT_NAME, new Highlight(...entries.map((entry) => entry.range)));
26
+
27
+ const active = entries.find((entry) => entry.threadId === activeId);
28
+ if (!active) {
29
+ CSS.highlights.delete(ACTIVE_HIGHLIGHT_NAME);
30
+ return;
31
+ }
32
+ const highlight = new Highlight(active.range);
33
+ highlight.priority = 1;
34
+ CSS.highlights.set(ACTIVE_HIGHLIGHT_NAME, highlight);
35
+ }
36
+
37
+ export function clearHighlights(): void {
38
+ drawn = [];
39
+ if (!supportsHighlights()) return;
40
+ CSS.highlights.delete(HIGHLIGHT_NAME);
41
+ CSS.highlights.delete(ACTIVE_HIGHLIGHT_NAME);
42
+ }
43
+
44
+ function caretAt(clientX: number, clientY: number): { node: Node; offset: number } | null {
45
+ if (typeof document.caretPositionFromPoint === "function") {
46
+ const position = document.caretPositionFromPoint(clientX, clientY);
47
+ return position ? { node: position.offsetNode, offset: position.offset } : null;
48
+ }
49
+ // Safari and older Chromium.
50
+ const legacy = (
51
+ document as Document & { caretRangeFromPoint?: (x: number, y: number) => Range | null }
52
+ ).caretRangeFromPoint?.(clientX, clientY);
53
+ return legacy ? { node: legacy.startContainer, offset: legacy.startOffset } : null;
54
+ }
55
+
56
+ /** The thread whose highlight is under the point; the shortest range wins when they overlap. */
57
+ export function threadAtPoint(clientX: number, clientY: number): string | null {
58
+ if (drawn.length === 0) return null;
59
+ const caret = caretAt(clientX, clientY);
60
+ if (!caret) return null;
61
+ let best: { threadId: string; length: number } | null = null;
62
+ for (const entry of drawn) {
63
+ let inside = false;
64
+ try {
65
+ inside = entry.range.isPointInRange(caret.node, caret.offset);
66
+ } catch {
67
+ inside = false;
68
+ }
69
+ if (!inside) continue;
70
+ // The caret snaps to the nearest character, so also require the point to be on the text.
71
+ const onText = Array.from(entry.range.getClientRects()).some(
72
+ (rect) =>
73
+ clientX >= rect.left &&
74
+ clientX <= rect.right &&
75
+ clientY >= rect.top &&
76
+ clientY <= rect.bottom,
77
+ );
78
+ if (!onText) continue;
79
+ const length = entry.range.toString().length;
80
+ if (!best || length < best.length) best = { threadId: entry.threadId, length };
81
+ }
82
+ return best?.threadId ?? null;
83
+ }
@@ -0,0 +1,241 @@
1
+ import { useAtom, useAtomValue, useSetAtom } from "jotai";
2
+ import { useCallback, useEffect, useMemo, useState } from "react";
3
+ import type { CommentThread } from "../../src/comments/schema";
4
+ import { useMediaQuery } from "../hooks";
5
+ import { DESKTOP_MEDIA } from "../platform";
6
+ import { shellInfo } from "../router";
7
+ import { openSectionAtom } from "../state";
8
+ import { resolutionPosition, type Resolution } from "./anchor";
9
+ import { commentActions, useDocThreads, type CommentActions } from "./data";
10
+ import { collectDoc, findArticle, resolveIndexOf, resolveInDom } from "./dom";
11
+ import { clearHighlights, setHighlights, threadAtPoint, type HighlightEntry } from "./highlights";
12
+ import {
13
+ activeThreadAtom,
14
+ commentsOpenAtom,
15
+ commentsSheetOpenAtom,
16
+ draftAtom,
17
+ popoverThreadAtom,
18
+ replyDraftsAtom,
19
+ } from "./state";
20
+
21
+ export interface ThreadView {
22
+ resolution: Resolution;
23
+ /** Document position for ordering; see `resolutionPosition`. */
24
+ position: number;
25
+ range: Range | null;
26
+ scrollTarget: Element | null;
27
+ }
28
+
29
+ export interface CommentsModel {
30
+ path: string;
31
+ threads: CommentThread[];
32
+ /** Resolution of every unresolved thread. Resolved threads are not resolved against the page. */
33
+ views: ReadonlyMap<string, ThreadView>;
34
+ openCount: number;
35
+ /** Restricted server: the panel reads, nothing writes. */
36
+ readOnly: boolean;
37
+ /** A section editor is open in this tab: every writing control is disabled (S10). */
38
+ writesDisabled: boolean;
39
+ /** The panel and its TopBar button exist for this doc. */
40
+ available: boolean;
41
+ actions: CommentActions;
42
+ /** Makes a thread active in the list and scrolls the doc to it. */
43
+ selectThread: (id: string) => void;
44
+ /** The thread shown in the popover: desktop with the sidebar closed only, else null. */
45
+ popoverId: string | null;
46
+ showPopover: (id: string) => void;
47
+ closePopover: () => void;
48
+ /** Docks the sidebar with this thread active and closes the popover. */
49
+ openInSidebar: (id: string) => void;
50
+ }
51
+
52
+ /** Panel visibility, switching between the persisted desktop sidebar and the transient phone sheet. */
53
+ export function useCommentsPanel() {
54
+ const isDesktop = useMediaQuery(DESKTOP_MEDIA, true);
55
+ const [railOpen, setRailOpen] = useAtom(commentsOpenAtom);
56
+ const [sheetOpen, setSheetOpen] = useAtom(commentsSheetOpenAtom);
57
+ const open = isDesktop ? railOpen : sheetOpen;
58
+ const setOpen = useCallback(
59
+ (next: boolean) => (isDesktop ? setRailOpen(next) : setSheetOpen(next)),
60
+ [isDesktop, setRailOpen, setSheetOpen],
61
+ );
62
+ return { isDesktop, open, setOpen, sidebarOpen: isDesktop && railOpen };
63
+ }
64
+
65
+ function scrollToView(view: ThreadView | undefined, isDesktop: boolean): void {
66
+ if (!view) return;
67
+ const rangeRect = view.range?.getBoundingClientRect();
68
+ const rect =
69
+ rangeRect && (rangeRect.width > 0 || rangeRect.height > 0)
70
+ ? rangeRect
71
+ : view.scrollTarget?.getBoundingClientRect();
72
+ if (!rect) return;
73
+ const topbar = document.querySelector("header")?.getBoundingClientRect().height ?? 48;
74
+ // The phone sheet covers the bottom 70% of the screen; centre in what is left.
75
+ const bottom = isDesktop ? window.innerHeight : window.innerHeight * 0.3;
76
+ const room = bottom - topbar;
77
+ const offset = Math.max(topbar + 16, topbar + (room - rect.height) / 2);
78
+ window.scrollTo({ top: Math.max(0, rect.top + window.scrollY - offset), behavior: "smooth" });
79
+ }
80
+
81
+ /**
82
+ * The comments state for the open doc: its threads, where each one lands on the
83
+ * page, the highlights, and click-to-focus. Mount once, in AppShell.
84
+ * `renderVersion` changes whenever DocView reports a render.
85
+ */
86
+ export function useCommentsModel(path: string | null, renderVersion: number): CommentsModel {
87
+ const { threads } = useDocThreads(path);
88
+ const editing = useAtomValue(openSectionAtom) !== null;
89
+ const [views, setViews] = useState<ReadonlyMap<string, ThreadView>>(new Map());
90
+ const [activeId, setActiveId] = useAtom(activeThreadAtom);
91
+ const setDraft = useSetAtom(draftAtom);
92
+ const setSheetOpen = useSetAtom(commentsSheetOpenAtom);
93
+ const setRailOpen = useSetAtom(commentsOpenAtom);
94
+ const [popoverThread, setPopoverThread] = useAtom(popoverThreadAtom);
95
+ const setReplyDrafts = useSetAtom(replyDraftsAtom);
96
+ const { isDesktop, sidebarOpen } = useCommentsPanel();
97
+ const readOnly = shellInfo.permissions === "restricted";
98
+
99
+ // Another doc starts clean.
100
+ useEffect(() => {
101
+ setActiveId(null);
102
+ setDraft(null);
103
+ setSheetOpen(false);
104
+ setPopoverThread(null);
105
+ setReplyDrafts({});
106
+ }, [path, setActiveId, setDraft, setSheetOpen, setPopoverThread, setReplyDrafts]);
107
+
108
+ // Bumped when a tab panel is shown or hidden, so anchors re-resolve.
109
+ const [visibility, setVisibility] = useState(0);
110
+ useEffect(() => {
111
+ const article = findArticle();
112
+ if (!article) return;
113
+ const observer = new MutationObserver(() => setVisibility((count) => count + 1));
114
+ observer.observe(article, {
115
+ attributes: true,
116
+ attributeFilter: ["inert", "aria-hidden"],
117
+ subtree: true,
118
+ });
119
+ return () => observer.disconnect();
120
+ }, [path, renderVersion]);
121
+
122
+ // Resolve after the thread list changes, after DocView renders, and when a
123
+ // section editor closes. While one is open its DOM is the editor's, so keep
124
+ // the last answer rather than flash everything to "detached".
125
+ useEffect(() => {
126
+ if (path === null || editing) return;
127
+ const article = findArticle();
128
+ if (!article) {
129
+ setViews(new Map());
130
+ return;
131
+ }
132
+ const doc = collectDoc(article);
133
+ const index = resolveIndexOf(doc);
134
+ const next = new Map<string, ThreadView>();
135
+ for (const thread of threads) {
136
+ if (thread.resolved) continue;
137
+ const { resolution, range, scrollTarget } = resolveInDom(doc, index, thread.anchor);
138
+ next.set(thread.id, {
139
+ resolution,
140
+ position: resolutionPosition(resolution),
141
+ range,
142
+ scrollTarget,
143
+ });
144
+ }
145
+ setViews(next);
146
+ }, [path, threads, renderVersion, editing, visibility]);
147
+
148
+ useEffect(() => {
149
+ const entries: HighlightEntry[] = [];
150
+ for (const [threadId, view] of views) {
151
+ if (view.range) entries.push({ threadId, range: view.range });
152
+ }
153
+ setHighlights(entries, activeId);
154
+ }, [views, activeId]);
155
+ useEffect(() => clearHighlights, []);
156
+
157
+ // A click on highlighted text focuses that thread: in the sidebar when it is open,
158
+ // else in the popover (desktop) or the sheet (phone).
159
+ useEffect(() => {
160
+ if (path === null) return;
161
+ function onClick(event: MouseEvent) {
162
+ if (event.button !== 0 || event.defaultPrevented) return;
163
+ const target = event.target instanceof Element ? event.target : null;
164
+ if (!target?.closest("article.mdx-prose")) return;
165
+ if (target.closest("a, button, input, textarea, [data-editing]")) return;
166
+ if (window.getSelection()?.isCollapsed === false) return;
167
+ const id = threadAtPoint(event.clientX, event.clientY);
168
+ if (!id) return;
169
+ setActiveId(id);
170
+ if (!isDesktop) {
171
+ setSheetOpen(true);
172
+ // The sheet covers the tapped text; once its scroll space is in place,
173
+ // bring the anchor into the part of the page it leaves uncovered.
174
+ requestAnimationFrame(() => scrollToView(views.get(id), isDesktop));
175
+ } else if (!sidebarOpen) setPopoverThread(id);
176
+ }
177
+ document.addEventListener("click", onClick);
178
+ return () => document.removeEventListener("click", onClick);
179
+ }, [path, isDesktop, sidebarOpen, views, setActiveId, setSheetOpen, setPopoverThread]);
180
+
181
+ const actions = useMemo(() => commentActions(path ?? ""), [path]);
182
+ const selectThread = useCallback(
183
+ (id: string) => {
184
+ setActiveId(id);
185
+ let view = views.get(id);
186
+ if (!view) {
187
+ // Resolved threads are not kept in `views`; find this one on demand.
188
+ const thread = threads.find((candidate) => candidate.id === id);
189
+ const article = findArticle();
190
+ if (thread && article) {
191
+ const doc = collectDoc(article);
192
+ const { resolution, range, scrollTarget } = resolveInDom(
193
+ doc,
194
+ resolveIndexOf(doc),
195
+ thread.anchor,
196
+ );
197
+ view = { resolution, position: resolutionPosition(resolution), range, scrollTarget };
198
+ }
199
+ }
200
+ scrollToView(view, isDesktop);
201
+ },
202
+ [setActiveId, views, threads, isDesktop],
203
+ );
204
+
205
+ const showPopover = useCallback(
206
+ (id: string) => {
207
+ setActiveId(id);
208
+ setPopoverThread(id);
209
+ },
210
+ [setActiveId, setPopoverThread],
211
+ );
212
+ const closePopover = useCallback(() => {
213
+ setPopoverThread(null);
214
+ setActiveId(null);
215
+ }, [setPopoverThread, setActiveId]);
216
+ const openInSidebar = useCallback(
217
+ (id: string) => {
218
+ setPopoverThread(null);
219
+ setRailOpen(true);
220
+ setActiveId(id);
221
+ },
222
+ [setPopoverThread, setRailOpen, setActiveId],
223
+ );
224
+
225
+ const openCount = threads.filter((thread) => !thread.resolved).length;
226
+ return {
227
+ path: path ?? "",
228
+ threads,
229
+ views,
230
+ openCount,
231
+ readOnly,
232
+ writesDisabled: readOnly || editing,
233
+ available: path !== null && (!readOnly || threads.length > 0),
234
+ actions,
235
+ selectThread,
236
+ popoverId: isDesktop && !sidebarOpen ? popoverThread : null,
237
+ showPopover,
238
+ closePopover,
239
+ openInSidebar,
240
+ };
241
+ }