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

main
ts 593 lines 22.4 KB
Raw
1 import { type Command, Extension, Mark as TiptapMark } from "@tiptap/core";
2 import {
3 closeHistory,
4 isHistoryTransaction,
5 redo,
6 redoDepth,
7 undo,
8 undoDepth,
9 } from "@tiptap/pm/history";
10 import type { MarkType, Node as ProseMirrorNode } from "@tiptap/pm/model";
11 import {
12 AllSelection,
13 type EditorState,
14 NodeSelection,
15 Plugin,
16 PluginKey,
17 type Selection,
18 TextSelection,
19 type Transaction,
20 } from "@tiptap/pm/state";
21 import { type Mapping, StepMap } from "@tiptap/pm/transform";
22 import { Decoration, DecorationSet, type EditorView } from "@tiptap/pm/view";
23
24 import {
25 inlineMarkdownUnitMarks,
26 MARKDOWN_SOURCE_MARK,
27 type RichTextMark,
28 } from "~/composer-rich-text";
29 import { caretTakesMarksBefore, serializeEditorDoc } from "~/composer-rich-text-doc";
30
31 // Styled text the selection touches becomes source text with the source mark,
32 // parsed back once the selection leaves. History steps only replay on the shape
33 // they were recorded in, so the history records both rewrites. Recording would
34 // clear redo after undo or redo, so until the next edit see `normalizeDetached`.
35
36 const STYLE_MARKS: RichTextMark[] = ["bold", "italic", "strike", "code"];
37 const PREVIEW_TAGS: Record<Exclude<RichTextMark, "code">, string> = {
38 bold: "strong",
39 italic: "em",
40 strike: "s",
41 };
42 const ATOM_TEXT = "";
43 const DELIMITER = /[*_~`]/;
44
45 type TextRange = { from: number; to: number };
46
47 type StyledRange = TextRange & {
48 escapedOpener: boolean;
49 markers: { at: number; closing: boolean; text: string }[];
50 };
51
52 function collectStyledRanges(doc: ProseMirrorNode): StyledRange[] {
53 const ranges: StyledRange[] = [];
54 const map = serializeEditorDoc(doc);
55 let range: StyledRange | null = null;
56 let openLength = 0;
57 for (const run of map.runs) {
58 if (run.nodeName === "codeBlock") continue;
59 if (run.openLen > 0) {
60 let backslashes = 0;
61 while (map.value[run.mdStart - backslashes - 1] === "\\") backslashes += 1;
62 range ??= {
63 from: run.pmPos,
64 to: run.pmPos,
65 escapedOpener: backslashes % 2 !== 0,
66 markers: [],
67 };
68 range.markers.push({
69 at: run.pmPos,
70 closing: false,
71 text: map.value.slice(run.mdStart, run.mdStart + run.openLen),
72 });
73 }
74 if (range === null) continue;
75 range.to = run.pmPos + run.docLen;
76 if (run.closeLen > 0) {
77 const end = run.mdStart + run.mdLen;
78 range.markers.push({
79 at: range.to,
80 closing: true,
81 text: map.value.slice(end - run.closeLen, end),
82 });
83 }
84 openLength += run.openLen - run.closeLen;
85 if (openLength === 0) {
86 ranges.push(range);
87 range = null;
88 }
89 }
90 return ranges;
91 }
92
93 /** Whether the Markdown that reveal shows for `range` parses back to the same styles. */
94 function revealsFaithfully(doc: ProseMirrorNode, range: StyledRange): boolean {
95 if (range.escapedOpener) return false;
96 const adjacent = withAdjacentDelimiters(doc, range);
97 if (adjacent.from !== range.from || adjacent.to !== range.to) return false;
98 // Parsing keeps escapes as text, so styled `path\` or `2*3` stays styled, unshown.
99 const markers = range.markers.toSorted(
100 (left, right) => left.at - right.at || Number(right.closing) - Number(left.closing),
101 );
102 const expected: Array<RichTextMark[] | null> = [];
103 let text = "";
104 let next = 0;
105 const addMarkers = (pos: number) => {
106 for (; next < markers.length && markers[next]!.at <= pos; next++) {
107 text += markers[next]!.text;
108 expected.push(...markers[next]!.text.split("").map(() => null));
109 }
110 };
111 doc.nodesBetween(range.from, range.to, (node, pos) => {
112 if (!node.isInline) return true;
113 const marks = STYLE_MARKS.filter((name) => node.marks.some((mark) => mark.type.name === name));
114 const from = Math.max(pos, range.from);
115 const content = node.isText ? node.text!.slice(from - pos, range.to - pos) : ATOM_TEXT;
116 for (let index = 0; index < content.length; index++) {
117 addMarkers(from + index);
118 text += content[index];
119 expected.push(marks);
120 }
121 return false;
122 });
123 addMarkers(range.to);
124 return inlineMarkdownUnitMarks(text).every((marks, index) => sameMarks(marks, expected[index]!));
125 }
126
127 function touches(selection: Selection, { from, to }: TextRange): boolean {
128 return selection.empty
129 ? selection.from >= from && selection.from <= to
130 : selection.from < to && selection.to > from;
131 }
132
133 function sourceRegions(doc: ProseMirrorNode, type: MarkType): TextRange[] {
134 const regions: TextRange[] = [];
135 doc.descendants((node, pos) => {
136 if (!node.isTextblock) return true;
137 let current: TextRange | null = null;
138 node.forEach((child, offset) => {
139 const start = pos + 1 + offset;
140 if (!type.isInSet(child.marks)) {
141 current = null;
142 } else if (current) {
143 current.to = start + child.nodeSize;
144 } else {
145 current = { from: start, to: start + child.nodeSize };
146 regions.push(current);
147 }
148 });
149 return false;
150 });
151 return regions;
152 }
153
154 /** Takes in delimiters typed beside the source, like a closing `**` retyped after its text. */
155 function withAdjacentDelimiters(doc: ProseMirrorNode, region: TextRange): TextRange {
156 const before = doc.resolve(region.from).nodeBefore;
157 const after = doc.resolve(region.to).nodeAfter;
158 let from = region.from;
159 let to = region.to;
160 if (before?.isText && before.marks.length === 0) {
161 const text = before.text!;
162 let count = 0;
163 while (count < text.length && DELIMITER.test(text[text.length - 1 - count]!)) count += 1;
164 // Only an odd backslash run escapes the first adjacent delimiter.
165 let backslashes = 0;
166 while (text[text.length - 1 - count - backslashes] === "\\") backslashes += 1;
167 if (count > 0 && backslashes % 2 === 1) count -= 1;
168 from -= count;
169 }
170 if (after?.isText && after.marks.length === 0) {
171 const text = after.text!;
172 let count = 0;
173 while (count < text.length && DELIMITER.test(text[count]!)) count += 1;
174 to += count;
175 }
176 return { from, to };
177 }
178
179 function sameMarks(left: RichTextMark[] | null, right: RichTextMark[] | null): boolean {
180 if (left === null || right === null) return left === right;
181 return left.length === right.length && left.every((mark) => right.includes(mark));
182 }
183
184 /** Calls `visit` for each run of units that parse the same way. */
185 function forEachUnitRun(
186 units: ReadonlyArray<RichTextMark[] | null>,
187 visit: (start: number, end: number, marks: RichTextMark[] | null) => void,
188 ): void {
189 let start = 0;
190 while (start < units.length) {
191 let end = start + 1;
192 while (end < units.length && sameMarks(units[end]!, units[start]!)) end += 1;
193 visit(start, end, units[start]!);
194 start = end;
195 }
196 }
197
198 function regionUnits(doc: ProseMirrorNode, { from, to }: TextRange) {
199 const text = doc.textBetween(from, to, undefined, ATOM_TEXT);
200 return { text, units: inlineMarkdownUnitMarks(text) };
201 }
202
203 function collapseRegion(tr: Transaction, region: TextRange, type: MarkType): void {
204 const { schema } = tr.doc.type;
205 const { units } = regionUnits(tr.doc, region);
206 tr.removeMark(region.from, region.to, type);
207 forEachUnitRun(units, (start, end, marks) => {
208 for (const name of marks ?? []) {
209 const markType = schema.marks[name];
210 if (markType) tr.addMark(region.from + start, region.from + end, markType.create());
211 }
212 });
213 const deletions: TextRange[] = [];
214 forEachUnitRun(units, (start, end, marks) => {
215 if (marks === null) deletions.push({ from: region.from + start, to: region.from + end });
216 });
217 for (const { from, to } of deletions.toReversed()) tr.delete(from, to);
218 }
219
220 /** Parses source the selection does not touch back into marks, in place. */
221 function collapseMarkdownSource(
222 tr: Transaction,
223 keep: (region: TextRange) => boolean = () => false,
224 ): TextRange[] {
225 const type = tr.doc.type.schema.marks[MARKDOWN_SOURCE_MARK];
226 if (!type) return [];
227 const regions: TextRange[] = [];
228 for (const region of sourceRegions(tr.doc, type)) {
229 const extended = withAdjacentDelimiters(tr.doc, region);
230 const previous = regions.at(-1);
231 if (previous && extended.from <= previous.to) previous.to = Math.max(previous.to, extended.to);
232 else regions.push(extended);
233 }
234 for (const region of regions.toReversed()) {
235 if (keep(region)) tr.addMark(region.from, region.to, type.create());
236 else collapseRegion(tr, region, type);
237 }
238 return regions;
239 }
240
241 function mapSelection(tr: Transaction, selection: Selection, map: (pos: number) => number) {
242 if (selection instanceof AllSelection) return new AllSelection(tr.doc);
243 if (selection instanceof NodeSelection) {
244 const pos = map(selection.from);
245 if (tr.doc.nodeAt(pos)) return NodeSelection.create(tr.doc, pos);
246 }
247 return TextSelection.create(tr.doc, map(selection.anchor), map(selection.head));
248 }
249
250 /** Parses all shown source first, so a command that splits it keeps its styles. */
251 export const collapseShownMarkdownSource: Command = ({ tr }) => {
252 const { selection } = tr;
253 const type = tr.doc.type.schema.marks[MARKDOWN_SOURCE_MARK];
254 const marks = tr.storedMarks ?? selection.$from.marks();
255 const regions = collapseMarkdownSource(tr);
256 // A caret after the closing markers is outside the styles, though parsed text there is inclusive.
257 if (type && selection.empty && regions.some(({ to }) => to === selection.from)) {
258 tr.setStoredMarks(type.removeFromSet(marks));
259 }
260 return true;
261 };
262
263 function mapRange(mapping: Mapping, { from, to }: TextRange): TextRange {
264 return { from: mapping.map(from, 1), to: mapping.map(to, -1) };
265 }
266
267 /** Shows styled text the selection touches as Markdown, returning the source it added. */
268 function revealStyledText(tr: Transaction, type: MarkType, typed: boolean, takesBefore: boolean) {
269 const { schema } = tr.doc.type;
270 const selection = tr.selection;
271 const ranges = collectStyledRanges(tr.doc).filter(
272 (range) => touches(selection, range) && revealsFaithfully(tr.doc, range),
273 );
274 const revealed: { range: TextRange; step: number }[] = [];
275 const insertions: { at: number; length: number; closing: boolean }[] = [];
276 for (const range of ranges.toReversed()) {
277 for (const name of STYLE_MARKS) {
278 const markType = schema.marks[name];
279 if (markType) tr.removeMark(range.from, range.to, markType);
280 }
281 let length = 0;
282 // Inserting from the end keeps earlier positions valid; at a shared
283 // position the opening marker goes in first so the closing one ends up before it.
284 const markers = range.markers.toSorted(
285 (left, right) => right.at - left.at || Number(left.closing) - Number(right.closing),
286 );
287 for (const { at, closing, text } of markers) {
288 tr.insert(at, schema.text(text, [type.create()]));
289 insertions.push({ at, length: text.length, closing });
290 length += text.length;
291 }
292 tr.addMark(range.from, range.to + length, type.create());
293 revealed.push({ range: { from: range.from, to: range.to + length }, step: tr.steps.length });
294 }
295 if (ranges.length === 0) return [];
296 // A caret that arrives at a styled edge stays outside its markers. One that
297 // just typed styled text stays inside them, so the next character continues it.
298 const map = (pos: number) => {
299 let next = pos;
300 for (const { at, length, closing } of insertions) {
301 const inside = typed && selection.empty && (closing ? takesBefore : !takesBefore);
302 if (at < pos || (at === pos && (selection instanceof NodeSelection || closing !== inside))) {
303 next += length;
304 }
305 }
306 return next;
307 };
308 tr.setSelection(mapSelection(tr, selection, map));
309 return revealed.map(({ range, step }) => mapRange(tr.mapping.slice(step), range));
310 }
311
312 /** Shows styled text the selection touches as Markdown, and parses source it left. */
313 function normalizeMarkdownSource(state: EditorState, typed: boolean): Transaction | null {
314 const type = state.schema.marks[MARKDOWN_SOURCE_MARK];
315 if (!type) return null;
316 const tr = state.tr;
317 collapseMarkdownSource(tr, (region) => touches(state.selection, region));
318 revealStyledText(tr, type, typed, caretTakesMarksBefore(state));
319 return tr.docChanged ? tr : null;
320 }
321
322 /**
323 * After undo or redo, history items may point inside shown source, and a
324 * rewrite in the history would clear redo. So until the next recorded edit,
325 * rewrites stay out of it and only remove text they added: source the history
326 * knows is hidden instead of parsed, and source revealed here is parsed back.
327 */
328 function normalizeDetached(state: EditorState, revealed: TextRange[]): Transaction | null {
329 const type = state.schema.marks[MARKDOWN_SOURCE_MARK];
330 if (!type) return null;
331 const tr = state.tr;
332 const kept: TextRange[] = [];
333 for (const region of revealed.toSorted((left, right) => right.from - left.from)) {
334 if (touches(state.selection, region)) kept.push(region);
335 else collapseRegion(tr, region, type);
336 }
337 const added = revealStyledText(tr, type, false, caretTakesMarksBefore(state));
338 if (!tr.docChanged) return null;
339 const shown = [...kept.map((region) => mapRange(tr.mapping, region)), ...added];
340 return tr.setMeta(markdownSourceKey, shown).setMeta("addToHistory", false);
341 }
342
343 /** Parses the source `normalizeDetached` revealed, leaving the document the history knows. */
344 function collapseRevealed(state: EditorState, revealed: TextRange[]): Transaction {
345 const tr = state.tr;
346 const type = state.schema.marks[MARKDOWN_SOURCE_MARK];
347 if (type) {
348 for (const region of revealed.toSorted((left, right) => right.from - left.from)) {
349 collapseRegion(tr, region, type);
350 }
351 }
352 return tr.setMeta(markdownSourceKey, []).setMeta("addToHistory", false);
353 }
354
355 /** Replays `edit` after undoing `collapse`, so the history records the reveal with the edit. */
356 function rebaseEdit(tr: Transaction, collapse: Transaction, edit: Transaction): Transaction {
357 for (let index = collapse.steps.length - 1; index >= 0; index--) {
358 tr.step(collapse.steps[index]!.invert(collapse.docs[index]!));
359 }
360 for (const step of edit.steps) tr.step(step);
361 tr.setSelection(edit.selection.map(tr.doc, StepMap.empty)).setTime(edit.time);
362 if (edit.storedMarksSet) tr.setStoredMarks(edit.storedMarks);
363 if (edit.scrolledIntoView) tr.scrollIntoView();
364 // Metadata has no public accessor, and grouping, paste rules and composition read it.
365 type WithMeta = { meta: Record<string, unknown> };
366 Object.assign((tr as unknown as WithMeta).meta, (edit as unknown as WithMeta).meta);
367 return tr;
368 }
369
370 const replayKey = new PluginKey("composer-markdown-source-replay");
371
372 /**
373 * Replays the edit a request carries after the source plugin appended its collapse,
374 * in the request's one view update so an IME keeps its preedit. History ignores what
375 * is appended to an unrecorded transaction, so the request itself records nothing.
376 */
377 const replayPlugin = new Plugin({
378 key: replayKey,
379 appendTransaction([request, collapse], _, state) {
380 const edit = request?.getMeta(replayKey) as Transaction | undefined;
381 // Appended transactions otherwise join the previous undo event.
382 return edit && collapse ? closeHistory(rebaseEdit(state.tr, collapse, edit)) : null;
383 },
384 });
385
386 function previewDecorations(
387 doc: ProseMirrorNode,
388 type: MarkType,
389 hidden: Selection | null,
390 ): DecorationSet {
391 const decorations: Decoration[] = [];
392 for (const region of sourceRegions(doc, type)) {
393 const hide = hidden !== null && !touches(hidden, region);
394 const { text, units } = regionUnits(doc, region);
395 const codeTicks = new Set<number>();
396 forEachUnitRun(units, (start, end, marks) => {
397 for (const name of marks ?? []) {
398 if (name !== "code") {
399 decorations.push(
400 Decoration.inline(region.from + start, region.from + end, {
401 nodeName: PREVIEW_TAGS[name],
402 }),
403 );
404 continue;
405 }
406 // One element holds the ticks and the code, so a right-to-left line
407 // keeps both ticks on their own sides of it.
408 let from = start;
409 let to = end;
410 if (units[from - 1] === null && text[from - 1] === "`") codeTicks.add((from -= 1));
411 if (units[to] === null && text[to] === "`") codeTicks.add(to++);
412 decorations.push(
413 Decoration.inline(region.from + from, region.from + to, { nodeName: "code", dir: "ltr" }),
414 );
415 }
416 });
417 forEachUnitRun(
418 units.map((marks, index) => (marks === null && (hide || !codeTicks.has(index)) ? null : [])),
419 (start, end, marks) => {
420 if (marks !== null) return;
421 decorations.push(
422 Decoration.inline(region.from + start, region.from + end, {
423 class: hide ? "composer-rich-marker-hidden" : "composer-rich-marker",
424 }),
425 );
426 },
427 );
428 }
429 return DecorationSet.create(doc, decorations);
430 }
431
432 type MarkdownSourceState = {
433 decorations: DecorationSet;
434 /** From an undo or redo until the next recorded edit; see `normalizeDetached`. */
435 detached: boolean;
436 /** Source `normalizeDetached` revealed, which the history knows as styled text. */
437 revealed: TextRange[];
438 };
439
440 const markdownSourceKey = new PluginKey<MarkdownSourceState>("composer-markdown-source");
441
442 function markdownSourcePlugin(type: MarkType): Plugin<MarkdownSourceState> {
443 let view: EditorView | null = null;
444 return new Plugin<MarkdownSourceState>({
445 key: markdownSourceKey,
446 view(editorView) {
447 view = editorView;
448 return {
449 destroy() {
450 view = null;
451 },
452 };
453 },
454 state: {
455 init: (_, state) => ({
456 decorations: previewDecorations(state.doc, type, null),
457 detached: false,
458 revealed: [],
459 }),
460 apply: (tr, old, _, state) => {
461 const history = isHistoryTransaction(tr);
462 const detached =
463 history || (old.detached && !(tr.docChanged && tr.getMeta("addToHistory") !== false));
464 const own = tr.getMeta(markdownSourceKey) as TextRange[] | undefined;
465 const revealed =
466 !detached || history
467 ? []
468 : (own ??
469 (tr.docChanged
470 ? old.revealed.map((range) => mapRange(tr.mapping, range))
471 : old.revealed));
472 const redraw = tr.docChanged || detached !== old.detached || (detached && tr.selectionSet);
473 return {
474 decorations: redraw
475 ? previewDecorations(state.doc, type, detached ? state.selection : null)
476 : old.decorations,
477 detached,
478 revealed,
479 };
480 },
481 },
482 props: {
483 decorations: (state) => markdownSourceKey.getState(state)?.decorations,
484 },
485 appendTransaction(transactions, _, state) {
486 if (transactions[0]?.getMeta(replayKey)) {
487 return collapseRevealed(state, markdownSourceKey.getState(state)?.revealed ?? []);
488 }
489 // Rewriting text mid-composition would break the IME's preedit.
490 if (view?.composing) return null;
491 // Rewrites appended to an undo or redo join its history step, which leaves
492 // the other direction unmapped. The dispatch hook normalizes after it instead.
493 if (transactions.some((tr) => isHistoryTransaction(tr) || tr.getMeta(markdownSourceKey))) {
494 return null;
495 }
496 if (!transactions.some((tr) => tr.docChanged || tr.selectionSet)) return null;
497 const source = markdownSourceKey.getState(state);
498 if (source?.detached) return normalizeDetached(state, source.revealed);
499 const tr = normalizeMarkdownSource(
500 state,
501 transactions.some((item) => item.docChanged),
502 );
503 // With nothing to undo, a recorded rewrite would only add a no-op undo.
504 if (tr && undoDepth(state) === 0) tr.setMeta("addToHistory", false);
505 return tr;
506 },
507 });
508 }
509
510 /** Keeps source `normalizeDetached` revealed out of what undo, redo and edits see. */
511 const MarkdownSourceHistoryExtension = Extension.create({
512 name: "composer-markdown-source-history",
513 // Runs after undo grouping, so a rebased edit keeps the grouping chosen for it.
514 priority: 1,
515 dispatchTransaction({ transaction, next }) {
516 const { editor } = this;
517 const revealed = markdownSourceKey.getState(editor.state)?.revealed ?? [];
518 if (isHistoryTransaction(transaction)) {
519 if (revealed.length === 0) {
520 next(transaction);
521 } else {
522 const undoing = redoDepth(editor.state.apply(transaction)) > redoDepth(editor.state);
523 next(collapseRevealed(editor.state, revealed));
524 (undoing ? undo : redo)(editor.state, next);
525 }
526 const source = markdownSourceKey.getState(editor.state);
527 const tr = editor.view.composing
528 ? null
529 : normalizeDetached(editor.state, source?.revealed ?? []);
530 if (tr) next(tr);
531 return;
532 }
533 const recordedEdit =
534 transaction.docChanged &&
535 transaction.getMeta("addToHistory") !== false &&
536 transaction.getMeta(markdownSourceKey) === undefined;
537 if (revealed.length === 0 || !recordedEdit) {
538 next(transaction);
539 return;
540 }
541 next(editor.state.tr.setMeta(replayKey, transaction));
542 },
543 });
544
545 export const ComposerMarkdownSourceExtension = TiptapMark.create({
546 name: MARKDOWN_SOURCE_MARK,
547 // Its shortcuts run ahead of the style marks' own.
548 priority: 1001,
549 inclusive: false,
550 parseHTML() {
551 return [{ tag: "span.composer-markdown-source" }];
552 },
553 renderHTML() {
554 return ["span", { class: "composer-markdown-source" }, 0];
555 },
556 addKeyboardShortcuts() {
557 // Shown markers are plain text, so toggling a style there would wrap them
558 // in another style. Parse the source first and toggle the result.
559 const toggle = (name: RichTextMark) => () => {
560 const { state } = this.editor;
561 const { selection } = state;
562 const touched = sourceRegions(state.doc, this.type).some((region) => {
563 if (!touches(selection, region)) return false;
564 if (!selection.empty) return true;
565 // Turning a style off just inside its own markers would type into them.
566 // Everywhere else Tiptap's own toggle styles the typed text correctly.
567 const { units } = regionUnits(state.doc, region);
568 const offset = selection.from - region.from;
569 const [before, after] = [units[offset - 1], units[offset]];
570 return (
571 (before === null && after?.includes(name) === true) ||
572 (after === null && before?.includes(name) === true)
573 );
574 });
575 if (!touched) return false;
576 return this.editor.chain().command(collapseShownMarkdownSource).toggleMark(name).run();
577 };
578 return {
579 "Mod-b": toggle("bold"),
580 "Mod-B": toggle("bold"),
581 "Mod-i": toggle("italic"),
582 "Mod-I": toggle("italic"),
583 "Mod-Shift-s": toggle("strike"),
584 "Mod-e": toggle("code"),
585 };
586 },
587 addExtensions() {
588 return [MarkdownSourceHistoryExtension];
589 },
590 addProseMirrorPlugins() {
591 return [markdownSourcePlugin(this.type), replayPlugin];
592 },
593 });