@peaske7/readit 0.2.0 → 0.2.1

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