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 const trailing = /\n[ \t]*\n[ \t]*$/.exec($from.parent.textContent);
82 if (!trailing) return false;
83 const above = $from.node(-1);
84 const after = $from.indexAfter(-1);
85 const exitType = defaultBlockAt(above.contentMatchAt(after));
86 const exitBlock = exitType?.createAndFill();
87 if (!exitType || !exitBlock || !above.canReplaceWith(after, after, exitType)) return false;
88
89 const transaction = view.state.tr.delete($from.pos - trailing[0].length, $from.pos);
90 // Close the fence on exit so following prose is not read as code.
91 if (!$from.parent.attrs.close) {
92 transaction.setNodeAttribute($from.before(), "close", `\n${$from.parent.attrs.fence}`);
93 }
94 const exitPos = transaction.mapping.map($from.after());
95 transaction.replaceWith(exitPos, exitPos, exitBlock);
96 transaction.setSelection(Selection.near(transaction.doc.resolve(exitPos), 1));
97 view.dispatch(transaction.scrollIntoView());
98 return true;
99}
100
101export function exitCodeBlockOnClosingFence(
102 state: EditorState,
103 dispatch?: (transaction: Transaction) => void,
104): boolean {
105 const block = codeBlockRange(state);
106 if (!block || !state.selection.empty) return false;
107 const caret = state.selection.from - block.from;
108 const lineStart = block.text.lastIndexOf("\n", caret - 1) + 1;
109 const newlineAfter = block.text.indexOf("\n", caret);
110 const lineEnd = newlineAfter === -1 ? block.text.length : newlineAfter;
111 const line = block.text.slice(lineStart, lineEnd);
112 const node = state.selection.$from.parent;
113 if (caret !== lineEnd || !isClosingFence(line, String(node.attrs.fence))) return false;
114
115 if (dispatch) {
116 const { schema } = state;
117 const paragraph = (text: string) =>
118 schema.nodes.paragraph!.create(null, text ? schema.text(text) : null);
119 const code = block.text.slice(0, Math.max(0, lineStart - 1));
120 const rest = newlineAfter === -1 ? [] : block.text.slice(newlineAfter + 1).split("\n");
121 const closed = node.type.create(
122 { ...node.attrs, close: `\n${line}` },
123 code ? schema.text(code) : null,
124 );
125 const start = state.selection.$from.before();
126 const transaction = state.tr.replaceWith(start, start + node.nodeSize, [
127 closed,
128 paragraph(""),
129 ...rest.map(paragraph),
130 ]);
131 transaction.setSelection(TextSelection.create(transaction.doc, start + closed.nodeSize + 1));
132 dispatch(transaction.scrollIntoView());
133 }
134 return true;
135}
136
137export function indentCodeBlock(
138 state: EditorState,
139 direction: "in" | "out",
140 dispatch?: (transaction: Transaction) => void,
141): boolean {
142 const block = codeBlockRange(state);
143 if (!block) return false;
144
145 const { from, to } = state.selection;
146 const startOffset = from - block.from;
147 const endOffset = to - block.from;
148
149 if (from === to && direction === "in") {
150 if (dispatch) {
151 const transaction = state.tr.insertText(CODE_BLOCK_INDENT, from, to);
152 dispatch(transaction.scrollIntoView());
153 }
154 return true;
155 }
156
157 const lineStart = startOffset === 0 ? 0 : block.text.lastIndexOf("\n", startOffset - 1) + 1;
158 const newlineAfter = block.text.indexOf("\n", Math.max(startOffset, endOffset - 1));
159 const lineEnd = newlineAfter === -1 ? block.text.length : newlineAfter;
160
161 const originalLines = block.text.slice(lineStart, lineEnd).split("\n");
162 const nextLines = indentLines(originalLines, direction);
163 if (nextLines.join("\n") === originalLines.join("\n")) return true;
164
165 if (dispatch) {
166 const transaction = state.tr;
167 let position = block.from + lineStart;
168 originalLines.forEach((line, index) => {
169 const delta = nextLines[index]!.length - line.length;
170 const start = transaction.mapping.map(position);
171 if (delta > 0) transaction.insertText(CODE_BLOCK_INDENT, start);
172 if (delta < 0) transaction.delete(start, start - delta);
173 position += line.length + 1;
174 });
175 transaction.setSelection(state.selection.map(transaction.doc, transaction.mapping));
176 dispatch(transaction.scrollIntoView());
177 }
178 return true;
179}
180
181/** Tiptap's input rules only fire on a space, leaving a fence followed by Enter literal. */
182export function convertCodeFenceOnEnter(
183 state: EditorState,
184 dispatch?: (transaction: Transaction) => void,
185): boolean {
186 const { $from, empty } = state.selection;
187 // List and quote serializers cannot write fences, so allow only top-level paragraphs.
188 if (!empty || $from.parent.type.name !== "paragraph" || $from.depth !== 1) return false;
189 if ($from.parentOffset !== $from.parent.content.size) return false;
190 const opening = parseOpeningFence(serializeSelection(state.doc, $from.start(), $from.end()));
191 const codeBlock = state.schema.nodes.codeBlock;
192 if (!opening || !codeBlock) return false;
193
194 if (dispatch) {
195 const blockStart = $from.before();
196 const { fence, language } = opening;
197 const transaction = state.tr.replaceWith(
198 blockStart,
199 blockStart + $from.parent.nodeSize,
200 codeBlock.create({ language, fence, close: `\n${fence}` }),
201 );
202 transaction.setSelection(TextSelection.create(transaction.doc, blockStart + 1));
203 dispatch(transaction.scrollIntoView());
204 }
205 return true;
206}