Open History to see the last commit
1import type { ContentMatch, NodeType } from "@tiptap/pm/model";
2import type { EditorState, Transaction } from "@tiptap/pm/state";
3import { Selection, TextSelection } from "@tiptap/pm/state";
4import type { EditorView } from "@tiptap/pm/view";
5
6import { isClosingFence, parseOpeningFence, serializeSelection } from "~/composer-rich-text-doc";
7
8const CODE_BLOCK_INDENT = " ";
9
10function leadingWhitespace(line: string): string {
11 return /^[ \t]*/.exec(line)?.[0] ?? "";
12}
13
14function outdentLine(line: string): string {
15 if (line.startsWith(CODE_BLOCK_INDENT)) return line.slice(CODE_BLOCK_INDENT.length);
16 if (line.startsWith("\t")) return line.slice(1);
17 if (line.startsWith(" ")) return line.slice(1);
18 return line;
19}
20
21function indentLines(lines: ReadonlyArray<string>, direction: "in" | "out"): string[] {
22 return lines.map((line) => {
23 if (direction === "in") return line.length === 0 ? line : `${CODE_BLOCK_INDENT}${line}`;
24 return outdentLine(line);
25 });
26}
27
28export function selectionInOneCodeBlock(state: EditorState): boolean {
29 const { $from, $to } = state.selection;
30 return $from.parent.type.spec.code === true && $from.sameParent($to);
31}
32
33function codeBlockRange(
34 state: EditorState,
35): { readonly from: number; readonly to: number; readonly text: string } | null {
36 const { $from, $to } = state.selection;
37 const parent = $from.parent;
38 if (parent.type.spec.code !== true) return null;
39 // Structural equality would let selections span identical fences.
40 if (!$from.sameParent($to)) return null;
41 const from = $from.start();
42 return { from, to: from + parent.content.size, text: parent.textContent };
43}
44
45export function indentedNewlineInCodeBlock(
46 state: EditorState,
47 dispatch?: (transaction: Transaction) => void,
48): boolean {
49 const block = codeBlockRange(state);
50 if (!block) return false;
51
52 const { from, to } = state.selection;
53 const beforeCursor = block.text.slice(0, from - block.from);
54 const currentLine = beforeCursor.slice(beforeCursor.lastIndexOf("\n") + 1);
55 const indent = leadingWhitespace(currentLine);
56
57 if (indent.length === 0) return false;
58
59 if (dispatch) {
60 const inserted = `\n${indent}`;
61 const transaction = state.tr.insertText(inserted, from, to);
62 const caret = from + inserted.length;
63 transaction.setSelection(TextSelection.create(transaction.doc, caret));
64 dispatch(transaction.scrollIntoView());
65 }
66 return true;
67}
68
69function defaultBlockAt(match: ContentMatch): NodeType | null {
70 for (let index = 0; index < match.edgeCount; index += 1) {
71 const { type } = match.edge(index);
72 if (type.isTextblock && !type.hasRequiredAttrs()) return type;
73 }
74 return null;
75}
76
77export function exitCodeBlockOnTrailingBlankLines(view: EditorView): boolean {
78 const { $from, empty } = view.state.selection;
79 if (!empty || $from.parent.type.spec.code !== true) return false;
80 if ($from.parentOffset !== $from.parent.content.size) return false;
81 // A closing fence's attr owns only the LF of a CRLF, so its CR stays at the end of the code.
82 const trailing = /(\r?\n[ \t]*\r?\n[ \t]*)\r?$/.exec($from.parent.textContent);
83 if (!trailing) return false;
84 const above = $from.node(-1);
85 const after = $from.indexAfter(-1);
86 const exitType = defaultBlockAt(above.contentMatchAt(after));
87 const exitBlock = exitType?.createAndFill();
88 if (!exitType || !exitBlock || !above.canReplaceWith(after, after, exitType)) return false;
89
90 const blankStart = $from.pos - trailing[0].length;
91 const transaction = view.state.tr.delete(blankStart, blankStart + trailing[1]!.length);
92 // Close the fence on exit so following prose is not read as code.
93 if (!$from.parent.attrs.close) {
94 transaction.setNodeAttribute($from.before(), "close", `\n${$from.parent.attrs.fence}`);
95 }
96 const exitPos = transaction.mapping.map($from.after());
97 transaction.replaceWith(exitPos, exitPos, exitBlock);
98 transaction.setSelection(Selection.near(transaction.doc.resolve(exitPos), 1));
99 view.dispatch(transaction.scrollIntoView());
100 return true;
101}
102
103export function exitCodeBlockOnClosingFence(
104 state: EditorState,
105 dispatch?: (transaction: Transaction) => void,
106): boolean {
107 const block = codeBlockRange(state);
108 if (!block || !state.selection.empty) return false;
109 const caret = state.selection.from - block.from;
110 const lineStart = block.text.lastIndexOf("\n", caret - 1) + 1;
111 const newlineAfter = block.text.indexOf("\n", caret);
112 const lineEnd = newlineAfter === -1 ? block.text.length : newlineAfter;
113 const line = block.text.slice(lineStart, lineEnd);
114 const node = state.selection.$from.parent;
115 if (caret !== lineEnd || !isClosingFence(line, String(node.attrs.fence))) return false;
116
117 if (dispatch) {
118 const { schema } = state;
119 const paragraph = (text: string) =>
120 schema.nodes.paragraph!.create(null, text ? schema.text(text) : null);
121 const code = block.text.slice(0, Math.max(0, lineStart - 1));
122 const rest = newlineAfter === -1 ? [] : block.text.slice(newlineAfter + 1).split("\n");
123 const closed = node.type.create(
124 { ...node.attrs, close: `\n${line}` },
125 code ? schema.text(code) : null,
126 );
127 const start = state.selection.$from.before();
128 const transaction = state.tr.replaceWith(start, start + node.nodeSize, [
129 closed,
130 paragraph(""),
131 ...rest.map(paragraph),
132 ]);
133 transaction.setSelection(TextSelection.create(transaction.doc, start + closed.nodeSize + 1));
134 dispatch(transaction.scrollIntoView());
135 }
136 return true;
137}
138
139export function indentCodeBlock(
140 state: EditorState,
141 direction: "in" | "out",
142 dispatch?: (transaction: Transaction) => void,
143): boolean {
144 const block = codeBlockRange(state);
145 if (!block) return false;
146
147 const { from, to } = state.selection;
148 const startOffset = from - block.from;
149 const endOffset = to - block.from;
150
151 if (from === to && direction === "in") {
152 if (dispatch) {
153 const transaction = state.tr.insertText(CODE_BLOCK_INDENT, from, to);
154 dispatch(transaction.scrollIntoView());
155 }
156 return true;
157 }
158
159 const lineStart = startOffset === 0 ? 0 : block.text.lastIndexOf("\n", startOffset - 1) + 1;
160 const newlineAfter = block.text.indexOf("\n", Math.max(startOffset, endOffset - 1));
161 const lineEnd = newlineAfter === -1 ? block.text.length : newlineAfter;
162
163 const originalLines = block.text.slice(lineStart, lineEnd).split("\n");
164 const nextLines = indentLines(originalLines, direction);
165 if (nextLines.join("\n") === originalLines.join("\n")) return true;
166
167 if (dispatch) {
168 const transaction = state.tr;
169 let position = block.from + lineStart;
170 originalLines.forEach((line, index) => {
171 const delta = nextLines[index]!.length - line.length;
172 const start = transaction.mapping.map(position);
173 if (delta > 0) transaction.insertText(CODE_BLOCK_INDENT, start);
174 if (delta < 0) transaction.delete(start, start - delta);
175 position += line.length + 1;
176 });
177 transaction.setSelection(state.selection.map(transaction.doc, transaction.mapping));
178 dispatch(transaction.scrollIntoView());
179 }
180 return true;
181}
182
183/** Tiptap's input rules only fire on a space, leaving a fence followed by Enter literal. */
184export function convertCodeFenceOnEnter(
185 state: EditorState,
186 dispatch?: (transaction: Transaction) => void,
187): boolean {
188 const { $from, empty } = state.selection;
189 // List and quote serializers cannot write fences, so allow only top-level paragraphs.
190 if (!empty || $from.parent.type.name !== "paragraph" || $from.depth !== 1) return false;
191 if ($from.parentOffset !== $from.parent.content.size) return false;
192 const opening = parseOpeningFence(serializeSelection(state.doc, $from.start(), $from.end()));
193 const codeBlock = state.schema.nodes.codeBlock;
194 if (!opening || !codeBlock) return false;
195
196 if (dispatch) {
197 const blockStart = $from.before();
198 const { fence, language } = opening;
199 const transaction = state.tr.replaceWith(
200 blockStart,
201 blockStart + $from.parent.nodeSize,
202 codeBlock.create({ language, fence, close: `\n${fence}` }),
203 );
204 transaction.setSelection(TextSelection.create(transaction.doc, blockStart + 1));
205 dispatch(transaction.scrollIntoView());
206 }
207 return true;
208}