// Editing behaviour on top of the base schema: block/mark commands, keyboard // shortcuts, markdown-style input rules, cursors for gaps and drops, and the // empty-note placeholder. The toolbar (toolbar.ts) drives the same commands. import { Fragment, type Attrs, type Mark, type MarkType, type Node as PMNode, type NodeType, type Schema, } from "prosemirror-model"; import { Plugin, TextSelection, type Command, type EditorState } from "prosemirror-state"; import { Decoration, DecorationSet, type EditorView } from "prosemirror-view"; import { t } from "./i18n"; import { keymap } from "prosemirror-keymap"; import { lift, setBlockType, toggleMark, wrapIn } from "prosemirror-commands"; import { liftListItem, wrapInList } from "prosemirror-schema-list"; import { InputRule, inputRules, textblockTypeInputRule, undoInputRule, wrappingInputRule, } from "prosemirror-inputrules"; import { dropCursor } from "prosemirror-dropcursor"; import { gapCursor } from "prosemirror-gapcursor"; /** True when the mark applies at the cursor (stored marks included) or across the selection. */ export function isMarkActive(state: EditorState, type: MarkType): boolean { const { from, to, empty, $from } = state.selection; if (empty) return !!type.isInSet(state.storedMarks || $from.marks()); return state.doc.rangeHasMark(from, to, type); } /** True when the selection's textblock is of `type` (and matches `attrs`, if given). */ export function isBlockActive(state: EditorState, type: NodeType, attrs?: Attrs): boolean { const parent = state.selection.$from.parent; if (parent.type !== type) return false; return !attrs || Object.keys(attrs).every((k) => parent.attrs[k] === attrs[k]); } /** Nearest ancestor of the selection matching `match`, with its document position. */ export function findAncestor( state: EditorState, match: (node: PMNode) => boolean, ): { node: PMNode; pos: number } | null { const { $from } = state.selection; for (let d = $from.depth; d > 0; d--) { const node = $from.node(d); if (match(node)) return { node, pos: $from.before(d) }; } return null; } /** * Input rule for inline marks written with delimiters ("**x**", "*x*", "`x`"). * `pattern` must end with the closing delimiter; capture group 1 is the marked text. * The delimiter length is passed explicitly so the text positions are exact. */ function markInputRule(pattern: RegExp, markType: MarkType, delimLength: number): InputRule { return new InputRule(pattern, (state, match, start, end) => { const content = match[1]; if (!content) return null; // Input rules run before the last typed character is inserted, so the closing // delimiter is one character short in the doc. Positions come from the match start. const textStart = start + match[0].length - delimLength - content.length; const textEnd = textStart + content.length; const openStart = textStart - delimLength; const tr = state.tr; tr.delete(textEnd, end); tr.delete(openStart, textStart); tr.addMark(openStart, openStart + content.length, markType.create()); tr.removeStoredMark(markType); return tr; }); } /** Range of the mark of `type` that contains `pos` within its textblock, or null. */ export function markRangeAt( doc: PMNode, pos: number, type: MarkType, ): { from: number; to: number; mark: Mark } | null { const $pos = doc.resolve(pos); if (!$pos.parent.inlineContent) return null; const start = $pos.start(); let found: { from: number; to: number; mark: Mark } | null = null; $pos.parent.forEach((child, offset) => { if (found) return; const from = start + offset; const to = from + child.nodeSize; const mark = type.isInSet(child.marks); if (mark && from <= pos && pos <= to) found = { from, to, mark }; }); return found; } /** Accepts plain URLs (adds https://) and http/mailto/relative links; rejects script-like schemes. */ export function normalizeHref(raw: string): string | null { const href = raw.trim(); if (!href) return null; // Whitespace and control characters are removed before the check, so "java\tscript:" is caught too. if (/^(javascript|data|vbscript):/i.test(href.replace(/[\s\x00-\x1f]/g, ""))) return null; if (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("/") || href.startsWith("#")) return href; return `https://${href}`; } export interface Editing { /** Keymap, input rules, drop/gap cursors and placeholder. Insert before baseKeymap. */ plugins: Plugin[]; paragraph: Command; heading(level: number): Command; codeBlock: Command; bold: Command; italic: Command; inlineCode: Command; link: Command; bulletList: Command; orderedList: Command; blockquote: Command; horizontalRule: Command; } export interface EditingHooks { /** Called by Mod-K and the toolbar/bubble link buttons; the floating UI opens the link popover. */ requestLink(view: EditorView): void; } export function createEditing(schema: Schema, hooks: EditingHooks): Editing { const { paragraph, heading, code_block, blockquote, horizontal_rule, bullet_list, ordered_list, list_item } = schema.nodes; const { strong, em, code, link: linkMark } = schema.marks; // Toggling variants: applying the active block type again returns to a paragraph. const toParagraph = setBlockType(paragraph); const toggleBlock = (type: NodeType, attrs?: Attrs): Command => (state, dispatch) => isBlockActive(state, type, attrs) ? toParagraph(state, dispatch) : setBlockType(type, attrs)(state, dispatch); const toggleList = (type: NodeType): Command => (state, dispatch) => { const list = findAncestor(state, (n) => n.type === bullet_list || n.type === ordered_list); if (!list) return wrapInList(type)(state, dispatch); if (list.node.type === type) return liftListItem(list_item)(state, dispatch); // Switching between bullet and ordered: retype the existing list in place. if (dispatch) dispatch(state.tr.setNodeMarkup(list.pos, type)); return true; }; const toggleQuote: Command = (state, dispatch) => findAncestor(state, (n) => n.type === blockquote) ? lift(state, dispatch) : wrapIn(blockquote)(state, dispatch); // Opens the link popover for a selection, or for the link the cursor is inside. const toggleLink: Command = (state, dispatch, view) => { const { $from, empty } = state.selection; const insideLink = empty && markRangeAt(state.doc, state.selection.from, linkMark) !== null; const canLink = !empty && $from.parent.inlineContent && $from.parent.type.allowsMarkType(linkMark); if (!insideLink && !canLink) return false; if (dispatch && view) hooks.requestLink(view); return true; }; const insertRule: Command = (state, dispatch) => { const { $from } = state.selection; if ($from.parent.type.spec.code) return false; if (!dispatch) return true; const tr = state.tr.replaceSelectionWith(horizontal_rule.create()); if (!tr.selection.$from.parent.inlineContent) { // Keep a text position after a trailing rule so the user can keep typing. const pos = tr.selection.from; tr.insert(pos, paragraph.create()); tr.setSelection(TextSelection.create(tr.doc, pos + 1)); } dispatch(tr.scrollIntoView()); return true; }; // "---" on its own line becomes a rule followed by an empty paragraph. const hrRule = new InputRule(/^---$/, (state, _match, start, end) => { const $start = state.doc.resolve(start); const depth = $start.depth; if (depth < 1 || $start.parent.type.spec.code) return null; const index = $start.index(depth - 1); const parent = $start.node(depth - 1); const replacement = Fragment.from([horizontal_rule.create(), paragraph.create()]); if (!parent.canReplace(index, index + 1, replacement)) return null; const before = $start.before(); const tr = state.tr.replaceWith(before, $start.after(), [horizontal_rule.create(), paragraph.create()]); tr.setSelection(TextSelection.create(tr.doc, before + horizontal_rule.create().nodeSize + 1)); return tr; }); // Ctrl/Cmd+Shift+V pastes plain text. The keydown sets a short-lived flag, and the paste // event the browser fires next reads it. Normal paste keeps basic structure and drops styling. let plainPasteUntil = 0; const paste = new Plugin({ props: { transformPastedHTML(html) { return html.replace(/\s(?:style|class)\s*=\s*("[^"]*"|'[^']*')/gi, ""); }, handleKeyDown(_view, event) { if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLowerCase() === "v") { plainPasteUntil = Date.now() + 1000; } return false; }, handlePaste(view, event) { if (Date.now() > plainPasteUntil) return false; plainPasteUntil = 0; const text = event.clipboardData?.getData("text/plain"); if (!text) return false; view.pasteText(text); return true; }, }, }); const keys = keymap({ "Mod-Alt-0": toParagraph, "Mod-Alt-1": toggleBlock(heading, { level: 1 }), "Mod-Alt-2": toggleBlock(heading, { level: 2 }), "Mod-Alt-3": toggleBlock(heading, { level: 3 }), "Mod-Shift-8": toggleList(bullet_list), "Mod-Shift-9": toggleList(ordered_list), "Mod-k": toggleLink, "Mod-e": toggleMark(code), Backspace: undoInputRule, }); const rules = inputRules({ rules: [ textblockTypeInputRule(/^(#{1,3})\s$/, heading, (m) => ({ level: m[1].length })), textblockTypeInputRule(/^```$/, code_block), wrappingInputRule(/^\s*([-*])\s$/, bullet_list), wrappingInputRule( /^(\d+)\.\s$/, ordered_list, (m) => ({ order: Number(m[1]) }), (m, node) => node.childCount + node.attrs.order === Number(m[1]), ), wrappingInputRule(/^\s*>\s$/, blockquote), markInputRule(/\*\*([^*]+)\*\*$/, strong, 2), markInputRule(/(?:^|[^*])\*([^*]+)\*$/, em, 1), markInputRule(/`([^`]+)`$/, code, 1), hrRule, ], }); // Shown only while the whole note is one empty paragraph. const placeholder = new Plugin({ props: { decorations(state) { const { doc } = state; const first = doc.firstChild; if (doc.childCount !== 1 || !first || first.type !== paragraph || first.content.size > 0) return null; return DecorationSet.create(doc, [ Decoration.node(0, first.nodeSize, { class: "is-placeholder", "data-placeholder": t("placeholder"), }), ]); }, }, }); return { plugins: [ paste, keys, rules, dropCursor({ color: "var(--primary)", width: 2 }), gapCursor(), placeholder, ], paragraph: toParagraph, heading: (level) => toggleBlock(heading, { level }), codeBlock: toggleBlock(code_block), bold: toggleMark(strong), italic: toggleMark(em), inlineCode: toggleMark(code), link: toggleLink, bulletList: toggleList(bullet_list), orderedList: toggleList(ordered_list), blockquote: toggleQuote, horizontalRule: insertRule, }; }