@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,142 @@
1
+ import { autoUpdate, computePosition, flip, offset, shift } from "@floating-ui/dom";
2
+ import { useAtom, useSetAtom } from "jotai";
3
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
4
+ import { Icon } from "../ui/Icon";
5
+ import type { AnchorFields } from "./anchor";
6
+ import { captureSelection } from "./dom";
7
+ import { useCommentsPanel, type CommentsModel } from "./model";
8
+ import { draftAtom, popoverThreadAtom } from "./state";
9
+
10
+ const SETTLE_MS = 60;
11
+
12
+ interface Pending {
13
+ anchor: AnchorFields;
14
+ range: Range;
15
+ }
16
+
17
+ /** The "Comment" button floating next to a selection. */
18
+ // Never reused, so a finished submission can tell its own draft from a later one
19
+ // even after the draft was discarded in between.
20
+ let draftNonce = 0;
21
+ function nextDraftNonce(): number {
22
+ draftNonce += 1;
23
+ return draftNonce;
24
+ }
25
+
26
+ export function SelectionButton({ model }: { model: CommentsModel }) {
27
+ const [pending, setPending] = useState<Pending | null>(null);
28
+ const [draft, setDraft] = useAtom(draftAtom);
29
+ const setPopover = useSetAtom(popoverThreadAtom);
30
+ const { isDesktop, setOpen } = useCommentsPanel();
31
+ const buttonRef = useRef<HTMLButtonElement>(null);
32
+ const pointerType = useRef("mouse");
33
+ const pointerDown = useRef(false);
34
+ const enabled = !model.writesDisabled && model.path !== "";
35
+
36
+ const refresh = useCallback(() => {
37
+ const selection = window.getSelection();
38
+ const anchor = enabled && !pointerDown.current ? captureSelection(selection) : null;
39
+ if (!anchor || !selection) {
40
+ setPending(null);
41
+ return;
42
+ }
43
+ setPending({ anchor, range: selection.getRangeAt(0).cloneRange() });
44
+ }, [enabled]);
45
+
46
+ useEffect(() => {
47
+ if (!enabled) {
48
+ setPending(null);
49
+ return;
50
+ }
51
+ let timer: ReturnType<typeof setTimeout> | undefined;
52
+ function onSelectionChange() {
53
+ clearTimeout(timer);
54
+ timer = setTimeout(refresh, SETTLE_MS);
55
+ }
56
+ function onPointerDown(event: PointerEvent) {
57
+ pointerType.current = event.pointerType;
58
+ if (event.pointerType === "mouse") pointerDown.current = true;
59
+ }
60
+ function onPointerUp(event: PointerEvent) {
61
+ pointerType.current = event.pointerType;
62
+ pointerDown.current = false;
63
+ // Let the browser finish the selection this release completes.
64
+ requestAnimationFrame(refresh);
65
+ }
66
+ document.addEventListener("selectionchange", onSelectionChange);
67
+ document.addEventListener("pointerdown", onPointerDown, true);
68
+ document.addEventListener("pointerup", onPointerUp, true);
69
+ refresh();
70
+ return () => {
71
+ clearTimeout(timer);
72
+ document.removeEventListener("selectionchange", onSelectionChange);
73
+ document.removeEventListener("pointerdown", onPointerDown, true);
74
+ document.removeEventListener("pointerup", onPointerUp, true);
75
+ };
76
+ }, [enabled, refresh]);
77
+
78
+ // Above the selection with a pointer, below it on touch, where the system menu sits above.
79
+ useLayoutEffect(() => {
80
+ const floating = buttonRef.current;
81
+ if (!pending || !floating) return;
82
+ const reference = {
83
+ getBoundingClientRect: () => pending.range.getBoundingClientRect(),
84
+ getClientRects: () => pending.range.getClientRects(),
85
+ };
86
+ const touch = pointerType.current === "touch" || window.matchMedia("(pointer: coarse)").matches;
87
+ return autoUpdate(reference, floating, () => {
88
+ void computePosition(reference, floating, {
89
+ strategy: "fixed",
90
+ placement: touch ? "bottom" : "top",
91
+ middleware: [offset(8), flip(), shift({ padding: 8 })],
92
+ }).then(({ x, y }) => {
93
+ floating.style.left = `${x}px`;
94
+ floating.style.top = `${y}px`;
95
+ floating.style.visibility = "visible";
96
+ });
97
+ });
98
+ }, [pending]);
99
+
100
+ // Escape discards the draft.
101
+ useEffect(() => {
102
+ if (!draft) return;
103
+ function onKeyDown(event: KeyboardEvent) {
104
+ if (event.key === "Escape") setDraft(null);
105
+ }
106
+ window.addEventListener("keydown", onKeyDown);
107
+ return () => window.removeEventListener("keydown", onKeyDown);
108
+ }, [draft, setDraft]);
109
+
110
+ if (!pending) return null;
111
+ const { anchor, range } = pending;
112
+
113
+ return (
114
+ <button
115
+ ref={buttonRef}
116
+ type="button"
117
+ data-print-hide
118
+ data-comments-keep
119
+ // Keep the selection alive through the press.
120
+ onPointerDown={(event) => event.preventDefault()}
121
+ onMouseDown={(event) => event.preventDefault()}
122
+ onClick={() => {
123
+ setDraft((previous) => ({
124
+ anchor,
125
+ range,
126
+ body: previous?.body ?? "",
127
+ nonce: nextDraftNonce(),
128
+ }));
129
+ // Desktop: the composer opens in a popover, whether or not the sidebar is
130
+ // open. Phone: it opens in the sheet.
131
+ setPopover(null);
132
+ if (!isDesktop) setOpen(true);
133
+ setPending(null);
134
+ }}
135
+ style={{ position: "fixed", left: 0, top: 0, visibility: "hidden" }}
136
+ className="z-[var(--z-dropdown)] inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-md border border-border-default bg-surface-raised px-2.5 font-sans text-[length:var(--size-sm)] font-semibold text-text-heading shadow-md hover:bg-surface-hover"
137
+ >
138
+ <Icon name="message-square" size="sm" />
139
+ Comment
140
+ </button>
141
+ );
142
+ }
@@ -0,0 +1,308 @@
1
+ import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
2
+ import { useAtom, useStore } from "jotai";
3
+ import { useEffect, useRef, useState, type ReactNode } from "react";
4
+ import type { CommentMessage, CommentThread } from "../../src/comments/schema";
5
+ import { Icon } from "../ui/Icon";
6
+ import { CtlButton } from "./CtlButton";
7
+ import { replyDraftOf, withReplyDraft } from "./drafts";
8
+ import type { CommentsModel, ThreadView } from "./model";
9
+ import { rowMotion } from "./motion";
10
+ import { ReplyField } from "./ReplyField";
11
+ import {
12
+ freshThreadAtom,
13
+ pendingReplyKey,
14
+ pendingSendsAtom,
15
+ replyDraftsAtom,
16
+ withPendingSend,
17
+ } from "./state";
18
+ import { relativeTime } from "./time";
19
+
20
+ /** Where a thread is drawn: a sidebar row, the sheet's row, or the popover's body. */
21
+ export type ThreadVariant = "sidebar" | "sheet" | "popover";
22
+
23
+ const ACTIVE_QUOTE = "bg-[color-mix(in_oklab,var(--status-warn-fg)_32%,var(--status-warn-bg))]";
24
+
25
+ export function Avatar({ author }: { author: CommentMessage["author"] }) {
26
+ const agent = author === "agent";
27
+ return (
28
+ <span
29
+ aria-hidden
30
+ className={
31
+ "grid h-6 w-6 place-items-center rounded-full " +
32
+ (agent ? "bg-surface-accent-soft text-text-accent" : "bg-surface-hover text-text-muted")
33
+ }
34
+ >
35
+ <Icon name={agent ? "sparkles" : "user"} size={13} />
36
+ </span>
37
+ );
38
+ }
39
+
40
+ /** The quoted text, in the doc highlight's amber, on one line. */
41
+ export function QuoteText({ text, active }: { text: string; active: boolean }) {
42
+ return (
43
+ <span className="block truncate text-[12.5px] leading-[1.6] text-text-body">
44
+ <mark className={"text-inherit " + (active ? ACTIVE_QUOTE : "bg-status-warn-bg")}>
45
+ {text}
46
+ </mark>
47
+ </span>
48
+ );
49
+ }
50
+
51
+ function Message({
52
+ message,
53
+ first,
54
+ last,
55
+ reserveTools,
56
+ canEdit,
57
+ editDisabled,
58
+ onEdit,
59
+ }: {
60
+ message: CommentMessage;
61
+ first: boolean;
62
+ last: boolean;
63
+ /** Leaves room for the popover's tool buttons beside the first header. */
64
+ reserveTools: boolean;
65
+ canEdit: boolean;
66
+ editDisabled: boolean;
67
+ onEdit: (body: string) => Promise<boolean>;
68
+ }) {
69
+ const [editing, setEditing] = useState(false);
70
+ const [draft, setDraft] = useState(message.body);
71
+ const [pending, setPending] = useState(false);
72
+ const agent = message.author === "agent";
73
+ const reducedMotion = useReducedMotion();
74
+
75
+ async function save() {
76
+ setPending(true);
77
+ const saved = await onEdit(draft);
78
+ setPending(false);
79
+ if (saved) setEditing(false);
80
+ }
81
+
82
+ // The gap above a message is drawn inside it (the timeline's connector, then
83
+ // 2px of air) instead of as a margin, so a new message's whole footprint
84
+ // grows from nothing and the reply field below is pushed down smoothly.
85
+ return (
86
+ <motion.div {...rowMotion(reducedMotion)} className="group overflow-hidden">
87
+ {first ? null : (
88
+ <span aria-hidden className="mb-0.5 ml-[11.5px] block h-3 w-px bg-border-default" />
89
+ )}
90
+ <div className="relative grid grid-cols-[24px_1fr] gap-x-2.5">
91
+ {last ? null : (
92
+ <span
93
+ aria-hidden
94
+ className="absolute top-7 bottom-0 left-[11.5px] w-px bg-border-default"
95
+ />
96
+ )}
97
+ <Avatar author={message.author} />
98
+ <div className="min-w-0">
99
+ <div
100
+ className={
101
+ "flex items-baseline gap-[7px] pt-[3px] text-[12.5px] leading-[1.3] " +
102
+ (reserveTools ? "pr-[84px]" : "")
103
+ }
104
+ >
105
+ <span className={"font-bold " + (agent ? "text-text-accent" : "text-text-heading")}>
106
+ {agent ? "Agent" : "You"}
107
+ </span>
108
+ <time
109
+ className="text-[11.5px] text-text-subtle tabular-nums"
110
+ dateTime={message.createdAt}
111
+ title={message.createdAt ? new Date(message.createdAt).toLocaleString() : undefined}
112
+ >
113
+ {relativeTime(message.createdAt)}
114
+ {message.editedAt ? " · edited" : ""}
115
+ </time>
116
+ {canEdit && !editing ? (
117
+ <button
118
+ type="button"
119
+ disabled={editDisabled}
120
+ aria-label="Edit comment"
121
+ onClick={() => {
122
+ setDraft(message.body);
123
+ setEditing(true);
124
+ }}
125
+ className="ml-auto inline-flex cursor-pointer items-center gap-1 rounded-sm border-0 bg-transparent p-0 text-[11.5px] font-semibold text-text-subtle opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 hover:text-text-heading focus-visible:opacity-100 disabled:cursor-not-allowed disabled:opacity-0 group-hover:disabled:opacity-45 [@media(hover:none)]:opacity-100"
126
+ >
127
+ <Icon name="pencil" size={11} />
128
+ Edit
129
+ </button>
130
+ ) : null}
131
+ </div>
132
+ {editing ? (
133
+ <div className="mt-1.5" data-comment-edit>
134
+ <ReplyField
135
+ label="Edit comment"
136
+ sendLabel="Save comment"
137
+ placeholder=""
138
+ value={draft}
139
+ onChange={setDraft}
140
+ onSubmit={() => void save()}
141
+ onCancel={() => setEditing(false)}
142
+ disabled={editDisabled}
143
+ pending={pending}
144
+ focusNonce={0}
145
+ />
146
+ </div>
147
+ ) : (
148
+ <p className="m-0 mt-[3px] text-[13.5px] leading-[1.55] break-words whitespace-pre-wrap text-text-body">
149
+ {message.body}
150
+ </p>
151
+ )}
152
+ </div>
153
+ </div>
154
+ </motion.div>
155
+ );
156
+ }
157
+
158
+ /**
159
+ * One thread as a conversation timeline: the quote and a resolve (or reopen)
160
+ * checkmark, the messages, and on the active thread a reply field.
161
+ */
162
+ export function Thread({
163
+ thread,
164
+ view,
165
+ active,
166
+ variant,
167
+ model,
168
+ }: {
169
+ thread: CommentThread;
170
+ view: ThreadView | undefined;
171
+ active: boolean;
172
+ variant: ThreadVariant;
173
+ model: CommentsModel;
174
+ }) {
175
+ const ref = useRef<HTMLDivElement>(null);
176
+ const [drafts, setDrafts] = useAtom(replyDraftsAtom);
177
+ const [pendingSends, setPendingSends] = useAtom(pendingSendsAtom);
178
+ const replyKey = pendingReplyKey(model.path, thread.id);
179
+ const replying = pendingSends.has(replyKey);
180
+ const setReplying = (active: boolean) =>
181
+ setPendingSends((previous) => withPendingSend(previous, replyKey, active));
182
+ const [resolving, setResolving] = useState(false);
183
+ const { readOnly, writesDisabled, actions } = model;
184
+ const popover = variant === "popover";
185
+ const reply = replyDraftOf(drafts, thread.id);
186
+
187
+ // A thread this tab just created shows its message arriving in the popover.
188
+ // In the panel the whole row expands in instead (CommentsPanel).
189
+ const store = useStore();
190
+ const [animateFirst] = useState(() => popover && store.get(freshThreadAtom) === thread.id);
191
+ useEffect(() => {
192
+ if (store.get(freshThreadAtom) === thread.id) store.set(freshThreadAtom, null);
193
+ }, [store, thread.id]);
194
+
195
+ useEffect(() => {
196
+ if (active && !popover) ref.current?.scrollIntoView({ block: "nearest" });
197
+ }, [active, popover]);
198
+
199
+ async function sendReply() {
200
+ setReplying(true);
201
+ const submitted = reply;
202
+ const saved = await actions.reply(thread.id, submitted);
203
+ setReplying(false);
204
+ // Text typed while the request ran stays.
205
+ if (saved)
206
+ setDrafts((previous) =>
207
+ replyDraftOf(previous, thread.id) === submitted
208
+ ? withReplyDraft(previous, thread.id, "")
209
+ : previous,
210
+ );
211
+ }
212
+
213
+ async function toggleResolved() {
214
+ setResolving(true);
215
+ await actions.setResolved(thread.id, !thread.resolved);
216
+ setResolving(false);
217
+ }
218
+
219
+ const state = view?.resolution.state;
220
+ const showReply = active && !readOnly && !thread.resolved;
221
+ const note =
222
+ state === "section"
223
+ ? "Original text not found. Showing on the section."
224
+ : state === "detached"
225
+ ? "Original section not found."
226
+ : null;
227
+
228
+ let toolbar: ReactNode = null;
229
+ if (!popover && !readOnly) {
230
+ toolbar = (
231
+ <CtlButton
232
+ tone="resolve"
233
+ icon={thread.resolved ? "rotate-ccw" : "check"}
234
+ label={thread.resolved ? "Reopen thread" : "Resolve thread"}
235
+ disabled={writesDisabled || resolving}
236
+ onClick={() => void toggleResolved()}
237
+ />
238
+ );
239
+ }
240
+
241
+ return (
242
+ <div
243
+ ref={ref}
244
+ data-thread-id={thread.id}
245
+ data-active={active || undefined}
246
+ onClick={
247
+ popover
248
+ ? undefined
249
+ : (event) => {
250
+ if (!(event.target as Element).closest("textarea, button, a")) {
251
+ model.selectThread(thread.id);
252
+ }
253
+ }
254
+ }
255
+ className={
256
+ "flex flex-col gap-3 " +
257
+ (popover ? "" : "pt-4 pr-3.5 pb-[18px] pl-4 ") +
258
+ (variant === "sidebar" && active ? "bg-surface-card" : "")
259
+ }
260
+ >
261
+ {popover ? null : (
262
+ <div className="flex items-center gap-2">
263
+ <button
264
+ type="button"
265
+ title="Show in the doc"
266
+ onClick={() => model.selectThread(thread.id)}
267
+ className="m-0 min-w-0 flex-1 cursor-pointer border-0 bg-transparent p-0 text-left"
268
+ >
269
+ <QuoteText text={thread.anchor.quote} active={active} />
270
+ </button>
271
+ {toolbar}
272
+ </div>
273
+ )}
274
+ {note ? <p className="m-0 text-xs text-status-warn-fg">{note}</p> : null}
275
+ <div>
276
+ <AnimatePresence initial={animateFirst}>
277
+ {thread.messages.map((message, index) => (
278
+ <Message
279
+ key={message.id}
280
+ message={message}
281
+ first={index === 0}
282
+ last={index === thread.messages.length - 1}
283
+ reserveTools={popover && index === 0}
284
+ canEdit={!readOnly && message.author === "human"}
285
+ editDisabled={writesDisabled}
286
+ onEdit={async (body) => (await actions.edit(thread.id, message.id, body)) !== null}
287
+ />
288
+ ))}
289
+ </AnimatePresence>
290
+ </div>
291
+ {showReply ? (
292
+ <div className="grid grid-cols-[24px_1fr] items-end gap-x-2.5">
293
+ <Avatar author="human" />
294
+ <ReplyField
295
+ label="Reply"
296
+ sendLabel="Send reply"
297
+ placeholder={writesDisabled ? "Close the section editor to reply" : "Reply…"}
298
+ value={reply}
299
+ onChange={(next) => setDrafts((previous) => withReplyDraft(previous, thread.id, next))}
300
+ onSubmit={() => void sendReply()}
301
+ disabled={writesDisabled}
302
+ pending={replying}
303
+ />
304
+ </div>
305
+ ) : null}
306
+ </div>
307
+ );
308
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Pure anchor logic: no DOM types, so it runs under plain Node in tests.
3
+ *
4
+ * `client/` may only `import type` from `src/`, so the limits and
5
+ * `normalizeText` below repeat `src/comments/schema.ts` and
6
+ * `src/comments/anchor.ts`; tests/client/comments-limits.test.ts asserts the
7
+ * two copies agree.
8
+ */
9
+
10
+ export const MAX_ANCHOR_TEXT = 500;
11
+ export const MAX_ANCHOR_HEADING = 300;
12
+ export const MAX_MESSAGE_BODY = 4000;
13
+
14
+ /** Collapse runs of whitespace to one space, then trim. Must match `src/comments/anchor.ts`. */
15
+ export function normalizeText(text: string): string {
16
+ return text.replace(/\s+/g, " ").trim();
17
+ }
18
+
19
+ /**
20
+ * The comparable form of a heading's text: normalized and cut to the schema's
21
+ * heading limit, so a very long heading still matches its stored anchor.
22
+ */
23
+ export function headingKey(text: string): string {
24
+ return normalizeText(text).slice(0, MAX_ANCHOR_HEADING).trimEnd();
25
+ }
26
+
27
+ export interface AnchorFields {
28
+ heading: string | null;
29
+ block: string;
30
+ quote: string;
31
+ }
32
+
33
+ // ── offset mapping ──────────────────────────────────────────────────────────
34
+
35
+ export interface NormalizedText {
36
+ /** `normalizeText(nodes.join(""))`. */
37
+ text: string;
38
+ /** For each normalized character, its index in the joined raw text. */
39
+ rawIndex: number[];
40
+ }
41
+
42
+ /** Normalizes the concatenated text nodes and remembers where each character came from. */
43
+ export function normalizeWithMap(nodes: readonly string[]): NormalizedText {
44
+ const raw = nodes.join("");
45
+ let text = "";
46
+ const rawIndex: number[] = [];
47
+ let pendingSpace = -1;
48
+ for (let index = 0; index < raw.length; index++) {
49
+ const char = raw[index];
50
+ if (/\s/.test(char)) {
51
+ if (text.length > 0 && pendingSpace === -1) pendingSpace = index;
52
+ continue;
53
+ }
54
+ if (pendingSpace !== -1) {
55
+ text += " ";
56
+ rawIndex.push(pendingSpace);
57
+ pendingSpace = -1;
58
+ }
59
+ text += char;
60
+ rawIndex.push(index);
61
+ }
62
+ return { text, rawIndex };
63
+ }
64
+
65
+ export interface NodePoint {
66
+ node: number;
67
+ offset: number;
68
+ }
69
+
70
+ export interface NodeRange {
71
+ start: NodePoint;
72
+ end: NodePoint;
73
+ }
74
+
75
+ function pointAt(nodes: readonly string[], rawIndex: number): NodePoint {
76
+ let remaining = rawIndex;
77
+ for (let node = 0; node < nodes.length; node++) {
78
+ if (remaining < nodes[node].length) return { node, offset: remaining };
79
+ remaining -= nodes[node].length;
80
+ }
81
+ return { node: Math.max(0, nodes.length - 1), offset: nodes[nodes.length - 1]?.length ?? 0 };
82
+ }
83
+
84
+ /**
85
+ * Maps the normalized-text span [start, end) back to text-node points. The start
86
+ * sits on the first character of the span and the end just after its last one, so
87
+ * a boundary between two nodes never gets ambiguous. Null for an empty or
88
+ * out-of-bounds span.
89
+ */
90
+ export function mapNormalizedRange(
91
+ nodes: readonly string[],
92
+ start: number,
93
+ end: number,
94
+ ): NodeRange | null {
95
+ const { text, rawIndex } = normalizeWithMap(nodes);
96
+ if (start < 0 || end > text.length || start >= end) return null;
97
+ const first = pointAt(nodes, rawIndex[start]);
98
+ const last = pointAt(nodes, rawIndex[end - 1]);
99
+ return { start: first, end: { node: last.node, offset: last.offset + 1 } };
100
+ }
101
+
102
+ // ── capture ─────────────────────────────────────────────────────────────────
103
+
104
+ export interface BlockDescription {
105
+ /** Heading text of the block's section (already `headingKey`ed), or null before the first heading. */
106
+ heading: string | null;
107
+ /** The text-node strings of the block, in document order. */
108
+ nodes: string[];
109
+ }
110
+
111
+ export interface SelectionDescription {
112
+ blockIndex: number;
113
+ start: NodePoint;
114
+ /** Null clips the selection to the end of the block. */
115
+ end: NodePoint | null;
116
+ }
117
+
118
+ function rawOffset(nodes: readonly string[], point: NodePoint): number {
119
+ let total = 0;
120
+ for (let node = 0; node < point.node && node < nodes.length; node++) total += nodes[node].length;
121
+ return total + point.offset;
122
+ }
123
+
124
+ /** The anchor for a selection, clipped to the block holding its start. Null when it has no text. */
125
+ export function captureAnchor(
126
+ blocks: readonly BlockDescription[],
127
+ selection: SelectionDescription,
128
+ ): AnchorFields | null {
129
+ const block = blocks[selection.blockIndex];
130
+ if (!block) return null;
131
+ const raw = block.nodes.join("");
132
+ const startRaw = rawOffset(block.nodes, selection.start);
133
+ const endRaw = selection.end ? rawOffset(block.nodes, selection.end) : raw.length;
134
+ if (endRaw <= startRaw) return null;
135
+
136
+ const quote = normalizeText(raw.slice(startRaw, endRaw)).slice(0, MAX_ANCHOR_TEXT).trimEnd();
137
+ if (!quote) return null;
138
+ const blockText = normalizeText(raw).slice(-MAX_ANCHOR_TEXT).trimStart();
139
+ return { heading: block.heading, block: blockText, quote };
140
+ }
141
+
142
+ // ── resolve ─────────────────────────────────────────────────────────────────
143
+
144
+ export interface ResolveBlock {
145
+ /** Normalized text of the block. */
146
+ text: string;
147
+ /** Index into `headings` of the block's section, or -1 before the first heading. */
148
+ section: number;
149
+ }
150
+
151
+ export interface ResolveHeading {
152
+ /** `headingKey` of the heading's text. */
153
+ key: string;
154
+ /** Index into `blocks` of the heading's own block. */
155
+ block: number;
156
+ }
157
+
158
+ export interface ResolveIndex {
159
+ headings: readonly ResolveHeading[];
160
+ blocks: readonly ResolveBlock[];
161
+ }
162
+
163
+ export type Resolution =
164
+ | { state: "exact"; block: number; start: number; end: number }
165
+ | { state: "block"; block: number }
166
+ /** `block` is the heading's block, or -1 for the top of the article. */
167
+ | { state: "section"; block: number }
168
+ | { state: "detached" };
169
+
170
+ export type AnchorState = Resolution["state"];
171
+
172
+ /** Where the thread sorts in the document: a block index, -1 for the top, Infinity when detached. */
173
+ export function resolutionPosition(resolution: Resolution): number {
174
+ return resolution.state === "detached" ? Infinity : resolution.block;
175
+ }
176
+
177
+ /** Finds the anchor in the document: exact, whole block, section heading, or detached. */
178
+ export function resolveAnchor(anchor: AnchorFields, index: ResolveIndex): Resolution {
179
+ const wantedBlock = normalizeText(anchor.block);
180
+ const wantedQuote = normalizeText(anchor.quote);
181
+ const sections: number[] = [];
182
+ if (anchor.heading === null) {
183
+ sections.push(-1);
184
+ } else {
185
+ const wantedHeading = headingKey(anchor.heading);
186
+ index.headings.forEach((heading, position) => {
187
+ if (heading.key === wantedHeading) sections.push(position);
188
+ });
189
+ if (sections.length === 0) return { state: "detached" };
190
+ }
191
+
192
+ for (const section of sections) {
193
+ for (let position = 0; position < index.blocks.length; position++) {
194
+ const block = index.blocks[position];
195
+ if (block.section !== section || !block.text.endsWith(wantedBlock)) continue;
196
+ const found = block.text.indexOf(wantedQuote);
197
+ if (found === -1) return { state: "block", block: position };
198
+ return { state: "exact", block: position, start: found, end: found + wantedQuote.length };
199
+ }
200
+ }
201
+
202
+ const headingBlock = sections[0] === -1 ? -1 : index.headings[sections[0]].block;
203
+ return { state: "section", block: headingBlock };
204
+ }