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

composer-code-block.ts

195 lines7.5 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​
8export const CODE_BLOCK_INDENT = " ";
9​
10export function leadingWhitespace(line: string): string {
11 return /^[ \t]*/.exec(line)?.[0] ?? "";
13​
14export function 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;
20​
21export function 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 });
27​
28export function selectionInOneCodeBlock(state: EditorState): boolean {
29 const { $from, $to } = state.selection;
30 return $from.parent.type.spec.code === true && $from.sameParent($to);
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 // Same occurrence, not merely equal structure: two identical fences would
40 // otherwise let a selection across them edit through the block boundary.
41 if (!$from.sameParent($to)) return null;
42 const from = $from.start();
43 return { from, to: from + parent.content.size, text: parent.textContent };
45​
46export function indentedNewlineInCodeBlock(
47 state: EditorState,
48 dispatch?: (transaction: Transaction) => void,
49): boolean {
50 const block = codeBlockRange(state);
51 if (!block) return false;
52​
53 const { from, to } = state.selection;
54 const beforeCursor = block.text.slice(0, from - block.from);
55 const currentLine = beforeCursor.slice(beforeCursor.lastIndexOf("\n") + 1);
56 const indent = leadingWhitespace(currentLine);
57​
58 if (indent.length === 0) return false;
59​
60 if (dispatch) {
61 const inserted = `\n${indent}`;
62 const transaction = state.tr.insertText(inserted, from, to);
63 const caret = from + inserted.length;
64 transaction.setSelection(TextSelection.create(transaction.doc, caret));
65 dispatch(transaction.scrollIntoView());
66 }
67 return true;
69​
70export function exitCodeBlockOnTrailingBlankLines(view: EditorView): boolean {
71 const { $from, empty } = view.state.selection;
72 if (!empty || $from.parent.type.spec.code !== true) return false;
73 if ($from.parentOffset !== $from.parent.content.size) return false;
74 const trailing = /\n[ \t]*\n[ \t]*$/.exec($from.parent.textContent);
75 if (!trailing) return false;
76 const transaction = view.state.tr.delete($from.pos - trailing[0].length, $from.pos);
77 // An unclosed fence runs to the end of the draft; the prose after it would
78 // be read back as code, so leaving it writes the closing fence.
79 if (!$from.parent.attrs.close) {
80 transaction.setNodeAttribute($from.before(), "close", `\n${$from.parent.attrs.fence}`);
81 }
82 view.dispatch(transaction);
83 return exitCode(view.state, (tr) => view.dispatch(tr.scrollIntoView()));
85​
86export function exitCodeBlockOnClosingFence(
87 state: EditorState,
88 dispatch?: (transaction: Transaction) => void,
89): boolean {
90 const block = codeBlockRange(state);
91 if (!block || !state.selection.empty) return false;
92 const caret = state.selection.from - block.from;
93 const lineStart = block.text.lastIndexOf("\n", caret - 1) + 1;
94 const newlineAfter = block.text.indexOf("\n", caret);
95 const lineEnd = newlineAfter === -1 ? block.text.length : newlineAfter;
96 const line = block.text.slice(lineStart, lineEnd);
97 const node = state.selection.$from.parent;
98 if (caret !== lineEnd || !isClosingFence(line, String(node.attrs.fence))) return false;
99​
100 if (dispatch) {
101 const { schema } = state;
102 const paragraph = (text: string) =>
103 schema.nodes.paragraph!.create(null, text ? schema.text(text) : null);
104 const code = block.text.slice(0, Math.max(0, lineStart - 1));
105 const rest = newlineAfter === -1 ? [] : block.text.slice(newlineAfter + 1).split("\n");
106 const closed = node.type.create(
107 { ...node.attrs, close: `\n${line}` },
108 code ? schema.text(code) : null,
109 );
110 const start = state.selection.$from.before();
111 const transaction = state.tr.replaceWith(start, start + node.nodeSize, [
112 closed,
113 paragraph(""),
114 ...rest.map(paragraph),
115 ]);
116 transaction.setSelection(TextSelection.create(transaction.doc, start + closed.nodeSize + 1));
117 dispatch(transaction.scrollIntoView());
118 }
119 return true;
121​
122export function indentCodeBlock(
123 state: EditorState,
124 direction: "in" | "out",
125 dispatch?: (transaction: Transaction) => void,
126): boolean {
127 const block = codeBlockRange(state);
128 if (!block) return false;
129​
130 const { from, to } = state.selection;
131 const startOffset = from - block.from;
132 const endOffset = to - block.from;
133​
134 if (from === to && direction === "in") {
135 if (dispatch) {
136 const transaction = state.tr.insertText(CODE_BLOCK_INDENT, from, to);
137 dispatch(transaction.scrollIntoView());
138 }
139 return true;
140 }
141​
142 const lineStart = block.text.lastIndexOf("\n", Math.max(0, startOffset - 1)) + 1;
143 const newlineAfter = block.text.indexOf("\n", Math.max(startOffset, endOffset - 1));
144 const lineEnd = newlineAfter === -1 ? block.text.length : newlineAfter;
145​
146 const originalLines = block.text.slice(lineStart, lineEnd).split("\n");
147 const nextLines = indentLines(originalLines, direction);
148 if (nextLines.join("\n") === originalLines.join("\n")) return true;
149​
150 if (dispatch) {
151 const transaction = state.tr.insertText(
152 nextLines.join("\n"),
153 block.from + lineStart,
154 block.from + lineEnd,
155 );
156 const firstDelta = (nextLines[0]?.length ?? 0) - (originalLines[0]?.length ?? 0);
157 const totalDelta = nextLines.join("\n").length - originalLines.join("\n").length;
158 const nextFrom = Math.max(block.from + lineStart, from + firstDelta);
159 const nextTo = Math.max(nextFrom, to + totalDelta);
160 transaction.setSelection(TextSelection.create(transaction.doc, nextFrom, nextTo));
161 dispatch(transaction.scrollIntoView());
162 }
163 return true;
165​
166/**
167 * Tiptap's own input rules only fire on a space, so without this the gesture every markdown editor
168 * has — ```` ```ts ```` then Enter — leaves the fence as literal text.
169 */
170export function convertCodeFenceOnEnter(
171 state: EditorState,
172 dispatch?: (transaction: Transaction) => void,
173): boolean {
174 const { $from, empty } = state.selection;
175 // Top-level paragraphs only: the list and quote serializers have no line
176 // to write a fence into, so one created inside them would vanish.
177 if (!empty || $from.parent.type.name !== "paragraph" || $from.depth !== 1) return false;
178 if ($from.parentOffset !== $from.parent.content.size) return false;
179 const opening = parseOpeningFence(serializeSelection(state.doc, $from.start(), $from.end()));
180 const codeBlock = state.schema.nodes.codeBlock;
181 if (!opening || !codeBlock) return false;
182​
183 if (dispatch) {
184 const blockStart = $from.before();
185 const { fence, language } = opening;
186 const transaction = state.tr.replaceWith(
187 blockStart,
188 blockStart + $from.parent.nodeSize,
189 codeBlock.create({ language, fence, close: `\n${fence}` }),
190 );
191 transaction.setSelection(TextSelection.create(transaction.doc, blockStart + 1));
192 dispatch(transaction.scrollIntoView());
193 }
194 return true;