The best way to control Claude Code, Codex and more from any computer or phone

main
ts 606 lines 21.2 KB
Raw
1 // Dev-only: makes `[data-copy]` elements editable and saves edits to source.
2 // Served by the copy-editor Vite plugin during `vite serve`; never built.
3 //
4 // Two editing modes:
5 // - inline: the element's rendered text is edited in place and mapped back
6 // onto its source text runs;
7 // - markdown (`data-copy-format="markdown"`): focusing the section swaps in
8 // its markdown source; leaving it saves the markdown and shows a preview
9 // rendered with the section's style (`data-copy-style`) until the page's
10 // own renderer catches up.
11
12 import { marked } from "marked";
13 // @ts-expect-error -- virtual module served by the plugin in index.ts
14 import config from "virtual:copy-editor/config";
15 import type { MarkdownStyle } from "./index.ts";
16
17 const SAVE_ENDPOINT = "/__copy-editor/save";
18 const SOURCE_ENDPOINT = "/__copy-editor/source";
19 const REFRESH_EVENT = "copy-editor:refresh";
20 const SELECTOR = "[data-copy]";
21 const styles = config.styles as Record<string, MarkdownStyle>;
22
23 const controller = new AbortController();
24 const { signal } = controller;
25 const listen = <K extends keyof DocumentEventMap>(
26 type: K,
27 handler: (event: DocumentEventMap[K]) => void,
28 capture = false,
29 ) => document.addEventListener(type, handler, { signal, capture });
30
31 const style = document.createElement("style");
32 style.textContent = `
33 ${SELECTOR} { cursor: text; }
34 ${SELECTOR}:hover { outline: 1px dashed rgb(255 120 80 / 0.7); outline-offset: 3px; }
35 ${SELECTOR}:focus {
36 outline: 2px solid rgb(255 120 80);
37 outline-offset: 3px;
38 background: rgb(255 120 80 / 0.08);
39 }
40 /* Source keeps the element's own font so the text doesn't jump; only
41 multi-line markdown needs its line breaks shown. */
42 :is([data-copy-editing], [data-copy-draft]) {
43 white-space: pre-wrap;
44 }
45 [data-copy-draft] { outline: 2px dashed #d33 !important; }
46 [data-copy-empty]:not([data-copy-editing]) { min-height: 1em; }
47 [data-copy-empty]:not([data-copy-editing]):is(:hover, :focus)::before {
48 content: "Add markdown…"; opacity: 0.45; font-style: italic;
49 }
50 #copy-editor-toast {
51 position: fixed; right: 16px; bottom: 16px; z-index: 2147483647;
52 max-width: 360px; padding: 8px 12px; border-radius: 8px;
53 font: 600 12px/1.3 system-ui, sans-serif; color: #fff; background: #1f6f3a;
54 box-shadow: 0 2px 10px rgb(0 0 0 / 0.4);
55 opacity: 0; transition: opacity 0.2s; pointer-events: none;
56 }
57 #copy-editor-toast[data-error] { background: #8c1d18; }
58 #copy-editor-toast[data-show] { opacity: 1; }
59 ${Object.values(styles)
60 .map((s) => s.css ?? "")
61 .join("\n")}
62 `;
63 const toast = document.createElement("div");
64 toast.id = "copy-editor-toast";
65 document.head.append(style);
66 document.body.append(toast);
67
68 let toastTimer: ReturnType<typeof setTimeout> | undefined;
69 const notify = (message: string, error = false) => {
70 toast.textContent = message;
71 toast.toggleAttribute("data-error", error);
72 toast.setAttribute("data-show", "");
73 clearTimeout(toastTimer);
74 toastTimer = setTimeout(() => toast.removeAttribute("data-show"), error ? 6000 : 1800);
75 };
76
77 const isMarkdown = (el: HTMLElement) => el.dataset.copyFormat === "markdown" || isInline(el);
78 /** Template copy edited as one line of inline markdown. */
79 const isInline = (el: HTMLElement) => el.dataset.copyFormat === "inline";
80
81 /**
82 * Renders inline markdown, copying attributes (classes, scoped styles) from
83 * the same tags in the element's previous rendering.
84 */
85 const renderInline = (source: string, rendered: string) => {
86 const previous = document.createElement("template");
87 previous.innerHTML = rendered;
88 const template = document.createElement("template");
89 template.innerHTML = marked.parseInline(source, {
90 async: false,
91 gfm: true,
92 breaks: true,
93 });
94 for (const node of template.content.querySelectorAll("*")) {
95 const sample = previous.content.querySelector(node.tagName);
96 for (const attr of sample?.attributes ?? []) {
97 if (attr.name !== "href") node.setAttribute(attr.name, attr.value);
98 }
99 }
100 return template.innerHTML;
101 };
102
103 const markEmpty = (el: HTMLElement) => {
104 if (isMarkdown(el) && !el.dataset.copyEditing) {
105 el.toggleAttribute("data-copy-empty", el.textContent?.trim() === "");
106 }
107 };
108
109 const makeEditable = (el: HTMLElement) => {
110 markEmpty(el);
111 if (el.isContentEditable) return;
112 // "true", not "plaintext-only": Chrome forces `white-space: pre-wrap` on
113 // plaintext-only elements, which renders source line breaks. Rich-text
114 // input is blocked below instead.
115 el.contentEditable = "true";
116 el.spellcheck = false;
117 };
118
119 // Content rendered outside Vite transforms (markdown, generated docs) marks
120 // its element with a trailing `<!--copy:ID-->` comment instead of an attribute.
121 const MARKER = /^copy:(.+)$/;
122 const claimMarkers = (root: Node) => {
123 const doc = root.ownerDocument ?? (root as Document);
124 const walker = doc.createTreeWalker(root, NodeFilter.SHOW_COMMENT);
125 const markers: Comment[] = [];
126 if (root.nodeType === Node.COMMENT_NODE) markers.push(root as Comment);
127 while (walker.nextNode()) markers.push(walker.currentNode as Comment);
128 for (const marker of markers) {
129 const id = MARKER.exec(marker.data)?.[1];
130 const parent = marker.parentElement;
131 if (!id || !parent) continue;
132 parent.setAttribute("data-copy", id);
133 marker.remove();
134 }
135 };
136
137 const enableWithin = (root: ParentNode) => {
138 claimMarkers(root as Node);
139 if (root instanceof HTMLElement && root.matches(SELECTOR)) makeEditable(root);
140 for (const el of root.querySelectorAll<HTMLElement>(SELECTOR)) makeEditable(el);
141 };
142 enableWithin(document);
143
144 // Elements rendered later (client routing, framework HMR) become editable too.
145 const observer = new MutationObserver((records) => {
146 for (const record of records) {
147 if (record.type === "attributes") enableWithin(record.target as HTMLElement);
148 for (const node of record.addedNodes) {
149 if (node instanceof HTMLElement) enableWithin(node);
150 else if (node.nodeType === Node.COMMENT_NODE) {
151 const parent = node.parentElement;
152 claimMarkers(node);
153 if (parent) enableWithin(parent);
154 }
155 }
156 }
157 });
158 observer.observe(document.body, {
159 subtree: true,
160 childList: true,
161 attributes: true,
162 attributeFilter: ["data-copy"],
163 });
164
165 const target = (event: Event) =>
166 event.target instanceof Element ? event.target.closest<HTMLElement>(SELECTOR) : null;
167
168 const post = async (url: string, body: object) => {
169 const res = await fetch(url, {
170 method: "POST",
171 headers: { "content-type": "application/json" },
172 body: JSON.stringify(body),
173 }).catch((error: unknown) => ({
174 ok: false,
175 json: async () => ({ error: String(error) }),
176 }));
177 const json = (await res.json().catch(() => ({}))) as {
178 file?: string;
179 changed?: boolean;
180 reload?: boolean;
181 error?: string;
182 };
183 return { ok: res.ok, ...json };
184 };
185
186 // ── inline text edits ─────────────────────────────────────────────────────
187
188 const textNodes = (el: HTMLElement): string[] => {
189 const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
190 const out: string[] = [];
191 while (walker.nextNode()) out.push((walker.currentNode as Text).data);
192 return out;
193 };
194
195 /** Browsers type spaces as non-breaking ones at run edges; keep real ones. */
196 const plainSpaces = (after: string[], before: string[]) =>
197 after.map((text, i) => (before[i]?.includes("\u00a0") ? text : text.replace(/\u00a0/g, " ")));
198
199 interface Snapshot {
200 html: string;
201 texts: string[];
202 }
203 const snapshots = new WeakMap<HTMLElement, Snapshot>();
204
205 const saveInline = async (el: HTMLElement) => {
206 const snap = snapshots.get(el);
207 if (!snap) return;
208 snapshots.delete(el);
209 const after = plainSpaces(textNodes(el), snap.texts);
210 if (after.join("\u0000") === snap.texts.join("\u0000")) return;
211 const result = await post(SAVE_ENDPOINT, {
212 id: el.dataset.copy,
213 before: snap.texts,
214 after,
215 });
216 if (result.ok) {
217 if (result.changed) notify(`Saved to ${result.file}`);
218 if (result.reload) needsReload();
219 } else {
220 el.innerHTML = snap.html;
221 notify(`Not saved: ${result.error ?? "unknown error"}`, true);
222 }
223 };
224
225 // ── markdown sections ─────────────────────────────────────────────────────
226
227 interface MarkdownState {
228 /** Rendered HTML to restore when leaving without changes. */
229 rendered: string;
230 /** The source the edit started from (sent back to detect staleness). */
231 base?: string;
232 /** Unsaved source kept after a failed save. */
233 draft?: string;
234 /** The page as served when editing started, to tell when it's rebuilt. */
235 servedAtFocus?: Promise<string>;
236 }
237 const sections = new WeakMap<HTMLElement, MarkdownState>();
238 /** Elements that are themselves a single markdown block. */
239 const BLOCK_TAGS = new Set([
240 "P",
241 "H1",
242 "H2",
243 "H3",
244 "H4",
245 "H5",
246 "H6",
247 "UL",
248 "OL",
249 "BLOCKQUOTE",
250 "TABLE",
251 "PRE",
252 ]);
253 /** Sections showing a preview until the page's renderer catches up. */
254 const previews = new Map<HTMLElement, { staleHtml: string; attempts: number }>();
255 /** An edit changed the page's structure; reload once the server has it. */
256 let reloadPending = false;
257 /** The server has it, but an edit was in progress. */
258 let reloadWhenIdle = false;
259 /** The page as served before a structural edit, to tell when it changed. */
260 let servedBefore: Promise<string> | undefined;
261 const fetchPage = () =>
262 fetch(location.href, { cache: "no-store" })
263 .then((res) => (res.ok ? res.text() : ""))
264 .catch(() => "");
265 /** `before`: the page as served before the edit, when already fetched. */
266 const needsReload = (before?: Promise<string>) => {
267 reloadPending = true;
268 servedBefore ??= before ?? fetchPage();
269 };
270 const busy = () => document.querySelector("[data-copy-editing], [data-copy-draft]") !== null;
271
272 /**
273 * Moves stylesheets out of a section before its content is replaced:
274 * renderers such as Expressive Code load page-wide styles from inside the
275 * first block that needs them.
276 */
277 const hoistStyles = (el: HTMLElement) => {
278 for (const node of el.querySelectorAll<HTMLElement>('link[rel="stylesheet"], style')) {
279 const href = node.getAttribute("href");
280 const present = href
281 ? document.head.querySelector(`link[rel="stylesheet"][href="${CSS.escape(href)}"]`)
282 : null;
283 if (!present) document.head.append(node.cloneNode(true));
284 }
285 };
286
287 /** Normalized text of a code block, for matching rendered and preview code. */
288 const codeText = (pre: Element) =>
289 (
290 pre.querySelector("[data-code]")?.getAttribute("data-code") ??
291 (pre as HTMLElement).innerText ??
292 pre.textContent ??
293 ""
294 ).replace(/\s+/g, "");
295
296 const renderPreview = (source: string, styleName: string | undefined, rendered?: string) => {
297 const preset = styleName ? styles[styleName] : undefined;
298 let markdown = source;
299 for (const [pattern, replacement] of preset?.rewrite ?? []) {
300 markdown = markdown.replace(new RegExp(pattern, "g"), replacement);
301 }
302 const template = document.createElement("template");
303 template.innerHTML = marked.parse(markdown, { async: false, gfm: true });
304 for (const [tag, attrs] of Object.entries(preset?.elements ?? {})) {
305 const selector = tag === "code" ? "code:not(pre code)" : tag;
306 for (const node of template.content.querySelectorAll(selector)) {
307 for (const [name, value] of Object.entries(attrs ?? {})) {
308 if (name === "class") node.classList.add(...value.split(/\s+/).filter(Boolean));
309 else node.setAttribute(name, value);
310 }
311 }
312 }
313 // Keep unchanged code blocks exactly as the page rendered them
314 // (highlighting, frames, copy buttons) instead of the plain preview.
315 if (rendered) {
316 const previous = document.createElement("template");
317 previous.innerHTML = rendered;
318 const blocks = [...previous.content.children].filter((child) =>
319 child.matches("pre, :has(pre)"),
320 );
321 for (const pre of template.content.querySelectorAll(":scope > pre")) {
322 const text = codeText(pre);
323 const match = blocks.findIndex((block) => codeText(block) === text);
324 if (match === -1) continue;
325 pre.replaceWith(blocks[match]!);
326 blocks.splice(match, 1);
327 }
328 }
329 return template.innerHTML;
330 };
331
332 /** Text just before the caret, to find the same spot in the source. */
333 const caretContext = (el: HTMLElement) => {
334 const selection = getSelection();
335 const node = selection?.anchorNode;
336 if (!node || node.nodeType !== Node.TEXT_NODE || !el.contains(node)) return "";
337 return (node as Text).data.slice(0, selection!.anchorOffset);
338 };
339
340 const placeCaret = (el: HTMLElement, source: string, context: string) => {
341 let at = 0;
342 for (const size of [24, 12, 6]) {
343 const needle = context.slice(-size);
344 const i = needle.trim() ? source.indexOf(needle) : -1;
345 if (i !== -1) {
346 at = i + needle.length;
347 break;
348 }
349 }
350 const node = el.firstChild;
351 if (!node) return;
352 const range = document.createRange();
353 range.setStart(node, Math.min(at, node.textContent?.length ?? 0));
354 range.collapse(true);
355 getSelection()?.removeAllRanges();
356 getSelection()?.addRange(range);
357 };
358
359 const enterSource = async (el: HTMLElement) => {
360 if (el.dataset.copyEditing) return;
361 const state: MarkdownState = sections.get(el) ?? { rendered: el.innerHTML };
362 sections.set(el, state);
363 el.dataset.copyEditing = "loading";
364
365 if (state.draft === undefined) {
366 const res = await fetch(
367 `${SOURCE_ENDPOINT}?id=${encodeURIComponent(el.dataset.copy ?? "")}`,
368 ).catch(() => undefined);
369 const body = (await res?.json().catch(() => ({}))) as {
370 source?: string;
371 error?: string;
372 };
373 if (!res?.ok || body.source === undefined) {
374 delete el.dataset.copyEditing;
375 notify(`Can't edit: ${body.error ?? "unknown error"}`, true);
376 return;
377 }
378 state.base = body.source;
379 state.rendered = el.innerHTML;
380 state.servedAtFocus = fetchPage();
381 }
382 if (document.activeElement !== el) {
383 delete el.dataset.copyEditing;
384 return;
385 }
386 const context = caretContext(el);
387 const source = state.draft ?? state.base ?? "";
388 hoistStyles(el);
389 el.dataset.copyEditing = "source";
390 el.removeAttribute("data-copy-draft");
391 el.removeAttribute("data-copy-empty");
392 el.textContent = source;
393 placeCaret(el, source, context);
394 };
395
396 const cancelSource = (el: HTMLElement) => {
397 const state = sections.get(el);
398 if (!state || !el.dataset.copyEditing) return;
399 state.draft = undefined;
400 delete el.dataset.copyEditing;
401 el.removeAttribute("data-copy-draft");
402 el.innerHTML = state.rendered;
403 markEmpty(el);
404 };
405
406 const leaveSource = async (el: HTMLElement) => {
407 const state = sections.get(el);
408 if (!state || el.dataset.copyEditing !== "source") {
409 if (el.dataset.copyEditing === "loading") delete el.dataset.copyEditing;
410 return;
411 }
412 const source = el.innerText.replace(/\u00a0/g, " ").replace(/\s+$/, "");
413 delete el.dataset.copyEditing;
414 if (source === (state.base ?? "").replace(/\s+$/, "")) {
415 state.draft = undefined;
416 el.innerHTML = state.rendered;
417 markEmpty(el);
418 return;
419 }
420
421 const id = el.dataset.copy ?? "";
422 const staleHtml = state.rendered;
423 const result = await post(SOURCE_ENDPOINT, { id, source, base: state.base });
424 if (!result.ok) {
425 state.draft = source;
426 el.setAttribute("data-copy-draft", "");
427 el.textContent = source;
428 notify(`Not saved: ${result.error ?? "unknown error"}`, true);
429 return;
430 }
431 const preview = isInline(el)
432 ? renderInline(source, staleHtml)
433 : renderPreview(source, el.dataset.copyStyle, staleHtml);
434 if (isInline(el)) {
435 el.innerHTML = preview;
436 } else if (BLOCK_TAGS.has(el.tagName)) {
437 // The section IS one block (e.g. a paragraph): show the preview's
438 // contents in place, or reload if the edit turned it into other blocks.
439 const template = document.createElement("template");
440 template.innerHTML = preview;
441 const [only, ...rest] = [...template.content.children];
442 if (only?.tagName === el.tagName && rest.length === 0) {
443 el.innerHTML = only.innerHTML;
444 } else {
445 // Now several blocks (e.g. a paragraph and a list): show them in its
446 // place, then reload once the page is rebuilt so every block gets an id.
447 notify(`Saved to ${result.file}`);
448 el.replaceWith(template.content);
449 needsReload(state.servedAtFocus);
450 return;
451 }
452 } else {
453 el.innerHTML = preview;
454 }
455 state.draft = undefined;
456 state.base = source;
457 state.rendered = el.innerHTML;
458 markEmpty(el);
459 if (result.changed) {
460 notify(`Saved to ${result.file}`);
461 previews.set(el, { staleHtml, attempts: 0 });
462 }
463 if (result.reload) needsReload();
464 };
465
466 /**
467 * Swaps previews for the page's own rendering once the server has caught
468 * up, or reloads when an edit changed the page's structure.
469 */
470 const refresh = async () => {
471 if (reloadPending) {
472 // Wait until the server serves the changed page (its watchers may lag
473 // behind the regeneration that triggered this refresh).
474 const before = await servedBefore;
475 for (let attempt = 0; attempt < 10; attempt++) {
476 if ((await fetchPage()) !== before) break;
477 await new Promise((resolve) => setTimeout(resolve, 1000));
478 }
479 if (busy()) reloadWhenIdle = true;
480 else location.reload();
481 return;
482 }
483 const res = await fetch(location.href, { cache: "no-store" }).catch(() => undefined);
484 if (!res?.ok) return;
485 const fresh = new DOMParser().parseFromString(await res.text(), "text/html");
486 claimMarkers(fresh.body);
487 // Pair editable elements by position: ids encode source locations, which
488 // shift when an edit changes the length of the text before them.
489 const current = [...document.querySelectorAll<HTMLElement>(SELECTOR)];
490 const next = [...fresh.querySelectorAll<HTMLElement>(SELECTOR)];
491 if (current.length !== next.length) {
492 // The edit added or removed blocks.
493 if (busy()) reloadWhenIdle = true;
494 else location.reload();
495 return;
496 }
497 let retry = false;
498 current.forEach((el, i) => {
499 const incoming = next[i]!;
500 if (el.dataset.copyEditing) return;
501 if (el.dataset.copy !== incoming.dataset.copy) {
502 el.dataset.copy = incoming.dataset.copy;
503 }
504 const preview = previews.get(el);
505 if (!preview) return;
506 if (incoming.innerHTML === preview.staleHtml && preview.attempts < 5) {
507 // The server hasn't picked up the edited source yet.
508 preview.attempts++;
509 retry = true;
510 return;
511 }
512 el.innerHTML = incoming.innerHTML;
513 sections.set(el, { rendered: el.innerHTML });
514 markEmpty(el);
515 previews.delete(el);
516 });
517 if (retry) setTimeout(refresh, 1000);
518 };
519
520 // ── events ────────────────────────────────────────────────────────────────
521
522 listen("focusin", (event) => {
523 const el = target(event);
524 if (!el) return;
525 if (isMarkdown(el)) void enterSource(el);
526 else snapshots.set(el, { html: el.innerHTML, texts: textNodes(el) });
527 });
528
529 listen("keydown", (event) => {
530 const el = target(event);
531 if (!el) return;
532 if (isMarkdown(el)) {
533 if (event.key === "Escape") {
534 cancelSource(el);
535 el.blur();
536 } else if (event.key === "Enter") {
537 event.preventDefault();
538 // Markdown sections: Enter adds a line, Ctrl/Cmd+Enter saves.
539 // One-line copy: Enter saves, Shift+Enter adds a line break (<br>).
540 const save = event.metaKey || event.ctrlKey || (isInline(el) && !event.shiftKey);
541 if (save) el.blur();
542 else document.execCommand("insertLineBreak");
543 } else if (event.key === "Tab") {
544 event.preventDefault();
545 document.execCommand("insertText", false, " ");
546 }
547 return;
548 }
549 if (event.key === "Enter" && !event.shiftKey) {
550 event.preventDefault();
551 el.blur();
552 } else if (event.key === "Escape") {
553 const snap = snapshots.get(el);
554 if (snap) el.innerHTML = snap.html;
555 el.blur();
556 }
557 });
558
559 // Clicking copy inside a link or button places the caret; Ctrl/Cmd+click
560 // still follows the link.
561 listen(
562 "click",
563 (event) => {
564 if (!target(event) || event.ctrlKey || event.metaKey) return;
565 if ((event.target as Element).closest("a, button")) event.preventDefault();
566 },
567 true,
568 );
569
570 // Editable elements are plain text: no bold/italic shortcuts or rich drops.
571 listen("beforeinput", (event) => {
572 if (!target(event)) return;
573 if (event.inputType.startsWith("format") || event.inputType === "insertFromDrop") {
574 event.preventDefault();
575 }
576 });
577
578 // Paste as plain text.
579 listen("paste", (event) => {
580 if (!target(event) || !event.clipboardData) return;
581 event.preventDefault();
582 document.execCommand("insertText", false, event.clipboardData.getData("text/plain"));
583 });
584
585 listen("focusout", async (event) => {
586 const el = target(event);
587 if (!el) return;
588 if (isMarkdown(el)) await leaveSource(el);
589 else await saveInline(el);
590 if (reloadWhenIdle && !busy()) location.reload();
591 });
592
593 // ── hot reload ────────────────────────────────────────────────────────────
594
595 if (import.meta.hot) {
596 import.meta.hot.on(REFRESH_EVENT, () => void refresh());
597 // Editing this file hot-swaps the editor without a page reload.
598 import.meta.hot.accept();
599 import.meta.hot.dispose(() => {
600 controller.abort();
601 observer.disconnect();
602 clearTimeout(toastTimer);
603 style.remove();
604 toast.remove();
605 });
606 }