Open History to see the last commit
1import { Mark, type Node as ProseMirrorNode } from "@tiptap/pm/model";
2import type { EditorState, Transaction } from "@tiptap/pm/state";
3import { Code } from "@tiptap/extension-code";
4import { TaskItem } from "@tiptap/extension-task-item";
5
6import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
7import { parseInlineMarkdown, RICH_TEXT_DELIMITERS, type RichTextMark } from "~/composer-rich-text";
8import { collectInlineContextIds } from "~/lib/composerContextReferences";
9
10/**
11 * Pure document model for the rich text (Tiptap) composer.
12 *
13 * The stored prompt stays markdown (`**bold**`, `@file` chips as canonical
14 * links). The Tiptap document holds styled text plus inline atom chips, so
15 * this module translates both ways and maps cursor offsets between the three
16 * coordinate spaces the composer speaks:
17 *
18 * - flat document offsets (styled markers excluded, chips count 1),
19 * - collapsed cursor offsets (markers literal, chips count 1 — the coordinate
20 * the draft store and mention detection use),
21 * - markdown offsets (markers literal, chips expand to their source).
22 *
23 * DOM-free on purpose: unit tests build a real ProseMirror document from the
24 * JSON this produces and assert the round trip without a browser.
25 */
26
27export type SkillMeta = { label: string; description: string | null };
28
29/** Outermost mark first, so closers mirror openers when nested. */
30const MARK_NESTING_ORDER: RichTextMark[] = ["strike", "bold", "italic", "code"];
31
32const MARK_TO_TIPTAP: Record<RichTextMark, string> = {
33 bold: "bold",
34 italic: "italic",
35 strike: "strike",
36 code: "code",
37};
38
39const TIPTAP_TO_MARK: Record<string, RichTextMark> = {
40 bold: "bold",
41 italic: "italic",
42 strike: "strike",
43 code: "code",
44};
45
46/**
47 * Tiptap's code mark excludes every other mark, which rejects the `bold+code`
48 * spans markdown like `**\`x\`**` parses into and drops the whole insert.
49 * Code nests inside emphasis here, so it only excludes itself like the rest.
50 */
51export const ComposerCodeExtension = Code.extend({
52 excludes: "code",
53 // ArrowRight leaves code through the caret stops at styled edges, so the
54 // stock exit (inserting a space at the end of a line) is not needed.
55 exitable: false,
56});
57
58/**
59 * Task list items keep their exact source indent in an attribute so nesting
60 * round-trips byte-identically. Checkbox case (`[X]`) normalizes to `[x]` —
61 * the same fixed-point deal as `__bold__` becoming `**bold**`.
62 */
63export const ComposerTaskItemExtension = TaskItem.extend({
64 addAttributes() {
65 return {
66 ...this.parent?.(),
67 indent: { default: "" },
68 markerSpace: { default: " " },
69 contentSpace: { default: null },
70 };
71 },
72}).configure({ nested: true });
73
74function randomNodeKey(): string {
75 return `tiptap-${Math.random().toString(36).slice(2)}`;
76}
77
78interface TaskLinePrefix {
79 indent: string;
80 checked: boolean;
81 markerSpace: string;
82 contentSpace: string;
83}
84
85function parseTaskPrefix(head: string): { prefix: TaskLinePrefix; markerLength: number } | null {
86 const match = head.match(/^([ \t]*)-([ \t]+)\[([ xX])\]([ \t]*)/);
87 if (!match) return null;
88 const after = head.slice(match[0].length);
89 if (after.length > 0 && !match[4]) return null;
90 return {
91 prefix: {
92 indent: match[1] ?? "",
93 checked: (match[3] ?? " ").toLowerCase() === "x",
94 markerSpace: match[2]!,
95 contentSpace: match[4]!,
96 },
97 markerLength: match[0].length,
98 };
99}
100
101type InlineJson = Record<string, unknown>;
102
103interface DocLine {
104 task: TaskLinePrefix | null;
105 inline: InlineJson[];
106}
107
108function atomJsonForSegment(
109 segment: Exclude<ReturnType<typeof splitPromptIntoComposerSegments>[number], { type: "text" }>,
110 skillLabelFor: (name: string) => SkillMeta,
111): InlineJson {
112 if (segment.type === "mention") {
113 return {
114 type: "composer-mention",
115 attrs: { path: segment.path, source: segment.source },
116 };
117 }
118 if (segment.type === "skill") {
119 const meta = skillLabelFor(segment.name);
120 return {
121 type: "composer-skill",
122 attrs: {
123 skillName: segment.name,
124 skillLabel: meta.label,
125 skillDescription: meta.description,
126 },
127 };
128 }
129 if (segment.type === "citation") {
130 return {
131 type: "composer-citation",
132 attrs: { citation: segment.citation, source: segment.source, citeKey: randomNodeKey() },
133 };
134 }
135 return {
136 type: "composer-context-reference",
137 attrs: {
138 kind: segment.kind,
139 contextId: segment.contextId,
140 label: segment.label,
141 source: segment.source,
142 },
143 };
144}
145
146interface PendingTaskItem extends TaskLinePrefix {
147 content: InlineJson[];
148 children: PendingTaskItem[];
149}
150
151function taskListJson(items: PendingTaskItem[]): InlineJson {
152 return {
153 type: "taskList",
154 content: items.map((item) => ({
155 type: "taskItem",
156 attrs: {
157 checked: item.checked,
158 indent: item.indent,
159 markerSpace: item.markerSpace,
160 contentSpace: item.contentSpace,
161 },
162 content: [
163 { type: "paragraph", content: item.content },
164 ...(item.children.length > 0 ? [taskListJson(item.children)] : []),
165 ],
166 })),
167 };
168}
169
170function textJsonForSpan(text: string, marks: RichTextMark[]): Record<string, unknown> {
171 const json: Record<string, unknown> = { type: "text", text };
172 if (marks.length > 0) {
173 json.marks = [...marks]
174 .sort((a, b) => MARK_NESTING_ORDER.indexOf(a) - MARK_NESTING_ORDER.indexOf(b))
175 .map((mark) => ({ type: MARK_TO_TIPTAP[mark] }));
176 }
177 return json;
178}
179
180export function buildTiptapContent(
181 value: string,
182 skillLabelFor: (name: string) => SkillMeta,
183 options?: { styling?: boolean },
184): Record<string, unknown>[] {
185 const styling = options?.styling ?? true;
186 // Hide token source from the markdown parser, then restore the atoms with
187 // the marks of their surrounding text. Choose a sentinel absent from input.
188 let sentinel = "\uFFFC";
189 for (let codePoint = 0xe000; value.includes(sentinel); codePoint += 1) {
190 sentinel = String.fromCodePoint(codePoint);
191 }
192 const atoms: InlineJson[] = [];
193 const text = splitPromptIntoComposerSegments(value)
194 .map((segment) => {
195 if (segment.type === "text") return segment.text;
196 atoms.push(atomJsonForSegment(segment, skillLabelFor));
197 return sentinel;
198 })
199 .join("");
200 let atomIndex = 0;
201 const lines: DocLine[] = text.split("\n").map((line) => {
202 const parsed = styling ? parseTaskPrefix(line) : null;
203 const content = parsed ? line.slice(parsed.markerLength) : line;
204 const spans = styling ? parseInlineMarkdown(content) : [{ text: content, marks: [] }];
205 const inline: InlineJson[] = [];
206 for (const span of spans) {
207 span.text.split(sentinel).forEach((piece, index) => {
208 if (index > 0) {
209 const atom = atoms[atomIndex++]!;
210 inline.push({ ...atom, marks: textJsonForSpan("", span.marks).marks });
211 }
212 if (piece) inline.push(textJsonForSpan(piece, span.marks));
213 });
214 }
215 return { task: parsed?.prefix ?? null, inline };
216 });
217
218 // Pass 2: consecutive task lines group into (possibly nested) task lists
219 // by indent prefix; everything else stays a paragraph.
220 const blocks: Record<string, unknown>[] = [];
221 let stack: { indent: string; items: PendingTaskItem[] }[] = [];
222 const flushTasks = () => {
223 if (stack.length > 0) {
224 blocks.push(taskListJson(stack[0]!.items));
225 stack = [];
226 }
227 };
228 for (const line of lines) {
229 if (!line.task) {
230 flushTasks();
231 blocks.push({ type: "paragraph", content: line.inline });
232 continue;
233 }
234 const item: PendingTaskItem = {
235 ...line.task,
236 content: line.inline,
237 children: [],
238 };
239 for (;;) {
240 const top = stack[stack.length - 1];
241 if (!top) {
242 // A leading indented item with no parent flattens but keeps indent.
243 stack.push({ indent: item.indent, items: [] });
244 continue;
245 }
246 if (top.indent === item.indent) {
247 top.items.push(item);
248 break;
249 }
250 if (top.indent !== "" && !item.indent.startsWith(top.indent)) {
251 if (stack.length > 1) {
252 stack.pop();
253 continue;
254 }
255 top.indent = item.indent;
256 top.items.push(item);
257 break;
258 }
259 const parent = top.items[top.items.length - 1];
260 if (!parent) {
261 top.items.push(item);
262 break;
263 }
264 parent.children.push(item);
265 stack.push({ indent: item.indent, items: parent.children });
266 break;
267 }
268 }
269 flushTasks();
270 return blocks;
271}
272
273export function buildDocJson(
274 value: string,
275 skillLabelFor: (name: string) => SkillMeta,
276 options?: { styling?: boolean },
277) {
278 return { type: "doc", content: buildTiptapContent(value, skillLabelFor, options) };
279}
280
281export interface RichRun {
282 kind: "text" | "token" | "break" | "prefix";
283 /** Flat document offset (atoms count 1, markers excluded). */
284 flatStart: number;
285 docLen: number;
286 /** Collapsed cursor length (markers literal, tokens count 1). */
287 collapsedLen: number;
288 /** Markdown length (tokens expand to their source). */
289 mdLen: number;
290 /** Marker layout inside text runs. */
291 openLen: number;
292 closeLen: number;
293 /** ProseMirror position of the run start. */
294 pmPos: number;
295 mdStart: number;
296 collapsedStart: number;
297 nodeName?: string;
298}
299
300export interface RichDocMap {
301 value: string;
302 runs: RichRun[];
303 docLength: number;
304 contextIds: string[];
305}
306
307function readAtomSource(node: ProseMirrorNode): string {
308 const attrs = node.attrs as Record<string, unknown>;
309 switch (node.type.name) {
310 case "composer-mention":
311 case "composer-citation":
312 case "composer-context-reference":
313 return typeof attrs.source === "string" ? attrs.source : "";
314 case "composer-skill": {
315 const name = typeof attrs.skillName === "string" ? attrs.skillName : "";
316 return name ? `$${name}` : "";
317 }
318 default:
319 return "";
320 }
321}
322
323interface RichAccumulator {
324 runs: RichRun[];
325 value: string;
326 flat: number;
327 collapsed: number;
328 md: number;
329}
330
331function pushBreakRun(acc: RichAccumulator, position?: number): void {
332 const previous = acc.runs[acc.runs.length - 1];
333 const pmPos = position ?? (previous ? previous.pmPos + previous.docLen : 1);
334 // Block boundary: one newline in every coordinate space.
335 acc.runs.push({
336 kind: "break",
337 flatStart: acc.flat,
338 docLen: 1,
339 collapsedLen: 1,
340 mdLen: 1,
341 openLen: 0,
342 closeLen: 0,
343 pmPos,
344 mdStart: acc.md,
345 collapsedStart: acc.collapsed,
346 });
347 acc.value += "\n";
348 acc.flat += 1;
349 acc.collapsed += 1;
350 acc.md += 1;
351}
352
353function appendInlineRuns(
354 container: ProseMirrorNode,
355 contentStart: number,
356 acc: RichAccumulator,
357): void {
358 const children: ProseMirrorNode[] = [];
359 container.forEach((child) => {
360 if (!child.isText || child.marks.some((mark) => mark.type.name === "code")) {
361 children.push(child);
362 return;
363 }
364 // Separate boundary whitespace so delimiters can move past it without
365 // changing the document offsets or marks on the visible text.
366 const text = child.text!;
367 const start = text.length - text.trimStart().length;
368 const end = Math.max(start, text.trimEnd().length);
369 let offset = 0;
370 for (const boundary of [start, end, text.length]) {
371 if (boundary > offset) children.push(child.cut(offset, boundary));
372 offset = boundary;
373 }
374 });
375 // Emphasis cannot open or close next to whitespace. Retain a whitespace
376 // mark only when its range has visible content on both sides.
377 for (const mark of MARK_NESTING_ORDER) {
378 if (mark === "code") continue;
379 for (const direction of [1, -1]) {
380 let hasContent = false;
381 for (
382 let index = direction === 1 ? 0 : children.length - 1;
383 index >= 0 && index < children.length;
384 index += direction
385 ) {
386 const child = children[index]!;
387 if (
388 child.type.name === "hardBreak" ||
389 !child.marks.some((item) => item.type.name === mark)
390 ) {
391 hasContent = false;
392 } else if (
393 child.isText &&
394 !child.marks.some((item) => item.type.name === "code") &&
395 /^\s+$/.test(child.text!)
396 ) {
397 if (!hasContent)
398 children[index] = child.mark(child.marks.filter((item) => item.type.name !== mark));
399 } else {
400 hasContent = true;
401 }
402 }
403 }
404 }
405 // Longer shared marks surround shorter ones. This keeps both nested
406 // formatting and formatting across chips inside a single delimiter pair.
407 const markEnds = new Map<RichTextMark, number>();
408 const orderedMarks: RichTextMark[][] = [];
409 for (let index = children.length - 1; index >= 0; index -= 1) {
410 const child = children[index]!;
411 const marks =
412 child.type.name === "hardBreak"
413 ? []
414 : child.marks
415 .map((mark) => TIPTAP_TO_MARK[mark.type.name])
416 .filter((mark): mark is RichTextMark => Boolean(mark));
417 for (const mark of MARK_NESTING_ORDER) {
418 if (!marks.includes(mark)) markEnds.delete(mark);
419 else if (!markEnds.has(mark)) markEnds.set(mark, index);
420 }
421 orderedMarks[index] = marks.sort(
422 (a, b) =>
423 markEnds.get(b)! - markEnds.get(a)! ||
424 MARK_NESTING_ORDER.indexOf(a) - MARK_NESTING_ORDER.indexOf(b),
425 );
426 }
427 for (let index = 1; index < orderedMarks.length; index += 1) {
428 const marks = orderedMarks[index]!;
429 const retained: RichTextMark[] = [];
430 for (const mark of orderedMarks[index - 1]!) {
431 if (!marks.includes(mark)) break;
432 retained.push(mark);
433 }
434 orderedMarks[index] = [...retained, ...marks.filter((mark) => !retained.includes(mark))];
435 }
436 const commonLength = (left: RichTextMark[], right: RichTextMark[]) => {
437 let index = 0;
438 while (index < left.length && left[index] === right[index]) index += 1;
439 return index;
440 };
441 let inlineOffset = 0;
442 children.forEach((child, index) => {
443 const pmPos = contentStart + inlineOffset;
444 inlineOffset += child.nodeSize;
445 if (child.type.name === "hardBreak") {
446 pushBreakRun(acc, pmPos);
447 return;
448 }
449 const marks = orderedMarks[index]!;
450 const open = marks
451 .slice(commonLength(marks, orderedMarks[index - 1] ?? []))
452 .map((mark) => RICH_TEXT_DELIMITERS[mark])
453 .join("");
454 const close = marks
455 .slice(commonLength(marks, orderedMarks[index + 1] ?? []))
456 .toReversed()
457 .map((mark) => RICH_TEXT_DELIMITERS[mark])
458 .join("");
459 const source = child.isText ? child.text! : readAtomSource(child);
460 const docLen = child.isText ? source.length : 1;
461 const mdText = open + source + close;
462 const collapsedLen = open.length + docLen + close.length;
463 acc.runs.push({
464 kind: child.isText ? "text" : "token",
465 flatStart: acc.flat,
466 docLen,
467 collapsedLen,
468 mdLen: mdText.length,
469 openLen: open.length,
470 closeLen: close.length,
471 pmPos,
472 mdStart: acc.md,
473 collapsedStart: acc.collapsed,
474 ...(child.isText ? {} : { nodeName: child.type.name }),
475 });
476 acc.value += mdText;
477 acc.flat += docLen;
478 acc.collapsed += collapsedLen;
479 acc.md += mdText.length;
480 });
481 // Empty paragraphs have an editable position even though they emit no text.
482 if (children.length === 0) {
483 acc.runs.push({
484 kind: "text",
485 flatStart: acc.flat,
486 docLen: 0,
487 collapsedLen: 0,
488 mdLen: 0,
489 openLen: 0,
490 closeLen: 0,
491 pmPos: contentStart,
492 mdStart: acc.md,
493 collapsedStart: acc.collapsed,
494 });
495 }
496}
497
498function walkTaskList(list: ProseMirrorNode, listStart: number, acc: RichAccumulator): void {
499 let itemPos = listStart + 1;
500 let firstItem = true;
501 list.content.forEach((item) => {
502 // Sibling items are separated by one newline in every coordinate space.
503 if (!firstItem) pushBreakRun(acc);
504 firstItem = false;
505 const itemContentStart = itemPos + 1;
506 const first = item.firstChild;
507 const empty = first?.type.name === "paragraph" && first.content.childCount === 0;
508 const attrs = item.attrs as Record<string, unknown>;
509 const indent = typeof attrs.indent === "string" ? attrs.indent : "";
510 const markerSpace = typeof attrs.markerSpace === "string" ? attrs.markerSpace : " ";
511 const contentSpace =
512 typeof attrs.contentSpace === "string"
513 ? attrs.contentSpace || (empty ? "" : " ")
514 : empty
515 ? ""
516 : " ";
517 const prefix = `${indent}-${markerSpace}[${attrs.checked === true ? "x" : " "}]${contentSpace}`;
518 // The checkbox owns no document characters; every prefix offset clamps
519 // to the start of the item text, exactly like style markers.
520 acc.runs.push({
521 kind: "prefix",
522 flatStart: acc.flat,
523 docLen: 0,
524 collapsedLen: prefix.length,
525 mdLen: prefix.length,
526 openLen: 0,
527 closeLen: 0,
528 pmPos: itemContentStart + 1,
529 mdStart: acc.md,
530 collapsedStart: acc.collapsed,
531 });
532 acc.value += prefix;
533 acc.collapsed += prefix.length;
534 acc.md += prefix.length;
535 let childPos = itemContentStart;
536 let firstBlock = true;
537 item.content.forEach((child) => {
538 if (!firstBlock) pushBreakRun(acc);
539 firstBlock = false;
540 if (child.type.name === "taskList") {
541 walkTaskList(child, childPos, acc);
542 } else if (child.type.name === "paragraph") {
543 appendInlineRuns(child, childPos + 1, acc);
544 }
545 childPos += child.nodeSize;
546 });
547 itemPos += item.nodeSize;
548 });
549}
550
551export function serializeEditorDoc(doc: ProseMirrorNode): RichDocMap {
552 const acc: RichAccumulator = { runs: [], value: "", flat: 0, collapsed: 0, md: 0 };
553 const blocks: ProseMirrorNode[] = [];
554 doc.content.forEach((node) => {
555 blocks.push(node);
556 });
557
558 let pmBlockStart = 0;
559 blocks.forEach((block, blockIndex) => {
560 if (blockIndex > 0) pushBreakRun(acc);
561 if (block.type.name === "taskList") {
562 walkTaskList(block, pmBlockStart, acc);
563 } else if (block.type.name === "paragraph") {
564 appendInlineRuns(block, pmBlockStart + 1, acc);
565 }
566 pmBlockStart += block.nodeSize;
567 });
568
569 return {
570 value: acc.value,
571 runs: acc.runs,
572 docLength: acc.flat,
573 contextIds: Array.from(new Set(collectInlineContextIds(acc.value))),
574 };
575}
576
577function lastRunEnd(map: RichDocMap, space: "collapsed" | "md"): number {
578 const last = map.runs[map.runs.length - 1];
579 if (!last) return 0;
580 return space === "collapsed"
581 ? last.collapsedStart + last.collapsedLen
582 : last.mdStart + last.mdLen;
583}
584
585export function flatToCollapsed(map: RichDocMap, flatOffset: number): number {
586 const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
587 for (const run of map.runs) {
588 if (bounded < run.flatStart + run.docLen) {
589 if (run.kind === "text" || run.kind === "token") {
590 return run.collapsedStart + run.openLen + (bounded - run.flatStart);
591 }
592 return run.collapsedStart + (bounded - run.flatStart);
593 }
594 }
595 return lastRunEnd(map, "collapsed");
596}
597
598export function flatToMarkdown(map: RichDocMap, flatOffset: number): number {
599 const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
600 for (const run of map.runs) {
601 if (bounded < run.flatStart + run.docLen) {
602 if (run.kind === "text" || run.kind === "token") {
603 return run.mdStart + run.openLen + (bounded - run.flatStart);
604 }
605 return run.mdStart + (bounded - run.flatStart);
606 }
607 }
608 return lastRunEnd(map, "md");
609}
610
611export function collapsedToFlat(map: RichDocMap, collapsedOffset: number): number {
612 for (const run of map.runs) {
613 if (collapsedOffset < run.collapsedStart + run.collapsedLen) {
614 // Checkbox prefixes and style markers are shown, never edited: every
615 // offset inside them clamps to the adjacent document position.
616 if (run.kind === "prefix") return run.flatStart;
617 if (run.kind === "text" || run.kind === "token") {
618 const within = collapsedOffset - run.collapsedStart;
619 // Marker characters clamp to the styled edge: they are shown, never edited.
620 if (within <= run.openLen) return run.flatStart;
621 if (within >= run.openLen + run.docLen) return run.flatStart + run.docLen;
622 return run.flatStart + (within - run.openLen);
623 }
624 return run.flatStart + (collapsedOffset - run.collapsedStart);
625 }
626 }
627 return map.docLength;
628}
629
630export function flatToPm(map: RichDocMap, flatOffset: number): number {
631 const bounded = Math.max(0, Math.min(flatOffset, map.docLength));
632 for (const run of map.runs) {
633 if (bounded < run.flatStart + run.docLen) {
634 return run.pmPos + (bounded - run.flatStart);
635 }
636 }
637 const last = map.runs[map.runs.length - 1];
638 if (!last) return 1;
639 return last.pmPos + last.docLen;
640}
641
642export function pmToFlat(map: RichDocMap, pmPos: number): number {
643 for (const run of map.runs) {
644 if (pmPos >= run.pmPos && pmPos <= run.pmPos + run.docLen) {
645 // A position on a chip's trailing edge belongs after the chip.
646 if (run.kind === "token" && pmPos === run.pmPos + run.docLen) {
647 return run.flatStart + run.docLen;
648 }
649 return run.flatStart + Math.min(pmPos - run.pmPos, run.docLen);
650 }
651 }
652 // A paragraph boundary position belongs to the newline between paragraphs.
653 let best = 0;
654 for (const run of map.runs) {
655 if (run.pmPos <= pmPos) best = run.flatStart + run.docLen;
656 }
657 return Math.max(0, Math.min(best, map.docLength));
658}
659
660// ── Caret stops at styled edges ────────────────────────────────────────────
661//
662// Markers are decorations, not text, so the position where styled text meets
663// unstyled text (or a paragraph edge) is a single document position. The
664// caret gets two stops there: one that types with the marks before the edge
665// and one that types with the marks after it. Stored marks pick the stop, and
666// the revealed markers render on the matching side of the caret, so a pasted
667// `**bold**` at the start of a line can still be typed in front of.
668
669function styledEdge(state: EditorState) {
670 const { selection } = state;
671 if (!selection.empty) return null;
672 const { $from } = selection;
673 if (!$from.parent.inlineContent) return null;
674 const before = $from.nodeBefore?.marks ?? Mark.none;
675 const after = $from.nodeAfter?.marks ?? Mark.none;
676 if (Mark.sameSet(before, after)) return null;
677 return { before, after, current: state.storedMarks ?? $from.marks() };
678}
679
680/** True when the caret sits on a styled edge and types with the marks before it. */
681export function caretTakesMarksBefore(state: EditorState): boolean {
682 const edge = styledEdge(state);
683 return edge !== null && Mark.sameSet(edge.current, edge.before);
684}
685
686/**
687 * Moves the caret to the other stop of the styled edge it sits on, toward
688 * `direction`. Returns null when there is no stop to take, so the arrow key
689 * moves the caret as usual.
690 */
691export function stepCaretAcrossStyledEdge(
692 state: EditorState,
693 direction: -1 | 1,
694): Transaction | null {
695 const edge = styledEdge(state);
696 if (!edge) return null;
697 // Marks the user toggled by hand (neither stop) are theirs: move as usual.
698 if (!Mark.sameSet(edge.current, edge.before) && !Mark.sameSet(edge.current, edge.after)) {
699 return null;
700 }
701 const target = direction === -1 ? edge.before : edge.after;
702 if (Mark.sameSet(edge.current, target)) return null;
703 return state.tr.setStoredMarks(target);
704}