@cueloop/client 0.1.0-alpha.8 → 0.1.0-alpha.81

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 (307) hide show
  1. package/native/build-pty.sh +51 -0
  2. package/native/build.sh +82 -0
  3. package/native/darwin-arm64/libcuelooppty.dylib +0 -0
  4. package/native/darwin-arm64/libcueloopvt.dylib +0 -0
  5. package/native/src/pty.zig +193 -0
  6. package/native/src/shim.zig +114 -0
  7. package/package.json +40 -32
  8. package/src/App.appearance.test.tsx +53 -0
  9. package/src/App.autoclose.test.tsx +77 -51
  10. package/src/App.diff.test.tsx +176 -45
  11. package/src/App.export.test.tsx +58 -41
  12. package/src/App.focus.test.ts +89 -0
  13. package/src/App.identity.test.tsx +78 -0
  14. package/src/App.plan-render.test.tsx +209 -0
  15. package/src/App.plan-review.test.tsx +428 -0
  16. package/src/App.prototype-markdown.test.tsx +92 -0
  17. package/src/App.prototype.test.tsx +176 -0
  18. package/src/App.readonly.test.tsx +129 -67
  19. package/src/App.regression.test.tsx +94 -0
  20. package/src/App.rendering.test.tsx +61 -35
  21. package/src/App.share-dialog.test.tsx +172 -0
  22. package/src/App.submit-confirm.test.tsx +222 -0
  23. package/src/App.test.tsx +333 -131
  24. package/src/App.toast.test.tsx +98 -0
  25. package/src/App.tsx +1338 -608
  26. package/src/App.visual.test.tsx +57 -0
  27. package/src/App.walk.test.tsx +299 -0
  28. package/src/App.workbench.test.tsx +701 -0
  29. package/src/__snapshots__/view-plan.regression.test.ts.snap +100 -0
  30. package/src/annotation-palette.ts +62 -0
  31. package/src/ansi-screen.test.ts +28 -0
  32. package/src/ansi-screen.ts +72 -0
  33. package/src/app-key-state.ts +61 -0
  34. package/src/app-screens.tsx +574 -0
  35. package/src/app-view-model.ts +162 -0
  36. package/src/attribution.test.ts +31 -0
  37. package/src/attribution.ts +42 -0
  38. package/src/clipboard.test.ts +23 -0
  39. package/src/clipboard.ts +33 -0
  40. package/src/components/AnnotatableFileView.stories.tsx +42 -0
  41. package/src/components/AnnotatableFileView.test.tsx +102 -0
  42. package/src/components/AnnotatableFileView.tsx +134 -0
  43. package/src/components/AnnotationCards.stories.tsx +86 -0
  44. package/src/components/AnnotationCards.tsx +341 -0
  45. package/src/components/AnsiScreen.stories.tsx +12 -0
  46. package/src/components/AnsiScreen.tsx +28 -0
  47. package/src/components/AppHeader.stories.tsx +50 -0
  48. package/src/components/AppHeader.tsx +83 -0
  49. package/src/components/AppShell.brand.test.tsx +58 -0
  50. package/src/components/AppShell.stories.tsx +89 -0
  51. package/src/components/AppShell.tsx +329 -0
  52. package/src/components/AppShell.zoom.test.tsx +135 -0
  53. package/src/components/BareWorkbenchFileView.stories.tsx +27 -0
  54. package/src/components/BareWorkbenchFileView.tsx +64 -0
  55. package/src/components/Breadcrumb.stories.tsx +19 -0
  56. package/src/components/Breadcrumb.tsx +45 -0
  57. package/src/components/ChangesColumn.stories.tsx +44 -0
  58. package/src/components/ChangesColumn.tsx +199 -0
  59. package/src/components/ChangesFileTree.test.tsx +61 -0
  60. package/src/components/CodeBlock.stories.tsx +42 -0
  61. package/src/components/CodeBlock.tsx +84 -0
  62. package/src/components/CompletionOverlay.stories.tsx +37 -0
  63. package/src/components/CompletionOverlay.tsx +77 -0
  64. package/src/components/ConfirmCard.stories.tsx +37 -0
  65. package/src/components/ConfirmCard.tsx +153 -0
  66. package/src/components/ConfirmDialog.stories.tsx +21 -0
  67. package/src/components/ConfirmDialog.tsx +72 -0
  68. package/src/components/DiffContentView.scroll.test.tsx +121 -0
  69. package/src/components/DiffContentView.split.test.tsx +140 -0
  70. package/src/components/DiffContentView.stories.tsx +80 -0
  71. package/src/components/DiffContentView.syntax.test.tsx +82 -0
  72. package/src/components/DiffContentView.tsx +876 -0
  73. package/src/components/DiscussionMarkerRail.stories.tsx +54 -0
  74. package/src/components/DiscussionMarkerRail.tsx +186 -0
  75. package/src/components/EditorGrid.stories.tsx +59 -0
  76. package/src/components/EditorGrid.tabs.test.tsx +118 -0
  77. package/src/components/EditorGrid.tsx +426 -0
  78. package/src/components/EditorGrid.zoom.test.tsx +68 -0
  79. package/src/components/FileContentsView.stories.tsx +16 -0
  80. package/src/components/FileContentsView.test.tsx +29 -0
  81. package/src/components/FileContentsView.tsx +98 -0
  82. package/src/components/GridTabContent.stories.tsx +59 -0
  83. package/src/components/GridTabContent.tsx +182 -0
  84. package/src/components/HandleChipsInput.stories.tsx +24 -0
  85. package/src/components/HandleChipsInput.test.tsx +35 -0
  86. package/src/components/HandleChipsInput.tsx +145 -0
  87. package/src/components/KeybindsDialog.stories.tsx +31 -0
  88. package/src/components/KeybindsDialog.tsx +103 -0
  89. package/src/components/MarkdownGridBlock.stories.tsx +33 -0
  90. package/src/components/MarkdownGridBlock.tsx +72 -0
  91. package/src/components/MarkdownThreadEditor.stories.tsx +15 -0
  92. package/src/components/MarkdownThreadEditor.test.tsx +98 -0
  93. package/src/components/MarkdownThreadEditor.tsx +162 -0
  94. package/src/components/MenuBar.stories.tsx +28 -0
  95. package/src/components/MenuBar.tsx +44 -0
  96. package/src/components/NavModeHint.stories.tsx +40 -0
  97. package/src/components/NavModeHint.tsx +31 -0
  98. package/src/components/OverlayScrollbar.stories.tsx +33 -0
  99. package/src/components/OverlayScrollbar.test.tsx +139 -0
  100. package/src/components/OverlayScrollbar.tsx +129 -0
  101. package/src/components/PaneGrid.stories.tsx +84 -0
  102. package/src/components/PaneGrid.tsx +128 -0
  103. package/src/components/PanelColumn.stories.tsx +25 -0
  104. package/src/components/PanelColumn.tsx +98 -0
  105. package/src/components/ProjectTreeView.stories.tsx +25 -0
  106. package/src/components/ProjectTreeView.test.tsx +59 -0
  107. package/src/components/ProjectTreeView.tsx +111 -0
  108. package/src/components/PromptDialog.stories.tsx +36 -0
  109. package/src/components/PromptDialog.test.tsx +61 -0
  110. package/src/components/PromptDialog.tsx +99 -0
  111. package/src/components/PrototypeContentView.stories.tsx +19 -0
  112. package/src/components/PrototypeContentView.tsx +446 -0
  113. package/src/components/RootOverlay.stories.tsx +45 -0
  114. package/src/components/RootOverlay.tsx +48 -0
  115. package/src/components/ScrollArea.stories.tsx +20 -0
  116. package/src/components/ScrollArea.tsx +44 -0
  117. package/src/components/SettingsDialog.stories.tsx +117 -0
  118. package/src/components/SettingsDialog.tsx +186 -0
  119. package/src/components/SettingsRows.stories.tsx +18 -0
  120. package/src/components/SettingsRows.tsx +112 -0
  121. package/src/components/ShareDialog.stories.tsx +121 -0
  122. package/src/components/ShareDialog.tsx +552 -0
  123. package/src/components/ShellHeader.stories.tsx +50 -0
  124. package/src/components/ShellHeader.tsx +137 -0
  125. package/src/components/SlashComposer.stories.tsx +37 -0
  126. package/src/components/SlashComposer.tsx +87 -0
  127. package/src/components/ThreadFooter.stories.tsx +30 -0
  128. package/src/components/ThreadFooter.test.tsx +47 -0
  129. package/src/components/ThreadFooter.tsx +76 -0
  130. package/src/components/ThreadTree.stories.tsx +46 -0
  131. package/src/components/ThreadTree.tsx +255 -0
  132. package/src/components/ThreadView.selection.test.tsx +899 -0
  133. package/src/components/ThreadView.slash.test.tsx +146 -0
  134. package/src/components/ThreadView.stories.tsx +26 -0
  135. package/src/components/ThreadView.tsx +472 -0
  136. package/src/components/Toast.stories.tsx +19 -0
  137. package/src/components/Toast.tsx +52 -0
  138. package/src/components/Tooltip.stories.tsx +26 -0
  139. package/src/components/Tooltip.tsx +72 -0
  140. package/src/components/TreePane.stories.tsx +106 -0
  141. package/src/components/TreePane.tsx +157 -0
  142. package/src/components/WalkWizard.stories.tsx +100 -0
  143. package/src/components/WalkWizard.tsx +150 -0
  144. package/src/components/WelcomePlayground.stories.tsx +12 -0
  145. package/src/components/WelcomePlayground.test.tsx +47 -0
  146. package/src/components/WelcomePlayground.tsx +142 -0
  147. package/src/components/__snapshots__/stories.test.tsx.snap +2238 -0
  148. package/src/components/diff-content-view-layout.test.ts +198 -0
  149. package/src/components/diff-content-view-layout.ts +84 -0
  150. package/src/components/editor-grid.test.ts +86 -0
  151. package/src/components/editor-grid.ts +138 -0
  152. package/src/components/file-tree.test.ts +60 -0
  153. package/src/components/file-tree.ts +112 -0
  154. package/src/components/menu-control.stories.tsx +35 -0
  155. package/src/components/menu-control.tsx +43 -0
  156. package/src/components/pages/Workspace.stories.tsx +181 -0
  157. package/src/components/primitives/Button.stories.tsx +32 -0
  158. package/src/components/primitives/Button.tsx +56 -0
  159. package/src/components/primitives/Card.stories.tsx +25 -0
  160. package/src/components/primitives/Card.tsx +63 -0
  161. package/src/components/primitives/Dialog.stories.tsx +24 -0
  162. package/src/components/primitives/Dialog.test.tsx +37 -0
  163. package/src/components/primitives/Dialog.tsx +71 -0
  164. package/src/components/primitives/DialogActions.stories.tsx +20 -0
  165. package/src/components/primitives/DialogActions.tsx +39 -0
  166. package/src/components/primitives/IconButton.stories.tsx +36 -0
  167. package/src/components/primitives/IconButton.tsx +62 -0
  168. package/src/components/primitives/StatusBar.stories.tsx +11 -0
  169. package/src/components/primitives/StatusBar.tsx +23 -0
  170. package/src/components/primitives/Switch.stories.tsx +17 -0
  171. package/src/components/primitives/Switch.tsx +32 -0
  172. package/src/components/primitives/Tabs.stories.tsx +29 -0
  173. package/src/components/primitives/Tabs.tsx +102 -0
  174. package/src/components/primitives/Toolbar.stories.tsx +17 -0
  175. package/src/components/primitives/Toolbar.tsx +14 -0
  176. package/src/components/primitives/Tree.stories.tsx +124 -0
  177. package/src/components/primitives/Tree.tsx +100 -0
  178. package/src/components/primitives/frame.test.ts +12 -0
  179. package/src/components/primitives/frame.ts +17 -0
  180. package/src/components/primitives/icons.ts +61 -0
  181. package/src/components/primitives/tree-model.test.ts +99 -0
  182. package/src/components/primitives/tree-model.ts +137 -0
  183. package/src/components/quick-actions-editor.stories.tsx +58 -0
  184. package/src/components/quick-actions-editor.test.tsx +117 -0
  185. package/src/components/quick-actions-editor.tsx +226 -0
  186. package/src/components/share-dialog-store.ts +58 -0
  187. package/src/components/stories-app.tsx +193 -0
  188. package/src/components/stories.test.tsx +74 -0
  189. package/src/components/story-fixtures.ts +102 -0
  190. package/src/components/story-tree.test.ts +108 -0
  191. package/src/components/story.ts +159 -0
  192. package/src/components/syntax-highlight.ts +133 -0
  193. package/src/components/terminal-pane.test.tsx +40 -0
  194. package/src/components/terminal-pane.ts +199 -0
  195. package/src/components/theme-context.stories.tsx +46 -0
  196. package/src/components/theme-context.tsx +37 -0
  197. package/src/components/thread-tree.test.ts +134 -0
  198. package/src/components/thread-tree.ts +109 -0
  199. package/src/components/truncate-text.ts +7 -0
  200. package/src/components/truncate-title.test.ts +31 -0
  201. package/src/components/truncate-title.ts +15 -0
  202. package/src/config-identity.test.ts +78 -0
  203. package/src/config.test.ts +517 -33
  204. package/src/config.ts +467 -57
  205. package/src/diff-fold.test.ts +78 -0
  206. package/src/diff-fold.ts +126 -0
  207. package/src/diff-hunk-curate.test.ts +315 -0
  208. package/src/diff-hunk-curate.ts +153 -0
  209. package/src/diff-intraline.test.ts +238 -0
  210. package/src/diff-intraline.ts +236 -0
  211. package/src/diff-syntax.test.ts +112 -0
  212. package/src/diff-syntax.ts +179 -0
  213. package/src/discussions.ts +79 -0
  214. package/src/editor.test.ts +149 -0
  215. package/src/editor.ts +139 -9
  216. package/src/ghostty-terminal.test.ts +85 -0
  217. package/src/ghostty-terminal.ts +199 -0
  218. package/src/github-identity.test.ts +58 -0
  219. package/src/github-identity.ts +41 -0
  220. package/src/herdr.test.ts +9 -34
  221. package/src/herdr.ts +25 -21
  222. package/src/index.ts +13 -0
  223. package/src/integrations.test.ts +41 -0
  224. package/src/integrations.ts +32 -0
  225. package/src/intent-dispatch.test.ts +723 -0
  226. package/src/intent-dispatch.ts +692 -0
  227. package/src/key-bindings.test.ts +156 -0
  228. package/src/key-bindings.ts +459 -0
  229. package/src/keymap.test.ts +461 -113
  230. package/src/keymap.ts +321 -79
  231. package/src/kitty-image.test.ts +66 -0
  232. package/src/kitty-image.ts +138 -0
  233. package/src/launch-layout.test.ts +52 -0
  234. package/src/launch-layout.ts +42 -0
  235. package/src/mark-runs.ts +121 -0
  236. package/src/markdown-editor-syntax-style.ts +50 -0
  237. package/src/markdown-grid.test.ts +101 -0
  238. package/src/markdown-grid.ts +203 -0
  239. package/src/markdown-highlight.test.ts +61 -0
  240. package/src/markdown-highlight.ts +122 -0
  241. package/src/pasted-image.test.ts +67 -0
  242. package/src/pasted-image.ts +60 -0
  243. package/src/perf/otlp-trace.test.ts +116 -0
  244. package/src/perf/otlp-trace.ts +130 -0
  245. package/src/perf/perf-report.ts +17 -0
  246. package/src/perf/perf-timings.test.ts +18 -0
  247. package/src/perf/perf-timings.ts +38 -0
  248. package/src/prototype-browser.test.ts +64 -0
  249. package/src/prototype-browser.ts +329 -0
  250. package/src/prototype-pixels.tsx +35 -0
  251. package/src/pty.test.ts +81 -0
  252. package/src/pty.ts +245 -0
  253. package/src/ready-signal.test.ts +85 -0
  254. package/src/ready-signal.ts +52 -0
  255. package/src/run.ts +78 -13
  256. package/src/serve.test.ts +24 -12
  257. package/src/serve.ts +52 -10
  258. package/src/share.ts +237 -0
  259. package/src/skills.test.ts +74 -0
  260. package/src/skills.ts +75 -0
  261. package/src/slash-palette.test.ts +103 -0
  262. package/src/slash-palette.ts +129 -0
  263. package/src/split-diff.test.ts +110 -0
  264. package/src/split-diff.ts +149 -0
  265. package/src/test-support.test.ts +264 -0
  266. package/src/test-support.ts +369 -0
  267. package/src/theme-presets.test.ts +51 -0
  268. package/src/theme-presets.ts +214 -0
  269. package/src/theme.ts +84 -19
  270. package/src/thread-chords.test.ts +79 -0
  271. package/src/thread-chords.ts +163 -0
  272. package/src/thread-controller.curate.test.ts +450 -0
  273. package/src/thread-controller.derivation.test.ts +62 -0
  274. package/src/thread-controller.live-diff.test.ts +322 -0
  275. package/src/thread-controller.optimistic.test.ts +69 -0
  276. package/src/thread-controller.share.test.ts +561 -0
  277. package/src/thread-controller.switch-cache.test.ts +176 -0
  278. package/src/thread-controller.tree.test.ts +261 -0
  279. package/src/thread-controller.ts +1893 -0
  280. package/src/thread-selection.test.ts +210 -0
  281. package/src/thread-selection.ts +243 -0
  282. package/src/tree-view.test.ts +128 -0
  283. package/src/tree-view.ts +148 -0
  284. package/src/use-annotation-surface.tsx +915 -0
  285. package/src/use-changes-workbench.ts +190 -0
  286. package/src/use-frame-measure.ts +41 -0
  287. package/src/use-remember-layout.ts +31 -0
  288. package/src/use-settings-dialog.tsx +320 -0
  289. package/src/use-terminal-virtualizer.ts +233 -0
  290. package/src/use-thread-body-editing.tsx +58 -0
  291. package/src/version.ts +5 -0
  292. package/src/view-diff.test.ts +137 -9
  293. package/src/view-diff.ts +269 -23
  294. package/src/view-plan.regression.test.ts +60 -0
  295. package/src/view-plan.test.ts +456 -0
  296. package/src/view-plan.ts +719 -0
  297. package/src/visual/contrast.test.ts +35 -0
  298. package/src/visual/contrast.ts +33 -0
  299. package/src/walk.test.ts +121 -0
  300. package/src/walk.ts +74 -0
  301. package/src/workbench-snapshot.test.ts +81 -0
  302. package/src/workbench-snapshot.ts +29 -0
  303. package/src/session-controller.ts +0 -345
  304. package/src/syntax.test.ts +0 -41
  305. package/src/syntax.ts +0 -88
  306. package/src/view.test.ts +0 -157
  307. package/src/view.ts +0 -312
@@ -0,0 +1,719 @@
1
+ /**
2
+ * The plan projection pipeline: parse → display blocks (base vs working
3
+ * copy reconciled) → styled runs. Pure functions - the TUI renders the runs
4
+ * (the native text primitive wraps them), tests assert on them directly.
5
+ * One planning layer: rendering, navigation, and selection all derive from
6
+ * this module; the rendered/work offset mappings keep the native selection
7
+ * addressable over word-diffed blocks.
8
+ */
9
+
10
+ import {
11
+ inlineRuns,
12
+ isAddressed,
13
+ lcsDiff,
14
+ parseBlocks,
15
+ resolveAnchor,
16
+ type Annotation,
17
+ type Block,
18
+ } from "@cueloop/schema";
19
+ import { wordLevelChanges } from "./diff-intraline";
20
+ import { spanRangeInBlock, type CharRange, type TextSpan } from "./thread-selection";
21
+ import type { MarkRange, VisualLine } from "./mark-runs";
22
+
23
+ // ── display model ─────────────────────────────
24
+
25
+ export type DisplayType = "same" | "mod" | "del" | "add";
26
+
27
+ export interface DisplayBlock {
28
+ type: DisplayType;
29
+ kind: Block["kind"];
30
+ /** Block in the working copy (absent for del). */
31
+ work?: Block;
32
+ /** Block in the submitted revision (absent for add). */
33
+ base?: Block;
34
+ orderedItemNumber?: number;
35
+ }
36
+
37
+ export function displayText(block: DisplayBlock): string {
38
+ return (block.work ?? block.base)!.text;
39
+ }
40
+
41
+ /**
42
+ * The text a block actually paints: every rendered run's text in order, with
43
+ * inline markers concealed. This is the coordinate space the read-only thread
44
+ * surface hit-tests and paints in; it differs from displayText wherever a block
45
+ * carries inline markup (a link, code, or emphasis) whose markers drop away.
46
+ */
47
+ export function renderedText(block: DisplayBlock): string {
48
+ return blockRuns(block, true)
49
+ .map((run) => run.text)
50
+ .join("");
51
+ }
52
+
53
+ /** Word-overlap similarity gate: an unrelated cut + insert must not merge. */
54
+ function similar(baseBlock: Block, workBlock: Block): boolean {
55
+ if (baseBlock.kind !== workBlock.kind) return false;
56
+ const words = (text: string) => new Set(text.toLowerCase().split(/\s+/).filter(Boolean));
57
+ const baseWords = words(baseBlock.text);
58
+ const workWords = words(workBlock.text);
59
+ let intersection = 0;
60
+
61
+ for (const word of baseWords) if (workWords.has(word)) intersection++;
62
+ const union = baseWords.size + workWords.size - intersection;
63
+
64
+ return union === 0 ? true : intersection / union >= 0.3;
65
+ }
66
+
67
+ /** Reconcile base blocks vs working blocks into the display list. */
68
+ export function buildDisplay(baseContent: string, workingContent?: string): DisplayBlock[] {
69
+ const baseBlocks = parseBlocks(baseContent);
70
+
71
+ if (workingContent === undefined) {
72
+ const display: DisplayBlock[] = baseBlocks.map((block) => ({
73
+ type: "same",
74
+ kind: block.kind,
75
+ work: block,
76
+ base: block,
77
+ }));
78
+
79
+ numberOrderedListItems(display);
80
+
81
+ return display;
82
+ }
83
+ const workBlocks = parseBlocks(workingContent);
84
+ const signature = (block: Block) => block.kind + "\0" + block.text;
85
+ const ops = lcsDiff(
86
+ baseBlocks,
87
+ workBlocks,
88
+ (baseBlock, workBlock) => signature(baseBlock) === signature(workBlock),
89
+ );
90
+ const display: DisplayBlock[] = [];
91
+ let opIndex = 0;
92
+
93
+ while (opIndex < ops.length) {
94
+ const op = ops[opIndex]!;
95
+
96
+ if (op.kind === "ctx") {
97
+ display.push({ type: "same", kind: op.newValue!.kind, work: op.newValue, base: op.oldValue });
98
+ opIndex++;
99
+ continue;
100
+ }
101
+ const deletedBlocks: Block[] = [];
102
+ const addedBlocks: Block[] = [];
103
+
104
+ while (opIndex < ops.length && ops[opIndex]!.kind !== "ctx") {
105
+ const changeOp = ops[opIndex]!;
106
+
107
+ if (changeOp.kind === "del") deletedBlocks.push(changeOp.oldValue!);
108
+ else addedBlocks.push(changeOp.newValue!);
109
+ opIndex++;
110
+ }
111
+ let deletedIndex = 0;
112
+ let addedIndex = 0;
113
+
114
+ while (deletedIndex < deletedBlocks.length && addedIndex < addedBlocks.length) {
115
+ if (similar(deletedBlocks[deletedIndex]!, addedBlocks[addedIndex]!)) {
116
+ display.push({
117
+ type: "mod",
118
+ kind: addedBlocks[addedIndex]!.kind,
119
+ base: deletedBlocks[deletedIndex]!,
120
+ work: addedBlocks[addedIndex]!,
121
+ });
122
+ deletedIndex++;
123
+ addedIndex++;
124
+ } else if (deletedBlocks.length - deletedIndex >= addedBlocks.length - addedIndex) {
125
+ display.push({
126
+ type: "del",
127
+ kind: deletedBlocks[deletedIndex]!.kind,
128
+ base: deletedBlocks[deletedIndex]!,
129
+ });
130
+ deletedIndex++;
131
+ } else {
132
+ display.push({
133
+ type: "add",
134
+ kind: addedBlocks[addedIndex]!.kind,
135
+ work: addedBlocks[addedIndex]!,
136
+ });
137
+ addedIndex++;
138
+ }
139
+ }
140
+ while (deletedIndex < deletedBlocks.length) {
141
+ display.push({
142
+ type: "del",
143
+ kind: deletedBlocks[deletedIndex]!.kind,
144
+ base: deletedBlocks[deletedIndex++]!,
145
+ });
146
+ }
147
+ while (addedIndex < addedBlocks.length) {
148
+ display.push({
149
+ type: "add",
150
+ kind: addedBlocks[addedIndex]!.kind,
151
+ work: addedBlocks[addedIndex++]!,
152
+ });
153
+ }
154
+ }
155
+ numberOrderedListItems(display);
156
+
157
+ return display;
158
+ }
159
+
160
+ function numberOrderedListItems(display: DisplayBlock[]): void {
161
+ let runLength = 0;
162
+
163
+ for (const block of display) {
164
+ if (block.kind === "oli") block.orderedItemNumber = ++runLength;
165
+ else runLength = 0;
166
+ }
167
+ }
168
+
169
+ // ── marks (annotation highlights + keyboard span) ──
170
+
171
+ export type RunRole =
172
+ | "plain"
173
+ | "ins"
174
+ | "del"
175
+ | "mark-comment"
176
+ | "kspan"
177
+ | "mark-focus"
178
+ | "strong"
179
+ | "em"
180
+ | "code"
181
+ | "strike"
182
+ | "link";
183
+
184
+ export interface StyleRun {
185
+ text: string;
186
+ role: RunRole;
187
+ /** Offset of this run in the block's working text; null for del runs. */
188
+ start: number | null;
189
+ annotationId?: string;
190
+ /** Link target for `link` runs. */
191
+ href?: string;
192
+ }
193
+
194
+ export interface Mark {
195
+ start: number;
196
+ end: number;
197
+ role: RunRole;
198
+ annotationId?: string;
199
+ /** The whole anchored stretch in display coordinates; one thread per span. */
200
+ span?: TextSpan;
201
+ }
202
+
203
+ /**
204
+ * Resolve annotations against the working blocks and group marks per display
205
+ * index. Working blocks are the blocks of (workingCopy ?? artifact) - the
206
+ * same list buildDisplay derived work entries from.
207
+ */
208
+ export function marksByDisplay(
209
+ annotations: Annotation[],
210
+ display: DisplayBlock[],
211
+ focusedId?: string,
212
+ ): Map<number, Mark[]> {
213
+ // block list in "work space": display entries that carry a work block, in order
214
+ const workEntries = display
215
+ .map((block, displayIndex) => ({ block, displayIndex }))
216
+ .filter((entry) => entry.block.work !== undefined);
217
+ const workBlocks = workEntries.map((entry) => entry.block.work!);
218
+ const marksByIndex = new Map<number, Mark[]>();
219
+
220
+ for (const annotation of annotations) {
221
+ // an addressed annotation keeps its record but paints no highlight
222
+ if (isAddressed(annotation)) continue;
223
+ const resolved = resolveAnchor(annotation.anchor, workBlocks);
224
+
225
+ if (!resolved) continue;
226
+ const startEntry = workEntries[resolved.blockIndex];
227
+ const endEntry = workEntries[resolved.endBlockIndex];
228
+
229
+ if (!startEntry || !endEntry) continue;
230
+ // resolveAnchor works in the block's work text; the surface paints and hit-tests in rendered
231
+ // text (markers concealed), so map the span onto the visible characters it covers
232
+ const renderedStart = renderedOffsetAtOrAfter(
233
+ blockRuns(startEntry.block, true),
234
+ resolved.start,
235
+ );
236
+ const renderedEndInclusive = renderedOffsetAtOrBefore(
237
+ blockRuns(endEntry.block, true),
238
+ Math.max(0, resolved.end - 1),
239
+ );
240
+
241
+ if (renderedStart === null || renderedEndInclusive === null) continue;
242
+ const span: TextSpan = {
243
+ start: { blockIndex: startEntry.displayIndex, char: renderedStart },
244
+ end: { blockIndex: endEntry.displayIndex, char: renderedEndInclusive + 1 },
245
+ };
246
+
247
+ // a span paints on every block it covers; the mark carries the whole span
248
+ for (let workIndex = resolved.blockIndex; workIndex <= resolved.endBlockIndex; workIndex++) {
249
+ const entry = workEntries[workIndex]!;
250
+ const range = spanRangeInBlock(span, entry.displayIndex, renderedText(entry.block).length);
251
+
252
+ if (!range) continue;
253
+ const marks = marksByIndex.get(entry.displayIndex) ?? [];
254
+
255
+ marks.push({
256
+ start: range.start,
257
+ end: range.end,
258
+ role: annotation.id === focusedId ? "mark-focus" : "mark-comment",
259
+ annotationId: annotation.id,
260
+ span,
261
+ });
262
+ marksByIndex.set(entry.displayIndex, marks);
263
+ }
264
+ }
265
+
266
+ return marksByIndex;
267
+ }
268
+
269
+ /** Base runs for a display block: plain text, or word-diff for mod blocks. */
270
+ export function blockRuns(block: DisplayBlock, markup: boolean): StyleRun[] {
271
+ const literal =
272
+ block.kind === "code" ||
273
+ block.kind === "hr" ||
274
+ block.kind === "table" ||
275
+ block.kind === "frontmatter";
276
+
277
+ if (block.type === "mod" && markup) {
278
+ const changes = wordLevelChanges(block.base!.text, block.work!.text);
279
+ const runs: StyleRun[] = [];
280
+ let workOffset = 0;
281
+
282
+ for (const change of changes) {
283
+ if (change.kind === "removed") {
284
+ runs.push({ text: change.text, role: "del", start: null });
285
+ continue;
286
+ }
287
+ // A code/rule block stays literal; prose segments inline-tokenize so their
288
+ // markers conceal while their work offsets stay intact. Added text keeps
289
+ // the green diff role (it wins over emphasis); context text shows emphasis.
290
+ const segment = literal
291
+ ? [{ text: change.text, role: "plain" as const, start: workOffset }]
292
+ : inlineStyleRuns(change.text, workOffset);
293
+
294
+ for (const run of segment) {
295
+ runs.push(change.kind === "added" ? { ...run, role: "ins" } : run);
296
+ }
297
+ workOffset += change.text.length;
298
+ }
299
+
300
+ return runs;
301
+ }
302
+ const text = displayText(block);
303
+
304
+ // Prose carries inline markup; code fences and rules are literal. Concealed
305
+ // markers are dropped, so every rendered cell still maps to a work offset.
306
+ if (markup && !literal) {
307
+ return inlineStyleRuns(text, 0);
308
+ }
309
+
310
+ return [{ text, role: "plain", start: 0 }];
311
+ }
312
+
313
+ /** A link href safe to hand a terminal as an OSC 8 target, or undefined. Only
314
+ * http(s) and mailto are trusted; a scheme like javascript: is dropped. The
315
+ * target must stay printable ASCII: a control byte (ESC, BEL) in a reviewed
316
+ * document could otherwise splice into the terminal escape stream. */
317
+ export function safeLinkHref(href: string | undefined): string | undefined {
318
+ if (href === undefined) return undefined;
319
+ if (!/^(https?:|mailto:)/i.test(href)) return undefined;
320
+
321
+ return /^[\x21-\x7e]+$/.test(href) ? href : undefined;
322
+ }
323
+
324
+ /**
325
+ * Map the schema inline tokens to positioned StyleRuns, dropping the concealed
326
+ * markers. `base` is the run's offset within the block's working text (0 for a
327
+ * whole prose block; a segment's start for a word-diff piece).
328
+ */
329
+ export function inlineStyleRuns(text: string, base: number): StyleRun[] {
330
+ const runs: StyleRun[] = [];
331
+
332
+ for (const run of inlineRuns(text)) {
333
+ if (run.role === "marker" || run.start === null) continue;
334
+ const styleRun: StyleRun = {
335
+ text: run.text,
336
+ role: run.role === "text" ? "plain" : run.role,
337
+ start: base + run.start,
338
+ };
339
+
340
+ if (run.href !== undefined) styleRun.href = run.href;
341
+ runs.push(styleRun);
342
+ }
343
+
344
+ return runs;
345
+ }
346
+
347
+ /** A rendered run positioned by its offset in the block's rendered (concealed) text. */
348
+ export interface RenderedRun {
349
+ text: string;
350
+ role: RunRole;
351
+ /** Offset of this run in the block's rendered text. */
352
+ start: number;
353
+ href?: string;
354
+ }
355
+
356
+ /** The block's role runs positioned in rendered-text coordinates, for painting and hit-testing. */
357
+ export function renderedStyleRuns(block: DisplayBlock): RenderedRun[] {
358
+ const runs: RenderedRun[] = [];
359
+ let rendered = 0;
360
+
361
+ for (const run of blockRuns(block, true)) {
362
+ const positioned: RenderedRun = { text: run.text, role: run.role, start: rendered };
363
+
364
+ if (run.href !== undefined) positioned.href = run.href;
365
+ runs.push(positioned);
366
+ rendered += run.text.length;
367
+ }
368
+
369
+ return runs;
370
+ }
371
+
372
+ /** A painted run of one visual line: its role, its href, and whether a mark or the caret cell covers it. */
373
+ export interface StyledRun {
374
+ text: string;
375
+ role: RunRole;
376
+ marked: boolean;
377
+ caretOnly: boolean;
378
+ href?: string;
379
+ }
380
+
381
+ /**
382
+ * Slice a block's rendered role runs to one visual line and split them further
383
+ * at mark boundaries, so each painted run carries both its markdown role and
384
+ * whether a discussion mark or the caret cell covers it. Every coordinate here
385
+ * is a rendered-text offset; `markRanges` are block-level and clipped to the line.
386
+ */
387
+ export function styledRunsFor(
388
+ roleRuns: RenderedRun[],
389
+ line: VisualLine,
390
+ markRanges: MarkRange[],
391
+ ): StyledRun[] {
392
+ const cuts = new Set<number>([line.start, line.end]);
393
+
394
+ for (const run of roleRuns) {
395
+ if (run.start > line.start && run.start < line.end) cuts.add(run.start);
396
+ const runEnd = run.start + run.text.length;
397
+
398
+ if (runEnd > line.start && runEnd < line.end) cuts.add(runEnd);
399
+ }
400
+ for (const range of markRanges) {
401
+ const start = Math.max(line.start, range.start);
402
+ const end = Math.min(line.end, range.end);
403
+
404
+ if (start < end) {
405
+ cuts.add(start);
406
+ cuts.add(end);
407
+ }
408
+ }
409
+ const edges = [...cuts].toSorted((left, right) => left - right);
410
+ const runs: StyledRun[] = [];
411
+
412
+ for (let index = 0; index < edges.length - 1; index++) {
413
+ const start = edges[index]!;
414
+ const end = edges[index + 1]!;
415
+
416
+ if (end <= start) continue;
417
+ const roleRun = roleRuns.find(
418
+ (candidate) => candidate.start <= start && start < candidate.start + candidate.text.length,
419
+ );
420
+ const covering = markRanges.filter((range) => range.start <= start && end <= range.end);
421
+ const styled: StyledRun = {
422
+ text: roleRun ? roleRun.text.slice(start - roleRun.start, end - roleRun.start) : "",
423
+ role: roleRun?.role ?? "plain",
424
+ marked: covering.some((range) => range.caretOnly !== true),
425
+ caretOnly: covering.some((range) => range.caretOnly === true),
426
+ };
427
+
428
+ if (roleRun?.href !== undefined) styled.href = roleRun.href;
429
+ runs.push(styled);
430
+ }
431
+
432
+ return runs.length > 0 ? runs : [{ text: "", role: "plain", marked: false, caretOnly: false }];
433
+ }
434
+
435
+ /** Split runs at mark boundaries; marks only bind to runs with offsets. */
436
+ export function overlayMarks(runs: StyleRun[], marks: Mark[]): StyleRun[] {
437
+ if (!marks.length) return runs;
438
+ const splitRuns: StyleRun[] = [];
439
+
440
+ for (const run of runs) {
441
+ if (run.start === null) {
442
+ splitRuns.push(run);
443
+ continue;
444
+ }
445
+ const bounds = new Set<number>([0, run.text.length]);
446
+
447
+ for (const mark of marks) {
448
+ const boundStart = Math.max(0, mark.start - run.start);
449
+ const boundEnd = Math.min(run.text.length, mark.end - run.start);
450
+
451
+ if (boundStart < boundEnd) {
452
+ bounds.add(boundStart);
453
+ bounds.add(boundEnd);
454
+ }
455
+ }
456
+ const runStart = run.start;
457
+ const boundaries = [...bounds].sort((left, right) => left - right);
458
+
459
+ for (let boundaryIndex = 0; boundaryIndex < boundaries.length - 1; boundaryIndex++) {
460
+ const sliceStart = boundaries[boundaryIndex]!;
461
+ const sliceEnd = boundaries[boundaryIndex + 1]!;
462
+
463
+ if (sliceStart >= sliceEnd) continue;
464
+ const absoluteStart = runStart + sliceStart;
465
+ const mark = marks.find(
466
+ (candidate) => candidate.start <= absoluteStart && runStart + sliceEnd <= candidate.end,
467
+ );
468
+
469
+ splitRuns.push({
470
+ text: run.text.slice(sliceStart, sliceEnd),
471
+ // a mark never overrides ins/del emphasis; it rides on plain text
472
+ role: mark && run.role === "plain" ? mark.role : run.role,
473
+ start: absoluteStart,
474
+ annotationId: mark?.annotationId ?? run.annotationId,
475
+ });
476
+ }
477
+ }
478
+
479
+ return splitRuns;
480
+ }
481
+
482
+ /**
483
+ * Rendered-text offset of a work-text offset within a block's runs. The
484
+ * rendered text is every run's text in order (inline del runs included);
485
+ * only positioned runs carry work offsets. Drives the renderer's native
486
+ * selection from keyboard span offsets - the quote-anchor path depends on
487
+ * this mapping staying exact.
488
+ */
489
+ export function renderedOffsetFor(runs: StyleRun[], workOffset: number): number | null {
490
+ let rendered = 0;
491
+
492
+ for (const run of runs) {
493
+ if (run.start !== null && workOffset >= run.start && workOffset < run.start + run.text.length) {
494
+ return rendered + (workOffset - run.start);
495
+ }
496
+ rendered += run.text.length;
497
+ }
498
+
499
+ return null;
500
+ }
501
+
502
+ /**
503
+ * Rendered offset of the first positioned character at or after `workOffset`.
504
+ * A word span may start on a concealed marker (the `**` of an emphasized
505
+ * word), which has no rendered cell; the span visuals snap to the first
506
+ * character that does. Positioned runs appear in ascending work order.
507
+ */
508
+ export function renderedOffsetAtOrAfter(runs: StyleRun[], workOffset: number): number | null {
509
+ let rendered = 0;
510
+
511
+ for (const run of runs) {
512
+ if (run.start !== null && run.start + run.text.length > workOffset) {
513
+ return rendered + Math.max(0, workOffset - run.start);
514
+ }
515
+ rendered += run.text.length;
516
+ }
517
+
518
+ return null;
519
+ }
520
+
521
+ /**
522
+ * Rendered offset of the last positioned character at or before `workOffset` -
523
+ * the closing-marker counterpart of `renderedOffsetAtOrAfter`.
524
+ */
525
+ export function renderedOffsetAtOrBefore(runs: StyleRun[], workOffset: number): number | null {
526
+ let rendered = 0;
527
+ let best: number | null = null;
528
+
529
+ for (const run of runs) {
530
+ if (run.start !== null && run.start <= workOffset) {
531
+ best = rendered + Math.min(workOffset - run.start, run.text.length - 1);
532
+ }
533
+ rendered += run.text.length;
534
+ }
535
+
536
+ return best;
537
+ }
538
+
539
+ /**
540
+ * Work-text range covered by a rendered-text selection [start, end). Del runs
541
+ * and other unpositioned text inside the selection contribute nothing; the
542
+ * result is the tightest work range whose text the selection touched.
543
+ */
544
+ export function workRangeForRendered(
545
+ runs: StyleRun[],
546
+ renderedStart: number,
547
+ renderedEnd: number,
548
+ ): { start: number; end: number } | null {
549
+ let rendered = 0;
550
+ let range: { start: number; end: number } | null = null;
551
+
552
+ for (const run of runs) {
553
+ const runRenderedStart = rendered;
554
+ const runRenderedEnd = rendered + run.text.length;
555
+
556
+ rendered = runRenderedEnd;
557
+ if (run.start === null) continue;
558
+ const overlapStart = Math.max(renderedStart, runRenderedStart);
559
+ const overlapEnd = Math.min(renderedEnd, runRenderedEnd);
560
+
561
+ if (overlapEnd <= overlapStart) continue;
562
+ const workStart = run.start + (overlapStart - runRenderedStart);
563
+ const workEnd = run.start + (overlapEnd - runRenderedStart);
564
+
565
+ if (!range) range = { start: workStart, end: workEnd };
566
+ else {
567
+ range.start = Math.min(range.start, workStart);
568
+ range.end = Math.max(range.end, workEnd);
569
+ }
570
+ }
571
+
572
+ return range;
573
+ }
574
+
575
+ /**
576
+ * Map a rendered-text selection back to the work-text range an anchor is cut
577
+ * from. The read-only surface yields rendered offsets (markers concealed); an
578
+ * anchor's quote must come from the block's work text, so convert at the seam
579
+ * before makeAnchor. A selection may cross blocks: the start rendered offset
580
+ * lives in `displayIndex`, the end in `endDisplayIndex`.
581
+ */
582
+ export function renderedSpanToWork(
583
+ display: DisplayBlock[],
584
+ displayIndex: number,
585
+ endDisplayIndex: number,
586
+ renderedStart: number,
587
+ renderedEnd: number,
588
+ ): CharRange {
589
+ const startBlock = display[displayIndex]!;
590
+
591
+ if (displayIndex === endDisplayIndex) {
592
+ const range = workRangeForRendered(blockRuns(startBlock, true), renderedStart, renderedEnd);
593
+
594
+ return range ?? { start: renderedStart, end: renderedEnd };
595
+ }
596
+ const startRuns = blockRuns(startBlock, true);
597
+ const startRange = workRangeForRendered(
598
+ startRuns,
599
+ renderedStart,
600
+ renderedText(startBlock).length,
601
+ );
602
+ const endRange = workRangeForRendered(blockRuns(display[endDisplayIndex]!, true), 0, renderedEnd);
603
+
604
+ return { start: startRange?.start ?? renderedStart, end: endRange?.end ?? renderedEnd };
605
+ }
606
+
607
+ /** Line delta between two revision contents, for the sheet-header summary. */
608
+ export function revisionDelta(previousContent: string, nextContent: string) {
609
+ const ops = lcsDiff(previousContent.split("\n"), nextContent.split("\n"));
610
+ let added = 0;
611
+ let removed = 0;
612
+
613
+ for (const op of ops) {
614
+ if (op.kind === "add") added++;
615
+ else if (op.kind === "del") removed++;
616
+ }
617
+
618
+ return { added, removed };
619
+ }
620
+
621
+ // ── keyboard span mode ────────────────────────
622
+
623
+ export interface SpanState {
624
+ displayIndex: number;
625
+ wordIndex: number;
626
+ wordEnd: number;
627
+ start: number;
628
+ end: number;
629
+ }
630
+
631
+ export function wordRanges(text: string): [number, number][] {
632
+ const ranges: [number, number][] = [];
633
+ const wordPattern = /\S+/g;
634
+ let match: RegExpExecArray | null;
635
+
636
+ while ((match = wordPattern.exec(text)))
637
+ ranges.push([match.index, match.index + match[0]!.length]);
638
+
639
+ return ranges;
640
+ }
641
+
642
+ export function startSpan(displayIndex: number, text: string): SpanState | null {
643
+ const words = wordRanges(text);
644
+
645
+ if (!words.length) return null;
646
+
647
+ return { displayIndex, wordIndex: 0, wordEnd: 0, start: words[0]![0], end: words[0]![1] };
648
+ }
649
+
650
+ /**
651
+ * Build a word-granular span from a raw char range (a mouse drag-selection),
652
+ * snapping to every word the range overlaps so w/b/l/h keep working after. Null
653
+ * when the range covers no word.
654
+ */
655
+ export function spanFromRange(
656
+ displayIndex: number,
657
+ text: string,
658
+ start: number,
659
+ end: number,
660
+ ): SpanState | null {
661
+ const words = wordRanges(text);
662
+ const wordIndex = words.findIndex((word) => word[1] > start);
663
+
664
+ if (wordIndex === -1) return null;
665
+ let wordEnd = wordIndex;
666
+
667
+ for (let index = wordIndex; index < words.length && words[index]![0] < end; index++) {
668
+ wordEnd = index;
669
+ }
670
+
671
+ return {
672
+ displayIndex,
673
+ wordIndex,
674
+ wordEnd,
675
+ start: words[wordIndex]![0],
676
+ end: words[wordEnd]![1],
677
+ };
678
+ }
679
+
680
+ export function spanKey(span: SpanState, key: string, text: string): SpanState {
681
+ const words = wordRanges(text);
682
+ const nextSpan = { ...span };
683
+ const width = nextSpan.wordEnd - nextSpan.wordIndex;
684
+
685
+ if (key === "l") nextSpan.wordEnd = Math.min(words.length - 1, nextSpan.wordEnd + 1);
686
+ else if (key === "h") nextSpan.wordEnd = Math.max(nextSpan.wordIndex, nextSpan.wordEnd - 1);
687
+ else if (key === "w") {
688
+ const slidTo = Math.min(words.length - 1 - width, nextSpan.wordIndex + 1);
689
+
690
+ nextSpan.wordIndex = slidTo;
691
+ nextSpan.wordEnd = slidTo + width;
692
+ } else if (key === "b") {
693
+ const slidTo = Math.max(0, nextSpan.wordIndex - 1);
694
+
695
+ nextSpan.wordIndex = slidTo;
696
+ nextSpan.wordEnd = slidTo + width;
697
+ } else if (key === "$") nextSpan.wordEnd = words.length - 1;
698
+ else if (key === "0") {
699
+ nextSpan.wordEnd = width;
700
+ nextSpan.wordIndex = 0;
701
+ } else return span;
702
+ nextSpan.start = words[nextSpan.wordIndex]![0];
703
+ nextSpan.end = words[nextSpan.wordEnd]![1];
704
+
705
+ return nextSpan;
706
+ }
707
+
708
+ // ── working-copy block operations ─────────────
709
+
710
+ /** The next work block after a display index (a del block re-enters before it). */
711
+ export function nextWorkBlock(display: DisplayBlock[], displayIndex: number): Block | undefined {
712
+ for (let candidateIndex = displayIndex + 1; candidateIndex < display.length; candidateIndex++) {
713
+ const workBlock = display[candidateIndex]!.work;
714
+
715
+ if (workBlock) return workBlock;
716
+ }
717
+
718
+ return undefined;
719
+ }