Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composer-code-block.ts

254 lines10.6 KB

1import { exitCode } from "@tiptap/pm/commands";
2import type { EditorState, Transaction } from "@tiptap/pm/state";
3import { TextSelection } from "@tiptap/pm/state";
4import type { EditorView } from "@tiptap/pm/view";
5​
6import { isClosingFence, parseOpeningFence, serializeSelection } from "~/composer-rich-text-doc";
7​
8/**
9 * Spaces rather than a tab: the fence round-trips through Markdown on its way
10 * to the agent, and a literal tab there renders at whatever width the reader
11 * happens to use. Two matches how this repo indents its own source.
12 */
13export const CODE_BLOCK_INDENT = " ";
14​
15/** The leading run of spaces and tabs on a line, which Enter carries forward. */
16export function leadingWhitespace(line: string): string {
17 return /^[ \t]*/.exec(line)?.[0] ?? "";
19​
20/**
21 * Removes one indent's worth of leading whitespace, tolerating lines that were
22 * indented by hand with an odd number of spaces or with tabs. A line with no
23 * leading whitespace is returned unchanged, so outdenting bottoms out quietly
24 * rather than eating the first character of code.
25 */
26export function outdentLine(line: string): string {
27 if (line.startsWith(CODE_BLOCK_INDENT)) return line.slice(CODE_BLOCK_INDENT.length);
28 if (line.startsWith("\t")) return line.slice(1);
29 if (line.startsWith(" ")) return line.slice(1);
30 return line;
32​
33/** Applies Tab/Shift+Tab to every line a selection touches, whole lines at a time. */
34export function indentLines(lines: ReadonlyArray<string>, direction: "in" | "out"): string[] {
35 return lines.map((line) => {
36 // Indenting a blank line would leave trailing whitespace behind on a line
37 // the user cannot see the caret move on, so leave it be.
38 if (direction === "in") return line.length === 0 ? line : `${CODE_BLOCK_INDENT}${line}`;
39 return outdentLine(line);
40 });
42​
43/** Whether every endpoint of the selection sits in the same code block. */
44export function selectionInOneCodeBlock(state: EditorState): boolean {
45 const { $from, $to } = state.selection;
46 return $from.parent.type.spec.code === true && $from.sameParent($to);
48​
49/**
50 * The code block containing the selection, or null when the selection is
51 * outside a fence or spans out of one. Both ends must sit in the same block: a
52 * selection that reaches past the fence belongs to the document, not to the
53 * code.
54 */
55function codeBlockRange(
56 state: EditorState,
57): { readonly from: number; readonly to: number; readonly text: string } | null {
58 const { $from, $to } = state.selection;
59 const parent = $from.parent;
60 if (parent.type.spec.code !== true) return null;
61 // Same occurrence, not merely equal structure: two identical fences would
62 // otherwise let a selection across them edit through the block boundary.
63 if (!$from.sameParent($to)) return null;
64 const from = $from.start();
65 return { from, to: from + parent.content.size, text: parent.textContent };
67​
68/**
69 * Enter inside a fence, carrying the current line's indentation onto the new
70 * line. ProseMirror's default splits the text but starts the new line at column
71 * zero, which means re-typing the indent on every line of a nested block.
72 */
73export function indentedNewlineInCodeBlock(
74 state: EditorState,
75 dispatch?: (transaction: Transaction) => void,
76): boolean {
77 const block = codeBlockRange(state);
78 if (!block) return false;
79​
80 const { from, to } = state.selection;
81 const beforeCursor = block.text.slice(0, from - block.from);
82 const currentLine = beforeCursor.slice(beforeCursor.lastIndexOf("\n") + 1);
83 const indent = leadingWhitespace(currentLine);
84​
85 // Nothing to carry, so let the default newline handle it and keep this path
86 // out of the undo history.
87 if (indent.length === 0) return false;
88​
89 if (dispatch) {
90 const inserted = `\n${indent}`;
91 const transaction = state.tr.insertText(inserted, from, to);
92 const caret = from + inserted.length;
93 transaction.setSelection(TextSelection.create(transaction.doc, caret));
94 dispatch(transaction.scrollIntoView());
95 }
96 return true;
98​
99/**
100 * Two blank lines at the end of a fence leave it, the way every code editor
101 * does. Without this a fence at the end of the prompt is a trap: Enter only
102 * ever adds another line and there is no way back to prose. A line holding
103 * only the indentation Enter carried forward counts as blank, and is removed
104 * with the rest.
105 */
106export function exitCodeBlockOnTrailingBlankLines(view: EditorView): boolean {
107 const { $from, empty } = view.state.selection;
108 if (!empty || $from.parent.type.spec.code !== true) return false;
109 if ($from.parentOffset !== $from.parent.content.size) return false;
110 const trailing = /\n[ \t]*\n[ \t]*$/.exec($from.parent.textContent);
111 if (!trailing) return false;
112 const transaction = view.state.tr.delete($from.pos - trailing[0].length, $from.pos);
113 // An unclosed fence runs to the end of the draft; the prose after it would
114 // be read back as code, so leaving it writes the closing fence.
115 if (!$from.parent.attrs.close) {
116 transaction.setNodeAttribute($from.before(), "close", `\n${$from.parent.attrs.fence}`);
117 }
118 view.dispatch(transaction);
119 return exitCode(view.state, (tr) => view.dispatch(tr.scrollIntoView()));
121​
122/**
123 * Enter at the end of a line that would close the fence, such as ```` ``` ````
124 * typed under the code, ends the block there. That line becomes the closing
125 * fence, and any lines after it continue as paragraphs after a new empty one,
126 * which is how the stored draft reads them.
127 */
128export function exitCodeBlockOnClosingFence(
129 state: EditorState,
130 dispatch?: (transaction: Transaction) => void,
131): boolean {
132 const block = codeBlockRange(state);
133 if (!block || !state.selection.empty) return false;
134 const caret = state.selection.from - block.from;
135 const lineStart = block.text.lastIndexOf("\n", caret - 1) + 1;
136 const newlineAfter = block.text.indexOf("\n", caret);
137 const lineEnd = newlineAfter === -1 ? block.text.length : newlineAfter;
138 const line = block.text.slice(lineStart, lineEnd);
139 const node = state.selection.$from.parent;
140 if (caret !== lineEnd || !isClosingFence(line, String(node.attrs.fence))) return false;
141​
142 if (dispatch) {
143 const { schema } = state;
144 const paragraph = (text: string) =>
145 schema.nodes.paragraph!.create(null, text ? schema.text(text) : null);
146 const code = block.text.slice(0, Math.max(0, lineStart - 1));
147 const rest = newlineAfter === -1 ? [] : block.text.slice(newlineAfter + 1).split("\n");
148 const closed = node.type.create(
149 { ...node.attrs, close: `\n${line}` },
150 code ? schema.text(code) : null,
151 );
152 const start = state.selection.$from.before();
153 const transaction = state.tr.replaceWith(start, start + node.nodeSize, [
154 closed,
155 paragraph(""),
156 ...rest.map(paragraph),
157 ]);
158 transaction.setSelection(TextSelection.create(transaction.doc, start + closed.nodeSize + 1));
159 dispatch(transaction.scrollIntoView());
160 }
161 return true;
163​
164/**
165 * Tab and Shift+Tab inside a fence. A collapsed cursor indents at the caret so
166 * Tab works mid-line the way typing does; any selection spanning text indents
167 * the whole lines it touches, which is what makes re-indenting a block possible.
168 */
169export function indentCodeBlock(
170 state: EditorState,
171 direction: "in" | "out",
172 dispatch?: (transaction: Transaction) => void,
173): boolean {
174 const block = codeBlockRange(state);
175 if (!block) return false;
176​
177 const { from, to } = state.selection;
178 const startOffset = from - block.from;
179 const endOffset = to - block.from;
180​
181 if (from === to && direction === "in") {
182 if (dispatch) {
183 const transaction = state.tr.insertText(CODE_BLOCK_INDENT, from, to);
184 dispatch(transaction.scrollIntoView());
185 }
186 return true;
187 }
188​
189 // Grow the range to whole lines so indenting is stable no matter where in the
190 // first and last lines the selection happens to start and end.
191 const lineStart = block.text.lastIndexOf("\n", Math.max(0, startOffset - 1)) + 1;
192 // A selection ending at the start of a line does not touch that line.
193 const newlineAfter = block.text.indexOf("\n", Math.max(startOffset, endOffset - 1));
194 const lineEnd = newlineAfter === -1 ? block.text.length : newlineAfter;
195​
196 const originalLines = block.text.slice(lineStart, lineEnd).split("\n");
197 const nextLines = indentLines(originalLines, direction);
198 if (nextLines.join("\n") === originalLines.join("\n")) return true;
199​
200 if (dispatch) {
201 const transaction = state.tr.insertText(
202 nextLines.join("\n"),
203 block.from + lineStart,
204 block.from + lineEnd,
205 );
206 // Keep the same lines selected after the shift, so repeated Tab presses
207 // keep indenting the block rather than collapsing the selection.
208 // `split` always yields at least one entry, so these stand in only for the
209 // compiler's benefit.
210 const firstDelta = (nextLines[0]?.length ?? 0) - (originalLines[0]?.length ?? 0);
211 const totalDelta = nextLines.join("\n").length - originalLines.join("\n").length;
212 const nextFrom = Math.max(block.from + lineStart, from + firstDelta);
213 const nextTo = Math.max(nextFrom, to + totalDelta);
214 transaction.setSelection(TextSelection.create(transaction.doc, nextFrom, nextTo));
215 dispatch(transaction.scrollIntoView());
216 }
217 return true;
219​
220/**
221 * Enter on a line that is nothing but an opening fence turns it into a code
222 * block. Tiptap's own input rules only fire on a space, so without this the
223 * gesture every markdown editor has — ```` ```ts ```` then Enter — leaves the
224 * fence as literal text.
225 */
226export function convertCodeFenceOnEnter(
227 state: EditorState,
228 dispatch?: (transaction: Transaction) => void,
229): boolean {
230 const { $from, empty } = state.selection;
231 // Top-level paragraphs only: the list and quote serializers have no line
232 // to write a fence into, so one created inside them would vanish.
233 if (!empty || $from.parent.type.name !== "paragraph" || $from.depth !== 1) return false;
234 if ($from.parentOffset !== $from.parent.content.size) return false;
235 // The parser's own grammar, read from the line's stored source, so a line
236 // Enter turns into a fence is exactly one the stored draft reads back as a
237 // fence, info string and all, including any chip's source in it.
238 const opening = parseOpeningFence(serializeSelection(state.doc, $from.start(), $from.end()));
239 const codeBlock = state.schema.nodes.codeBlock;
240 if (!opening || !codeBlock) return false;
241​
242 if (dispatch) {
243 const blockStart = $from.before();
244 const { fence, language } = opening;
245 const transaction = state.tr.replaceWith(
246 blockStart,
247 blockStart + $from.parent.nodeSize,
248 codeBlock.create({ language, fence, close: `\n${fence}` }),
249 );
250 transaction.setSelection(TextSelection.create(transaction.doc, blockStart + 1));
251 dispatch(transaction.scrollIntoView());
252 }
253 return true;