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