@peaske7/readit 0.2.0 → 0.3.0-rc.0

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 (179) hide show
  1. package/.claude/CLAUDE.md +118 -76
  2. package/.claude/commands/review.md +1 -1
  3. package/.claude/roadmap.md +32 -9
  4. package/.claude/user-stories.md +100 -15
  5. package/AGENTS.md +30 -26
  6. package/Makefile +32 -0
  7. package/README.md +90 -2
  8. package/biome.json +18 -8
  9. package/bun.lock +426 -568
  10. package/bunfig.toml +2 -0
  11. package/docs/perf-baseline.md +56 -1
  12. package/docs/superpowers/specs/2026-03-27-go-server-rewrite-design.md +284 -0
  13. package/e2e/comments.spec.ts +14 -58
  14. package/e2e/document-load.spec.ts +1 -23
  15. package/e2e/export.spec.ts +4 -4
  16. package/e2e/perf/add-comment.spec.ts +9 -11
  17. package/e2e/perf/fixtures/generate.ts +1 -5
  18. package/e2e/perf/screenshot-final.png +0 -0
  19. package/e2e/perf/utils/metrics.ts +73 -9
  20. package/e2e/persistence-file.spec.ts +41 -26
  21. package/e2e/utils/selection.ts +17 -73
  22. package/go/cmd/readit/main.go +416 -0
  23. package/go/go.mod +20 -0
  24. package/go/go.sum +41 -0
  25. package/go/internal/server/anchor.go +302 -0
  26. package/go/internal/server/anchor_test.go +111 -0
  27. package/go/internal/server/comments.go +390 -0
  28. package/go/internal/server/documents.go +113 -0
  29. package/go/internal/server/embed.go +17 -0
  30. package/go/internal/server/headings.go +33 -0
  31. package/go/internal/server/headings_test.go +75 -0
  32. package/go/internal/server/htmltext.go +123 -0
  33. package/go/internal/server/markdown.go +157 -0
  34. package/go/internal/server/markdown_bench_test.go +42 -0
  35. package/go/internal/server/markdown_test.go +79 -0
  36. package/go/internal/server/server.go +453 -0
  37. package/go/internal/server/server_bench_test.go +122 -0
  38. package/go/internal/server/settings.go +110 -0
  39. package/go/internal/server/sse.go +140 -0
  40. package/go/internal/server/storage.go +275 -0
  41. package/go/internal/server/storage_test.go +152 -0
  42. package/go/internal/server/template.go +66 -0
  43. package/go/internal/server/types.go +101 -0
  44. package/go/internal/server/watcher.go +74 -0
  45. package/index.html +4 -14
  46. package/nvim-readit/lua/readit/health.lua +64 -0
  47. package/nvim-readit/lua/readit/init.lua +463 -0
  48. package/nvim-readit/plugin/readit.lua +19 -0
  49. package/package.json +20 -28
  50. package/shell/_readit +158 -0
  51. package/shell/readit.zsh +87 -0
  52. package/src/App.svelte +890 -0
  53. package/src/cli.ts +183 -21
  54. package/src/components/ActionsMenu.svelte +95 -0
  55. package/src/components/CommentBadge.svelte +67 -0
  56. package/src/components/CommentErrorBanner.svelte +33 -0
  57. package/src/components/CommentInput.svelte +75 -0
  58. package/src/components/CommentListItem.svelte +95 -0
  59. package/src/components/CommentManager.svelte +129 -0
  60. package/src/components/CommentNav.svelte +109 -0
  61. package/src/components/DocumentViewer.svelte +233 -0
  62. package/src/components/FloatingComment.svelte +107 -0
  63. package/src/components/Header.svelte +76 -0
  64. package/src/components/InlineEditor.svelte +72 -0
  65. package/src/components/MarginNote.svelte +167 -0
  66. package/src/components/MarginNotesContainer.svelte +33 -0
  67. package/src/components/MermaidEnhancer.svelte +218 -0
  68. package/src/components/MermaidModal.svelte +67 -0
  69. package/src/components/RawModal.svelte +126 -0
  70. package/src/components/ReanchorConfirm.svelte +30 -0
  71. package/src/components/SettingsModal.svelte +220 -0
  72. package/src/components/ShortcutCapture.svelte +82 -0
  73. package/src/components/ShortcutList.svelte +145 -0
  74. package/src/components/TabBar.svelte +52 -0
  75. package/src/components/TableOfContents.svelte +125 -0
  76. package/src/components/ui/ActionLink.svelte +40 -0
  77. package/src/components/ui/{Button.tsx → Button.svelte} +19 -20
  78. package/src/components/ui/Dialog.svelte +97 -0
  79. package/src/components/ui/DropdownMenu.svelte +85 -0
  80. package/src/components/ui/DropdownMenuItem.svelte +38 -0
  81. package/src/components/ui/DropdownMenuSeparator.svelte +11 -0
  82. package/src/components/ui/{Text.tsx → Text.svelte} +18 -23
  83. package/src/env.d.ts +6 -0
  84. package/src/index.css +141 -166
  85. package/src/lib/__fixtures__/bench-data.ts +0 -13
  86. package/src/lib/anchor.bench.ts +1 -12
  87. package/src/lib/anchor.test.ts +0 -8
  88. package/src/lib/anchor.ts +0 -4
  89. package/src/lib/comment-storage.bench.ts +49 -0
  90. package/src/lib/comment-storage.test.ts +103 -33
  91. package/src/lib/comment-storage.ts +25 -18
  92. package/src/lib/export.bench.ts +21 -0
  93. package/src/lib/export.ts +0 -1
  94. package/src/lib/fetch-or-throw.test.ts +59 -0
  95. package/src/lib/fetch-or-throw.ts +12 -0
  96. package/src/{hooks/useHeadings.test.ts → lib/headings.test.ts} +10 -24
  97. package/src/{hooks/useHeadings.ts → lib/headings.ts} +11 -13
  98. package/src/lib/highlight/core.test.ts +0 -5
  99. package/src/lib/highlight/dom.ts +52 -216
  100. package/src/lib/highlight/highlight-registry.ts +221 -0
  101. package/src/lib/highlight/highlight.bench.ts +92 -0
  102. package/src/lib/highlight/highlighter.ts +112 -132
  103. package/src/lib/highlight/resolver.ts +5 -79
  104. package/src/lib/highlight/types.ts +0 -5
  105. package/src/lib/html-text.test.ts +162 -0
  106. package/src/lib/html-text.ts +161 -0
  107. package/src/lib/i18n/en.ts +34 -0
  108. package/src/lib/i18n/ja.ts +34 -0
  109. package/src/lib/i18n/types.ts +33 -0
  110. package/src/lib/key-lock.test.ts +104 -0
  111. package/src/lib/key-lock.ts +23 -0
  112. package/src/lib/margin-layout.bench.ts +61 -0
  113. package/src/lib/margin-layout.ts +0 -7
  114. package/src/lib/markdown-renderer.test.ts +154 -0
  115. package/src/lib/markdown-renderer.ts +178 -0
  116. package/src/lib/mermaid-config.ts +38 -0
  117. package/src/lib/mermaid-renderer.ts +162 -0
  118. package/src/lib/mermaid-worker.ts +60 -0
  119. package/src/lib/positions.ts +31 -24
  120. package/src/lib/shortcut-registry.ts +244 -0
  121. package/src/lib/utils.ts +0 -29
  122. package/src/main.ts +16 -0
  123. package/src/schema.ts +16 -5
  124. package/src/server.ts +355 -95
  125. package/src/stores/app.svelte.ts +231 -0
  126. package/src/stores/locale.svelte.ts +46 -0
  127. package/src/stores/settings.svelte.ts +90 -0
  128. package/src/stores/shortcuts.svelte.ts +104 -0
  129. package/src/stores/ui.svelte.ts +12 -0
  130. package/src/template.ts +104 -0
  131. package/src/test-setup.ts +47 -0
  132. package/svelte.config.js +5 -0
  133. package/tsconfig.json +2 -2
  134. package/vite.config.ts +23 -3
  135. package/vscode-readit/.mcp.json +7 -0
  136. package/vscode-readit/.vscodeignore +7 -0
  137. package/vscode-readit/bun.lock +78 -0
  138. package/vscode-readit/icon.svg +10 -0
  139. package/vscode-readit/package.json +110 -0
  140. package/vscode-readit/src/extension.ts +117 -0
  141. package/vscode-readit/src/server-manager.ts +272 -0
  142. package/vscode-readit/src/webview-provider.ts +204 -0
  143. package/vscode-readit/tsconfig.json +20 -0
  144. package/e2e/fixtures/sample.html +0 -13
  145. package/src/App.tsx +0 -368
  146. package/src/components/ActionsMenu.tsx +0 -91
  147. package/src/components/DocumentViewer/CodeBlock.tsx +0 -160
  148. package/src/components/DocumentViewer/DocumentViewer.tsx +0 -230
  149. package/src/components/DocumentViewer/MermaidDiagram.tsx +0 -136
  150. package/src/components/Header.tsx +0 -54
  151. package/src/components/InlineEditor.tsx +0 -74
  152. package/src/components/MarginNote.tsx +0 -185
  153. package/src/components/MarginNotes.tsx +0 -23
  154. package/src/components/RawModal.tsx +0 -144
  155. package/src/components/ReanchorConfirm.tsx +0 -36
  156. package/src/components/SettingsModal.tsx +0 -232
  157. package/src/components/TabBar.tsx +0 -60
  158. package/src/components/TableOfContents.tsx +0 -108
  159. package/src/components/comments/CommentBadge.tsx +0 -49
  160. package/src/components/comments/CommentInput.tsx +0 -86
  161. package/src/components/comments/CommentListItem.tsx +0 -90
  162. package/src/components/comments/CommentManager.tsx +0 -129
  163. package/src/components/comments/CommentNav.tsx +0 -109
  164. package/src/components/ui/ActionLink.tsx +0 -28
  165. package/src/components/ui/Dialog.tsx +0 -116
  166. package/src/components/ui/DropdownMenu.tsx +0 -158
  167. package/src/contexts/CommentContext.tsx +0 -198
  168. package/src/contexts/LocaleContext.tsx +0 -76
  169. package/src/contexts/PositionsContext.tsx +0 -16
  170. package/src/contexts/SettingsContext.tsx +0 -133
  171. package/src/hooks/useClickOutside.ts +0 -31
  172. package/src/hooks/useCommentNavigation.ts +0 -107
  173. package/src/hooks/useComments.ts +0 -311
  174. package/src/hooks/useDocument.ts +0 -157
  175. package/src/hooks/useScrollSpy.ts +0 -77
  176. package/src/hooks/useTextSelection.ts +0 -86
  177. package/src/lib/highlight/worker.ts +0 -45
  178. package/src/main.tsx +0 -13
  179. package/src/store.ts +0 -222
package/src/App.svelte ADDED
@@ -0,0 +1,890 @@
1
+ <script lang="ts">
2
+ import { onDestroy, onMount, untrack } from "svelte";
3
+ import CommentErrorBanner from "./components/CommentErrorBanner.svelte";
4
+ import CommentInput from "./components/CommentInput.svelte";
5
+ import CommentNav from "./components/CommentNav.svelte";
6
+ import DocumentViewer from "./components/DocumentViewer.svelte";
7
+ import FloatingComment from "./components/FloatingComment.svelte";
8
+ import Header from "./components/Header.svelte";
9
+ import MarginNotesContainer from "./components/MarginNotesContainer.svelte";
10
+ import ReanchorConfirm from "./components/ReanchorConfirm.svelte";
11
+ import TabBar from "./components/TabBar.svelte";
12
+ import TableOfContents from "./components/TableOfContents.svelte";
13
+ import {
14
+ exportCommentsAsJson,
15
+ formatComment,
16
+ generatePrompt,
17
+ } from "./lib/export";
18
+ import { fetchOrThrow } from "./lib/fetch-or-throw";
19
+ import { Positions } from "./lib/positions";
20
+ import { matchesBinding, ShortcutActions } from "./lib/shortcut-registry";
21
+ import { AnchorConfidences, type Comment } from "./schema";
22
+ import {
23
+ app,
24
+ getActiveDocumentState,
25
+ openDocument,
26
+ setActiveDocument,
27
+ setComments,
28
+ setCommentsError,
29
+ setHeadings,
30
+ setPendingSelectionTop,
31
+ setReanchorTarget,
32
+ setScrollY,
33
+ setSelection,
34
+ setWorkingDirectory,
35
+ updateDocumentHtml,
36
+ } from "./stores/app.svelte";
37
+ import { t } from "./stores/locale.svelte";
38
+ import { initSettings } from "./stores/settings.svelte";
39
+ import { initShortcuts, shortcutState } from "./stores/shortcuts.svelte";
40
+ import {
41
+ setActiveCommentId,
42
+ setHoveredCommentId,
43
+ ui,
44
+ } from "./stores/ui.svelte";
45
+
46
+ let isInitialized = $state(false);
47
+ let error = $state<string | null>(null);
48
+ const positionsMap = new Map<string, Positions>();
49
+ let currentIndex = $state(0);
50
+ const highlighterMap = new Map<
51
+ string,
52
+ {
53
+ setFocused: (id: string | undefined) => void;
54
+ scrollTo: (id: string) => void;
55
+ }
56
+ >();
57
+ let hoverTimeout: ReturnType<typeof setTimeout> | undefined;
58
+ const prevActiveMap = new Map<string, boolean>();
59
+
60
+ function clearPendingHighlight() {
61
+ if (typeof CSS !== "undefined" && CSS.highlights) {
62
+ CSS.highlights.delete("pending-selection");
63
+ }
64
+ }
65
+
66
+ function getPositions(filePath: string): Positions {
67
+ let pos = positionsMap.get(filePath);
68
+ if (!pos) {
69
+ pos = new Positions();
70
+ positionsMap.set(filePath, pos);
71
+ }
72
+ return pos;
73
+ }
74
+
75
+ async function addComment(
76
+ filePath: string,
77
+ selectedText: string,
78
+ commentText: string,
79
+ startOffset: number,
80
+ endOffset: number,
81
+ ) {
82
+ const tempId = `temp-${crypto.randomUUID()}`;
83
+ const optimisticComment: Comment = {
84
+ id: tempId,
85
+ selectedText,
86
+ comment: commentText.trim(),
87
+ startOffset,
88
+ endOffset,
89
+ };
90
+
91
+ const docState = app.documents.get(filePath);
92
+ const previousComments = [...(docState?.comments ?? [])];
93
+
94
+ setComments([...previousComments, optimisticComment], filePath);
95
+ setCommentsError(null, filePath);
96
+
97
+ try {
98
+ const response = await fetchOrThrow(
99
+ `/api/comments?path=${encodeURIComponent(filePath)}`,
100
+ {
101
+ method: "POST",
102
+ headers: { "Content-Type": "application/json" },
103
+ body: JSON.stringify({
104
+ selectedText,
105
+ comment: commentText.trim(),
106
+ startOffset,
107
+ endOffset,
108
+ }),
109
+ },
110
+ "Failed to add comment",
111
+ );
112
+ const data = await response.json();
113
+ const current = app.documents.get(filePath)?.comments ?? [];
114
+ setComments(
115
+ current.map((c) => (c.id === tempId ? data.comment : c)),
116
+ filePath,
117
+ );
118
+ } catch (err) {
119
+ console.error("Failed to add comment:", err);
120
+ setCommentsError(
121
+ err instanceof Error ? err.message : "Failed to add comment",
122
+ filePath,
123
+ );
124
+ setComments(previousComments, filePath);
125
+ }
126
+ }
127
+
128
+ async function editComment(filePath: string, id: string, newText: string) {
129
+ const trimmed = newText.trim();
130
+ if (!trimmed) return;
131
+
132
+ const docState = app.documents.get(filePath);
133
+ const previousComments = [...(docState?.comments ?? [])];
134
+
135
+ setComments(
136
+ previousComments.map((c) => (c.id === id ? { ...c, comment: trimmed } : c)),
137
+ filePath,
138
+ );
139
+
140
+ setCommentsError(null, filePath);
141
+ try {
142
+ await fetchOrThrow(
143
+ `/api/comments/${id}?path=${encodeURIComponent(filePath)}`,
144
+ {
145
+ method: "PUT",
146
+ headers: { "Content-Type": "application/json" },
147
+ body: JSON.stringify({ comment: trimmed }),
148
+ },
149
+ "Failed to update comment",
150
+ );
151
+ } catch (err) {
152
+ console.error("Failed to edit comment:", err);
153
+ setCommentsError(
154
+ err instanceof Error ? err.message : "Failed to update comment",
155
+ filePath,
156
+ );
157
+ setComments(previousComments, filePath);
158
+ }
159
+ }
160
+
161
+ async function deleteComment(filePath: string, id: string) {
162
+ const docState = app.documents.get(filePath);
163
+ const previousComments = [...(docState?.comments ?? [])];
164
+
165
+ setComments(
166
+ previousComments.filter((c) => c.id !== id),
167
+ filePath,
168
+ );
169
+
170
+ setCommentsError(null, filePath);
171
+ try {
172
+ await fetchOrThrow(
173
+ `/api/comments/${id}?path=${encodeURIComponent(filePath)}`,
174
+ { method: "DELETE" },
175
+ "Failed to delete comment",
176
+ );
177
+ } catch (err) {
178
+ console.error("Failed to delete comment:", err);
179
+ setCommentsError(
180
+ err instanceof Error ? err.message : "Failed to delete comment",
181
+ filePath,
182
+ );
183
+ setComments(previousComments, filePath);
184
+ }
185
+ }
186
+
187
+ async function deleteAllComments(filePath: string) {
188
+ const docState = app.documents.get(filePath);
189
+ const previousComments = [...(docState?.comments ?? [])];
190
+
191
+ setComments([], filePath);
192
+
193
+ setCommentsError(null, filePath);
194
+ try {
195
+ await fetchOrThrow(
196
+ `/api/comments?path=${encodeURIComponent(filePath)}`,
197
+ { method: "DELETE" },
198
+ "Failed to delete all comments",
199
+ );
200
+ } catch (err) {
201
+ console.error("Failed to delete all comments:", err);
202
+ setCommentsError(
203
+ err instanceof Error ? err.message : "Failed to delete all comments",
204
+ filePath,
205
+ );
206
+ setComments(previousComments, filePath);
207
+ }
208
+ }
209
+
210
+ async function reanchorComment(
211
+ filePath: string,
212
+ id: string,
213
+ selectedText: string,
214
+ startOffset: number,
215
+ endOffset: number,
216
+ ) {
217
+ const docState = app.documents.get(filePath);
218
+ const previousComments = [...(docState?.comments ?? [])];
219
+
220
+ setComments(
221
+ previousComments.map((c) =>
222
+ c.id === id
223
+ ? {
224
+ ...c,
225
+ selectedText,
226
+ startOffset,
227
+ endOffset,
228
+ anchorConfidence: AnchorConfidences.EXACT,
229
+ }
230
+ : c,
231
+ ),
232
+ filePath,
233
+ );
234
+
235
+ setCommentsError(null, filePath);
236
+ try {
237
+ const response = await fetchOrThrow(
238
+ `/api/comments/${id}/reanchor?path=${encodeURIComponent(filePath)}`,
239
+ {
240
+ method: "PUT",
241
+ headers: { "Content-Type": "application/json" },
242
+ body: JSON.stringify({ selectedText, startOffset, endOffset }),
243
+ },
244
+ "Failed to re-anchor comment",
245
+ );
246
+ const data = await response.json();
247
+ const current = app.documents.get(filePath)?.comments ?? [];
248
+ setComments(
249
+ current.map((c) => (c.id === id ? data.comment : c)),
250
+ filePath,
251
+ );
252
+ } catch (err) {
253
+ console.error("Failed to re-anchor comment:", err);
254
+ setCommentsError(
255
+ err instanceof Error ? err.message : "Failed to re-anchor comment",
256
+ filePath,
257
+ );
258
+ setComments(previousComments, filePath);
259
+ }
260
+ }
261
+
262
+ function registerHighlighter(
263
+ filePath: string,
264
+ focused: (id: string | undefined) => void,
265
+ scrollTo: (id: string) => void,
266
+ ) {
267
+ highlighterMap.set(filePath, { setFocused: focused, scrollTo });
268
+ }
269
+
270
+ function unregisterHighlighter(filePath: string) {
271
+ highlighterMap.delete(filePath);
272
+ }
273
+
274
+ function navigateToComment(commentId: string) {
275
+ const active = app.activeDocumentPath;
276
+ const entry = active ? highlighterMap.get(active) : undefined;
277
+ entry?.scrollTo(commentId);
278
+ setHoveredCommentId(commentId);
279
+ entry?.setFocused(commentId);
280
+ clearTimeout(hoverTimeout);
281
+ hoverTimeout = setTimeout(() => {
282
+ setHoveredCommentId(undefined);
283
+ entry?.setFocused(undefined);
284
+ }, 1500);
285
+ }
286
+
287
+ function navigatePrevious(sortedComments: Comment[]) {
288
+ if (sortedComments.length === 0) return;
289
+ currentIndex =
290
+ currentIndex === 0 ? sortedComments.length - 1 : currentIndex - 1;
291
+ navigateToComment(sortedComments[currentIndex].id);
292
+ }
293
+
294
+ function navigateNext(sortedComments: Comment[]) {
295
+ if (sortedComments.length === 0) return;
296
+ currentIndex =
297
+ currentIndex === sortedComments.length - 1 ? 0 : currentIndex + 1;
298
+ navigateToComment(sortedComments[currentIndex].id);
299
+ }
300
+
301
+ function copyComment(comment: Comment) {
302
+ navigator.clipboard.writeText(formatComment(comment));
303
+ }
304
+
305
+ function onTextSelect(
306
+ filePath: string,
307
+ text: string,
308
+ startOffset: number,
309
+ endOffset: number,
310
+ selectionTop: number,
311
+ ) {
312
+ setActiveCommentId(undefined);
313
+ setSelection({ text, startOffset, endOffset }, filePath);
314
+ setPendingSelectionTop(selectionTop, filePath);
315
+ }
316
+
317
+ function clearSelection(filePath: string) {
318
+ setSelection(null, filePath);
319
+ setPendingSelectionTop(undefined, filePath);
320
+ clearPendingHighlight();
321
+ window.getSelection()?.removeAllRanges();
322
+ }
323
+
324
+ function handleClickOutside(e: MouseEvent) {
325
+ const target = e.target as HTMLElement;
326
+ if (target.closest("[data-comment-input]")) return;
327
+
328
+ if (!app.activeDocumentPath) return;
329
+ const docState = app.documents.get(app.activeDocumentPath);
330
+ if (!docState?.selection) return;
331
+
332
+ setSelection(null, app.activeDocumentPath);
333
+ setPendingSelectionTop(undefined, app.activeDocumentPath);
334
+ clearPendingHighlight();
335
+ requestAnimationFrame(() => {
336
+ const sel = window.getSelection();
337
+ if (sel?.isCollapsed) {
338
+ sel.removeAllRanges();
339
+ }
340
+ });
341
+ }
342
+
343
+ function handleCopyAll(filePath: string) {
344
+ const docState = app.documents.get(filePath);
345
+ if (!docState) return;
346
+ navigator.clipboard.writeText(
347
+ generatePrompt(docState.comments, docState.document.fileName),
348
+ );
349
+ }
350
+
351
+ function handleExportJson(filePath: string) {
352
+ const docState = app.documents.get(filePath);
353
+ if (!docState) return;
354
+ exportCommentsAsJson(docState.comments, docState.document);
355
+ }
356
+
357
+ function handleAddComment(filePath: string, commentText: string) {
358
+ const docState = app.documents.get(filePath);
359
+ if (!docState?.selection) return;
360
+ const { text, startOffset, endOffset } = docState.selection;
361
+ addComment(filePath, text, commentText, startOffset, endOffset);
362
+ clearSelection(filePath);
363
+ }
364
+
365
+ function handleConfirmReanchor(filePath: string) {
366
+ const docState = app.documents.get(filePath);
367
+ if (!docState?.selection || !docState.reanchorTarget) return;
368
+ const { text, startOffset, endOffset } = docState.selection;
369
+ reanchorComment(
370
+ filePath,
371
+ docState.reanchorTarget.commentId,
372
+ text,
373
+ startOffset,
374
+ endOffset,
375
+ );
376
+ setReanchorTarget(null, filePath);
377
+ clearSelection(filePath);
378
+ }
379
+
380
+ function handleCancelReanchor(filePath: string) {
381
+ setReanchorTarget(null, filePath);
382
+ clearSelection(filePath);
383
+ }
384
+
385
+ function handleHighlightClick(commentId: string) {
386
+ // On narrow viewports where margin notes are hidden, show floating overlay
387
+ const marginColumn = document.querySelector("[data-margin-column]");
388
+ const isMarginVisible =
389
+ marginColumn && getComputedStyle(marginColumn).display !== "none";
390
+
391
+ if (isMarginVisible) {
392
+ const marginNote = document.querySelector(
393
+ `article[data-comment-id="${commentId}"]`,
394
+ );
395
+ if (marginNote) {
396
+ marginNote.scrollIntoView({ behavior: "smooth", block: "center" });
397
+ }
398
+ } else {
399
+ // Show floating comment overlay
400
+ setActiveCommentId(commentId);
401
+ }
402
+ }
403
+
404
+ function scrollToHeading(id: string) {
405
+ const rect = document.getElementById(id)?.getBoundingClientRect();
406
+ if (!rect) return;
407
+ const elementTop = window.scrollY + rect.top;
408
+ const scrollTarget = Math.max(0, elementTop - window.innerHeight * 0.25);
409
+ window.scrollTo({ top: scrollTarget, behavior: "smooth" });
410
+ }
411
+
412
+ function startReanchor(filePath: string, commentId: string) {
413
+ setReanchorTarget({ commentId }, filePath);
414
+ }
415
+
416
+ let heartbeatSource: EventSource | undefined;
417
+ let documentStreamSource: EventSource | undefined;
418
+
419
+ async function initialize() {
420
+ // If already hydrated by main.ts from inline data, skip
421
+ if (app.documentOrder.length > 0) {
422
+ isInitialized = true;
423
+ return;
424
+ }
425
+
426
+ // Fallback: fetch from API (e.g. if inline data was missing)
427
+ try {
428
+ const res = await fetch("/api/documents");
429
+ if (!res.ok) throw new Error(`Server error: ${res.status}`);
430
+ const data = await res.json();
431
+
432
+ const clean = data.clean || false;
433
+ if (data.workingDirectory) setWorkingDirectory(data.workingDirectory);
434
+
435
+ for (const file of data.files) {
436
+ openDocument(
437
+ { html: "", filePath: file.path, fileName: file.fileName, clean },
438
+ { active: false },
439
+ );
440
+ }
441
+
442
+ if (data.files.length > 0) {
443
+ setActiveDocument(data.files[0].path);
444
+ }
445
+
446
+ initSettings();
447
+ initShortcuts(data.settings?.keybindings ?? []);
448
+ } catch (err) {
449
+ error = err instanceof Error ? err.message : "Failed to load documents";
450
+ } finally {
451
+ isInitialized = true;
452
+ }
453
+ }
454
+
455
+ function setupDocumentStream() {
456
+ let reconnectDelay = 1000;
457
+ const MAX_RECONNECT_DELAY = 30000;
458
+
459
+ function connect() {
460
+ documentStreamSource = new EventSource("/api/document/stream");
461
+
462
+ documentStreamSource.onopen = () => {
463
+ reconnectDelay = 1000; // Reset on successful connection
464
+ };
465
+
466
+ documentStreamSource.onmessage = async (e) => {
467
+ try {
468
+ const data = JSON.parse(e.data);
469
+ if (data.type === "document-added" && data.path) {
470
+ openDocument(
471
+ {
472
+ html: "",
473
+ filePath: data.path,
474
+ fileName: data.fileName,
475
+ clean: false,
476
+ },
477
+ { active: false },
478
+ );
479
+ return;
480
+ }
481
+ if (data.type === "document-updated" && data.path) {
482
+ const path = data.path;
483
+ const state = app.documents.get(path);
484
+ if (!state?.document.html) return;
485
+
486
+ // Fetch updated document and comments in parallel
487
+ const [docRes, commentsRes] = await Promise.all([
488
+ fetch(`/api/document?path=${encodeURIComponent(path)}`),
489
+ fetch(`/api/comments?path=${encodeURIComponent(path)}`),
490
+ ]);
491
+
492
+ if (docRes.ok) {
493
+ const doc = await docRes.json();
494
+ setHeadings(doc.headings ?? [], path);
495
+ updateDocumentHtml(doc.html, path);
496
+ }
497
+ if (commentsRes.ok) {
498
+ const commentsData = await commentsRes.json();
499
+ setComments(commentsData.comments ?? [], path);
500
+ }
501
+ }
502
+ } catch (err) {
503
+ // SSE message parse failure — non-critical, stream will continue
504
+ console.warn("Failed to parse document stream message:", err);
505
+ }
506
+ };
507
+
508
+ documentStreamSource.onerror = () => {
509
+ documentStreamSource?.close();
510
+ // Auto-reconnect with exponential backoff
511
+ setTimeout(() => {
512
+ reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY);
513
+ connect();
514
+ }, reconnectDelay);
515
+ };
516
+ }
517
+
518
+ connect();
519
+ }
520
+
521
+ $effect(() => {
522
+ const path = app.activeDocumentPath;
523
+ if (!path) return;
524
+ const state = app.documents.get(path);
525
+ if (!state || state.document.html) return;
526
+
527
+ const query = `?path=${encodeURIComponent(path)}`;
528
+ const isClean = state.document.clean;
529
+
530
+ const docFetch = fetch(`/api/document${query}`).then((r) => {
531
+ if (!r.ok) throw new Error(`Server error: ${r.status}`);
532
+ return r.json();
533
+ });
534
+
535
+ const commentsFetch = isClean
536
+ ? fetch(`/api/comments${query}`, { method: "DELETE" }).then(
537
+ () => [] as unknown[],
538
+ )
539
+ : fetch(`/api/comments${query}`)
540
+ .then((r) => (r.ok ? r.json() : { comments: [] }))
541
+ .then((d) => d.comments || []);
542
+
543
+ Promise.all([docFetch, commentsFetch]).then(
544
+ ([docData, comments]) => {
545
+ setComments(comments as Comment[], path);
546
+ setHeadings(docData.headings ?? [], path);
547
+ updateDocumentHtml(docData.html, path);
548
+ },
549
+ (err) => {
550
+ error = err instanceof Error ? err.message : "Failed to load document";
551
+ },
552
+ );
553
+ });
554
+
555
+ async function reload() {
556
+ const path = app.activeDocumentPath;
557
+ if (!path) return;
558
+ try {
559
+ const res = await fetch(`/api/document?path=${encodeURIComponent(path)}`);
560
+ if (!res.ok) throw new Error(`Server error: ${res.status}`);
561
+ const data = await res.json();
562
+ setHeadings(data.headings ?? [], path);
563
+ updateDocumentHtml(data.html, path);
564
+
565
+ // Also refresh comments
566
+ const commentsRes = await fetch(
567
+ `/api/comments?path=${encodeURIComponent(path)}`,
568
+ );
569
+ if (commentsRes.ok) {
570
+ const commentsData = await commentsRes.json();
571
+ setComments(commentsData.comments ?? [], path);
572
+ }
573
+ } catch (err) {
574
+ console.error("Failed to reload:", err);
575
+ }
576
+ }
577
+
578
+ function handleKeyDown(event: KeyboardEvent) {
579
+ const target = event.target as HTMLElement;
580
+ const tagName = target.tagName;
581
+
582
+ if (
583
+ tagName === "INPUT" ||
584
+ tagName === "TEXTAREA" ||
585
+ target.isContentEditable
586
+ ) {
587
+ return;
588
+ }
589
+
590
+ if (event.metaKey) {
591
+ const digit = Number.parseInt(event.key, 10);
592
+ if (digit >= 1 && digit <= 9) {
593
+ if (app.documentOrder.length <= 1) return;
594
+ const targetIndex = Math.min(digit - 1, app.documentOrder.length - 1);
595
+ const targetPath = app.documentOrder[targetIndex];
596
+ if (targetPath) {
597
+ event.preventDefault();
598
+ setActiveDocument(targetPath);
599
+ }
600
+ return;
601
+ }
602
+ }
603
+
604
+ const filePath = app.activeDocumentPath;
605
+ if (!filePath) return;
606
+
607
+ const docState = app.documents.get(filePath);
608
+ if (!docState) return;
609
+
610
+ for (const shortcut of shortcutState.shortcuts) {
611
+ if (!shortcut.enabled) continue;
612
+ if (!matchesBinding(event, shortcut.binding)) continue;
613
+
614
+ event.preventDefault();
615
+
616
+ switch (shortcut.id) {
617
+ case ShortcutActions.COPY_ALL:
618
+ handleCopyAll(filePath);
619
+ break;
620
+ case ShortcutActions.COPY_ALL_RAW:
621
+ navigator.clipboard.writeText(
622
+ docState.comments.map(formatComment).join("\n\n---\n\n"),
623
+ );
624
+ break;
625
+ case ShortcutActions.NAVIGATE_NEXT:
626
+ navigateNext(docState.sortedComments);
627
+ break;
628
+ case ShortcutActions.NAVIGATE_PREVIOUS:
629
+ navigatePrevious(docState.sortedComments);
630
+ break;
631
+ case ShortcutActions.COPY_SELECTION_RAW: {
632
+ const sel = window.getSelection()?.toString();
633
+ if (sel) navigator.clipboard.writeText(sel);
634
+ break;
635
+ }
636
+ case ShortcutActions.COPY_SELECTION_LLM: {
637
+ const selText = window.getSelection()?.toString();
638
+ if (selText) {
639
+ const context = `# Selected Text from ${docState.document.fileName}\n\n${selText}`;
640
+ navigator.clipboard.writeText(context);
641
+ }
642
+ break;
643
+ }
644
+ case ShortcutActions.CLEAR_SELECTION:
645
+ clearSelection(filePath);
646
+ break;
647
+ }
648
+
649
+ return;
650
+ }
651
+ }
652
+
653
+ $effect(() => {
654
+ for (const filePath of app.documentOrder) {
655
+ const isActive = filePath === app.activeDocumentPath;
656
+ const wasActive = prevActiveMap.get(filePath) ?? false;
657
+
658
+ if (wasActive && !isActive) {
659
+ untrack(() => setScrollY(window.scrollY, filePath));
660
+ }
661
+
662
+ if (!wasActive && isActive) {
663
+ const savedY = app.documents.get(filePath)?.scrollY ?? 0;
664
+ requestAnimationFrame(() => {
665
+ requestAnimationFrame(() => {
666
+ window.scrollTo(0, savedY);
667
+ });
668
+ });
669
+ }
670
+
671
+ prevActiveMap.set(filePath, isActive);
672
+ }
673
+ });
674
+
675
+ $effect(() => {
676
+ const docState = getActiveDocumentState();
677
+ if (!docState) return;
678
+ const max = docState.sortedComments.length - 1;
679
+ if (max >= 0 && untrack(() => currentIndex) > max) {
680
+ currentIndex = max;
681
+ }
682
+ });
683
+
684
+ onMount(() => {
685
+ initialize();
686
+
687
+ heartbeatSource = new EventSource("/api/heartbeat");
688
+ setupDocumentStream();
689
+
690
+ window.addEventListener("keydown", handleKeyDown);
691
+ document.addEventListener("mousedown", handleClickOutside);
692
+ });
693
+
694
+ onDestroy(() => {
695
+ heartbeatSource?.close();
696
+ documentStreamSource?.close();
697
+ clearTimeout(hoverTimeout);
698
+ window.removeEventListener("keydown", handleKeyDown);
699
+ document.removeEventListener("mousedown", handleClickOutside);
700
+
701
+ for (const pos of positionsMap.values()) {
702
+ pos.dispose();
703
+ }
704
+ });
705
+ </script>
706
+
707
+ {#if error}
708
+ <div class="min-h-screen bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 flex items-center justify-center">
709
+ <div class="text-red-600">{error}</div>
710
+ </div>
711
+ {:else if !isInitialized}
712
+ <div class="min-h-screen bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 flex items-center justify-center">
713
+ <div class="text-zinc-500 dark:text-zinc-400">
714
+ {t("app.loading")}
715
+ </div>
716
+ </div>
717
+ {:else if app.documentOrder.length === 0}
718
+ <div class="min-h-screen bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 flex flex-col">
719
+ <TabBar />
720
+ <div class="flex-1 flex flex-col items-center justify-center gap-3">
721
+ <p class="text-zinc-400 dark:text-zinc-500 text-sm">
722
+ {t("app.noDocuments")}
723
+ </p>
724
+ <p class="text-zinc-400 dark:text-zinc-500 text-xs">
725
+ {t("app.noDocumentsHintPrefix")}
726
+ {#if t("app.noDocumentsHintPrefix")}{" "}{/if}
727
+ <code class="bg-zinc-100 dark:bg-zinc-800 px-1.5 py-0.5 rounded text-xs">
728
+ readit open &lt;file.md&gt;
729
+ </code>
730
+ {" "}
731
+ {t("app.noDocumentsHintSuffix")}
732
+ </p>
733
+ </div>
734
+ </div>
735
+ {:else}
736
+ <TabBar />
737
+
738
+ {#each app.documentOrder as filePath (filePath)}
739
+ {@const docState = app.documents.get(filePath)}
740
+ {@const isActive = filePath === app.activeDocumentPath}
741
+ {@const hasContent = !!docState?.document.html}
742
+
743
+ {#if hasContent || isActive}
744
+ <div style={isActive ? undefined : "display: none"}>
745
+ {#if !hasContent}
746
+ <div class="min-h-screen bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 flex items-center justify-center">
747
+ <div class="text-zinc-500 dark:text-zinc-400">
748
+ {t("app.loading")}
749
+ </div>
750
+ </div>
751
+ {:else if docState}
752
+ {@const headings = docState.headings}
753
+ {@const comments = docState.comments}
754
+ {@const sortedComments = docState.sortedComments}
755
+ {@const selection = docState.selection}
756
+ {@const pendingSelectionTop = docState.pendingSelectionTop}
757
+ {@const reanchorTarget = docState.reanchorTarget}
758
+
759
+ <div class="min-h-screen bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 flex flex-col overflow-x-hidden">
760
+ <Header
761
+ fileName={docState.document.fileName}
762
+ {comments}
763
+ hasReanchorTarget={reanchorTarget !== null}
764
+ oncopyall={() => handleCopyAll(filePath)}
765
+ onexportjson={() => handleExportJson(filePath)}
766
+ onreload={reload}
767
+ onedit={(id, text) => editComment(filePath, id, text)}
768
+ ondelete={(id) => deleteComment(filePath, id)}
769
+ ondeleteall={() => deleteAllComments(filePath)}
770
+ onnavigate={navigateToComment}
771
+ onstartreanchor={(id) => startReanchor(filePath, id)}
772
+ />
773
+
774
+ <CommentErrorBanner
775
+ error={docState.commentsError}
776
+ ondismiss={() => setCommentsError(null, filePath)}
777
+ />
778
+
779
+ <div class="flex-1 flex gap-4 w-full max-w-7xl mx-auto overflow-x-hidden">
780
+ {#if headings.length > 0}
781
+ <aside class="w-48 flex-shrink-0 py-6 pl-6 hidden xl:block">
782
+ <div class="sticky top-64 max-h-[calc(100vh-17rem)] overflow-y-auto">
783
+ <TableOfContents
784
+ {headings}
785
+ onheadingclick={scrollToHeading}
786
+ />
787
+ </div>
788
+ </aside>
789
+ {/if}
790
+
791
+ <div class="flex-1 px-6 py-6">
792
+ <DocumentViewer
793
+ content={docState.document.html}
794
+ {comments}
795
+ {isActive}
796
+ onTextSelect={(text, start, end, top) => onTextSelect(filePath, text, start, end, top)}
797
+ onHighlightHover={(id) => {
798
+ setHoveredCommentId(id);
799
+ const entry = highlighterMap.get(filePath);
800
+ entry?.setFocused(id);
801
+ }}
802
+ onHighlightClick={handleHighlightClick}
803
+ registerHighlighter={(focused, scrollTo) => registerHighlighter(filePath, focused, scrollTo)}
804
+ unregisterHighlighter={() => unregisterHighlighter(filePath)}
805
+ positions={getPositions(filePath)}
806
+ />
807
+ </div>
808
+
809
+ <div data-margin-column class="w-72 flex-shrink-0 py-6 pr-4 relative hidden lg:block">
810
+ {#if selection && pendingSelectionTop !== undefined}
811
+ <div
812
+ class="absolute left-0 right-0 z-10 bg-white dark:bg-zinc-900"
813
+ style="top: {pendingSelectionTop}px"
814
+ >
815
+ {#if reanchorTarget !== null}
816
+ <ReanchorConfirm
817
+ selectionText={selection.text}
818
+ onconfirm={() => handleConfirmReanchor(filePath)}
819
+ oncancel={() => handleCancelReanchor(filePath)}
820
+ />
821
+ {:else}
822
+ <CommentInput
823
+ selectedText={selection.text}
824
+ onsubmit={(text) => handleAddComment(filePath, text)}
825
+ oncancel={() => clearSelection(filePath)}
826
+ />
827
+ {/if}
828
+ </div>
829
+ {/if}
830
+
831
+ <MarginNotesContainer
832
+ {sortedComments}
833
+ positions={getPositions(filePath)}
834
+ onedit={(id, text) => editComment(filePath, id, text)}
835
+ ondelete={(id) => deleteComment(filePath, id)}
836
+ oncopy={copyComment}
837
+ onnavigate={navigateToComment}
838
+ />
839
+ </div>
840
+ </div>
841
+
842
+ <!-- Floating comment input for narrow viewports (below lg) -->
843
+ {#if selection && pendingSelectionTop !== undefined}
844
+ <div class="fixed bottom-16 left-4 right-4 z-50 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 rounded-lg shadow-lg p-4 lg:hidden">
845
+ {#if reanchorTarget !== null}
846
+ <ReanchorConfirm
847
+ selectionText={selection.text}
848
+ onconfirm={() => handleConfirmReanchor(filePath)}
849
+ oncancel={() => handleCancelReanchor(filePath)}
850
+ />
851
+ {:else}
852
+ <CommentInput
853
+ selectedText={selection.text}
854
+ onsubmit={(text) => handleAddComment(filePath, text)}
855
+ oncancel={() => clearSelection(filePath)}
856
+ />
857
+ {/if}
858
+ </div>
859
+ {/if}
860
+
861
+ <!-- Floating comment viewer for narrow viewports (click highlight to show) -->
862
+ {#if ui.activeCommentId}
863
+ {@const activeComment = comments.find((c) => c.id === ui.activeCommentId)}
864
+ {#if activeComment}
865
+ <FloatingComment
866
+ comment={activeComment}
867
+ onedit={(id, text) => editComment(filePath, id, text)}
868
+ ondelete={(id) => deleteComment(filePath, id)}
869
+ oncopy={copyComment}
870
+ onnavigate={navigateToComment}
871
+ />
872
+ {/if}
873
+ {/if}
874
+
875
+ <CommentNav
876
+ {sortedComments}
877
+ {currentIndex}
878
+ onprevious={() => navigatePrevious(sortedComments)}
879
+ onnext={() => navigateNext(sortedComments)}
880
+ />
881
+
882
+ <footer class="py-4 text-center text-sm text-zinc-400 dark:text-zinc-500">
883
+ {t("app.footer")}
884
+ </footer>
885
+ </div>
886
+ {/if}
887
+ </div>
888
+ {/if}
889
+ {/each}
890
+ {/if}