forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksJavaScript3.6 MiBe100df4Tahinli1 month ago1 commit

editing.ts294 lines, 10.9 KiBHistoryRawDownload
1// Editing behaviour on top of the base schema: block/mark commands, keyboard
2// shortcuts, markdown-style input rules, cursors for gaps and drops, and the
3// empty-note placeholder. The toolbar (toolbar.ts) drives the same commands.
4import {
5 Fragment,
6 type Attrs,
7 type Mark,
8 type MarkType,
9 type Node as PMNode,
10 type NodeType,
11 type Schema,
12} from "prosemirror-model";
13import { Plugin, TextSelection, type Command, type EditorState } from "prosemirror-state";
14import { Decoration, DecorationSet, type EditorView } from "prosemirror-view";
15import { t } from "./i18n";
16import { keymap } from "prosemirror-keymap";
17import { lift, setBlockType, toggleMark, wrapIn } from "prosemirror-commands";
18import { liftListItem, wrapInList } from "prosemirror-schema-list";
19import {
20 InputRule,
21 inputRules,
22 textblockTypeInputRule,
23 undoInputRule,
24 wrappingInputRule,
25} from "prosemirror-inputrules";
26import { dropCursor } from "prosemirror-dropcursor";
27import { gapCursor } from "prosemirror-gapcursor";
28
29/** True when the mark applies at the cursor (stored marks included) or across the selection. */
30export function isMarkActive(state: EditorState, type: MarkType): boolean {
31 const { from, to, empty, $from } = state.selection;
32 if (empty) return !!type.isInSet(state.storedMarks || $from.marks());
33 return state.doc.rangeHasMark(from, to, type);
34}
35
36/** True when the selection's textblock is of `type` (and matches `attrs`, if given). */
37export function isBlockActive(state: EditorState, type: NodeType, attrs?: Attrs): boolean {
38 const parent = state.selection.$from.parent;
39 if (parent.type !== type) return false;
40 return !attrs || Object.keys(attrs).every((k) => parent.attrs[k] === attrs[k]);
41}
42
43/** Nearest ancestor of the selection matching `match`, with its document position. */
44export function findAncestor(
45 state: EditorState,
46 match: (node: PMNode) => boolean,
47): { node: PMNode; pos: number } | null {
48 const { $from } = state.selection;
49 for (let d = $from.depth; d > 0; d--) {
50 const node = $from.node(d);
51 if (match(node)) return { node, pos: $from.before(d) };
52 }
53 return null;
54}
55
56/**
57 * Input rule for inline marks written with delimiters ("**x**", "*x*", "`x`").
58 * `pattern` must end with the closing delimiter; capture group 1 is the marked text.
59 * The delimiter length is passed explicitly so the text positions are exact.
60 */
61function markInputRule(pattern: RegExp, markType: MarkType, delimLength: number): InputRule {
62 return new InputRule(pattern, (state, match, start, end) => {
63 const content = match[1];
64 if (!content) return null;
65 // Input rules run before the last typed character is inserted, so the closing
66 // delimiter is one character short in the doc. Positions come from the match start.
67 const textStart = start + match[0].length - delimLength - content.length;
68 const textEnd = textStart + content.length;
69 const openStart = textStart - delimLength;
70 const tr = state.tr;
71 tr.delete(textEnd, end);
72 tr.delete(openStart, textStart);
73 tr.addMark(openStart, openStart + content.length, markType.create());
74 tr.removeStoredMark(markType);
75 return tr;
76 });
77}
78
79/** Range of the mark of `type` that contains `pos` within its textblock, or null. */
80export function markRangeAt(
81 doc: PMNode,
82 pos: number,
83 type: MarkType,
84): { from: number; to: number; mark: Mark } | null {
85 const $pos = doc.resolve(pos);
86 if (!$pos.parent.inlineContent) return null;
87 const start = $pos.start();
88 let found: { from: number; to: number; mark: Mark } | null = null;
89 $pos.parent.forEach((child, offset) => {
90 if (found) return;
91 const from = start + offset;
92 const to = from + child.nodeSize;
93 const mark = type.isInSet(child.marks);
94 if (mark && from <= pos && pos <= to) found = { from, to, mark };
95 });
96 return found;
97}
98
99/** Accepts plain URLs (adds https://) and http/mailto/relative links; rejects script-like schemes. */
100export function normalizeHref(raw: string): string | null {
101 const href = raw.trim();
102 if (!href) return null;
103 // Whitespace and control characters are removed before the check, so "java\tscript:" is caught too.
104 if (/^(javascript|data|vbscript):/i.test(href.replace(/[\s\x00-\x1f]/g, ""))) return null;
105 if (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("/") || href.startsWith("#")) return href;
106 return `https://${href}`;
107}
108
109export interface Editing {
110 /** Keymap, input rules, drop/gap cursors and placeholder. Insert before baseKeymap. */
111 plugins: Plugin[];
112 paragraph: Command;
113 heading(level: number): Command;
114 codeBlock: Command;
115 bold: Command;
116 italic: Command;
117 inlineCode: Command;
118 link: Command;
119 bulletList: Command;
120 orderedList: Command;
121 blockquote: Command;
122 horizontalRule: Command;
123}
124
125export interface EditingHooks {
126 /** Called by Mod-K and the toolbar/bubble link buttons; the floating UI opens the link popover. */
127 requestLink(view: EditorView): void;
128}
129
130export function createEditing(schema: Schema, hooks: EditingHooks): Editing {
131 const { paragraph, heading, code_block, blockquote, horizontal_rule, bullet_list, ordered_list, list_item } =
132 schema.nodes;
133 const { strong, em, code, link: linkMark } = schema.marks;
134
135 // Toggling variants: applying the active block type again returns to a paragraph.
136 const toParagraph = setBlockType(paragraph);
137 const toggleBlock =
138 (type: NodeType, attrs?: Attrs): Command =>
139 (state, dispatch) =>
140 isBlockActive(state, type, attrs)
141 ? toParagraph(state, dispatch)
142 : setBlockType(type, attrs)(state, dispatch);
143
144 const toggleList =
145 (type: NodeType): Command =>
146 (state, dispatch) => {
147 const list = findAncestor(state, (n) => n.type === bullet_list || n.type === ordered_list);
148 if (!list) return wrapInList(type)(state, dispatch);
149 if (list.node.type === type) return liftListItem(list_item)(state, dispatch);
150 // Switching between bullet and ordered: retype the existing list in place.
151 if (dispatch) dispatch(state.tr.setNodeMarkup(list.pos, type));
152 return true;
153 };
154
155 const toggleQuote: Command = (state, dispatch) =>
156 findAncestor(state, (n) => n.type === blockquote)
157 ? lift(state, dispatch)
158 : wrapIn(blockquote)(state, dispatch);
159
160 // Opens the link popover for a selection, or for the link the cursor is inside.
161 const toggleLink: Command = (state, dispatch, view) => {
162 const { $from, empty } = state.selection;
163 const insideLink = empty && markRangeAt(state.doc, state.selection.from, linkMark) !== null;
164 const canLink = !empty && $from.parent.inlineContent && $from.parent.type.allowsMarkType(linkMark);
165 if (!insideLink && !canLink) return false;
166 if (dispatch && view) hooks.requestLink(view);
167 return true;
168 };
169
170 const insertRule: Command = (state, dispatch) => {
171 const { $from } = state.selection;
172 if ($from.parent.type.spec.code) return false;
173 if (!dispatch) return true;
174 const tr = state.tr.replaceSelectionWith(horizontal_rule.create());
175 if (!tr.selection.$from.parent.inlineContent) {
176 // Keep a text position after a trailing rule so the user can keep typing.
177 const pos = tr.selection.from;
178 tr.insert(pos, paragraph.create());
179 tr.setSelection(TextSelection.create(tr.doc, pos + 1));
180 }
181 dispatch(tr.scrollIntoView());
182 return true;
183 };
184
185 // "---" on its own line becomes a rule followed by an empty paragraph.
186 const hrRule = new InputRule(/^---$/, (state, _match, start, end) => {
187 const $start = state.doc.resolve(start);
188 const depth = $start.depth;
189 if (depth < 1 || $start.parent.type.spec.code) return null;
190 const index = $start.index(depth - 1);
191 const parent = $start.node(depth - 1);
192 const replacement = Fragment.from([horizontal_rule.create(), paragraph.create()]);
193 if (!parent.canReplace(index, index + 1, replacement)) return null;
194 const before = $start.before();
195 const tr = state.tr.replaceWith(before, $start.after(), [horizontal_rule.create(), paragraph.create()]);
196 tr.setSelection(TextSelection.create(tr.doc, before + horizontal_rule.create().nodeSize + 1));
197 return tr;
198 });
199
200 // Ctrl/Cmd+Shift+V pastes plain text. The keydown sets a short-lived flag, and the paste
201 // event the browser fires next reads it. Normal paste keeps basic structure and drops styling.
202 let plainPasteUntil = 0;
203 const paste = new Plugin({
204 props: {
205 transformPastedHTML(html) {
206 return html.replace(/\s(?:style|class)\s*=\s*("[^"]*"|'[^']*')/gi, "");
207 },
208 handleKeyDown(_view, event) {
209 if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLowerCase() === "v") {
210 plainPasteUntil = Date.now() + 1000;
211 }
212 return false;
213 },
214 handlePaste(view, event) {
215 if (Date.now() > plainPasteUntil) return false;
216 plainPasteUntil = 0;
217 const text = event.clipboardData?.getData("text/plain");
218 if (!text) return false;
219 view.pasteText(text);
220 return true;
221 },
222 },
223 });
224
225 const keys = keymap({
226 "Mod-Alt-0": toParagraph,
227 "Mod-Alt-1": toggleBlock(heading, { level: 1 }),
228 "Mod-Alt-2": toggleBlock(heading, { level: 2 }),
229 "Mod-Alt-3": toggleBlock(heading, { level: 3 }),
230 "Mod-Shift-8": toggleList(bullet_list),
231 "Mod-Shift-9": toggleList(ordered_list),
232 "Mod-k": toggleLink,
233 "Mod-e": toggleMark(code),
234 Backspace: undoInputRule,
235 });
236
237 const rules = inputRules({
238 rules: [
239 textblockTypeInputRule(/^(#{1,3})\s$/, heading, (m) => ({ level: m[1].length })),
240 textblockTypeInputRule(/^```$/, code_block),
241 wrappingInputRule(/^\s*([-*])\s$/, bullet_list),
242 wrappingInputRule(
243 /^(\d+)\.\s$/,
244 ordered_list,
245 (m) => ({ order: Number(m[1]) }),
246 (m, node) => node.childCount + node.attrs.order === Number(m[1]),
247 ),
248 wrappingInputRule(/^\s*>\s$/, blockquote),
249 markInputRule(/\*\*([^*]+)\*\*$/, strong, 2),
250 markInputRule(/(?:^|[^*])\*([^*]+)\*$/, em, 1),
251 markInputRule(/`([^`]+)`$/, code, 1),
252 hrRule,
253 ],
254 });
255
256 // Shown only while the whole note is one empty paragraph.
257 const placeholder = new Plugin({
258 props: {
259 decorations(state) {
260 const { doc } = state;
261 const first = doc.firstChild;
262 if (doc.childCount !== 1 || !first || first.type !== paragraph || first.content.size > 0) return null;
263 return DecorationSet.create(doc, [
264 Decoration.node(0, first.nodeSize, {
265 class: "is-placeholder",
266 "data-placeholder": t("placeholder"),
267 }),
268 ]);
269 },
270 },
271 });
272
273 return {
274 plugins: [
275 paste,
276 keys,
277 rules,
278 dropCursor({ color: "var(--primary)", width: 2 }),
279 gapCursor(),
280 placeholder,
281 ],
282 paragraph: toParagraph,
283 heading: (level) => toggleBlock(heading, { level }),
284 codeBlock: toggleBlock(code_block),
285 bold: toggleMark(strong),
286 italic: toggleMark(em),
287 inlineCode: toggleMark(code),
288 link: toggleLink,
289 bulletList: toggleList(bullet_list),
290 orderedList: toggleList(ordered_list),
291 blockquote: toggleQuote,
292 horizontalRule: insertRule,
293 };
294}