@cueloop/client 0.1.0-alpha.65 → 0.1.0-alpha.67

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 (160) hide show
  1. package/package.json +6 -5
  2. package/src/App.autoclose.test.tsx +2 -2
  3. package/src/App.diff.test.tsx +79 -112
  4. package/src/App.plan-review.test.tsx +23 -205
  5. package/src/App.prototype.test.tsx +1 -8
  6. package/src/App.readonly.test.tsx +9 -27
  7. package/src/App.submit-confirm.test.tsx +19 -72
  8. package/src/App.test.tsx +136 -31
  9. package/src/App.tsx +491 -322
  10. package/src/App.walk.test.tsx +15 -16
  11. package/src/App.workbench.test.tsx +390 -0
  12. package/src/__snapshots__/view-plan.regression.test.ts.snap +1 -1
  13. package/src/annotation-palette.ts +61 -0
  14. package/src/app-screens.tsx +197 -77
  15. package/src/app-view-model.ts +9 -69
  16. package/src/components/AnnotationCard.stories.tsx +1 -1
  17. package/src/components/AnnotationCard.tsx +1 -1
  18. package/src/components/AnnotationCards.stories.tsx +87 -0
  19. package/src/components/AnnotationCards.tsx +303 -0
  20. package/src/components/AppHeader.stories.tsx +50 -0
  21. package/src/components/AppHeader.tsx +83 -0
  22. package/src/components/AppShell.stories.tsx +89 -0
  23. package/src/components/AppShell.tsx +239 -0
  24. package/src/components/AppShell.zoom.test.tsx +94 -0
  25. package/src/components/Breadcrumb.stories.tsx +1 -1
  26. package/src/components/ChangesColumn.stories.tsx +39 -0
  27. package/src/components/ChangesColumn.tsx +170 -0
  28. package/src/components/CodeBlock.stories.tsx +1 -1
  29. package/src/components/CompletionOverlay.stories.tsx +1 -1
  30. package/src/components/ConfirmCard.stories.tsx +1 -1
  31. package/src/components/ConfirmCard.tsx +3 -4
  32. package/src/components/ConfirmDialog.stories.tsx +1 -1
  33. package/src/components/DiffSheet.scroll.test.tsx +38 -55
  34. package/src/components/DiffSheet.split.test.tsx +140 -0
  35. package/src/components/DiffSheet.stories.tsx +56 -54
  36. package/src/components/DiffSheet.syntax.test.tsx +24 -7
  37. package/src/components/DiffSheet.tsx +607 -276
  38. package/src/components/DiscussionMarkerRail.stories.tsx +54 -0
  39. package/src/components/DiscussionMarkerRail.tsx +181 -0
  40. package/src/components/EditorGrid.stories.tsx +59 -0
  41. package/src/components/EditorGrid.tabs.test.tsx +105 -0
  42. package/src/components/EditorGrid.tsx +338 -0
  43. package/src/components/EditorGrid.zoom.test.tsx +68 -0
  44. package/src/components/FileContentsView.stories.tsx +16 -0
  45. package/src/components/FileContentsView.test.tsx +29 -0
  46. package/src/components/FileContentsView.tsx +78 -0
  47. package/src/components/InboxList.stories.tsx +23 -8
  48. package/src/components/InboxList.tsx +188 -33
  49. package/src/components/KeybindsDialog.stories.tsx +1 -1
  50. package/src/components/MarkerPopover.stories.tsx +1 -1
  51. package/src/components/MenuBar.stories.tsx +3 -12
  52. package/src/components/MenuBar.tsx +25 -56
  53. package/src/components/PaneGrid.stories.tsx +84 -0
  54. package/src/components/PaneGrid.tsx +128 -0
  55. package/src/components/PanelColumn.stories.tsx +25 -0
  56. package/src/components/PanelColumn.tsx +95 -0
  57. package/src/components/ProjectTreeView.stories.tsx +25 -0
  58. package/src/components/ProjectTreeView.test.tsx +32 -0
  59. package/src/components/ProjectTreeView.tsx +82 -0
  60. package/src/components/PromptDialog.stories.tsx +1 -1
  61. package/src/components/PromptDialog.tsx +8 -1
  62. package/src/components/PrototypeSheet.stories.tsx +1 -1
  63. package/src/components/RootOverlay.stories.tsx +44 -0
  64. package/src/components/RootOverlay.tsx +35 -0
  65. package/src/components/SettingsDialog.stories.tsx +7 -1
  66. package/src/components/SettingsDialog.tsx +114 -67
  67. package/src/components/SettingsRows.stories.tsx +1 -1
  68. package/src/components/ShellHeader.stories.tsx +50 -0
  69. package/src/components/ShellHeader.tsx +137 -0
  70. package/src/components/SurfaceScrollbar.stories.tsx +34 -0
  71. package/src/components/SurfaceScrollbar.test.tsx +111 -0
  72. package/src/components/SurfaceScrollbar.tsx +93 -0
  73. package/src/components/ThreadFooter.stories.tsx +30 -0
  74. package/src/components/ThreadFooter.test.tsx +31 -0
  75. package/src/components/ThreadFooter.tsx +54 -0
  76. package/src/components/ThreadView.slash.test.tsx +113 -0
  77. package/src/components/ThreadView.stories.tsx +1 -1
  78. package/src/components/ThreadView.tsx +62 -1352
  79. package/src/components/ThreadsSidebar.stories.tsx +36 -0
  80. package/src/components/ThreadsSidebar.tsx +70 -0
  81. package/src/components/Toast.stories.tsx +1 -1
  82. package/src/components/Tooltip.stories.tsx +26 -0
  83. package/src/components/Tooltip.tsx +72 -0
  84. package/src/components/TreePane.stories.tsx +1 -1
  85. package/src/components/WalkWizard.stories.tsx +1 -1
  86. package/src/components/WelcomeSurface.stories.tsx +12 -0
  87. package/src/components/WelcomeSurface.tsx +52 -0
  88. package/src/components/__snapshots__/stories.test.tsx.snap +732 -572
  89. package/src/components/agent-launcher.stories.tsx +1 -1
  90. package/src/components/diff-sheet-layout.test.ts +125 -55
  91. package/src/components/diff-sheet-layout.ts +3 -103
  92. package/src/components/editor-grid.test.ts +86 -0
  93. package/src/components/editor-grid.ts +138 -0
  94. package/src/components/fade-title.test.ts +49 -0
  95. package/src/components/fade-title.ts +61 -0
  96. package/src/components/file-tree.test.ts +60 -0
  97. package/src/components/file-tree.ts +112 -0
  98. package/src/components/pages/Workspace.stories.tsx +181 -0
  99. package/src/components/primitives/Button.stories.tsx +1 -1
  100. package/src/components/primitives/Card.stories.tsx +1 -1
  101. package/src/components/primitives/Dialog.stories.tsx +1 -1
  102. package/src/components/primitives/IconButton.stories.tsx +36 -0
  103. package/src/components/primitives/IconButton.tsx +62 -0
  104. package/src/components/primitives/StatusBar.stories.tsx +1 -1
  105. package/src/components/primitives/Tabs.stories.tsx +1 -1
  106. package/src/components/primitives/Toolbar.stories.tsx +1 -1
  107. package/src/components/primitives/Tree.stories.tsx +124 -0
  108. package/src/components/primitives/Tree.tsx +96 -0
  109. package/src/components/primitives/icons.ts +61 -0
  110. package/src/components/primitives/tree-model.test.ts +99 -0
  111. package/src/components/primitives/tree-model.ts +137 -0
  112. package/src/components/quick-actions-editor.stories.tsx +1 -1
  113. package/src/components/session-tree.test.ts +134 -0
  114. package/src/components/session-tree.ts +108 -0
  115. package/src/components/stories-app.tsx +142 -82
  116. package/src/components/story-tree.test.ts +100 -0
  117. package/src/components/story.ts +55 -0
  118. package/src/components/theme-context.stories.tsx +1 -1
  119. package/src/config.test.ts +20 -49
  120. package/src/config.ts +26 -28
  121. package/src/diff-fold.test.ts +78 -0
  122. package/src/diff-fold.ts +126 -0
  123. package/src/diff-syntax.test.ts +16 -0
  124. package/src/diff-syntax.ts +6 -3
  125. package/src/discussions.ts +79 -0
  126. package/src/intent-dispatch.test.ts +31 -11
  127. package/src/intent-dispatch.ts +93 -48
  128. package/src/key-bindings.test.ts +1 -1
  129. package/src/keymap.test.ts +3 -25
  130. package/src/keymap.ts +17 -18
  131. package/src/mark-runs.ts +120 -0
  132. package/src/pty.ts +10 -2
  133. package/src/run.ts +17 -7
  134. package/src/serve.test.ts +4 -8
  135. package/src/session-controller.curate.test.ts +75 -0
  136. package/src/session-controller.share.test.ts +1 -0
  137. package/src/session-controller.tree.test.ts +26 -0
  138. package/src/session-controller.ts +160 -31
  139. package/src/slash-palette.ts +83 -0
  140. package/src/split-diff.test.ts +110 -0
  141. package/src/split-diff.ts +149 -0
  142. package/src/test-support.test.ts +3 -3
  143. package/src/test-support.ts +39 -8
  144. package/src/theme.ts +4 -4
  145. package/src/thread-chords.test.ts +25 -9
  146. package/src/thread-chords.ts +33 -8
  147. package/src/use-annotation-surface.tsx +837 -0
  148. package/src/use-changes-workbench.ts +151 -0
  149. package/src/use-frame-measure.ts +38 -0
  150. package/src/use-settings-dialog.tsx +23 -24
  151. package/src/use-terminal-virtualizer.ts +233 -0
  152. package/src/view-diff.ts +114 -0
  153. package/src/App.review-panel.test.tsx +0 -140
  154. package/src/App.tree.test.tsx +0 -224
  155. package/src/components/ReviewPanel.stories.tsx +0 -100
  156. package/src/components/ReviewPanel.tsx +0 -103
  157. package/src/components/ReviewRail.stories.tsx +0 -232
  158. package/src/components/ReviewRail.tsx +0 -327
  159. package/src/review-panel.test.ts +0 -113
  160. package/src/review-panel.ts +0 -83
@@ -1,10 +1,9 @@
1
1
  /**
2
2
  * The thread view: the plan surface where discussions live inline in the
3
- * document instead of the rail. A character-precise caret sits in the text;
4
- * typing opens a composer anchored at the caret word or held selection, a
5
- * discussion's replies stack in an edge-segmented card below the marked line,
6
- * and the right-edge scroll markers navigate between discussions. Gated behind
7
- * CUELOOP_THREAD_VIEW=1 while it graduates from the UX spike.
3
+ * document instead of the rail. The caret, marks, composer, palette, and cards
4
+ * come from the shared annotation surface (the diff sheet drives the same hook);
5
+ * this view paints the plan's blocks - headings, lists, quotes, tracked changes -
6
+ * and the right-edge scroll markers that navigate between discussions.
8
7
  *
9
8
  * Grammar: arrows move (caret flows across blocks) · shift+arrows select ·
10
9
  * click/drag mark · typing comments (or edits my trailing comment / replies
@@ -13,656 +12,23 @@
13
12
  * dismisses · tab folds · cmd+[ / cmd+] cycle discussions · blur-save on click.
14
13
  */
15
14
 
16
- import React, { useEffect, useRef, useState } from "react";
17
- import {
18
- createTextAttributes,
19
- type BoxRenderable,
20
- type KeyBinding,
21
- type KeyEvent,
22
- type MouseEvent as TerminalMouseEvent,
23
- type ScrollBoxRenderable,
24
- type TextareaRenderable,
25
- type TextRenderable,
26
- } from "@opentui/core";
27
- import { useKeyboard, useRenderer } from "@opentui/react";
28
- import type { Annotation, ReviewSession } from "@cueloop/schema";
15
+ import React, { useEffect, useRef } from "react";
16
+ import type { ScrollBoxRenderable } from "@opentui/core";
17
+ import type { ReviewSession } from "@cueloop/schema";
29
18
  import { displayText, type DisplayBlock, type Mark } from "../view-plan";
30
- import {
31
- comparePositions,
32
- isDoubleClick,
33
- nextWordStart,
34
- orderedSpan,
35
- positionAt,
36
- previousWordStart,
37
- snapSpanToWords,
38
- spanRangeInBlock,
39
- tightenSpan,
40
- wordRangeAt,
41
- wordRanges,
42
- type ClickStamp,
43
- type LineGeometry,
44
- type TextPosition,
45
- type TextSpan,
46
- } from "../thread-selection";
47
- import { quickActionBody, type QuickAction } from "../config";
19
+ import type { TextSpan } from "../thread-selection";
20
+ import type { QuickAction } from "../config";
48
21
  import type { CheatsheetSection } from "../key-bindings";
49
22
  import type { Theme } from "../theme";
23
+ import { BOLD, CUT, UNDERLINE } from "../annotation-palette";
24
+ import { lineMarkRanges, runsFor, wrapLines, type MarkRange, type VisualLine } from "../mark-runs";
25
+ import { useFrameMeasure } from "../use-frame-measure";
26
+ import { useAnnotationSurface, type LineSource } from "../use-annotation-surface";
27
+ import { DiscussionMarkerRail } from "./DiscussionMarkerRail";
50
28
  import { useComponentTheme } from "./theme-context";
51
29
 
52
- /* ------------------------------------------------------------- palette */
53
-
54
- const UNDERLINE = createTextAttributes({ underline: true });
55
- const CUT = createTextAttributes({ strikethrough: true, dim: true });
56
- const BOLD = createTextAttributes({ bold: true });
57
-
58
- /** The marked-words treatment: a violet backdrop under an underline. */
59
- const MARK_BACKDROP_DARK = "#463852";
60
- const MARK_BACKDROP_LIGHT = "#e6ddf5";
61
- /** The discussion card's accent left edge. */
62
- const CARD_EDGE_DARK = "#ab7aca";
63
- const CARD_EDGE_LIGHT = "#8b5fd6";
64
- /** The caret cell: a visible cursor painted on the character under the caret. */
65
- const CARET_CELL_DARK = "#565b68";
66
- const CARET_CELL_LIGHT = "#b8bcc8";
67
-
68
- interface ThreadViewPalette {
69
- markBackdrop: string;
70
- cardEdge: string;
71
- caretCell: string;
72
- }
73
-
74
- /** Dark tokens carry light text; use that to pick the palette variant. */
75
- function paletteFor(tokens: Theme): ThreadViewPalette {
76
- const dark = Number.parseInt(tokens.text.slice(1, 3) || "e4", 16) > 128;
77
-
78
- return dark
79
- ? {
80
- markBackdrop: MARK_BACKDROP_DARK,
81
- cardEdge: CARD_EDGE_DARK,
82
- caretCell: CARET_CELL_DARK,
83
- }
84
- : {
85
- markBackdrop: MARK_BACKDROP_LIGHT,
86
- cardEdge: CARD_EDGE_LIGHT,
87
- caretCell: CARET_CELL_LIGHT,
88
- };
89
- }
90
-
91
- /** Focus cue: mix a hex color toward white, keeping its hue readable. */
92
- export function lighten(hex: string, amount = 0.25): string {
93
- const channels = hex.match(/^#(..)(..)(..)$/);
94
-
95
- if (!channels) return hex;
96
- const lifted = channels
97
- .slice(1)
98
- .map((channel) => {
99
- const value = Number.parseInt(channel, 16);
100
-
101
- return Math.round(value + (255 - value) * amount)
102
- .toString(16)
103
- .padStart(2, "0");
104
- })
105
- .join("");
106
-
107
- return `#${lifted}`;
108
- }
109
-
110
- /* ------------------------------------------------------------ measurement */
111
-
112
- /**
113
- * Read a layout-dependent value after every rendered frame (and resize),
114
- * committing only on change. Layout lands after the commit, so a timer
115
- * would race the visual-idle wait; measuring on the frame event converges
116
- * deterministically within a frame or two.
117
- */
118
- function useFrameMeasure<T>(read: () => T, isEqual: (left: T, right: T) => boolean, initial: T): T {
119
- const renderer = useRenderer();
120
- const [value, setValue] = useState(initial);
121
-
122
- useEffect(() => {
123
- const measure = (): void => {
124
- const next = read();
125
-
126
- setValue((current) => (isEqual(current, next) ? current : next));
127
- };
128
-
129
- measure();
130
- renderer?.on("frame", measure);
131
- renderer?.on("resize", measure);
132
-
133
- return () => {
134
- renderer?.off("frame", measure);
135
- renderer?.off("resize", measure);
136
- };
137
- // eslint-disable-next-line react-hooks/exhaustive-deps
138
- }, [renderer]);
139
-
140
- return value;
141
- }
142
-
143
- /* -------------------------------------------------------------- geometry */
144
-
145
- interface MarkRange {
146
- start: number;
147
- end: number;
148
- /** The bare caret's single cell - a cursor, not yet a mark. */
149
- caretOnly?: boolean;
150
- }
151
-
152
- interface Run {
153
- text: string;
154
- marked: boolean;
155
- caretOnly: boolean;
156
- }
157
-
158
- /** Split a block's text into plain/marked runs from the union of ranges. */
159
- function runsFor(text: string, ranges: MarkRange[]): Run[] {
160
- const cuts = new Set<number>([0, text.length]);
161
-
162
- for (const range of ranges) {
163
- cuts.add(Math.max(0, range.start));
164
- cuts.add(Math.min(text.length, range.end));
165
- }
166
- const edges = [...cuts].toSorted((left, right) => left - right);
167
- const runs: Run[] = [];
168
-
169
- for (let index = 0; index < edges.length - 1; index++) {
170
- const start = edges[index]!;
171
- const end = edges[index + 1]!;
172
-
173
- if (end <= start) continue;
174
- const covering = ranges.filter((range) => range.start <= start && end <= range.end);
175
- // the caret cell shows through a mark, so the head of a selection is visible
176
- runs.push({
177
- text: text.slice(start, end),
178
- marked: covering.some((range) => range.caretOnly !== true),
179
- caretOnly: covering.some((range) => range.caretOnly === true),
180
- });
181
- }
182
-
183
- return runs.length > 0 ? runs : [{ text, marked: false, caretOnly: false }];
184
- }
185
-
186
- /**
187
- * Greedy word wrap into visual-line char ranges, so a comment card can slot
188
- * in directly below the line its mark ends on (mid-paragraph when needed).
189
- */
190
- function wrapLines(text: string, width: number): Array<{ start: number; end: number }> {
191
- const lines: Array<{ start: number; end: number }> = [];
192
- let segmentStart = 0;
193
-
194
- // hard breaks first: every visual line must be exactly one terminal row,
195
- // or hit-testing and the mark geometry drift from what is painted
196
- for (const segment of text.split("\n")) {
197
- const segmentEnd = segmentStart + segment.length;
198
-
199
- if (width <= 0 || segment.length <= width) {
200
- lines.push({ start: segmentStart, end: segmentEnd });
201
- } else {
202
- // greedy word wrap inside the segment; the first line keeps its
203
- // leading indentation, continuation lines start at a word
204
- let lineStart = segmentStart;
205
- let lineEnd = segmentStart;
206
-
207
- for (const word of wordRanges(segment)) {
208
- const wordStart = segmentStart + word.start;
209
- const wordEnd = segmentStart + word.end;
210
-
211
- if (wordEnd - lineStart > width && lineEnd > lineStart) {
212
- lines.push({ start: lineStart, end: lineEnd });
213
- lineStart = wordStart;
214
- }
215
- lineEnd = wordEnd;
216
- }
217
- lines.push({ start: lineStart, end: Math.max(lineEnd, lineStart) });
218
- }
219
- segmentStart = segmentEnd + 1;
220
- }
221
-
222
- return lines;
223
- }
224
-
225
- /** A printable character: single-width input that should reach a composer. */
226
- function printableSequence(key: KeyEvent): string | null {
227
- const printable =
228
- key.sequence && key.sequence.length === 1 && !key.ctrl && !key.meta && key.sequence >= " ";
229
-
230
- return printable ? key.sequence : null;
231
- }
232
-
233
- /* ---------------------------------------------------------------- discussions */
234
-
235
- /** One conversation: a root annotation, its replies, and the span they mark. */
236
- interface Discussion {
237
- key: string;
238
- /** The annotation replies attach to. */
239
- rootId: string;
240
- /** The block the card renders under: where the span ends. */
241
- blockIndex: number;
242
- span: TextSpan;
243
- annotations: Annotation[];
244
- }
245
-
246
- function spanKey(span: TextSpan): string {
247
- return `${span.start.blockIndex}:${span.start.char}:${span.end.blockIndex}:${span.end.char}`;
248
- }
249
-
250
- /**
251
- * Roots group by the span they resolved to (two roots on the very same text
252
- * read as one conversation); replies join the discussion their replyTo names, or
253
- * stand as roots when that root is gone.
254
- */
255
- function discussionsFrom(session: ReviewSession, marks: Map<number, Mark[]>): Discussion[] {
256
- const byId = new Map(session.annotations.map((annotation) => [annotation.id, annotation]));
257
- const spanOf = new Map<string, TextSpan>();
258
-
259
- for (const [displayIndex, blockMarks] of marks) {
260
- for (const mark of blockMarks) {
261
- if (!mark.annotationId || spanOf.has(mark.annotationId)) continue;
262
- spanOf.set(
263
- mark.annotationId,
264
- mark.span ?? {
265
- start: { blockIndex: displayIndex, char: mark.start },
266
- end: { blockIndex: displayIndex, char: mark.end },
267
- },
268
- );
269
- }
270
- }
271
- const resolved = [...spanOf.keys()].map((id) => byId.get(id)!).filter(Boolean);
272
- const isRoot = (annotation: Annotation): boolean =>
273
- annotation.replyTo === undefined || !spanOf.has(annotation.replyTo);
274
- const grouped = new Map<string, Discussion>();
275
- const discussionOfRoot = new Map<string, Discussion>();
276
-
277
- for (const annotation of resolved.filter(isRoot)) {
278
- const span = spanOf.get(annotation.id)!;
279
- const key = spanKey(span);
280
- const discussion = grouped.get(key) ?? {
281
- key,
282
- rootId: annotation.id,
283
- blockIndex: span.end.blockIndex,
284
- span,
285
- annotations: [],
286
- };
287
-
288
- discussion.annotations.push(annotation);
289
- grouped.set(key, discussion);
290
- discussionOfRoot.set(annotation.id, discussion);
291
- }
292
- for (const annotation of resolved.filter((candidate) => !isRoot(candidate))) {
293
- discussionOfRoot.get(annotation.replyTo!)?.annotations.push(annotation);
294
- }
295
- for (const discussion of grouped.values()) {
296
- discussion.annotations.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
297
- }
298
-
299
- return [...grouped.values()].toSorted((left, right) =>
300
- comparePositions(left.span.start, right.span.start),
301
- );
302
- }
303
-
304
- /* -------------------------------------------------------------- composer */
305
-
306
- // cmd+enter sends (super under the kitty protocol, meta where cmd arrives
307
- // ESC-prefixed, ctrl as the fallback where the terminal itself consumes
308
- // cmd+enter); plain enter breaks the line
309
- const COMPOSE_KEY_BINDINGS: KeyBinding[] = [
310
- { name: "return", super: true, action: "submit" },
311
- { name: "return", meta: true, action: "submit" },
312
- { name: "return", ctrl: true, action: "submit" },
313
- { name: "return", action: "newline" },
314
- { name: "return", shift: true, action: "newline" },
315
- ];
316
-
317
- function composeRowCount(text: string, contentWidth: number): number {
318
- const usableWidth = contentWidth > 0 ? contentWidth : Number.MAX_SAFE_INTEGER;
319
- let visualRowCount = 0;
320
-
321
- for (const line of text.split("\n")) {
322
- visualRowCount += Math.max(1, Math.ceil(line.length / usableWidth));
323
- }
324
-
325
- // no cap: the card is the discussion, and folding is its containment
326
- return Math.max(1, visualRowCount);
327
- }
328
-
329
- function Composer({
330
- seed,
331
- glyph,
332
- tokens,
333
- onSave,
334
- onReady,
335
- onInput,
336
- }: {
337
- seed: string;
338
- glyph: string;
339
- tokens: Theme;
340
- onSave: (body: string) => void;
341
- onReady: () => void;
342
- onInput: (text: string) => void;
343
- }): React.ReactNode {
344
- const editorRef = useRef<TextareaRenderable | null>(null);
345
- const [rows, setRows] = useState(1);
346
-
347
- // once per mount (the composer is keyed by its seed): later re-renders
348
- // must NOT reset the caret, or input lands before a just-typed newline
349
- useEffect(() => {
350
- const editor = editorRef.current;
351
-
352
- if (!editor) return;
353
- editor.cursorOffset = seed.length;
354
- setRows(composeRowCount(editor.plainText, editor.width));
355
- onReady();
356
- // eslint-disable-next-line react-hooks/exhaustive-deps
357
- }, []);
358
-
359
- return (
360
- <box style={{ flexDirection: "row" }}>
361
- <text selectable={false} fg={tokens.text} style={{ flexShrink: 0 }}>{`${glyph} `}</text>
362
- <textarea
363
- ref={editorRef}
364
- focused
365
- initialValue={seed}
366
- cursorStyle={{ style: "block", blinking: true }}
367
- keyBindings={COMPOSE_KEY_BINDINGS}
368
- onSubmit={() => onSave(editorRef.current?.plainText ?? "")}
369
- onContentChange={() => {
370
- const editor = editorRef.current;
371
-
372
- if (!editor) return;
373
- setRows(composeRowCount(editor.plainText, editor.width));
374
- onInput(editor.plainText);
375
- }}
376
- style={{
377
- height: rows,
378
- flexGrow: 1,
379
- backgroundColor: "transparent",
380
- focusedBackgroundColor: "transparent",
381
- textColor: tokens.text,
382
- focusedTextColor: tokens.text,
383
- }}
384
- />
385
- </box>
386
- );
387
- }
388
-
389
- /* ---------------------------------------------------------- slash palette */
390
-
391
- interface SlashItem {
392
- name: string;
393
- description: string;
394
- body: string;
395
- }
396
-
397
- function slashItemsFrom(quickActions: QuickAction[]): SlashItem[] {
398
- return quickActions.map((action) => ({
399
- name: action.prompt
400
- .toLowerCase()
401
- .replace(/[^a-z0-9]+/g, "-")
402
- .replace(/^-|-$/g, ""),
403
- description: action.metadata ?? action.prompt,
404
- body: quickActionBody(action),
405
- }));
406
- }
407
-
408
- /** Prefix beats substring beats subsequence. */
409
- function slashFilter(items: SlashItem[], query: string): SlashItem[] {
410
- const needle = query.toLowerCase();
411
-
412
- if (needle.length === 0) return items;
413
- const scored: Array<{ item: SlashItem; score: number }> = [];
414
-
415
- for (const item of items) {
416
- const name = item.name.toLowerCase();
417
- let score = 0;
418
-
419
- if (name.startsWith(needle)) score = 3;
420
- else if (name.includes(needle)) score = 2;
421
- else {
422
- let matched = 0;
423
-
424
- for (const character of name) {
425
- if (character === needle[matched]) matched++;
426
- }
427
- if (matched === needle.length) score = 1;
428
- }
429
- if (score > 0) scored.push({ item, score });
430
- }
431
-
432
- return scored.toSorted((left, right) => right.score - left.score).map((entry) => entry.item);
433
- }
434
-
435
- function SlashList({
436
- items,
437
- selected,
438
- tokens,
439
- }: {
440
- items: SlashItem[];
441
- selected: number;
442
- tokens: Theme;
443
- }): React.ReactNode {
444
- const WINDOW = 5;
445
- const start = Math.max(0, Math.min(selected - 2, items.length - WINDOW));
446
- const visible = items.slice(start, start + WINDOW);
447
-
448
- if (items.length === 0) return <text fg={tokens.textDim}>no matching actions</text>;
449
-
450
- return (
451
- <box style={{ flexDirection: "column" }}>
452
- {visible.map((item, offset) => {
453
- const index = start + offset;
454
- const isSelected = index === selected;
455
-
456
- return (
457
- <text key={item.name} style={{ flexShrink: 1 }}>
458
- <span fg={isSelected ? tokens.accent : tokens.textDim}>{isSelected ? "→ " : " "}</span>
459
- <span fg={isSelected ? tokens.text : tokens.textMuted}>
460
- {`action:${item.name}`.padEnd(34)}
461
- </span>
462
- <span fg={tokens.textDim}>{item.description.slice(0, 52)}</span>
463
- </text>
464
- );
465
- })}
466
- {items.length > WINDOW ? (
467
- <text fg={tokens.textDim}>{`(${selected + 1}/${items.length})`}</text>
468
- ) : null}
469
- </box>
470
- );
471
- }
472
-
473
- /* ------------------------------------------------------------ discussion card */
474
-
475
- /** One card row group with its own accent-edge color, one per voice. */
476
- interface EdgeSegment {
477
- color: string;
478
- node: React.ReactNode;
479
- }
480
-
481
- /**
482
- * The comment-card frame. The accent edge is drawn by hand so that (a) its
483
- * corner cells are half-height glyphs ("╷"/"╵") terminating flush with the
484
- * hairline rows, and (b) each voice's rows carry their own edge color with
485
- * zero gap. Focus lightens every segment; the hairlines never change.
486
- */
487
- function DiscussionCard({
488
- segments,
489
- tokens,
490
- focused = false,
491
- onFocus,
492
- }: {
493
- segments: EdgeSegment[];
494
- tokens: Theme;
495
- focused?: boolean;
496
- onFocus?: () => void;
497
- }): React.ReactNode {
498
- const segmentRefs = useRef<Array<BoxRenderable | null>>([]);
499
- const noHeights: number[] = [];
500
- const heights = useFrameMeasure(
501
- () => segmentRefs.current.map((renderable) => renderable?.height ?? 0),
502
- (left, right) => left.join() === right.join(),
503
- noHeights,
504
- );
505
-
506
- const edgeColor = (color: string): string => (focused ? lighten(color) : color);
507
- const glyphs = focused
508
- ? { top: "╻", middle: "┃", bottom: "╹" }
509
- : { top: "╷", middle: "│", bottom: "╵" };
510
- const edgeRows: Array<{ glyph: string; color: string }> = [
511
- {
512
- glyph: glyphs.top,
513
- color: edgeColor(segments[0]?.color ?? tokens.border),
514
- },
515
- ];
516
-
517
- for (let index = 0; index < segments.length; index++) {
518
- const segmentRows = Math.max(1, heights[index] ?? 1);
519
-
520
- for (let row = 0; row < segmentRows; row++) {
521
- edgeRows.push({
522
- glyph: glyphs.middle,
523
- color: edgeColor(segments[index]!.color),
524
- });
525
- }
526
- }
527
- edgeRows.push({
528
- glyph: glyphs.bottom,
529
- color: edgeColor(segments[segments.length - 1]?.color ?? tokens.border),
530
- });
531
-
532
- return (
533
- <box style={{ flexDirection: "row", marginTop: 1, marginLeft: 2 }}>
534
- <text selectable={false} style={{ flexShrink: 0, width: 1 }}>
535
- {edgeRows.map((row, index) => (
536
- <span key={index} fg={row.color}>
537
- {index < edgeRows.length - 1 ? `${row.glyph}\n` : row.glyph}
538
- </span>
539
- ))}
540
- </text>
541
- <box
542
- onMouseDown={onFocus}
543
- style={{
544
- flexGrow: 1,
545
- flexDirection: "column",
546
- border: ["top", "right", "bottom"],
547
- borderStyle: "single",
548
- borderColor: tokens.border,
549
- backgroundColor: "transparent",
550
- paddingLeft: 1,
551
- paddingRight: 1,
552
- }}
553
- >
554
- {segments.map((segment, index) => (
555
- <box
556
- key={index}
557
- ref={(renderable: BoxRenderable | null) => {
558
- segmentRefs.current[index] = renderable;
559
- }}
560
- style={{ flexDirection: "column" }}
561
- >
562
- {segment.node}
563
- </box>
564
- ))}
565
- </box>
566
- </box>
567
- );
568
- }
569
-
570
- function CommentRow({
571
- annotation,
572
- tokens,
573
- }: {
574
- annotation: Annotation;
575
- tokens: Theme;
576
- }): React.ReactNode {
577
- // own comments (no author) wear the filled dot, collaborators the outline
578
- const own = annotation.author === undefined;
579
- const glyph = own ? "●" : "○";
580
- const glyphColor = own ? tokens.text : tokens.textMuted;
581
-
582
- return (
583
- <box style={{ flexDirection: "column" }}>
584
- {annotation.body.split("\n").map((line, lineIndex) => (
585
- <box key={lineIndex} style={{ flexDirection: "row" }}>
586
- <text selectable={false} fg={glyphColor} style={{ flexShrink: 0 }}>
587
- {lineIndex === 0 ? `${glyph} ` : " "}
588
- </text>
589
- <text fg={tokens.text} style={{ wrapMode: "word", flexGrow: 1, flexShrink: 1 }}>
590
- {line}
591
- </text>
592
- </box>
593
- ))}
594
- </box>
595
- );
596
- }
597
-
598
- /* ---------------------------------------------------------- scroll markers */
599
-
600
- function ScrollMarkers({
601
- discussions,
602
- hovered,
603
- tokens,
604
- onHover,
605
- onJump,
606
- }: {
607
- discussions: Discussion[];
608
- hovered: string | null;
609
- tokens: Theme;
610
- onHover: (marker: { key: string; row: number } | null) => void;
611
- onJump: (key: string) => void;
612
- }): React.ReactNode {
613
- const railRef = useRef<BoxRenderable | null>(null);
614
- const height = useFrameMeasure(
615
- () => railRef.current?.height ?? 0,
616
- (left, right) => left === right,
617
- 0,
618
- );
619
-
620
- const firstRow = Math.max(0, Math.floor((height - discussions.length) / 2));
621
- const rowFor = (index: number): number => firstRow + index;
622
- const indexAt = (row: number): number | null => {
623
- const index = row - firstRow;
624
-
625
- return index >= 0 && index < discussions.length ? index : null;
626
- };
627
- const hoveredIndex = discussions.findIndex((discussion) => discussion.key === hovered);
628
- const colorFor = (index: number): string => {
629
- if (index === hoveredIndex) return tokens.text;
630
- if (hoveredIndex >= 0 && discussions.length >= 5 && Math.abs(index - hoveredIndex) === 1) {
631
- return tokens.textMuted;
632
- }
633
-
634
- return tokens.textDim;
635
- };
636
-
637
- return (
638
- <box
639
- ref={railRef}
640
- style={{ width: 3, flexShrink: 0, flexDirection: "column" }}
641
- onMouseMove={(event) => {
642
- const index = indexAt(event.y - (railRef.current?.y ?? 0));
643
-
644
- onHover(index === null ? null : { key: discussions[index]!.key, row: rowFor(index) });
645
- }}
646
- onMouseOut={() => onHover(null)}
647
- onMouseDown={(event) => {
648
- const index = indexAt(event.y - (railRef.current?.y ?? 0));
649
-
650
- if (index !== null) onJump(discussions[index]!.key);
651
- }}
652
- >
653
- {discussions.map((discussion, index) => (
654
- <text
655
- key={discussion.key}
656
- selectable={false}
657
- style={{ position: "absolute", top: rowFor(index), left: 0 }}
658
- fg={colorFor(index)}
659
- >
660
- {(index === hoveredIndex ? "●" : "○").padStart(2)}
661
- </text>
662
- ))}
663
- </box>
664
- );
665
- }
30
+ export { lighten } from "../annotation-palette";
31
+ export { inlineSlashToken, resolveInlineSuggestion } from "../slash-palette";
666
32
 
667
33
  /**
668
34
  * How a block's rows are painted: heading weight, muted kinds, the list or
@@ -705,17 +71,6 @@ function blockStyle(block: DisplayBlock, tokens: Theme): BlockStyle {
705
71
 
706
72
  /* ------------------------------------------------------------------ view */
707
73
 
708
- interface ComposeState {
709
- /** The block the card renders under: where the span ends. */
710
- blockIndex: number;
711
- /** Reply target; null composes a new discussion. */
712
- discussionKey: string | null;
713
- span: TextSpan | null;
714
- seed: string;
715
- /** When set, the composer rewrites this annotation instead of appending. */
716
- editAnnotationId: string | null;
717
- }
718
-
719
74
  /** The grammar as the keybinds dialog lists it; the view owns these keys, so they are not rebindable. */
720
75
  export const THREAD_VIEW_CHEATSHEET: CheatsheetSection[] = [
721
76
  {
@@ -798,580 +153,50 @@ export function ThreadView({
798
153
  theme,
799
154
  }: ThreadViewProps): React.ReactNode {
800
155
  const tokens = useComponentTheme(theme);
801
- const palette = paletteFor(tokens);
802
- const discussions = discussionsFrom(session, marks);
803
- const [cursor, setCursor] = useState(0);
804
- // character-precise: `head` is the caret, `anchor` the other end of a held
805
- // selection (the same position when collapsed); both are full positions, so
806
- // the cursor block (cards, folding) can move without conjuring a selection
807
- const [caret, setCaret] = useState<{
808
- head: TextPosition;
809
- anchor: TextPosition;
810
- }>({
811
- head: { blockIndex: 0, char: 0 },
812
- anchor: { blockIndex: 0, char: 0 },
813
- });
814
- const [compose, setCompose] = useState<ComposeState | null>(null);
815
-
816
- useEffect(() => {
817
- onComposingChange?.(compose !== null);
818
- }, [compose, onComposingChange]);
819
- useEffect(() => {
820
- onCursorChange?.(caret.head.blockIndex);
821
- }, [caret.head.blockIndex, onCursorChange]);
822
-
823
- // discussion focus is the rail's card focus seen from the document: when the
824
- // app owns it (onFocusAnnotation), the focused discussion is the one holding
825
- // the focused card and focusing here names the root comment; standalone, it
826
- // is local state
827
- const [localFocus, setLocalFocus] = useState<string | null>(null);
828
- const focusedDiscussion =
829
- onFocusAnnotation === undefined
830
- ? localFocus
831
- : (discussions.find((discussion) =>
832
- discussion.annotations.some((annotation) => annotation.id === focusedAnnotationId),
833
- )?.key ?? null);
834
- const setFocusedDiscussion = (key: string | null): void => {
835
- if (onFocusAnnotation === undefined) return setLocalFocus(key);
836
- onFocusAnnotation(discussions.find((discussion) => discussion.key === key)?.rootId);
156
+ const source: LineSource = {
157
+ count: display.length,
158
+ textAt: (blockIndex) => displayText(display[blockIndex]!),
159
+ annotatable: () => true,
837
160
  };
838
- const [folded, setFolded] = useState<Set<string>>(new Set());
839
- const [composeText, setComposeText] = useState("");
840
- const [slashIndex, setSlashIndex] = useState(0);
841
- const [hoveredMarker, setHoveredMarker] = useState<{
842
- key: string;
843
- row: number;
844
- } | null>(null);
161
+ const surface = useAnnotationSurface({
162
+ source,
163
+ session,
164
+ marks,
165
+ quickActions,
166
+ tokens,
167
+ observer,
168
+ resolved,
169
+ suspended,
170
+ onComposingChange,
171
+ onObserverBlocked,
172
+ onCursorChange,
173
+ focusedAnnotationId,
174
+ onFocusAnnotation,
175
+ onAnnotate,
176
+ onReply,
177
+ onUpdateAnnotation,
178
+ onExit,
179
+ });
180
+ const { palette, discussions } = surface;
845
181
  const scrollRef = useRef<ScrollBoxRenderable | null>(null);
846
- const composerReady = useRef(false);
847
- const composeRef = useRef<ComposeState | null>(null);
848
- // every visual line registers its renderable so a drag can hit-test any
849
- // row on screen, across blocks (rows without text resolve to the block above)
850
- const lineRenderables = useRef(
851
- new Map<
852
- string,
853
- {
854
- blockIndex: number;
855
- start: number;
856
- end: number;
857
- renderable: TextRenderable;
858
- }
859
- >(),
860
- );
861
- // the press anchors the gesture; the first drag samples can land before
862
- // React has re-rendered, so the anchor travels with the gesture, not the closure
863
- const dragging = useRef<{
864
- wordMode: boolean;
865
- anchor: TextPosition;
866
- head: TextPosition;
867
- } | null>(null);
868
- const lastClick = useRef<ClickStamp | null>(null);
869
182
  const viewWidth = useFrameMeasure(
870
183
  () => scrollRef.current?.content?.width ?? 0,
871
184
  (left, right) => left === right,
872
185
  0,
873
186
  );
874
187
 
875
- // an opening card shifts the layout, so the block it belongs to is revealed
876
- // again; a discussion focused from the rail is scrolled into view the same way
877
- const revealBlockIndex =
878
- compose?.blockIndex ??
879
- discussions.find((discussion) => discussion.key === focusedDiscussion)?.blockIndex ??
880
- cursor;
881
-
882
188
  useEffect(() => {
883
189
  try {
884
- scrollRef.current?.scrollChildIntoView(`discussion-block-${revealBlockIndex}`);
190
+ scrollRef.current?.scrollChildIntoView(`discussion-block-${surface.revealBlockIndex}`);
885
191
  } catch {
886
192
  // best-effort reveal
887
193
  }
888
- }, [revealBlockIndex]);
889
-
890
- const blockText = (blockIndex: number): string => displayText(display[blockIndex]!);
891
- const textLengthOf = (blockIndex: number): number => blockText(blockIndex).length;
892
- const { head } = caret;
893
- /** The held selection in document order, off block edges; null when collapsed. */
894
- const heldSpan = ((): TextSpan | null => {
895
- const span = orderedSpan({ anchor: caret.anchor, head });
896
-
897
- return span ? tightenSpan(span, textLengthOf) : null;
898
- })();
899
- const caretIsSelection = heldSpan !== null;
900
- /** The typing anchor: the held selection (char-precise), else the marked word. */
901
- const caretSpan = (): TextSpan | null => {
902
- if (heldSpan) return heldSpan;
903
- const word = wordRangeAt(blockText(head.blockIndex), head.char);
904
-
905
- return word
906
- ? {
907
- start: { blockIndex: cursor, char: word.start },
908
- end: { blockIndex: cursor, char: word.end },
909
- }
910
- : null;
911
- };
912
- const collapseCaret = (): void => setCaret({ head, anchor: head });
913
- /** The text a span covers, blocks joined by a space, for previews. */
914
- const spanQuote = (span: TextSpan): string => {
915
- const parts: string[] = [];
916
-
917
- for (let blockIndex = span.start.blockIndex; blockIndex <= span.end.blockIndex; blockIndex++) {
918
- const range = spanRangeInBlock(span, blockIndex, textLengthOf(blockIndex));
919
-
920
- if (range) parts.push(blockText(blockIndex).slice(range.start, range.end));
921
- }
922
-
923
- return parts.join(" ");
924
- };
925
- const allGeometry = (): LineGeometry[] =>
926
- [...lineRenderables.current.values()].map((entry) => ({
927
- blockIndex: entry.blockIndex,
928
- start: entry.start,
929
- end: entry.end,
930
- x: entry.renderable.x,
931
- y: entry.renderable.y,
932
- }));
933
-
934
- const openCompose = (state: ComposeState): void => {
935
- if (observer) return onObserverBlocked?.("observer");
936
- if (resolved) return onObserverBlocked?.("resolved");
937
- composerReady.current = false;
938
- composeRef.current = state;
939
- setCompose(state);
940
- setComposeText(state.seed);
941
- setSlashIndex(0);
942
- };
943
- const closeCompose = (): void => {
944
- composeRef.current = null;
945
- setCompose(null);
946
- setComposeText("");
947
- };
948
- const slashActive = compose !== null && composeText.startsWith("/");
949
- const slashItems = slashActive
950
- ? slashFilter(slashItemsFrom(quickActions), composeText.slice(1).trim())
951
- : [];
952
-
953
- const saveComment = (body: string): void => {
954
- // the body saves verbatim - typed newlines are the author's choice;
955
- // trimming only decides whether the draft is empty enough to discard
956
- const target = composeRef.current;
957
-
958
- closeCompose();
959
- collapseCaret();
960
- if (!target || body.trim().length === 0) return;
961
- if (target.editAnnotationId !== null) {
962
- onUpdateAnnotation(target.editAnnotationId, body);
963
-
964
- return;
965
- }
966
- if (target.discussionKey !== null) {
967
- const discussion = discussions.find((candidate) => candidate.key === target.discussionKey);
968
-
969
- if (discussion) {
970
- onReply(discussion.rootId, body);
971
-
972
- return;
973
- }
974
- }
975
- const span = target.span ?? caretSpan();
976
-
977
- if (span) onAnnotate(span, body);
978
- };
979
- /** A new discussion on the typing anchor; the card renders under the span's last block. */
980
- const openNewCompose = (seed: string): void => {
981
- const span = caretSpan();
982
-
983
- openCompose({
984
- blockIndex: span?.end.blockIndex ?? head.blockIndex,
985
- discussionKey: null,
986
- span,
987
- seed,
988
- editAnnotationId: null,
989
- });
990
- };
991
-
992
- // clicking away from an open composer commits the draft (blur-save);
993
- // a half-typed slash query is never a comment, so it discards instead
994
- const blurSaveCompose = (): void => {
995
- if (!composeRef.current) return;
996
- if (slashActive || composeText.trim().length === 0) return closeCompose();
997
- saveComment(composeText);
998
- };
999
-
1000
- /** Extend the held selection to the pointer's position (word mode snaps both ends). */
1001
- const extendSelectionTo = (pointer: TextPosition): void => {
1002
- const drag = dragging.current;
1003
-
1004
- if (!drag) return;
1005
- let next = { head: pointer, anchor: drag.anchor };
1006
-
1007
- if (drag.wordMode) {
1008
- const span = orderedSpan({ anchor: drag.anchor, head: pointer });
1009
-
1010
- if (span) {
1011
- const snapped = snapSpanToWords(span, blockText);
1012
- const forward = comparePositions(pointer, drag.anchor) >= 0;
1013
-
1014
- next = forward
1015
- ? { anchor: snapped.start, head: snapped.end }
1016
- : { anchor: snapped.end, head: snapped.start };
1017
- }
1018
- }
1019
- if (comparePositions(next.head, drag.head) === 0) return;
1020
- drag.head = next.head;
1021
- setCursor(next.head.blockIndex);
1022
- setCaret({ head: next.head, anchor: next.anchor });
1023
- };
1024
-
1025
- // Drag routing lives on the view root: the renderer captures the drag on
1026
- // its FIRST drag sample, to whatever is under the pointer then, so a fast
1027
- // flick off the text row would otherwise strand the gesture. Events
1028
- // bubble, so the root sees every drag and resolves it against every line
1029
- // on screen - the mark follows the pointer across blocks.
1030
- const handleRootDrag = (event: TerminalMouseEvent): void => {
1031
- if (!dragging.current) return;
1032
- const position = positionAt(allGeometry(), event.x, event.y);
1033
-
1034
- if (position) extendSelectionTo(position);
1035
- };
1036
- const endDrag = (): void => {
1037
- dragging.current = null;
1038
- };
1039
-
1040
- const jumpToDiscussion = (key: string): void => {
1041
- const target = discussions.find((discussion) => discussion.key === key);
1042
-
1043
- if (!target) return;
1044
- blurSaveCompose();
1045
- setCursor(target.blockIndex);
1046
- setFocusedDiscussion(key);
1047
- };
1048
-
1049
- // ── keyboard, split per concern to stay within the complexity budget ──
1050
-
1051
- const handleSlashKey = (key: KeyEvent, activeCompose: ComposeState): boolean => {
1052
- if (!slashActive || slashItems.length === 0) return false;
1053
- const selected = Math.min(slashIndex, slashItems.length - 1);
1054
-
1055
- if (key.name === "up") {
1056
- setSlashIndex(Math.max(0, selected - 1));
1057
-
1058
- return true;
1059
- }
1060
- if (key.name === "down") {
1061
- setSlashIndex(Math.min(slashItems.length - 1, selected + 1));
1062
-
1063
- return true;
1064
- }
1065
- if (key.name === "return" || key.name === "tab") {
1066
- openCompose({ ...activeCompose, seed: slashItems[selected]!.body });
1067
-
1068
- return true;
1069
- }
1070
-
1071
- return false;
1072
- };
1073
-
1074
- /** Pre-mount window: buffer printables, honor a fast cmd+enter or newline. */
1075
- const handlePremountKey = (key: KeyEvent, activeCompose: ComposeState): void => {
1076
- if (key.name === "return") {
1077
- if (key.super || key.meta || key.ctrl) return saveComment(activeCompose.seed);
1078
- const grown = { ...activeCompose, seed: `${activeCompose.seed}\n` };
1079
-
1080
- composeRef.current = grown;
1081
- setComposeText(grown.seed);
1082
-
1083
- return setCompose(grown);
1084
- }
1085
- const sequence = printableSequence(key);
1086
-
1087
- if (sequence) {
1088
- const grown = { ...activeCompose, seed: activeCompose.seed + sequence };
1089
-
1090
- composeRef.current = grown;
1091
- setComposeText(grown.seed);
1092
- setCompose(grown);
1093
- }
1094
- };
1095
-
1096
- const handleComposeKey = (key: KeyEvent, activeCompose: ComposeState): void => {
1097
- // the textarea owns every key while open; the view takes dismiss (which
1098
- // also releases the discussion focus), the slash palette, and pre-mount input
1099
- if (key.name === "escape") {
1100
- setFocusedDiscussion(null);
1101
-
1102
- return closeCompose();
1103
- }
1104
- // backspace on an already empty draft undoes it: the card dissolves
1105
- // and the caret sits back on the still-held selection, ready to re-type
1106
- // (an edit of an existing comment is never deleted this way)
1107
- if (
1108
- key.name === "backspace" &&
1109
- composeText.length === 0 &&
1110
- activeCompose.editAnnotationId === null
1111
- ) {
1112
- return closeCompose();
1113
- }
1114
- if (handleSlashKey(key, activeCompose)) return;
1115
- if (!composerReady.current) handlePremountKey(key, activeCompose);
1116
- };
1117
-
1118
- /** m / cmd+[ / cmd+] / tab / return - true when the key was a discussion primitive. */
1119
- const handleDiscussionVerb = (key: KeyEvent): boolean => {
1120
- // comment on selection: cmd+option+m (alt+m where cmd arrives ESC-prefixed)
1121
- if (key.name === "m" && (key.super || key.meta || key.option)) {
1122
- openNewCompose("");
1123
-
1124
- return true;
1125
- }
1126
- if ((key.super || key.meta || key.ctrl) && (key.name === "[" || key.name === "]")) {
1127
- if (discussions.length === 0) return true;
1128
- const currentIndex = discussions.findIndex(
1129
- (discussion) => discussion.key === focusedDiscussion,
1130
- );
1131
- const nextIndex =
1132
- key.name === "]"
1133
- ? (currentIndex + 1) % discussions.length
1134
- : currentIndex <= 0
1135
- ? discussions.length - 1
1136
- : currentIndex - 1;
1137
-
1138
- jumpToDiscussion(discussions[nextIndex]!.key);
1139
-
1140
- return true;
1141
- }
1142
- if (key.name === "tab") {
1143
- setFolded((current) => {
1144
- const next = new Set(current);
1145
-
1146
- for (const discussion of discussions) {
1147
- if (discussion.blockIndex !== cursor) continue;
1148
- if (next.has(discussion.key)) next.delete(discussion.key);
1149
- else next.add(discussion.key);
1150
- }
1151
-
1152
- return next;
1153
- });
1154
-
1155
- return true;
1156
- }
1157
- // enter replies into the focused discussion, else the cursor block's discussion
1158
- if (key.name === "return") {
1159
- const replyTarget =
1160
- discussions.find((discussion) => discussion.key === focusedDiscussion) ??
1161
- discussions.findLast((discussion) => discussion.blockIndex === cursor);
1162
-
1163
- if (replyTarget) {
1164
- openCompose({
1165
- blockIndex: replyTarget.blockIndex,
1166
- discussionKey: replyTarget.key,
1167
- span: null,
1168
- seed: "",
1169
- editAnnotationId: null,
1170
- });
1171
- }
1172
-
1173
- return true;
1174
- }
1175
-
1176
- return false;
1177
- };
1178
-
1179
- /** Arrows step by word start; shift holds the anchor; the caret flows across blocks. */
1180
- const moveCaretHorizontal = (delta: 1 | -1, extend: boolean): void => {
1181
- const text = blockText(head.blockIndex);
1182
- const target =
1183
- delta === 1 ? nextWordStart(text, head.char) : previousWordStart(text, head.char);
1184
- const moveTo = (blockIndex: number, char: number): void => {
1185
- const next = { blockIndex, char };
1186
-
1187
- setCursor(blockIndex);
1188
- setCaret({ head: next, anchor: extend ? caret.anchor : next });
1189
- };
1190
-
1191
- if (target !== null) return moveTo(head.blockIndex, target);
1192
- if (extend && head.char !== (delta === 1 ? text.length : 0)) {
1193
- // the block edge first, then the next step crosses into the neighbour
1194
- return moveTo(head.blockIndex, delta === 1 ? text.length : 0);
1195
- }
1196
- if (delta === 1 && head.blockIndex < display.length - 1) return moveTo(head.blockIndex + 1, 0);
1197
- if (delta === -1 && head.blockIndex > 0) {
1198
- const previousText = blockText(head.blockIndex - 1);
1199
-
1200
- moveTo(
1201
- head.blockIndex - 1,
1202
- extend ? previousText.length : (previousWordStart(previousText, previousText.length) ?? 0),
1203
- );
1204
- }
1205
- };
1206
-
1207
- const handleCaretKey = (key: KeyEvent): boolean => {
1208
- const vertical =
1209
- key.name === "up" || (key.ctrl && key.name === "p")
1210
- ? -1
1211
- : key.name === "down" || (key.ctrl && key.name === "n")
1212
- ? 1
1213
- : 0;
1214
-
1215
- if (vertical !== 0) {
1216
- const next = Math.max(0, Math.min(display.length - 1, cursor + vertical));
1217
-
1218
- setCaret({
1219
- head: { blockIndex: next, char: 0 },
1220
- anchor: { blockIndex: next, char: 0 },
1221
- });
1222
- setFocusedDiscussion(null);
1223
- setCursor(next);
1224
-
1225
- return true;
1226
- }
1227
- if (key.name === "right" || (key.ctrl && key.name === "l")) {
1228
- moveCaretHorizontal(1, Boolean(key.shift || key.meta || key.ctrl));
1229
-
1230
- return true;
1231
- }
1232
- if (key.name === "left" || (key.ctrl && key.name === "h")) {
1233
- moveCaretHorizontal(-1, Boolean(key.shift || key.meta || key.ctrl));
1234
-
1235
- return true;
1236
- }
1237
-
1238
- return false;
1239
- };
1240
-
1241
- /** A printable starts a comment: edit my trailing, reply, or a new discussion. */
1242
- const startTyping = (key: KeyEvent): void => {
1243
- const sequence = printableSequence(key);
1244
-
1245
- if (!sequence) return;
1246
- const discussion = discussions.find((candidate) => candidate.key === focusedDiscussion);
1247
-
1248
- if (discussion) {
1249
- const last = discussion.annotations.at(-1)!;
1250
- const editingOwn = last.author === undefined;
1251
-
1252
- return openCompose({
1253
- blockIndex: discussion.blockIndex,
1254
- discussionKey: discussion.key,
1255
- span: null,
1256
- seed: editingOwn ? `${last.body}${sequence}` : sequence,
1257
- editAnnotationId: editingOwn ? last.id : null,
1258
- });
1259
- }
1260
- openNewCompose(sequence);
1261
- };
1262
-
1263
- useKeyboard((key) => {
1264
- if (suspended) return;
1265
- if (key.ctrl && key.name === "q") return onExit();
1266
- const activeCompose = composeRef.current;
1267
-
1268
- if (activeCompose) return handleComposeKey(key, activeCompose);
1269
- if (key.name === "escape") {
1270
- if (focusedDiscussion !== null) return setFocusedDiscussion(null);
1271
-
1272
- return collapseCaret();
1273
- }
1274
- if (handleDiscussionVerb(key)) return;
1275
- if (handleCaretKey(key)) return;
1276
- startTyping(key);
1277
- });
1278
-
1279
- // ── render, split per concern to stay within the complexity budget ──
1280
-
1281
- // one composer element (keyed by seed so slash acceptance remounts it);
1282
- // the slash palette renders BELOW the whole card, not inside it
1283
- const composerNode = compose ? (
1284
- <Composer
1285
- key={compose.seed}
1286
- seed={compose.seed}
1287
- glyph="●"
1288
- tokens={tokens}
1289
- onSave={saveComment}
1290
- onReady={() => (composerReady.current = true)}
1291
- onInput={setComposeText}
1292
- />
1293
- ) : null;
1294
- const slashNode = slashActive ? (
1295
- <box key="slash-palette" style={{ flexDirection: "column", marginLeft: 3 }}>
1296
- <SlashList
1297
- items={slashItems}
1298
- selected={Math.min(slashIndex, Math.max(0, slashItems.length - 1))}
1299
- tokens={tokens}
1300
- />
1301
- </box>
1302
- ) : null;
1303
-
1304
- const foldedSummaryFor = (discussion: Discussion): React.ReactNode => (
1305
- <box key={discussion.key} style={{ flexDirection: "row", marginTop: 1, marginLeft: 2 }}>
1306
- <text fg={tokens.textDim}>
1307
- {`○ ${discussion.annotations.length} comment${discussion.annotations.length === 1 ? "" : "s"} ›`}
1308
- </text>
1309
- </box>
1310
- );
1311
-
1312
- const discussionCardFor = (discussion: Discussion, composingHere: boolean): React.ReactNode => {
1313
- const segments: EdgeSegment[] = discussion.annotations.map((annotation) => {
1314
- const editingHere =
1315
- composingHere && compose?.editAnnotationId === annotation.id && composerNode !== null;
1316
-
1317
- return {
1318
- color: annotation.author === undefined ? palette.cardEdge : tokens.text,
1319
- node: editingHere ? (
1320
- composerNode
1321
- ) : (
1322
- <CommentRow key={annotation.id} annotation={annotation} tokens={tokens} />
1323
- ),
1324
- };
1325
- });
1326
-
1327
- if (composingHere && compose?.editAnnotationId === null && composerNode) {
1328
- segments.push({ color: palette.cardEdge, node: composerNode });
1329
- }
1330
-
1331
- return (
1332
- <DiscussionCard
1333
- key={discussion.key}
1334
- segments={segments}
1335
- tokens={tokens}
1336
- focused={focusedDiscussion === discussion.key}
1337
- onFocus={() => {
1338
- if (composeRef.current?.discussionKey === discussion.key) return;
1339
- blurSaveCompose();
1340
- setFocusedDiscussion(discussion.key);
1341
- setCursor(discussion.blockIndex);
1342
- }}
1343
- />
1344
- );
1345
- };
1346
-
1347
- /** Ranges to paint on a block: discussion marks, the compose mark, the caret. */
1348
- const blockRangesFor = (blockIndex: number): MarkRange[] => {
1349
- const textLength = textLengthOf(blockIndex);
1350
- const ranges: MarkRange[] = [];
1351
- const pushSpan = (span: TextSpan | null): void => {
1352
- const range = span ? spanRangeInBlock(span, blockIndex, textLength) : null;
1353
-
1354
- if (range) ranges.push(range);
1355
- };
1356
-
1357
- for (const discussion of discussions) pushSpan(discussion.span);
1358
- if (compose) pushSpan(compose.span);
1359
- if (caretIsSelection && !compose) pushSpan(heldSpan);
1360
- // the idle caret cell sits at the head, also at the end of a held mark;
1361
- // an open card takes the cursor with it, so no cell is painted then
1362
- if (blockIndex === head.blockIndex && !compose && textLength > 0) {
1363
- const cell = Math.max(0, Math.min(textLength - 1, head.char));
1364
-
1365
- ranges.push({ start: cell, end: cell + 1, caretOnly: true });
1366
- }
1367
-
1368
- return ranges;
1369
- };
194
+ }, [surface.revealBlockIndex]);
1370
195
 
1371
196
  interface LineContext {
1372
197
  blockIndex: number;
1373
198
  text: string;
1374
- line: { start: number; end: number };
199
+ line: VisualLine;
1375
200
  lineIndex: number;
1376
201
  ranges: MarkRange[];
1377
202
  marker: string;
@@ -1384,13 +209,7 @@ export function ThreadView({
1384
209
  const lineRowFor = (context: LineContext): React.ReactNode => {
1385
210
  const { blockIndex, text, line, lineIndex, ranges, marker, baseFg, baseAttributes, trailing } =
1386
211
  context;
1387
- const lineRanges = ranges
1388
- .map((range) => ({
1389
- start: Math.max(range.start, line.start) - line.start,
1390
- end: Math.min(range.end, line.end) - line.start,
1391
- caretOnly: range.caretOnly,
1392
- }))
1393
- .filter((range) => range.end > range.start);
212
+ const lineRanges = lineMarkRanges(ranges, line);
1394
213
 
1395
214
  return (
1396
215
  <box key={`line-${lineIndex}`} style={{ flexDirection: "row" }}>
@@ -1401,36 +220,8 @@ export function ThreadView({
1401
220
  <text
1402
221
  selectable={false}
1403
222
  style={{ flexGrow: 1, flexShrink: 1 }}
1404
- ref={(renderable: TextRenderable | null) => {
1405
- const key = `${blockIndex}:${lineIndex}`;
1406
-
1407
- if (renderable) {
1408
- lineRenderables.current.set(key, {
1409
- blockIndex,
1410
- start: line.start,
1411
- end: line.end,
1412
- renderable,
1413
- });
1414
- } else lineRenderables.current.delete(key);
1415
- }}
1416
- onMouseDown={(event) => {
1417
- blurSaveCompose();
1418
- const pressed = positionAt(allGeometry(), event.x, event.y);
1419
-
1420
- if (!pressed) return;
1421
- const stamp = { time: Date.now(), x: event.x, y: event.y };
1422
- const wordMode = isDoubleClick(lastClick.current, stamp);
1423
-
1424
- lastClick.current = stamp;
1425
- const word = wordMode ? wordRangeAt(blockText(pressed.blockIndex), pressed.char) : null;
1426
- const anchor = word ? { blockIndex: pressed.blockIndex, char: word.start } : pressed;
1427
- const pressHead = word ? { blockIndex: pressed.blockIndex, char: word.end } : pressed;
1428
-
1429
- dragging.current = { wordMode, anchor, head: pressHead };
1430
- setFocusedDiscussion(null);
1431
- setCursor(pressed.blockIndex);
1432
- setCaret({ head: pressHead, anchor });
1433
- }}
223
+ ref={surface.registerLine(blockIndex, lineIndex, line)}
224
+ onMouseDown={surface.onLineMouseDown}
1434
225
  >
1435
226
  {runsFor(text.slice(line.start, line.end), lineRanges).map((run, runIndex) => (
1436
227
  <span
@@ -1448,54 +239,10 @@ export function ThreadView({
1448
239
  );
1449
240
  };
1450
241
 
1451
- /** Cards anchored to a visual line: discussion cards, the new-discussion composer. */
1452
- const cardsAfterLine = (
1453
- blockIndex: number,
1454
- line: { start: number; end: number },
1455
- isLastLine: boolean,
1456
- blockDiscussions: Discussion[],
1457
- ): React.ReactNode[] => {
1458
- const endsInLine = (end: number): boolean => end - 1 >= line.start && end - 1 < line.end;
1459
- const nodes: React.ReactNode[] = [];
1460
- const composeHere = compose && compose.blockIndex === blockIndex;
1461
-
1462
- for (const discussion of blockDiscussions) {
1463
- if (!endsInLine(discussion.span.end.char)) continue;
1464
- const composingHere = Boolean(composeHere && compose.discussionKey === discussion.key);
1465
-
1466
- if (folded.has(discussion.key) && !composingHere) {
1467
- nodes.push(foldedSummaryFor(discussion));
1468
- continue;
1469
- }
1470
- nodes.push(discussionCardFor(discussion, composingHere));
1471
- if (composingHere && slashNode) nodes.push(slashNode);
1472
- }
1473
- if (composeHere && compose.discussionKey === null && composerNode) {
1474
- const anchoredHere = compose.span ? endsInLine(compose.span.end.char) : isLastLine;
1475
-
1476
- if (anchoredHere) {
1477
- nodes.push(
1478
- <DiscussionCard
1479
- key="compose-new"
1480
- tokens={tokens}
1481
- segments={[{ color: palette.cardEdge, node: composerNode }]}
1482
- />,
1483
- );
1484
- if (slashNode) nodes.push(slashNode);
1485
- }
1486
- }
1487
-
1488
- return nodes;
1489
- };
1490
-
1491
242
  const blockNodeFor = (blockIndex: number): React.ReactNode => {
1492
243
  const block = display[blockIndex]!;
1493
- const text = blockText(blockIndex);
1494
- // cards live under the block a span ends in; marks paint on every block it covers
1495
- const blockDiscussions = discussions.filter(
1496
- (discussion) => discussion.blockIndex === blockIndex,
1497
- );
1498
- const ranges = blockRangesFor(blockIndex);
244
+ const text = displayText(block);
245
+ const ranges = surface.rangesFor(blockIndex);
1499
246
  const { baseFg, baseAttributes, marker, changeTag } = blockStyle(block, tokens);
1500
247
  const lines = wrapLines(text, viewWidth > 0 ? viewWidth - marker.length - 6 : 0);
1501
248
  const lineRows: React.ReactNode[] = [];
@@ -1517,7 +264,7 @@ export function ThreadView({
1517
264
  trailing: lineIndex === 0 ? changeTag : null,
1518
265
  }),
1519
266
  );
1520
- const cards = cardsAfterLine(blockIndex, line, isLastLine, blockDiscussions);
267
+ const cards = surface.cardsAfterLine(blockIndex, line, isLastLine);
1521
268
 
1522
269
  lineRows.push(...cards);
1523
270
  if (cards.length > 0 && !isLastLine) {
@@ -1551,50 +298,8 @@ export function ThreadView({
1551
298
  );
1552
299
  };
1553
300
 
1554
- const markerPreview = (): React.ReactNode => {
1555
- if (hoveredMarker === null) return null;
1556
- const preview = discussions.find((discussion) => discussion.key === hoveredMarker.key);
1557
-
1558
- if (!preview) return null;
1559
- const quote = spanQuote(preview.span);
1560
- const lastComment = preview.annotations.at(-1)!;
1561
-
1562
- return (
1563
- <box
1564
- style={{
1565
- position: "absolute",
1566
- top: Math.max(0, hoveredMarker.row - 1),
1567
- right: 4,
1568
- width: 48,
1569
- flexDirection: "column",
1570
- border: true,
1571
- borderStyle: "single",
1572
- borderColor: tokens.border,
1573
- backgroundColor: tokens.elevated,
1574
- paddingLeft: 1,
1575
- paddingRight: 1,
1576
- }}
1577
- >
1578
- <text fg={tokens.textDim}>{`"${quote.slice(0, 42)}"`}</text>
1579
- <text fg={tokens.text}>
1580
- {`${lastComment.author === undefined ? "●" : "○"} ${lastComment.body}`.slice(0, 44)}
1581
- </text>
1582
- <text fg={tokens.textDim}>
1583
- {`${preview.annotations.length} comment${
1584
- preview.annotations.length === 1 ? "" : "s"
1585
- } · click to jump`}
1586
- </text>
1587
- </box>
1588
- );
1589
- };
1590
-
1591
301
  return (
1592
- <box
1593
- style={{ flexGrow: 1, flexDirection: "row" }}
1594
- onMouseDrag={handleRootDrag}
1595
- onMouseDragEnd={endDrag}
1596
- onMouseUp={endDrag}
1597
- >
302
+ <box style={{ flexGrow: 1, flexDirection: "row" }} {...surface.rootMouseProps}>
1598
303
  <box style={{ flexGrow: 1, flexDirection: "column" }}>
1599
304
  {editOrphanCount > 0 ? (
1600
305
  <box style={{ height: 1, backgroundColor: palette.markBackdrop, paddingLeft: 2 }}>
@@ -1603,18 +308,23 @@ export function ThreadView({
1603
308
  </text>
1604
309
  </box>
1605
310
  ) : null}
1606
- <scrollbox ref={scrollRef} style={{ flexGrow: 1, paddingTop: 1 }} focused={false}>
311
+ {/* the rail draws this box's scrollbar past the dots, so the built-in one stays hidden */}
312
+ <scrollbox
313
+ ref={scrollRef}
314
+ style={{ flexGrow: 1, paddingTop: 1 }}
315
+ focused={false}
316
+ verticalScrollbarOptions={{ visible: false }}
317
+ >
1607
318
  {display.map((_block, blockIndex) => blockNodeFor(blockIndex))}
1608
319
  </scrollbox>
1609
320
  </box>
1610
- <ScrollMarkers
321
+ <DiscussionMarkerRail
1611
322
  discussions={discussions}
1612
- hovered={hoveredMarker?.key ?? null}
1613
- tokens={tokens}
1614
- onHover={setHoveredMarker}
1615
- onJump={jumpToDiscussion}
323
+ spanQuote={surface.spanQuote}
324
+ onJump={surface.jumpToDiscussion}
325
+ scrollbox={scrollRef}
326
+ theme={theme}
1616
327
  />
1617
- {markerPreview()}
1618
328
  </box>
1619
329
  );
1620
330
  }