@peaske7/readit 0.1.8 → 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 (221) 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 -5
  8. package/biome.json +18 -8
  9. package/bun.lock +426 -710
  10. package/bunfig.toml +2 -0
  11. package/docs/perf-baseline.md +130 -0
  12. package/docs/superpowers/plans/2026-03-26-surgical-pruning.md +1176 -0
  13. package/docs/superpowers/specs/2026-03-27-go-server-rewrite-design.md +284 -0
  14. package/e2e/comments.spec.ts +14 -58
  15. package/e2e/document-load.spec.ts +1 -23
  16. package/e2e/export.spec.ts +4 -4
  17. package/e2e/perf/add-comment.spec.ts +116 -0
  18. package/e2e/perf/fixtures/generate.ts +327 -0
  19. package/e2e/perf/initial-load.spec.ts +49 -0
  20. package/e2e/perf/perf.setup.ts +23 -0
  21. package/e2e/perf/perf.teardown.ts +9 -0
  22. package/e2e/perf/screenshot-final.png +0 -0
  23. package/e2e/perf/scroll.spec.ts +39 -0
  24. package/e2e/perf/tab-switch.spec.ts +69 -0
  25. package/e2e/perf/text-selection.spec.ts +119 -0
  26. package/e2e/perf/utils/metrics.ts +350 -0
  27. package/e2e/perf/utils/perf-cli.ts +86 -0
  28. package/e2e/persistence-file.spec.ts +41 -26
  29. package/e2e/utils/selection.ts +17 -73
  30. package/go/cmd/readit/main.go +416 -0
  31. package/go/go.mod +20 -0
  32. package/go/go.sum +41 -0
  33. package/go/internal/server/anchor.go +302 -0
  34. package/go/internal/server/anchor_test.go +111 -0
  35. package/go/internal/server/comments.go +390 -0
  36. package/go/internal/server/documents.go +113 -0
  37. package/go/internal/server/embed.go +17 -0
  38. package/go/internal/server/headings.go +33 -0
  39. package/go/internal/server/headings_test.go +75 -0
  40. package/go/internal/server/htmltext.go +123 -0
  41. package/go/internal/server/markdown.go +157 -0
  42. package/go/internal/server/markdown_bench_test.go +42 -0
  43. package/go/internal/server/markdown_test.go +79 -0
  44. package/go/internal/server/server.go +453 -0
  45. package/go/internal/server/server_bench_test.go +122 -0
  46. package/go/internal/server/settings.go +110 -0
  47. package/go/internal/server/sse.go +140 -0
  48. package/go/internal/server/storage.go +275 -0
  49. package/go/internal/server/storage_test.go +118 -0
  50. package/go/internal/server/template.go +66 -0
  51. package/go/internal/server/types.go +101 -0
  52. package/go/internal/server/watcher.go +74 -0
  53. package/index.html +4 -14
  54. package/nvim-readit/lua/readit/health.lua +64 -0
  55. package/nvim-readit/lua/readit/init.lua +463 -0
  56. package/nvim-readit/plugin/readit.lua +19 -0
  57. package/package.json +24 -41
  58. package/playwright.config.ts +12 -0
  59. package/shell/_readit +158 -0
  60. package/shell/readit.zsh +87 -0
  61. package/src/App.svelte +881 -0
  62. package/src/{cli/index.ts → cli.ts} +216 -70
  63. package/src/components/ActionsMenu.svelte +95 -0
  64. package/src/components/CommentBadge.svelte +67 -0
  65. package/src/components/CommentErrorBanner.svelte +33 -0
  66. package/src/components/CommentInput.svelte +75 -0
  67. package/src/components/CommentListItem.svelte +95 -0
  68. package/src/components/CommentManager.svelte +129 -0
  69. package/src/components/CommentNav.svelte +109 -0
  70. package/src/components/DocumentViewer.svelte +218 -0
  71. package/src/components/FloatingComment.svelte +107 -0
  72. package/src/components/Header.svelte +76 -0
  73. package/src/components/InlineEditor.svelte +72 -0
  74. package/src/components/MarginNote.svelte +167 -0
  75. package/src/components/MarginNotesContainer.svelte +33 -0
  76. package/src/components/RawModal.svelte +126 -0
  77. package/src/components/ReanchorConfirm.svelte +30 -0
  78. package/src/components/SettingsModal.svelte +220 -0
  79. package/src/components/ShortcutCapture.svelte +82 -0
  80. package/src/components/ShortcutList.svelte +145 -0
  81. package/src/components/TabBar.svelte +52 -0
  82. package/src/components/TableOfContents.svelte +125 -0
  83. package/src/components/ui/ActionLink.svelte +40 -0
  84. package/src/components/ui/Button.svelte +53 -0
  85. package/src/components/ui/Dialog.svelte +97 -0
  86. package/src/components/ui/DropdownMenu.svelte +85 -0
  87. package/src/components/ui/DropdownMenuItem.svelte +38 -0
  88. package/src/components/ui/DropdownMenuSeparator.svelte +11 -0
  89. package/src/components/ui/Text.svelte +42 -0
  90. package/src/env.d.ts +6 -0
  91. package/src/index.css +36 -166
  92. package/src/lib/__fixtures__/bench-data.ts +1 -54
  93. package/src/lib/anchor.bench.ts +47 -68
  94. package/src/lib/anchor.test.ts +5 -9
  95. package/src/lib/anchor.ts +9 -93
  96. package/src/lib/comment-storage.bench.ts +6 -20
  97. package/src/lib/comment-storage.test.ts +45 -37
  98. package/src/lib/comment-storage.ts +23 -64
  99. package/src/lib/export.bench.ts +9 -23
  100. package/src/lib/export.ts +7 -14
  101. package/src/lib/headings.test.ts +103 -0
  102. package/src/lib/headings.ts +44 -0
  103. package/src/lib/highlight/core.test.ts +1 -6
  104. package/src/lib/highlight/dom.ts +53 -280
  105. package/src/lib/highlight/highlight-registry.ts +221 -0
  106. package/src/lib/highlight/highlight.bench.ts +92 -0
  107. package/src/lib/highlight/highlighter.ts +122 -302
  108. package/src/lib/highlight/{core.ts → resolver.ts} +3 -19
  109. package/src/lib/highlight/types.ts +0 -40
  110. package/src/lib/html-text.test.ts +162 -0
  111. package/src/lib/html-text.ts +161 -0
  112. package/src/lib/i18n/en.ts +13 -36
  113. package/src/lib/i18n/ja.ts +14 -37
  114. package/src/lib/i18n/types.ts +13 -36
  115. package/src/lib/margin-layout.bench.ts +48 -15
  116. package/src/lib/margin-layout.ts +2 -31
  117. package/src/lib/markdown-renderer.test.ts +154 -0
  118. package/src/lib/markdown-renderer.ts +177 -0
  119. package/src/lib/mermaid-config.ts +38 -0
  120. package/src/lib/mermaid-renderer.ts +162 -0
  121. package/src/lib/mermaid-worker.ts +60 -0
  122. package/src/lib/positions.ts +157 -0
  123. package/src/lib/shortcut-registry.ts +138 -103
  124. package/src/lib/utils.ts +2 -48
  125. package/src/main.ts +16 -0
  126. package/src/schema.ts +92 -0
  127. package/src/{server/index.ts → server.ts} +427 -163
  128. package/src/stores/app.svelte.ts +231 -0
  129. package/src/stores/locale.svelte.ts +46 -0
  130. package/src/stores/settings.svelte.ts +90 -0
  131. package/src/stores/shortcuts.svelte.ts +104 -0
  132. package/src/stores/ui.svelte.ts +12 -0
  133. package/src/template.ts +104 -0
  134. package/src/test-setup.ts +47 -0
  135. package/svelte.config.js +5 -0
  136. package/tsconfig.json +2 -2
  137. package/vite.config.ts +31 -3
  138. package/vscode-readit/.mcp.json +7 -0
  139. package/vscode-readit/.vscodeignore +7 -0
  140. package/vscode-readit/bun.lock +78 -0
  141. package/vscode-readit/icon.svg +10 -0
  142. package/vscode-readit/package.json +110 -0
  143. package/vscode-readit/src/extension.ts +117 -0
  144. package/vscode-readit/src/server-manager.ts +272 -0
  145. package/vscode-readit/src/webview-provider.ts +204 -0
  146. package/vscode-readit/tsconfig.json +20 -0
  147. package/e2e/fixtures/sample.html +0 -13
  148. package/src/App.tsx +0 -416
  149. package/src/components/ActionsMenu.tsx +0 -112
  150. package/src/components/DocumentViewer/CodeBlock.tsx +0 -160
  151. package/src/components/DocumentViewer/DocumentViewer.tsx +0 -259
  152. package/src/components/DocumentViewer/IframeContainer.tsx +0 -251
  153. package/src/components/DocumentViewer/InlineCode.tsx +0 -60
  154. package/src/components/DocumentViewer/MermaidDiagram.tsx +0 -137
  155. package/src/components/DocumentViewer/index.ts +0 -1
  156. package/src/components/FloatingTOC.tsx +0 -61
  157. package/src/components/Header.tsx +0 -65
  158. package/src/components/InlineEditor.tsx +0 -74
  159. package/src/components/MarginNote.tsx +0 -207
  160. package/src/components/MarginNotes.tsx +0 -50
  161. package/src/components/RawModal.tsx +0 -143
  162. package/src/components/ReanchorConfirm.tsx +0 -36
  163. package/src/components/SettingsModal.tsx +0 -310
  164. package/src/components/ShortcutCapture.tsx +0 -48
  165. package/src/components/ShortcutList.tsx +0 -198
  166. package/src/components/TabBar.tsx +0 -60
  167. package/src/components/TableOfContents.tsx +0 -108
  168. package/src/components/comments/CommentBadge.tsx +0 -49
  169. package/src/components/comments/CommentInput.tsx +0 -114
  170. package/src/components/comments/CommentListItem.tsx +0 -92
  171. package/src/components/comments/CommentManager.tsx +0 -113
  172. package/src/components/comments/CommentMinimap.tsx +0 -62
  173. package/src/components/comments/CommentNav.tsx +0 -109
  174. package/src/components/ui/ActionBar.tsx +0 -16
  175. package/src/components/ui/ActionLink.tsx +0 -32
  176. package/src/components/ui/Button.tsx +0 -55
  177. package/src/components/ui/Dialog.tsx +0 -156
  178. package/src/components/ui/DropdownMenu.tsx +0 -114
  179. package/src/components/ui/SeparatorDot.tsx +0 -9
  180. package/src/components/ui/Text.tsx +0 -54
  181. package/src/contexts/CommentContext.tsx +0 -229
  182. package/src/contexts/LayoutContext.tsx +0 -88
  183. package/src/contexts/LocaleContext.tsx +0 -35
  184. package/src/hooks/useClickOutside.ts +0 -35
  185. package/src/hooks/useClipboard.ts +0 -82
  186. package/src/hooks/useCommentNavigation.ts +0 -130
  187. package/src/hooks/useComments.ts +0 -323
  188. package/src/hooks/useDocument.ts +0 -156
  189. package/src/hooks/useEditorScheme.ts +0 -51
  190. package/src/hooks/useFontPreference.ts +0 -59
  191. package/src/hooks/useHeadings.test.ts +0 -159
  192. package/src/hooks/useHeadings.ts +0 -129
  193. package/src/hooks/useKeybindings.ts +0 -108
  194. package/src/hooks/useKeyboardShortcuts.ts +0 -63
  195. package/src/hooks/useLayoutMode.ts +0 -44
  196. package/src/hooks/useLocalePreference.ts +0 -42
  197. package/src/hooks/useReanchorMode.ts +0 -33
  198. package/src/hooks/useScrollMetrics.ts +0 -56
  199. package/src/hooks/useScrollSpy.ts +0 -81
  200. package/src/hooks/useTextSelection.ts +0 -123
  201. package/src/hooks/useThemePreference.ts +0 -66
  202. package/src/lib/context.bench.ts +0 -41
  203. package/src/lib/context.test.ts +0 -224
  204. package/src/lib/context.ts +0 -193
  205. package/src/lib/editor-links.ts +0 -59
  206. package/src/lib/highlight/colors.ts +0 -37
  207. package/src/lib/highlight/index.ts +0 -23
  208. package/src/lib/highlight/script-builder.ts +0 -485
  209. package/src/lib/html-processor.test.tsx +0 -170
  210. package/src/lib/html-processor.tsx +0 -95
  211. package/src/lib/i18n/completeness.test.ts +0 -51
  212. package/src/lib/i18n/translations.test.ts +0 -39
  213. package/src/lib/layout-constants.ts +0 -12
  214. package/src/lib/scroll.test.ts +0 -118
  215. package/src/lib/scroll.ts +0 -47
  216. package/src/lib/shortcut-registry.test.ts +0 -173
  217. package/src/lib/utils.test.ts +0 -110
  218. package/src/main.tsx +0 -13
  219. package/src/store/index.test.ts +0 -242
  220. package/src/store/index.ts +0 -254
  221. package/src/types/index.ts +0 -127
@@ -0,0 +1,231 @@
1
+ import type { Heading } from "../lib/headings";
2
+ import type { Comment, Document, Selection } from "../schema";
3
+
4
+ export interface DocumentState {
5
+ document: Document;
6
+ headings: Heading[];
7
+ comments: Comment[];
8
+ commentsError: string | null;
9
+ sortedComments: Comment[];
10
+ selection: Selection | null;
11
+ pendingSelectionTop: number | undefined;
12
+ scrollY: number;
13
+ reanchorTarget: { commentId: string } | null;
14
+ }
15
+
16
+ interface InlineData {
17
+ files: { path: string; fileName: string }[];
18
+ activeFile: string;
19
+ clean: boolean;
20
+ workingDirectory: string;
21
+ documents: Record<
22
+ string,
23
+ {
24
+ html: string;
25
+ headings: { id: string; text: string; level: number }[];
26
+ comments: Comment[];
27
+ }
28
+ >;
29
+ settings: { version: number; fontFamily: string };
30
+ }
31
+
32
+ function createInitialDocumentState(doc: Document): DocumentState {
33
+ return {
34
+ document: doc,
35
+ headings: [],
36
+ comments: [],
37
+ commentsError: null,
38
+ sortedComments: [],
39
+ selection: null,
40
+ pendingSelectionTop: undefined,
41
+ scrollY: 0,
42
+ reanchorTarget: null,
43
+ };
44
+ }
45
+
46
+ function sortComments(comments: Comment[]): Comment[] {
47
+ return [...comments].sort((a, b) => a.startOffset - b.startOffset);
48
+ }
49
+
50
+ export const app = $state({
51
+ documents: new Map<string, DocumentState>(),
52
+ activeDocumentPath: null as string | null,
53
+ documentOrder: [] as string[],
54
+ workingDirectory: null as string | null,
55
+ });
56
+
57
+ export function getActiveDocumentState(): DocumentState | undefined {
58
+ if (!app.activeDocumentPath) return undefined;
59
+ return app.documents.get(app.activeDocumentPath);
60
+ }
61
+
62
+ export function setWorkingDirectory(dir: string): void {
63
+ app.workingDirectory = dir;
64
+ }
65
+
66
+ export function openDocument(doc: Document, opts?: { active?: boolean }): void {
67
+ const active = opts?.active ?? true;
68
+ const nextActive =
69
+ active || !app.activeDocumentPath ? doc.filePath : app.activeDocumentPath;
70
+
71
+ if (app.documents.has(doc.filePath)) {
72
+ const prevDoc = app.documents.get(doc.filePath)!;
73
+ const newDocs = new Map(app.documents);
74
+ newDocs.set(doc.filePath, {
75
+ ...prevDoc,
76
+ document: { ...prevDoc.document, ...doc },
77
+ });
78
+ app.documents = newDocs;
79
+ app.activeDocumentPath = nextActive;
80
+ return;
81
+ }
82
+
83
+ const newDocs = new Map(app.documents);
84
+ newDocs.set(doc.filePath, createInitialDocumentState(doc));
85
+ app.documents = newDocs;
86
+ app.activeDocumentPath = nextActive;
87
+ app.documentOrder = [...app.documentOrder, doc.filePath];
88
+ }
89
+
90
+ export function closeDocument(filePath: string): void {
91
+ const newDocs = new Map(app.documents);
92
+ newDocs.delete(filePath);
93
+
94
+ const newOrder = app.documentOrder.filter((p) => p !== filePath);
95
+
96
+ let newActive = app.activeDocumentPath;
97
+ if (app.activeDocumentPath === filePath) {
98
+ const oldIndex = app.documentOrder.indexOf(filePath);
99
+ newActive = newOrder[oldIndex] ?? newOrder[oldIndex - 1] ?? null;
100
+ }
101
+
102
+ app.documents = newDocs;
103
+ app.documentOrder = newOrder;
104
+ app.activeDocumentPath = newActive;
105
+ }
106
+
107
+ export function setActiveDocument(filePath: string): void {
108
+ if (app.documents.has(filePath)) {
109
+ app.activeDocumentPath = filePath;
110
+ }
111
+ }
112
+
113
+ function resolveFilePath(filePath?: string): string | null {
114
+ return filePath ?? app.activeDocumentPath;
115
+ }
116
+
117
+ function updateDocState(
118
+ filePath: string,
119
+ updater: (state: DocumentState) => Partial<DocumentState>,
120
+ ): void {
121
+ const docState = app.documents.get(filePath);
122
+ if (!docState) return;
123
+
124
+ const updates = updater(docState);
125
+ const newDocs = new Map(app.documents);
126
+ newDocs.set(filePath, { ...docState, ...updates });
127
+ app.documents = newDocs;
128
+ }
129
+
130
+ export function setComments(comments: Comment[], filePath?: string): void {
131
+ const path = resolveFilePath(filePath);
132
+ if (!path) return;
133
+ updateDocState(path, () => ({
134
+ comments,
135
+ sortedComments: sortComments(comments),
136
+ }));
137
+ }
138
+
139
+ export function setCommentsError(
140
+ error: string | null,
141
+ filePath?: string,
142
+ ): void {
143
+ const path = resolveFilePath(filePath);
144
+ if (!path) return;
145
+ updateDocState(path, () => ({ commentsError: error }));
146
+ }
147
+
148
+ export function setSelection(
149
+ selection: Selection | null,
150
+ filePath?: string,
151
+ ): void {
152
+ const path = resolveFilePath(filePath);
153
+ if (!path) return;
154
+ updateDocState(path, () => ({ selection }));
155
+ }
156
+
157
+ export function setPendingSelectionTop(
158
+ top: number | undefined,
159
+ filePath?: string,
160
+ ): void {
161
+ const path = resolveFilePath(filePath);
162
+ if (!path) return;
163
+ updateDocState(path, () => ({ pendingSelectionTop: top }));
164
+ }
165
+
166
+ export function setScrollY(y: number, filePath?: string): void {
167
+ const path = resolveFilePath(filePath);
168
+ if (!path) return;
169
+ updateDocState(path, () => ({ scrollY: y }));
170
+ }
171
+
172
+ export function setReanchorTarget(
173
+ target: { commentId: string } | null,
174
+ filePath?: string,
175
+ ): void {
176
+ const path = resolveFilePath(filePath);
177
+ if (!path) return;
178
+ updateDocState(path, () => ({ reanchorTarget: target }));
179
+ }
180
+
181
+ export function updateDocumentHtml(html: string, filePath?: string): void {
182
+ const path = resolveFilePath(filePath);
183
+ if (!path) return;
184
+ updateDocState(path, (s) => ({
185
+ document: { ...s.document, html },
186
+ }));
187
+ }
188
+
189
+ export function setHeadings(headings: Heading[], filePath?: string): void {
190
+ const path = resolveFilePath(filePath);
191
+ if (!path) return;
192
+ updateDocState(path, () => ({ headings }));
193
+ }
194
+
195
+ export function hydrateFromInlineData(data: InlineData): void {
196
+ app.workingDirectory = data.workingDirectory;
197
+
198
+ const newDocs = new Map<string, DocumentState>();
199
+ const order: string[] = [];
200
+
201
+ const articleEl =
202
+ typeof document !== "undefined"
203
+ ? document.getElementById("document-content")
204
+ : null;
205
+
206
+ for (const file of data.files) {
207
+ const docData = data.documents[file.path];
208
+ const isActiveFile = file.path === data.activeFile;
209
+ const doc: Document = {
210
+ html: docData?.html ?? (isActiveFile ? (articleEl?.innerHTML ?? "") : ""),
211
+ filePath: file.path,
212
+ fileName: file.fileName,
213
+ clean: data.clean,
214
+ };
215
+
216
+ const comments = docData?.comments ?? [];
217
+ const headings = (docData?.headings ?? []) as Heading[];
218
+
219
+ newDocs.set(file.path, {
220
+ ...createInitialDocumentState(doc),
221
+ comments,
222
+ sortedComments: sortComments(comments),
223
+ headings,
224
+ });
225
+ order.push(file.path);
226
+ }
227
+
228
+ app.documents = newDocs;
229
+ app.documentOrder = order;
230
+ app.activeDocumentPath = data.activeFile;
231
+ }
@@ -0,0 +1,46 @@
1
+ import {
2
+ createT,
3
+ type Locale,
4
+ Locales,
5
+ type TranslationKey,
6
+ } from "../lib/i18n";
7
+
8
+ const STORAGE_KEY = "readit:locale";
9
+
10
+ function detectLocale(): Locale {
11
+ const browserLang = navigator.language.slice(0, 2).toLowerCase();
12
+ if (browserLang === "ja") return Locales.JA;
13
+ return Locales.EN;
14
+ }
15
+
16
+ function getStoredLocale(): Locale {
17
+ try {
18
+ const stored = localStorage.getItem(STORAGE_KEY);
19
+ if (stored === Locales.JA || stored === Locales.EN) {
20
+ return stored;
21
+ }
22
+ } catch {
23
+ // localStorage may be unavailable
24
+ }
25
+ return detectLocale();
26
+ }
27
+
28
+ export const localeState = $state({
29
+ locale: getStoredLocale() as Locale,
30
+ });
31
+
32
+ export function setLocale(newLocale: Locale): void {
33
+ localeState.locale = newLocale;
34
+ try {
35
+ localStorage.setItem(STORAGE_KEY, newLocale);
36
+ } catch {
37
+ // localStorage may be unavailable
38
+ }
39
+ }
40
+
41
+ export function t(
42
+ key: TranslationKey,
43
+ params?: Record<string, string | number>,
44
+ ): string {
45
+ return createT(localeState.locale)(key, params);
46
+ }
@@ -0,0 +1,90 @@
1
+ import {
2
+ FontFamilies,
3
+ type FontFamily,
4
+ type ThemeMode,
5
+ ThemeModes,
6
+ } from "../schema";
7
+
8
+ const THEME_STORAGE_KEY = "readit:theme";
9
+ const DARK_MQ = "(prefers-color-scheme: dark)";
10
+
11
+ function getStoredTheme(): ThemeMode {
12
+ try {
13
+ const stored = localStorage.getItem(THEME_STORAGE_KEY);
14
+ if (
15
+ stored === ThemeModes.LIGHT ||
16
+ stored === ThemeModes.DARK ||
17
+ stored === ThemeModes.SYSTEM
18
+ ) {
19
+ return stored;
20
+ }
21
+ } catch {}
22
+ return ThemeModes.SYSTEM;
23
+ }
24
+
25
+ function applyTheme(mode: ThemeMode): void {
26
+ const isDark =
27
+ mode === ThemeModes.DARK ||
28
+ (mode === ThemeModes.SYSTEM && window.matchMedia(DARK_MQ).matches);
29
+
30
+ document.documentElement.classList.toggle("dark", isDark);
31
+ }
32
+
33
+ export const settings = $state({
34
+ fontFamily: FontFamilies.SERIF as FontFamily,
35
+ themeMode: getStoredTheme() as ThemeMode,
36
+ });
37
+
38
+ export async function updateFontFamily(font: FontFamily): Promise<void> {
39
+ settings.fontFamily = font;
40
+
41
+ try {
42
+ const response = await fetch("/api/settings", {
43
+ method: "PUT",
44
+ headers: { "Content-Type": "application/json" },
45
+ body: JSON.stringify({ fontFamily: font }),
46
+ });
47
+
48
+ if (!response.ok) {
49
+ throw new Error("Failed to save settings");
50
+ }
51
+ } catch (err) {
52
+ console.error("Failed to save font preference:", err);
53
+ }
54
+ }
55
+
56
+ export function updateThemeMode(mode: ThemeMode): void {
57
+ settings.themeMode = mode;
58
+ applyTheme(mode);
59
+ syncSystemPreference();
60
+
61
+ try {
62
+ localStorage.setItem(THEME_STORAGE_KEY, mode);
63
+ } catch {}
64
+ }
65
+
66
+ export function initSettings(data?: { fontFamily?: string }): void {
67
+ if (data?.fontFamily) {
68
+ settings.fontFamily = data.fontFamily as FontFamily;
69
+ }
70
+
71
+ applyTheme(settings.themeMode);
72
+ syncSystemPreference();
73
+ }
74
+
75
+ let mediaCleanup: (() => void) | undefined;
76
+
77
+ function syncSystemPreference(): void {
78
+ if (mediaCleanup) {
79
+ mediaCleanup();
80
+ mediaCleanup = undefined;
81
+ }
82
+
83
+ if (settings.themeMode !== ThemeModes.SYSTEM) return;
84
+
85
+ const mq = window.matchMedia(DARK_MQ);
86
+ const handler = () => applyTheme(ThemeModes.SYSTEM);
87
+
88
+ mq.addEventListener("change", handler);
89
+ mediaCleanup = () => mq.removeEventListener("change", handler);
90
+ }
@@ -0,0 +1,104 @@
1
+ import {
2
+ bindingsEqual,
3
+ DEFAULT_SHORTCUTS,
4
+ resolveShortcuts,
5
+ type ShortcutDefinition,
6
+ } from "../lib/shortcut-registry";
7
+ import type { KeybindingOverride, ShortcutBinding } from "../schema";
8
+
9
+ export const shortcutState = $state({
10
+ shortcuts: DEFAULT_SHORTCUTS as ShortcutDefinition[],
11
+ });
12
+
13
+ export function initShortcuts(overrides: KeybindingOverride[]): void {
14
+ shortcutState.shortcuts = resolveShortcuts(overrides);
15
+ }
16
+
17
+ export async function updateBinding(
18
+ id: string,
19
+ binding: ShortcutBinding,
20
+ ): Promise<void> {
21
+ const target = shortcutState.shortcuts.find((s) => s.id === id);
22
+ const conflict = shortcutState.shortcuts.find(
23
+ (s) => s.id !== id && s.enabled && bindingsEqual(s.binding, binding),
24
+ );
25
+
26
+ const updated = shortcutState.shortcuts.map((s) => {
27
+ if (s.id === id) return { ...s, binding };
28
+ if (conflict && s.id === conflict.id) {
29
+ // Only swap bindings when the target is enabled; otherwise
30
+ // just revert the conflicting shortcut to its default binding
31
+ // to avoid creating two enabled shortcuts on the same combo.
32
+ if (target?.enabled) {
33
+ return { ...s, binding: target.binding };
34
+ }
35
+ return { ...s, binding: s.defaultBinding };
36
+ }
37
+ return s;
38
+ });
39
+
40
+ shortcutState.shortcuts = updated;
41
+ await persistOverrides(updated);
42
+ }
43
+
44
+ export async function toggleEnabled(id: string): Promise<void> {
45
+ const target = shortcutState.shortcuts.find((s) => s.id === id);
46
+ if (!target) return;
47
+
48
+ // When re-enabling, check for binding conflicts with other enabled shortcuts
49
+ if (!target.enabled) {
50
+ const conflict = shortcutState.shortcuts.find(
51
+ (s) =>
52
+ s.id !== id && s.enabled && bindingsEqual(s.binding, target.binding),
53
+ );
54
+ if (conflict) {
55
+ // Disable the conflicting shortcut to resolve the conflict
56
+ shortcutState.shortcuts = shortcutState.shortcuts.map((s) => {
57
+ if (s.id === id) return { ...s, enabled: true };
58
+ if (s.id === conflict.id) return { ...s, enabled: false };
59
+ return s;
60
+ });
61
+ await persistOverrides(shortcutState.shortcuts);
62
+ return;
63
+ }
64
+ }
65
+
66
+ shortcutState.shortcuts = shortcutState.shortcuts.map((s) =>
67
+ s.id === id ? { ...s, enabled: !s.enabled } : s,
68
+ );
69
+ await persistOverrides(shortcutState.shortcuts);
70
+ }
71
+
72
+ export async function resetToDefaults(): Promise<void> {
73
+ shortcutState.shortcuts = DEFAULT_SHORTCUTS.map((s) => ({ ...s }));
74
+ await persistOverrides(shortcutState.shortcuts);
75
+ }
76
+
77
+ function toOverrides(shortcuts: ShortcutDefinition[]): KeybindingOverride[] {
78
+ return shortcuts
79
+ .filter((s) => !s.enabled || !bindingsEqual(s.binding, s.defaultBinding))
80
+ .map((s) => ({
81
+ id: s.id,
82
+ binding: bindingsEqual(s.binding, s.defaultBinding)
83
+ ? undefined
84
+ : s.binding,
85
+ enabled: s.enabled,
86
+ }));
87
+ }
88
+
89
+ async function persistOverrides(
90
+ shortcuts: ShortcutDefinition[],
91
+ ): Promise<void> {
92
+ try {
93
+ const response = await fetch("/api/settings", {
94
+ method: "PUT",
95
+ headers: { "Content-Type": "application/json" },
96
+ body: JSON.stringify({ keybindings: toOverrides(shortcuts) }),
97
+ });
98
+ if (!response.ok) {
99
+ throw new Error(`Failed to save keybindings: ${response.status}`);
100
+ }
101
+ } catch (err) {
102
+ console.error("Failed to save keybindings:", err);
103
+ }
104
+ }
@@ -0,0 +1,12 @@
1
+ export const ui = $state({
2
+ hoveredCommentId: undefined as string | undefined,
3
+ activeCommentId: undefined as string | undefined,
4
+ });
5
+
6
+ export function setHoveredCommentId(id: string | undefined): void {
7
+ ui.hoveredCommentId = id;
8
+ }
9
+
10
+ export function setActiveCommentId(id: string | undefined): void {
11
+ ui.activeCommentId = id;
12
+ }
@@ -0,0 +1,104 @@
1
+ export interface TemplateOptions {
2
+ title: string;
3
+ cssPath: string;
4
+ jsPath: string;
5
+ documentHtml: string;
6
+ inlineData: object;
7
+ isDev: boolean;
8
+ fontFamily: string;
9
+ }
10
+
11
+ function safeJsonStringify(data: object): string {
12
+ return JSON.stringify(data).replace(/</g, "\\u003c");
13
+ }
14
+
15
+ function escapeHtml(str: string): string {
16
+ return str
17
+ .replace(/&/g, "&amp;")
18
+ .replace(/</g, "&lt;")
19
+ .replace(/>/g, "&gt;")
20
+ .replace(/"/g, "&quot;")
21
+ .replace(/'/g, "&#39;");
22
+ }
23
+
24
+ function escapeAttr(str: string): string {
25
+ return str.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
26
+ }
27
+
28
+ /**
29
+ * Sanitize server-rendered HTML to prevent XSS from raw HTML in markdown source.
30
+ * While readit is designed for local use with the user's own files, this
31
+ * provides defense-in-depth against untrusted markdown content.
32
+ *
33
+ * Uses a simple tag-stripping approach to remove dangerous elements while
34
+ * preserving the rendered content. The Go server uses bluemonday for the
35
+ * same purpose.
36
+ */
37
+ function sanitizeHtml(html: string): string {
38
+ // Remove <script> tags and their content
39
+ let sanitized = html.replace(
40
+ /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
41
+ "",
42
+ );
43
+ // Remove event handler attributes (onclick, onerror, onload, etc.)
44
+ sanitized = sanitized.replace(
45
+ /\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,
46
+ "",
47
+ );
48
+ // Remove javascript: URLs
49
+ sanitized = sanitized.replace(
50
+ /\bhref\s*=\s*(?:"javascript:[^"]*"|'javascript:[^']*')/gi,
51
+ "",
52
+ );
53
+ sanitized = sanitized.replace(
54
+ /\bsrc\s*=\s*(?:"javascript:[^"]*"|'javascript:[^']*')/gi,
55
+ "",
56
+ );
57
+ return sanitized;
58
+ }
59
+
60
+ export function renderTemplate(options: TemplateOptions): string {
61
+ const {
62
+ title,
63
+ cssPath,
64
+ jsPath,
65
+ documentHtml,
66
+ inlineData,
67
+ isDev,
68
+ fontFamily,
69
+ } = options;
70
+
71
+ const viteClient = isDev
72
+ ? '<script type="module" src="http://127.0.0.1:24678/@vite/client"></script>'
73
+ : "";
74
+
75
+ const cssLink = cssPath
76
+ ? `<link rel="stylesheet" href="${escapeAttr(cssPath)}">`
77
+ : "";
78
+ const proseClass = fontFamily === "sans-serif" ? "prose-sans" : "prose-serif";
79
+
80
+ return `<!DOCTYPE html>
81
+ <html lang="en">
82
+ <head>
83
+ <meta charset="UTF-8">
84
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
85
+ <title>readit — ${escapeHtml(title)}</title>
86
+ <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>📖</text></svg>">
87
+ <script>
88
+ (() => {
89
+ var t = localStorage.getItem("readit:theme");
90
+ var d = t === "dark" || (t !== "light" && matchMedia("(prefers-color-scheme: dark)").matches);
91
+ if (d) document.documentElement.classList.add("dark");
92
+ })();
93
+ </script>
94
+ ${viteClient}
95
+ ${cssLink}
96
+ </head>
97
+ <body class="min-h-screen">
98
+ <article id="document-content" class="prose ${proseClass}">${sanitizeHtml(documentHtml)}</article>
99
+ <div id="app"></div>
100
+ <script type="application/json" id="__readit">${safeJsonStringify(inlineData)}</script>
101
+ <script type="module" src="${escapeAttr(jsPath)}" defer></script>
102
+ </body>
103
+ </html>`;
104
+ }
package/src/test-setup.ts CHANGED
@@ -1 +1,48 @@
1
1
  import "@testing-library/jest-dom/vitest";
2
+
3
+ // Mock CSS Custom Highlight API for jsdom (not supported natively)
4
+ if (typeof globalThis.Highlight === "undefined") {
5
+ globalThis.Highlight = class Highlight {
6
+ _ranges: AbstractRange[];
7
+ priority = 0;
8
+ type: "highlight" | "spelling-error" | "grammar-error" = "highlight";
9
+ get size() {
10
+ return this._ranges.length;
11
+ }
12
+ constructor(...ranges: AbstractRange[]) {
13
+ this._ranges = ranges;
14
+ }
15
+ add(range: AbstractRange) {
16
+ this._ranges.push(range);
17
+ }
18
+ delete(range: AbstractRange) {
19
+ const idx = this._ranges.indexOf(range);
20
+ if (idx >= 0) {
21
+ this._ranges.splice(idx, 1);
22
+ return true;
23
+ }
24
+ return false;
25
+ }
26
+ clear() {
27
+ this._ranges = [];
28
+ }
29
+ has(range: AbstractRange) {
30
+ return this._ranges.includes(range);
31
+ }
32
+ [Symbol.iterator]() {
33
+ return this._ranges[Symbol.iterator]();
34
+ }
35
+ } as unknown as typeof Highlight;
36
+ }
37
+
38
+ if (typeof CSS === "undefined" || !CSS.highlights) {
39
+ const highlightsMap = new Map<string, Highlight>();
40
+ Object.defineProperty(globalThis, "CSS", {
41
+ value: {
42
+ ...((globalThis as Record<string, unknown>).CSS ?? {}),
43
+ highlights: highlightsMap,
44
+ },
45
+ writable: true,
46
+ configurable: true,
47
+ });
48
+ }
@@ -0,0 +1,5 @@
1
+ import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
2
+
3
+ export default {
4
+ preprocess: vitePreprocess(),
5
+ };
package/tsconfig.json CHANGED
@@ -2,6 +2,7 @@
2
2
  "compilerOptions": {
3
3
  "target": "ES2022",
4
4
  "lib": ["ES2022", "DOM", "DOM.Iterable"],
5
+ "types": ["node"],
5
6
  "module": "ESNext",
6
7
  "moduleResolution": "bundler",
7
8
  "strict": true,
@@ -10,11 +11,10 @@
10
11
  "resolveJsonModule": true,
11
12
  "isolatedModules": true,
12
13
  "noEmit": true,
13
- "jsx": "react-jsx",
14
14
  "allowImportingTsExtensions": true,
15
15
  "noUnusedLocals": true,
16
16
  "noUnusedParameters": true
17
17
  },
18
18
  "include": ["src"],
19
- "exclude": ["node_modules", "dist"]
19
+ "exclude": ["node_modules", "dist", "vscode-readit"]
20
20
  }