// slash.mjs — the / menu (spec §6.6): at the start of an empty block, or // after a space, "/" offers the blocks Insert has, each with the // Markdown it writes, and filters them as you type. The Markdown // shortcuts work too; this is the dependable path on a phone, where // smart punctuation changes what is typed (§6.11). Date opens the date // picker (build note 83); Today's date puts today in at once. Image opens // the file picker (images §4.1). import { Plugin } from 'prosemirror-state' import { Combobox } from './combobox.mjs' import { blockCommands } from './commands.mjs' import { pickDate, insertToday } from './datepicker.mjs' const trigger = /(?:^|\s)\/([A-Za-z0-9 ]{0,24})$/u export const blocks = [ ['Heading 1', '#', 'insert-h1'], ['Heading 2', '##', 'insert-h2'], ['Heading 3', '###', 'insert-h3'], ['List', '-', 'insert-list'], ['Numbered', '1.', 'insert-numbered'], ['Checklist', '- [ ]', 'insert-check'], ['Quote', '>', 'insert-quote'], ['Code', '```', 'insert-code'], ['Divider', '---', 'insert-rule'], ['Columns', 'two side by side', 'insert-columns-2'], ['Link to a page', '[[', 'insert-link'], ['Date', 'choose a day', 'insert-date-pick'], ['Today’s date', 'today’s note', 'insert-date'], ['Image', 'upload an image', 'insert-image'] ] function slashing (state) { const { $from, empty } = state.selection if (!empty || $from.parent.type.spec.code || !$from.parent.inlineContent) return null const before = $from.parent.textBetween(0, $from.parentOffset, null, '') const match = trigger.exec(before) if (!match) return null return { text: match[1].toLowerCase().trim(), from: $from.pos - match[1].length - 1, to: $from.pos } } // extra is commands the page brings: Image's file picker (images §4.1). export function slashPlugin (extra = {}) { let box = null return new Plugin({ view (view) { const commands = { ...blockCommands(view.state.schema), 'insert-date-pick': pickDate, 'insert-date': insertToday, ...extra } box = new Combobox(view, { label: 'Blocks', count: items => items.length === 1 ? '1 block' : `${items.length} blocks` }) return { update (view, previous) { if (view.state.doc.eq(previous.doc) && view.state.selection.eq(previous.selection)) return const query = slashing(view.state) if (!query) { box.close() return } const items = blocks .filter(([label, , name]) => commands[name] && label.toLowerCase().includes(query.text)) .map(([label, detail, name]) => ({ label, detail, run: view => { const now = slashing(view.state) if (!now) return view.dispatch(view.state.tr.delete(now.from, now.to)) commands[name](view.state, view.dispatch, view) } })) box.show(items, query.from) }, destroy () { box.destroy() } } }, props: { handleKeyDown (view, event) { return box?.keys(event) ?? false }, handleDOMEvents: { blur () { box?.close(); return false } } } }) }