@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 273 lines 8.78 KB
Raw
1 /**
2 * Format-agnostic text rewriting.
3 *
4 * An editable element renders as a sequence of DOM text nodes. The source
5 * that produced it is described as a matching sequence of {@link Run}s
6 * (source ranges between markup). An edit pairs each changed text node with
7 * its run and rewrites only the words that changed, so markup, escapes, and
8 * line wrapping outside the edited words are preserved verbatim.
9 *
10 * A {@link Dialect} supplies the source-format specifics: how a run splits
11 * into words and whitespace, how words compare with rendered text, and how
12 * new words are escaped.
13 */
14
15 // oxlint-disable-next-line effecttsgo/extends-native-error -- package does not depend on effect; thrown and caught with try/catch
16 export class CopyEditError extends Error {
17 constructor(
18 message: string,
19 readonly status = 400,
20 ) {
21 super(message);
22 }
23 }
24
25 /** `text` is editable prose, `code` is literal (no escaping), `locked` can't be edited. */
26 export type RunKind = "text" | "code" | "locked";
27
28 export interface Run {
29 start: number;
30 end: number;
31 kind?: RunKind;
32 /** Rendered text of a `locked` run (its source is not literal text). */
33 expected?: string;
34 /** True when the run starts a source line (block syntax applies there). */
35 lineStart?: boolean;
36 }
37
38 export interface TextToken {
39 raw: string;
40 ws: boolean;
41 /** Rendered text of the token (whitespace tokens render as a space). */
42 text: string;
43 }
44
45 export interface EscapeContext {
46 kind: RunKind;
47 /** True when the escaped word will begin a source line. */
48 lineStart: boolean;
49 }
50
51 export interface Dialect {
52 tokenize(raw: string, kind: RunKind): TextToken[];
53 /** Canonical form used to compare source text with rendered text. */
54 compare(text: string): string;
55 /** Escapes a word typed in the browser for insertion into the source. */
56 escape(word: string, context: EscapeContext): string;
57 }
58
59 export interface TextEdit {
60 /** The element's DOM text nodes when editing started. */
61 before: string[];
62 /** The element's DOM text nodes after editing. */
63 after: string[];
64 }
65
66 /** HTML whitespace (deliberately excludes the non-breaking space). */
67 export const WS = /[ \t\n\r\f]+/;
68
69 export const normalize = (text: string) => text.split(WS).filter(Boolean).join(" ");
70
71 const runText = (code: string, run: Run, dialect: Dialect) =>
72 dialect.compare(
73 normalize(
74 run.kind === "locked"
75 ? (run.expected ?? "")
76 : dialect
77 .tokenize(code.slice(run.start, run.end), run.kind ?? "text")
78 .map((t) => t.text)
79 .join(""),
80 ),
81 );
82
83 /**
84 * Rewrites one raw source run so it renders as `next`, touching only the
85 * words that changed.
86 */
87 const rewriteRun = (
88 raw: string,
89 next: string,
90 dialect: Dialect,
91 kind: RunKind,
92 runLineStart: boolean,
93 ): string => {
94 const tokens = dialect.tokenize(raw, kind);
95 const wordIdx = tokens.flatMap((t, i) => (t.ws ? [] : [i]));
96 const oldWords = wordIdx.map((i) => dialect.compare(tokens[i].text));
97 const typed = next.split(WS).filter(Boolean);
98 const newWords = typed.map((w) => dialect.compare(w));
99
100 const lineStartAt = (tokenIndex: number) =>
101 tokenIndex === 0 ? runLineStart : tokens[tokenIndex - 1].raw.includes("\n");
102 const render = (words: string[], lineStart: boolean) =>
103 words.map((w, i) => dialect.escape(w, { kind, lineStart: lineStart && i === 0 })).join(" ");
104
105 if (oldWords.length === 0) {
106 if (typed.length === 0) return raw;
107 const lead = tokens[0]?.raw ?? "";
108 const trail = tokens.length > 1 ? tokens[tokens.length - 1].raw : lead;
109 return `${lead}${render(typed, runLineStart || lead.includes("\n"))}${trail}`;
110 }
111
112 let p = 0;
113 const max = Math.min(oldWords.length, newWords.length);
114 while (p < max && oldWords[p] === newWords[p]) p++;
115 let s = 0;
116 while (s < max - p && oldWords[oldWords.length - 1 - s] === newWords[newWords.length - 1 - s])
117 s++;
118
119 const middleWords = typed.slice(p, typed.length - s);
120 const oldCount = oldWords.length - s - p;
121 const raws = tokens.map((t) => t.raw);
122
123 if (oldCount > 0) {
124 let from = wordIdx[p];
125 let to = wordIdx[oldWords.length - s - 1];
126 const middle = render(middleWords, lineStartAt(from));
127 if (!middle) {
128 // Drop one whitespace neighbour so the surrounding words don't collide.
129 if (p > 0) from = wordIdx[p - 1] + 1;
130 else if (s > 0) to = wordIdx[oldWords.length - s] - 1;
131 }
132 raws.splice(from, to - from + 1, middle);
133 } else if (middleWords.length > 0) {
134 if (p > 0) {
135 raws.splice(wordIdx[p - 1] + 1, 0, ` ${render(middleWords, false)}`);
136 } else {
137 raws.splice(wordIdx[0], 0, `${render(middleWords, lineStartAt(wordIdx[0]))} `);
138 }
139 }
140 return raws.join("");
141 };
142
143 /**
144 * Applies a browser edit to `code`, given the source runs that produced the
145 * edited element's text nodes. Returns the new source.
146 */
147 export const applyRuns = (
148 code: string,
149 runs: Run[],
150 dialect: Dialect,
151 { before, after }: TextEdit,
152 ): string => {
153 if (before.length !== after.length) {
154 throw new CopyEditError(
155 "The edit removed or added markup (for example, deleted a whole <code>). Edit within text runs, or change the markup in code.",
156 );
157 }
158 const texts = runs.map((run) => runText(code, run, dialect));
159 const rendered = (t: string) => dialect.compare(normalize(t));
160
161 // Pair DOM text nodes with source runs: one-to-one when the counts agree,
162 // otherwise (renderers drop empty and whitespace-only runs) only the
163 // non-blank ones. The first pairing whose texts all match wins.
164 type Pairs = [run: number, node: number][];
165 const candidates: Pairs[] = [];
166 if (runs.length === before.length) candidates.push(runs.map((_, i) => [i, i]));
167 const runIdx = texts.flatMap((t, i) => (t === "" ? [] : [i]));
168 const domIdx = before.flatMap((t, i) => (normalize(t) === "" ? [] : [i]));
169 if (runIdx.length === domIdx.length) {
170 candidates.push(runIdx.map((r, i) => [r, domIdx[i]]));
171 }
172 const pairs = candidates.find((c) => c.every(([r, d]) => texts[r] === rendered(before[d])));
173 if (!pairs) throw stale();
174 const paired = new Set(pairs.map(([, d]) => d));
175 if (before.some((t, d) => !paired.has(d) && rendered(t) !== rendered(after[d]))) {
176 throw new CopyEditError(
177 "That spot (between two pieces of markup) has no text in the source. Type inside an existing word run instead.",
178 );
179 }
180
181 let out = code;
182 // Apply from the end so earlier offsets stay valid.
183 for (const [r, d] of [...pairs].reverse()) {
184 if (rendered(after[d]) === rendered(before[d])) continue;
185 const run = runs[r];
186 if (run.kind === "locked") {
187 throw new CopyEditError(
188 `"${normalize(before[d])}" is generated (for example, a link to another page) and can't be edited here. Change it in the source.`,
189 );
190 }
191 out =
192 out.slice(0, run.start) +
193 rewriteRun(
194 out.slice(run.start, run.end),
195 after[d],
196 dialect,
197 run.kind ?? "text",
198 run.lineStart ?? false,
199 ) +
200 out.slice(run.end);
201 }
202 return out;
203 };
204
205 export const stale = () =>
206 new CopyEditError(
207 "The text on the page doesn't match the source (the file changed, or a script rewrote this element). Reload and try again.",
208 409,
209 );
210
211 // ── HTML templates (.astro, .html, JSX, Vue, Svelte) ──────────────────────
212
213 const ENTITIES: Record<string, string> = {
214 amp: "&",
215 lt: "<",
216 gt: ">",
217 quot: '"',
218 apos: "'",
219 nbsp: "\u00a0",
220 mdash: "—",
221 ndash: "–",
222 rarr: "→",
223 larr: "←",
224 hellip: "…",
225 middot: "·",
226 copy: "©",
227 trade: "™",
228 rsquo: "’",
229 lsquo: "‘",
230 ldquo: "“",
231 rdquo: "”",
232 times: "×",
233 bull: "•",
234 };
235
236 export const decodeEntities = (raw: string): string =>
237 raw.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, body: string) => {
238 if (body[0] === "#") {
239 const code =
240 body[1] === "x" || body[1] === "X"
241 ? parseInt(body.slice(2), 16)
242 : parseInt(body.slice(1), 10);
243 return Number.isNaN(code) ? m : String.fromCodePoint(code);
244 }
245 return ENTITIES[body.toLowerCase()] ?? m;
246 });
247
248 /** Text between tags in HTML-like templates; `{" "}` counts as whitespace. */
249 export const htmlDialect: Dialect = {
250 tokenize(raw) {
251 const tokens: TextToken[] = [];
252 const re = /(\{\s*(?:"\s+"|'\s+')\s*\})|([ \t\n\r\f]+)|([^ \t\n\r\f{]+)|(\{)/g;
253 for (const m of raw.matchAll(re)) {
254 if (m[4]) {
255 throw new CopyEditError(
256 "Editable copy can't contain {expressions}. Move data-copy to a plain-text element.",
257 );
258 }
259 const ws = Boolean(m[1] || m[2]);
260 tokens.push({ raw: m[0], ws, text: ws ? " " : decodeEntities(m[0]) });
261 }
262 return tokens;
263 },
264 compare: (text) => text,
265 escape: (word) =>
266 word
267 .replace(/&/g, "&amp;")
268 .replace(/</g, "&lt;")
269 .replace(/>/g, "&gt;")
270 .replace(/\{/g, "&#123;")
271 .replace(/\}/g, "&#125;")
272 .replace(/\u00a0/g, "&nbsp;"),
273 };