@vitral/editor 0.2.12 → 0.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -37,6 +37,11 @@ A slash menu entry is `{ id, label, description, icon, command }` or carries a
37
37
  for the block handle's actions. What a framework component draws better — a
38
38
  select, a colour picker — it hands over instead.
39
39
 
40
+ The text area (when a height makes it scroll), the slash menu and the formula list wear the theme's drawn scrollbars, the ScrollPanel's, over native
41
+ scrolling: `scrollbar: 'hover'` (the default) shows them under the pointer and
42
+ while scrolling, `'always'` keeps them on the screen, `'native'` gives the
43
+ browser's own back.
44
+
40
45
  **[Documentation](https://vitralui.github.io/vitral/#/components/editor)**
41
46
 
42
47
  LGPL-3.0-or-later. Part of the [Vitral](https://github.com/vitralui/vitral) monorepo.
package/dist/editor.js CHANGED
@@ -8,9 +8,9 @@ import { createFindBar } from "./find.js";
8
8
  import { createSlashMenu, defaultSlashCommands } from "./slash.js";
9
9
  import { activeEditorBlockType, activeEditorMark, ariaEditorShortcut, createEditor, createEditorView, editorKeyName, editorLinkAt, editorLinkHint, editorPalette, editorSelectionRange, editorShortcutFor, en, followEditorLink, formatEditorShortcut, formatMessage, isEmptyEditorDoc, isMacPlatform, loadStyle, matchEditorPaletteColor, visuallyHidden } from "@vitral/core";
10
10
  import { createOverlay, createSelect, createTooltips } from "@vitral/controls";
11
- import { createRoot, h, mergeAttrs, partResolver } from "@vitral/dom";
11
+ import { createRoot, h, mergeAttrs, partResolver, scrollbarSet } from "@vitral/dom";
12
12
  import { registerIcons } from "@vitral/icons";
13
- import { baseStyle, buttonStyle, editorStyle } from "@vitral/styles";
13
+ import { baseStyle, buttonStyle, editorStyle, scrollpanelStyle } from "@vitral/styles";
14
14
  //#region src/editor.ts
15
15
  /**
16
16
  * A rich text editor with no framework in it: the document, the commands and
@@ -60,6 +60,14 @@ function createTextEditor(element, config = {}) {
60
60
  loadStyle(buttonStyle.name, buttonStyle.css, options);
61
61
  loadStyle(editorStyle.name, editorStyle.css, options);
62
62
  }
63
+ const barOptions = () => ({
64
+ mode: current.scrollbar,
65
+ style: scrollpanelStyle,
66
+ unstyled: current.unstyled,
67
+ nonce: current.nonce,
68
+ cssLayer: current.cssLayer
69
+ });
70
+ const bars = scrollbarSet(barOptions);
63
71
  const tooltips = createTooltips(() => ({
64
72
  placement: "bottom",
65
73
  unstyled: current.unstyled,
@@ -246,7 +254,8 @@ function createTextEditor(element, config = {}) {
246
254
  focus: () => view?.focus(),
247
255
  id: `${id}-math`,
248
256
  overlayTarget: current.overlayTarget,
249
- zIndex: current.zIndex
257
+ zIndex: current.zIndex,
258
+ scrollbars: barOptions
250
259
  });
251
260
  const slashMenu = createSlashMenu({
252
261
  editor,
@@ -260,6 +269,7 @@ function createTextEditor(element, config = {}) {
260
269
  ids,
261
270
  overlayTarget: current.overlayTarget,
262
271
  zIndex: current.zIndex,
272
+ scrollbars: barOptions,
263
273
  onRun: (command) => {
264
274
  if (command.run) command.run(handle);
265
275
  else if (command.command?.[0] === "math") return mathTools.open();
@@ -492,6 +502,7 @@ function createTextEditor(element, config = {}) {
492
502
  }, locale().editor.keyboardHelp),
493
503
  current.hooks?.footer ? current.hooks.footer() : current.showCount ? h("div", mergeAttrs({ key: "footer" }, part("footer")), h("span", part("count", { limit: !!current.maxLength }), countText())) : null
494
504
  ]);
505
+ bars.sync([contentEl]);
495
506
  syncBlockSelect();
496
507
  syncBubble();
497
508
  renderPanels();
@@ -575,6 +586,7 @@ function createTextEditor(element, config = {}) {
575
586
  [...panels(), bubble].forEach((overlay) => overlay.destroy());
576
587
  blockSelect?.destroy();
577
588
  tooltips.destroy();
589
+ bars.destroy();
578
590
  view?.destroy();
579
591
  root.clear();
580
592
  }
@@ -1 +1 @@
1
- {"version":3,"file":"editor.js","names":[],"sources":["../src/editor.ts"],"sourcesContent":["import {\n activeEditorBlockType,\n activeEditorMark,\n ariaEditorShortcut,\n createEditor as createEditorInstance,\n createEditorView,\n editorLinkAt,\n editorKeyName,\n editorLinkHint,\n editorPalette,\n editorShortcutFor,\n editorSelectionRange,\n editorTextblocks,\n en,\n formatEditorShortcut,\n followEditorLink,\n formatMessage,\n isEmptyEditorDoc,\n isMacPlatform,\n loadStyle,\n matchEditorPaletteColor,\n visuallyHidden,\n type EditorColor,\n type EditorInstance,\n type EditorNode,\n type EditorView,\n type Locale\n} from '@vitral/core';\nimport { createOverlay, createSelect, createTooltips, type Overlay, type SelectHandle } from '@vitral/controls';\nimport { createRoot, h, mergeAttrs, partResolver, type Child, type Props } from '@vitral/dom';\nimport { registerIcons } from '@vitral/icons';\nimport { baseStyle, buttonStyle, editorStyle } from '@vitral/styles';\nimport { defaultBubbleMenu, defaultToolbar, editorIcons } from './buttons';\nimport { createBlockHandle, defaultBlockActions } from './block';\nimport { colorPanelView, imagePanelView, linkPanelView, tablePanelView, type LinkPanelState, type PanelContext } from './render/menus';\nimport { createChipMenu } from './chips';\nimport { createMathTools, defaultMathTemplates } from './math';\nimport { createFindBar } from './find';\nimport { createSlashMenu, defaultSlashCommands } from './slash';\nimport { bubbleView, toolbarView, type ToolbarContext } from './render/toolbar';\nimport type { TextEditorConfig, TextEditorHandle, EditorToolbarItem } from './types';\n\n/**\n * A rich text editor with no framework in it: the document, the commands and\n * the history are `@vitral/core`'s, the text itself is its view over a\n * `contenteditable` element, and everything around them — the toolbar, the\n * panels, the floating toolbar over a selection, the menu a `/` opens and the\n * handle beside a block — is drawn here.\n */\n\nlet counter = 0;\n\nexport function createTextEditor(element: HTMLElement, config: TextEditorConfig = {}): TextEditorHandle {\n let current: TextEditorConfig = { ...config };\n let view: EditorView | null = null;\n let contentEl: HTMLElement | null = null;\n let caretEl: HTMLElement | null = null;\n let blockSelect: SelectHandle | null = null;\n let blockSelectHost: HTMLElement | null = null;\n let link: LinkPanelState = { href: '', text: '', newTab: false, existing: false };\n const anchors = new Map<string, HTMLElement>();\n\n const id = config.id ?? `vt-texteditor-${++counter}`;\n const ids = { content: `${id}-content`, help: `${id}-help`, slash: `${id}-slash`, block: `${id}-block` };\n const root = createRoot(element);\n const locale = (): Locale => current.locale ?? en;\n const palette = (): readonly EditorColor[] => current.palette ?? editorPalette;\n const part = partResolver({\n style: editorStyle,\n unstyled: () => !!current.unstyled,\n classes: () => current.classes,\n pt: () => current.pt,\n props: () => current as Record<string, unknown>\n });\n\n if (!config.unstyled) {\n const options = { nonce: config.nonce, cssLayer: config.cssLayer };\n loadStyle(baseStyle.name, baseStyle.css, options);\n loadStyle(buttonStyle.name, buttonStyle.css, options);\n loadStyle(editorStyle.name, editorStyle.css, options);\n }\n // The toolbar holds its own definitions, but the slash menu, the block\n // handle and any command an application names its own icon for are looked\n // up by name: the editor puts its set in the registry rather than drawing\n // a bar of empty buttons in an application that never registered them.\n // What each button is, shown the way every other Vitral control shows it.\n const tooltips = createTooltips(() => ({\n placement: 'bottom',\n unstyled: current.unstyled,\n nonce: current.nonce,\n cssLayer: current.cssLayer,\n zIndex: current.zIndex,\n pt: current.pt\n }));\n\n registerIcons(editorIcons);\n\n const editor: EditorInstance = createEditorInstance({\n content: current.content ?? '',\n maxLength: current.maxLength ?? null,\n historyDelay: current.historyDelay,\n mathOutput: typeof current.math === 'object' ? current.math.output : undefined\n });\n\n const editable = () => !current.readonly && !current.disabled;\n const collapsed = () => editorSelectionRange(editor.state.selection).empty;\n const run = (name: string, ...args: unknown[]) => (editor.run as (n: string, ...a: unknown[]) => boolean)(name, ...args);\n const can = (name: string, ...args: unknown[]) => (editor.can as (n: string, ...a: unknown[]) => boolean)(name, ...args);\n\n // ---- what the outside hears ---------------------------------------------------------\n\n const stop = editor.subscribe((update) => {\n if (update.docChanged) {\n current.on?.change?.({ html: editor.getHTML(), json: editor.getJSON(), text: editor.getText() });\n }\n if (update.docChanged) findBar.sync();\n if (update.selectionChanged) {\n current.on?.['selection-change']?.({ empty: collapsed(), source: update.origin === 'user' ? 'user' : update.origin === 'history' ? 'history' : 'api' });\n }\n render();\n });\n\n // ---- the panels ------------------------------------------------------------------------\n\n const panelContext = (): PanelContext => ({ locale: locale(), part, ids });\n\n const anchorFor = (name: string) => () => anchors.get(name) ?? caretEl;\n\n function panel(name: string, render: () => ReturnType<typeof linkPanelView> | null, placement: 'bottom-start' | 'bottom-end' = 'bottom-start'): Overlay {\n return createOverlay({\n anchor: anchorFor(name),\n render,\n placement,\n target: () => current.overlayTarget,\n zIndex: current.zIndex,\n onClose: () => renderPanels()\n });\n }\n\n const linkPanel = panel('link', () => linkPanelView(panelContext(), link, linkActions));\n const imagePanel = panel('image', () => imagePanelView(panelContext(), imageActions));\n const tablePanel = panel('table', () => tablePanelView(panelContext(), { insert: insertTable }));\n const colorPanel = panel('color', () => colorPanelView(panelContext(), { kind: colorKind, palette: palette(), chosen: colorOf(colorKind), onChoose: chooseColor }));\n let colorKind: 'color' | 'highlight' = 'color';\n\n const linkActions = {\n change: (patch: Partial<LinkPanelState>) => {\n link = { ...link, ...patch, error: undefined };\n linkPanel.update();\n },\n apply: () => {\n const href = link.href.trim();\n if (!href) {\n link = { ...link, error: locale().editor.invalidUrl };\n linkPanel.update();\n return;\n }\n run('setLink', href, { target: link.newTab ? '_blank' : null, text: link.text.trim() || undefined });\n linkPanel.close();\n focus();\n },\n remove: () => {\n run('unsetLink');\n linkPanel.close();\n focus();\n },\n open: () => {\n followEditorLink(link.href.trim());\n linkPanel.close();\n },\n cancel: () => {\n linkPanel.close();\n focus();\n }\n };\n\n /** The link editor, filled in with the link under the caret when there is one. */\n function openLinkPanel(event?: MouseEvent) {\n if (!editable()) return;\n const at = editorLinkAt(editor.state);\n link = { href: at?.href ?? '', text: at?.text ?? '', newTab: at?.target === '_blank', existing: !!at };\n if (!event) placeCaret();\n openPanel(linkPanel, 'link', event);\n }\n\n const imageActions = {\n insert: (src: string, alt: string) => {\n if (src.trim()) run('insertImage', { src: src.trim(), alt: alt.trim() });\n imagePanel.close();\n focus();\n },\n cancel: () => {\n imagePanel.close();\n focus();\n }\n };\n\n function insertTable(rows: number, columns: number) {\n run('insertTable', rows, columns, true);\n tablePanel.close();\n focus();\n }\n\n const colorOf = (kind: 'color' | 'highlight'): EditorColor | undefined => {\n const mark = activeEditorMark(editor.state, kind);\n const value = mark?.attrs?.color;\n if (typeof value !== 'string') return undefined;\n const name = matchEditorPaletteColor(value, kind, palette());\n return palette().find((color) => color.name === name);\n };\n\n function chooseColor(color: EditorColor | null) {\n run(colorKind === 'color' ? 'setColor' : 'setHighlight', color?.name ?? null);\n colorPanel.close();\n focus();\n }\n\n // ---- the floating toolbar over a selection -----------------------------------------------\n\n const bubble = createOverlay({\n anchor: () => caretEl,\n render: () => bubbleView(toolbarContext(), bubbleItems()) as never,\n placement: 'top',\n target: () => current.overlayTarget,\n zIndex: current.zIndex,\n restoreFocus: false\n });\n\n const bubbleItems = (): EditorToolbarItem[] => (Array.isArray(current.bubbleMenu) ? current.bubbleMenu : defaultBubbleMenu);\n\n function syncBubble() {\n const wanted = current.bubbleMenu !== false && editable() && !collapsed() && !editor.isEmpty();\n if (wanted) {\n placeCaret();\n bubble.open();\n bubble.update();\n } else bubble.close();\n }\n\n // ---- the menu a slash opens, and the handle beside a block ---------------------------------\n\n const chipMenu = createChipMenu({\n editor,\n content: () => contentEl,\n anchor: () => caretEl,\n triggers: () => (current.chips ? (Array.isArray(current.chips) ? current.chips : [current.chips]) : []),\n part,\n locale,\n enabled: () => !!current.chips && editable(),\n place: placeCaret,\n id: `${ids.slash}-chips`,\n overlayTarget: current.overlayTarget,\n zIndex: current.zIndex\n });\n\n // ---- formulas ---------------------------------------------------------------------------------\n\n const mathOn = () => current.math !== false;\n const mathOptions = () => (typeof current.math === 'object' ? current.math : {});\n const mathTools = createMathTools({\n editor,\n view: () => view,\n content: () => contentEl,\n anchor: () => caretEl,\n place: placeCaret,\n templates: () => mathOptions().templates ?? defaultMathTemplates(locale()),\n inlineEdit: () => mathOptions().inlineEdit !== false,\n part,\n locale,\n enabled: () => mathOn() && editable(),\n focus: () => view?.focus(),\n id: `${id}-math`,\n overlayTarget: current.overlayTarget,\n zIndex: current.zIndex\n });\n\n const slashMenu = createSlashMenu({\n editor,\n content: () => contentEl,\n anchor: () => caretEl,\n commands: () => (Array.isArray(current.slashMenu) ? current.slashMenu : defaultSlashCommands(locale()).filter((command) => command.id !== 'math' || mathOn())),\n part,\n locale,\n enabled: () => current.slashMenu !== false && editable(),\n place: placeCaret,\n ids,\n overlayTarget: current.overlayTarget,\n zIndex: current.zIndex,\n onRun: (command) => {\n if (command.run) command.run(handle);\n // The formula panel takes the keyboard itself: it opens where the caret was left.\n else if (command.command?.[0] === 'math') return mathTools.open();\n else if (command.command) run(command.command[0], ...command.command.slice(1));\n focus();\n }\n });\n\n const blockHandle = createBlockHandle({\n editor,\n host: () => element,\n caretRect: () => view?.selectionRect() ?? null,\n content: () => contentEl,\n actions: () => (Array.isArray(current.blockMenu) ? current.blockMenu : defaultBlockActions(locale())),\n part,\n locale,\n enabled: () => current.blockMenu !== false && editable(),\n ids,\n overlayTarget: current.overlayTarget,\n zIndex: current.zIndex\n });\n\n // ---- find and replace ---------------------------------------------------------------------\n\n const findBar = createFindBar({\n editor,\n view: () => view,\n part,\n locale,\n editable,\n render: () => render(),\n id: `${id}-find`\n });\n\n // Ctrl/⌘+F finds and Ctrl+H (⌘+⌥+F on a Mac, where ⌘+H hides the app)\n // replaces, anywhere in the editor — the text, the toolbar or the bar.\n const onFindKey = (event: KeyboardEvent) => {\n if (current.find === false) return;\n const name = editorKeyName(event);\n const replace = name === (isMacPlatform() ? 'Mod-Alt-f' : 'Mod-h');\n if (name !== 'Mod-f' && !replace) return;\n event.preventDefault();\n findBar.open({ replace });\n };\n element.addEventListener('keydown', onFindKey);\n\n // ---- where a popup hangs from ---------------------------------------------------------------\n\n /** The caret's own rectangle, as an element popups can be anchored to. */\n function placeCaret() {\n if (!caretEl || !contentEl) return;\n const rect = view?.selectionRect();\n if (!rect) return;\n const host = element.getBoundingClientRect();\n caretEl.style.top = `${rect.top - host.top}px`;\n caretEl.style.left = `${rect.left - host.left}px`;\n caretEl.style.width = `${Math.max(1, rect.width)}px`;\n caretEl.style.height = `${rect.height}px`;\n }\n\n function openPanel(overlay: Overlay, name: string, event?: MouseEvent) {\n if (event) anchors.set(name, event.currentTarget as HTMLElement);\n else anchors.delete(name);\n closePanels(overlay);\n overlay.open();\n overlay.update();\n }\n\n const panels = () => [linkPanel, imagePanel, tablePanel, colorPanel];\n const closePanels = (except?: Overlay) => panels().forEach((overlay) => overlay !== except && overlay.close());\n const renderPanels = () => panels().forEach((overlay) => overlay.update());\n\n // ---- the toolbar -----------------------------------------------------------------------------\n\n function toolbarContext(): ToolbarContext {\n return {\n locale: locale(),\n part,\n editable: editable(),\n can,\n isActive: (name, attrs) => editor.isActive(name, attrs as never),\n shortcut: (name, args) => {\n const binding = editorShortcutFor(name, args);\n return binding ? { label: formatEditorShortcut(binding), aria: ariaEditorShortcut(binding) } : undefined;\n },\n colors: { text: colorOf('color'), highlight: colorOf('highlight') },\n ref: (name) => (el) => {\n if (el) anchors.set(name, el as HTMLElement);\n else anchors.delete(name);\n },\n on: {\n tip: (element, text) => tooltips.attach(element, text),\n command: (name, args, event) => {\n run(name, ...args);\n if (event.detail > 0) focus();\n },\n openLink: (event) => openLinkPanel(event),\n openFind: () => (findBar.isOpen ? findBar.close() : findBar.open()),\n openImage: (event) => openPanel(imagePanel, 'image', event),\n openTable: (event) => openPanel(tablePanel, 'table', event),\n openMath: (event) => {\n closePanels();\n // On a formula it hangs from the formula; for a new one, from the button.\n mathTools.open(editor.isActive('math') ? null : (event.currentTarget as HTMLElement));\n },\n openColor: (kind, event) => {\n colorKind = kind;\n openPanel(colorPanel, kind, event);\n },\n blockSelect: (el) => {\n blockSelectHost = (el as HTMLElement | null) ?? null;\n syncBlockSelect();\n }\n }\n };\n }\n\n /** The block type, drawn by the control kit's select. */\n function syncBlockSelect() {\n if (!blockSelectHost) return;\n const words = locale().editor;\n const options = [\n { label: words.paragraph, value: 'paragraph' },\n { label: words.heading1, value: 'heading1' },\n { label: words.heading2, value: 'heading2' },\n { label: words.heading3, value: 'heading3' },\n { label: words.codeBlock, value: 'codeBlock' }\n ];\n const active = activeEditorBlockType(editor.state);\n const settings = {\n options,\n optionValue: 'value',\n value: active,\n size: 'small' as const,\n ariaLabel: words.blockType,\n disabled: !editable(),\n locale: locale(),\n unstyled: current.unstyled,\n overlayTarget: current.overlayTarget,\n zIndex: current.zIndex,\n nonce: current.nonce,\n cssLayer: current.cssLayer\n };\n if (blockSelect) blockSelect.update(settings);\n else\n blockSelect = createSelect(blockSelectHost, {\n ...settings,\n onChange: (value) => {\n if (value === 'paragraph') run('setParagraph');\n else if (value === 'codeBlock') run('toggleCodeBlock');\n else run('toggleHeading', Number(String(value).slice(-1)));\n focus();\n }\n });\n }\n\n // ---- drawing --------------------------------------------------------------------------------\n\n /** The groups of the toolbar, without the formula button where formulas are off. */\n const toolbarGroups = (): EditorToolbarItem[][] => {\n const groups = Array.isArray(current.toolbar) ? current.toolbar : defaultToolbar;\n return mathOn() ? groups : groups.map((group) => group.filter((item) => item !== 'math')).filter((group) => group.length);\n };\n\n function countText(): string {\n const words = locale().editor;\n const count = editor.characterCount();\n const characters = current.maxLength\n ? formatMessage(words.charactersLimit, { count, limit: current.maxLength })\n : formatMessage(count === 1 ? words.character : words.characters, { count });\n const mode = current.showCount === true ? 'characters' : current.showCount;\n if (mode === 'characters' || !mode) return characters;\n const wordCount = editor.wordCount();\n const wordText = formatMessage(wordCount === 1 ? words.word : words.words, { count: wordCount });\n return mode === 'words' ? wordText : `${wordText} · ${characters}`;\n }\n\n function contentView(): Child {\n return h(\n 'div',\n mergeAttrs({ key: 'content', id: ids.content }, part('content'), {\n class: isEmptyEditorDoc(editor.state.doc) ? 'vt-editor-content-empty' : undefined,\n role: 'textbox',\n 'aria-multiline': 'true',\n 'aria-label': current.ariaLabelledby ? undefined : current.ariaLabel,\n 'aria-labelledby': current.ariaLabelledby,\n 'aria-describedby': ids.help,\n 'aria-readonly': current.readonly ? 'true' : undefined,\n 'aria-disabled': current.disabled ? 'true' : undefined,\n 'aria-invalid': current.invalid ? 'true' : undefined,\n 'aria-placeholder': current.placeholder || undefined,\n 'data-placeholder': current.placeholder || undefined,\n // How a formula answers a press, which is what its look under the pointer follows.\n 'data-math-edit': mathOn() && editable() ? (mathOptions().inlineEdit === false ? 'panel' : 'inline') : undefined,\n contenteditable: editable() ? 'true' : 'false',\n tabindex: current.disabled ? '-1' : '0',\n spellcheck: 'true',\n translate: 'no',\n ref: (el: Element | null) => {\n const next = el as HTMLElement | null;\n if (next === contentEl) return;\n contentEl = next;\n attachView();\n },\n onFocus: (event: FocusEvent) => current.on?.focus?.(event),\n onBlur: (event: FocusEvent) => current.on?.blur?.(event)\n })\n );\n }\n\n function render() {\n const drawn = toolbarContext();\n root.attrs(part('root', { readonly: current.readonly, disabled: current.disabled, invalid: current.invalid }));\n root.render([\n current.hooks?.toolbar ? (current.hooks.toolbar() as Child) : current.toolbar === false ? null : toolbarView(drawn, toolbarGroups()),\n findBar.view(),\n contentView(),\n h('span', mergeAttrs({ key: 'caret', 'aria-hidden': 'true' }, part('caret'), { ref: (el: Element | null) => (caretEl = el as HTMLElement | null) })),\n h('span', { key: 'help', id: ids.help, style: visuallyHidden }, locale().editor.keyboardHelp),\n current.hooks?.footer\n ? (current.hooks.footer() as Child)\n : current.showCount\n ? h('div', mergeAttrs({ key: 'footer' }, part('footer')), h('span', part('count', { limit: !!current.maxLength }), countText()))\n : null\n ]);\n syncBlockSelect();\n syncBubble();\n renderPanels();\n blockHandle.sync();\n mathTools.sync();\n }\n\n function attachView() {\n view?.destroy();\n view = null;\n if (!contentEl) return;\n view = createEditorView(contentEl, editor, {\n editable,\n taskLabel: locale().editor.taskDone,\n selectedClass: 'vt-editor-node-selected',\n emptyClass: 'vt-editor-content-empty',\n chipClass: (kind) => (current.unstyled ? undefined : ['vt-editor-chip', kind ? `vt-editor-chip-${kind}` : ''].filter(Boolean).join(' ')),\n mathClass: ({ display, pending }) => (current.unstyled ? undefined : ['vt-editor-math', display ? 'vt-editor-math-display' : '', pending ? 'vt-editor-math-pending' : ''].filter(Boolean).join(' ')),\n // Ctrl/⌘+K opens the link editor, over the caret.\n handleKey: (_name, binding) => {\n if (binding?.[0] !== 'link' || !editable()) return false;\n openLinkPanel();\n return true;\n },\n linkHint: (href) => ({ ...tooltips.options(editorLinkHint(href, locale().editor.followLink)), placement: 'top' })\n });\n if (current.autofocus) view.focus();\n }\n\n const focus = () => view?.focus();\n\n render();\n\n const handle: TextEditorHandle = {\n element,\n update(next) {\n const content = 'content' in next;\n current = { ...current, ...next };\n if (content) editor.setContent(current.content ?? '', { emit: false });\n if ('maxLength' in next) editor.maxLength = current.maxLength ?? null;\n if ('math' in next) editor.mathOutput = mathOptions().output ?? 'drawing';\n render();\n },\n getHTML: (options) => editor.getHTML(options),\n getJSON: () => editor.getJSON(),\n getText: () => editor.getText(),\n getMarkdown: () => editor.getMarkdown(),\n typeText: (text) => {\n const typed = editor.typeText(text);\n render();\n return typed;\n },\n setContent: (value) => {\n editor.setContent(value);\n render();\n },\n run: (name, ...args) => {\n const applied = run(name, ...args);\n render();\n return applied;\n },\n can,\n isActive: (name, attrs) => editor.isActive(name, attrs as never),\n focus,\n openFind: (options) => findBar.open(options),\n closeFind: () => findBar.close({ focusEditor: false }),\n refresh: render,\n destroy() {\n stop();\n element.removeEventListener('keydown', onFindKey);\n findBar.destroy();\n slashMenu.destroy();\n chipMenu.destroy();\n mathTools.destroy();\n blockHandle.destroy();\n [...panels(), bubble].forEach((overlay) => overlay.destroy());\n blockSelect?.destroy();\n tooltips.destroy();\n view?.destroy();\n root.clear();\n }\n };\n\n return handle;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkDA,IAAI,UAAU;AAEd,SAAgB,iBAAiB,SAAsB,SAA2B,CAAC,GAAqB;CACpG,IAAI,UAA4B,EAAE,GAAG,OAAO;CAC5C,IAAI,OAA0B;CAC9B,IAAI,YAAgC;CACpC,IAAI,UAA8B;CAClC,IA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GACjE,IAAI,UAAU,MAAM,OAAO,aAAa,YAAY,CAAC,CAAC,UAAU;GAChE,OAAO;EACX;EACA,UAAU,YAAY,OAAO,QAAQ,OAAO;EAC5C,eAAe,OAAO,QAAQ;EAC9B,eAAe,OAAO,QAAQ;EAC9B,mBAAmB,OAAO,YAAY;EACtC,WAAW,SAAS;GAChB,MAAM,QAAQ,OAAO,SAAS,IAAI;GAClC,OAAO;GACP,OAAO;EACX;EACA,aAAa,UAAU;GACnB,OAAO,WAAW,KAAK;GACvB,OAAO;EACX;EACA,MAAM,MAAM,GAAG,SAAS;GACpB,MAAM,UAAU,IAAI,MAAM,GAAG,IAAI;GACjC,OAAO;GACP,OAAO;EACX;EACA;EACA,WAAW,MAAM,UAAU,OAAO,SAAS,MAAM,KAAc;EAC/D;EACA,WAAW,YAAY,QAAQ,KAAK,OAAO;EAC3C,iBAAiB,QAAQ,MAAM,EAAE,aAAa,MAAM,CAAC;EACrD,SAAS;EACT,UAAU;GACN,KAAK;GACL,QAAQ,oBAAoB,WAAW,SAAS;GAChD,QAAQ,QAAQ;GAChB,UAAU,QAAQ;GAClB,SAAS,QAAQ;GACjB,UAAU,QAAQ;GAClB,YAAY,QAAQ;GACpB,CAAC,GAAG,OAAO,GAAG,MAAM,CAAC,CAAC,SAAS,YAAY,QAAQ,QAAQ,CAAC;GAC5D,aAAa,QAAQ;GACrB,SAAS,QAAQ;GACjB,MAAM,QAAQ;GACd,KAAK,MAAM;EACf;CACJ;CAEA,OAAO;AACX"}
1
+ {"version":3,"file":"editor.js","names":[],"sources":["../src/editor.ts"],"sourcesContent":["import {\n activeEditorBlockType,\n activeEditorMark,\n ariaEditorShortcut,\n createEditor as createEditorInstance,\n createEditorView,\n editorLinkAt,\n editorKeyName,\n editorLinkHint,\n editorPalette,\n editorShortcutFor,\n editorSelectionRange,\n editorTextblocks,\n en,\n formatEditorShortcut,\n followEditorLink,\n formatMessage,\n isEmptyEditorDoc,\n isMacPlatform,\n loadStyle,\n matchEditorPaletteColor,\n visuallyHidden,\n type EditorColor,\n type EditorInstance,\n type EditorNode,\n type EditorView,\n type Locale\n} from '@vitral/core';\nimport { createOverlay, createSelect, createTooltips, type Overlay, type SelectHandle } from '@vitral/controls';\nimport { createRoot, h, mergeAttrs, partResolver, scrollbarSet, type Child, type Props } from '@vitral/dom';\nimport { registerIcons } from '@vitral/icons';\nimport { baseStyle, buttonStyle, editorStyle, scrollpanelStyle } from '@vitral/styles';\nimport { defaultBubbleMenu, defaultToolbar, editorIcons } from './buttons';\nimport { createBlockHandle, defaultBlockActions } from './block';\nimport { colorPanelView, imagePanelView, linkPanelView, tablePanelView, type LinkPanelState, type PanelContext } from './render/menus';\nimport { createChipMenu } from './chips';\nimport { createMathTools, defaultMathTemplates } from './math';\nimport { createFindBar } from './find';\nimport { createSlashMenu, defaultSlashCommands } from './slash';\nimport { bubbleView, toolbarView, type ToolbarContext } from './render/toolbar';\nimport type { TextEditorConfig, TextEditorHandle, EditorToolbarItem } from './types';\n\n/**\n * A rich text editor with no framework in it: the document, the commands and\n * the history are `@vitral/core`'s, the text itself is its view over a\n * `contenteditable` element, and everything around them — the toolbar, the\n * panels, the floating toolbar over a selection, the menu a `/` opens and the\n * handle beside a block — is drawn here.\n */\n\nlet counter = 0;\n\nexport function createTextEditor(element: HTMLElement, config: TextEditorConfig = {}): TextEditorHandle {\n let current: TextEditorConfig = { ...config };\n let view: EditorView | null = null;\n let contentEl: HTMLElement | null = null;\n let caretEl: HTMLElement | null = null;\n let blockSelect: SelectHandle | null = null;\n let blockSelectHost: HTMLElement | null = null;\n let link: LinkPanelState = { href: '', text: '', newTab: false, existing: false };\n const anchors = new Map<string, HTMLElement>();\n\n const id = config.id ?? `vt-texteditor-${++counter}`;\n const ids = { content: `${id}-content`, help: `${id}-help`, slash: `${id}-slash`, block: `${id}-block` };\n const root = createRoot(element);\n const locale = (): Locale => current.locale ?? en;\n const palette = (): readonly EditorColor[] => current.palette ?? editorPalette;\n const part = partResolver({\n style: editorStyle,\n unstyled: () => !!current.unstyled,\n classes: () => current.classes,\n pt: () => current.pt,\n props: () => current as Record<string, unknown>\n });\n\n if (!config.unstyled) {\n const options = { nonce: config.nonce, cssLayer: config.cssLayer };\n loadStyle(baseStyle.name, baseStyle.css, options);\n loadStyle(buttonStyle.name, buttonStyle.css, options);\n loadStyle(editorStyle.name, editorStyle.css, options);\n }\n // The ScrollPanel's bars on the text area, so one theme dresses every bar.\n const barOptions = () => ({ mode: current.scrollbar, style: scrollpanelStyle, unstyled: current.unstyled, nonce: current.nonce, cssLayer: current.cssLayer });\n const bars = scrollbarSet(barOptions);\n // The toolbar holds its own definitions, but the slash menu, the block\n // handle and any command an application names its own icon for are looked\n // up by name: the editor puts its set in the registry rather than drawing\n // a bar of empty buttons in an application that never registered them.\n // What each button is, shown the way every other Vitral control shows it.\n const tooltips = createTooltips(() => ({\n placement: 'bottom',\n unstyled: current.unstyled,\n nonce: current.nonce,\n cssLayer: current.cssLayer,\n zIndex: current.zIndex,\n pt: current.pt\n }));\n\n registerIcons(editorIcons);\n\n const editor: EditorInstance = createEditorInstance({\n content: current.content ?? '',\n maxLength: current.maxLength ?? null,\n historyDelay: current.historyDelay,\n mathOutput: typeof current.math === 'object' ? current.math.output : undefined\n });\n\n const editable = () => !current.readonly && !current.disabled;\n const collapsed = () => editorSelectionRange(editor.state.selection).empty;\n const run = (name: string, ...args: unknown[]) => (editor.run as (n: string, ...a: unknown[]) => boolean)(name, ...args);\n const can = (name: string, ...args: unknown[]) => (editor.can as (n: string, ...a: unknown[]) => boolean)(name, ...args);\n\n // ---- what the outside hears ---------------------------------------------------------\n\n const stop = editor.subscribe((update) => {\n if (update.docChanged) {\n current.on?.change?.({ html: editor.getHTML(), json: editor.getJSON(), text: editor.getText() });\n }\n if (update.docChanged) findBar.sync();\n if (update.selectionChanged) {\n current.on?.['selection-change']?.({ empty: collapsed(), source: update.origin === 'user' ? 'user' : update.origin === 'history' ? 'history' : 'api' });\n }\n render();\n });\n\n // ---- the panels ------------------------------------------------------------------------\n\n const panelContext = (): PanelContext => ({ locale: locale(), part, ids });\n\n const anchorFor = (name: string) => () => anchors.get(name) ?? caretEl;\n\n function panel(name: string, render: () => ReturnType<typeof linkPanelView> | null, placement: 'bottom-start' | 'bottom-end' = 'bottom-start'): Overlay {\n return createOverlay({\n anchor: anchorFor(name),\n render,\n placement,\n target: () => current.overlayTarget,\n zIndex: current.zIndex,\n onClose: () => renderPanels()\n });\n }\n\n const linkPanel = panel('link', () => linkPanelView(panelContext(), link, linkActions));\n const imagePanel = panel('image', () => imagePanelView(panelContext(), imageActions));\n const tablePanel = panel('table', () => tablePanelView(panelContext(), { insert: insertTable }));\n const colorPanel = panel('color', () => colorPanelView(panelContext(), { kind: colorKind, palette: palette(), chosen: colorOf(colorKind), onChoose: chooseColor }));\n let colorKind: 'color' | 'highlight' = 'color';\n\n const linkActions = {\n change: (patch: Partial<LinkPanelState>) => {\n link = { ...link, ...patch, error: undefined };\n linkPanel.update();\n },\n apply: () => {\n const href = link.href.trim();\n if (!href) {\n link = { ...link, error: locale().editor.invalidUrl };\n linkPanel.update();\n return;\n }\n run('setLink', href, { target: link.newTab ? '_blank' : null, text: link.text.trim() || undefined });\n linkPanel.close();\n focus();\n },\n remove: () => {\n run('unsetLink');\n linkPanel.close();\n focus();\n },\n open: () => {\n followEditorLink(link.href.trim());\n linkPanel.close();\n },\n cancel: () => {\n linkPanel.close();\n focus();\n }\n };\n\n /** The link editor, filled in with the link under the caret when there is one. */\n function openLinkPanel(event?: MouseEvent) {\n if (!editable()) return;\n const at = editorLinkAt(editor.state);\n link = { href: at?.href ?? '', text: at?.text ?? '', newTab: at?.target === '_blank', existing: !!at };\n if (!event) placeCaret();\n openPanel(linkPanel, 'link', event);\n }\n\n const imageActions = {\n insert: (src: string, alt: string) => {\n if (src.trim()) run('insertImage', { src: src.trim(), alt: alt.trim() });\n imagePanel.close();\n focus();\n },\n cancel: () => {\n imagePanel.close();\n focus();\n }\n };\n\n function insertTable(rows: number, columns: number) {\n run('insertTable', rows, columns, true);\n tablePanel.close();\n focus();\n }\n\n const colorOf = (kind: 'color' | 'highlight'): EditorColor | undefined => {\n const mark = activeEditorMark(editor.state, kind);\n const value = mark?.attrs?.color;\n if (typeof value !== 'string') return undefined;\n const name = matchEditorPaletteColor(value, kind, palette());\n return palette().find((color) => color.name === name);\n };\n\n function chooseColor(color: EditorColor | null) {\n run(colorKind === 'color' ? 'setColor' : 'setHighlight', color?.name ?? null);\n colorPanel.close();\n focus();\n }\n\n // ---- the floating toolbar over a selection -----------------------------------------------\n\n const bubble = createOverlay({\n anchor: () => caretEl,\n render: () => bubbleView(toolbarContext(), bubbleItems()) as never,\n placement: 'top',\n target: () => current.overlayTarget,\n zIndex: current.zIndex,\n restoreFocus: false\n });\n\n const bubbleItems = (): EditorToolbarItem[] => (Array.isArray(current.bubbleMenu) ? current.bubbleMenu : defaultBubbleMenu);\n\n function syncBubble() {\n const wanted = current.bubbleMenu !== false && editable() && !collapsed() && !editor.isEmpty();\n if (wanted) {\n placeCaret();\n bubble.open();\n bubble.update();\n } else bubble.close();\n }\n\n // ---- the menu a slash opens, and the handle beside a block ---------------------------------\n\n const chipMenu = createChipMenu({\n editor,\n content: () => contentEl,\n anchor: () => caretEl,\n triggers: () => (current.chips ? (Array.isArray(current.chips) ? current.chips : [current.chips]) : []),\n part,\n locale,\n enabled: () => !!current.chips && editable(),\n place: placeCaret,\n id: `${ids.slash}-chips`,\n overlayTarget: current.overlayTarget,\n zIndex: current.zIndex\n });\n\n // ---- formulas ---------------------------------------------------------------------------------\n\n const mathOn = () => current.math !== false;\n const mathOptions = () => (typeof current.math === 'object' ? current.math : {});\n const mathTools = createMathTools({\n editor,\n view: () => view,\n content: () => contentEl,\n anchor: () => caretEl,\n place: placeCaret,\n templates: () => mathOptions().templates ?? defaultMathTemplates(locale()),\n inlineEdit: () => mathOptions().inlineEdit !== false,\n part,\n locale,\n enabled: () => mathOn() && editable(),\n focus: () => view?.focus(),\n id: `${id}-math`,\n overlayTarget: current.overlayTarget,\n zIndex: current.zIndex,\n scrollbars: barOptions\n });\n\n const slashMenu = createSlashMenu({\n editor,\n content: () => contentEl,\n anchor: () => caretEl,\n commands: () => (Array.isArray(current.slashMenu) ? current.slashMenu : defaultSlashCommands(locale()).filter((command) => command.id !== 'math' || mathOn())),\n part,\n locale,\n enabled: () => current.slashMenu !== false && editable(),\n place: placeCaret,\n ids,\n overlayTarget: current.overlayTarget,\n zIndex: current.zIndex,\n scrollbars: barOptions,\n onRun: (command) => {\n if (command.run) command.run(handle);\n // The formula panel takes the keyboard itself: it opens where the caret was left.\n else if (command.command?.[0] === 'math') return mathTools.open();\n else if (command.command) run(command.command[0], ...command.command.slice(1));\n focus();\n }\n });\n\n const blockHandle = createBlockHandle({\n editor,\n host: () => element,\n caretRect: () => view?.selectionRect() ?? null,\n content: () => contentEl,\n actions: () => (Array.isArray(current.blockMenu) ? current.blockMenu : defaultBlockActions(locale())),\n part,\n locale,\n enabled: () => current.blockMenu !== false && editable(),\n ids,\n overlayTarget: current.overlayTarget,\n zIndex: current.zIndex\n });\n\n // ---- find and replace ---------------------------------------------------------------------\n\n const findBar = createFindBar({\n editor,\n view: () => view,\n part,\n locale,\n editable,\n render: () => render(),\n id: `${id}-find`\n });\n\n // Ctrl/⌘+F finds and Ctrl+H (⌘+⌥+F on a Mac, where ⌘+H hides the app)\n // replaces, anywhere in the editor — the text, the toolbar or the bar.\n const onFindKey = (event: KeyboardEvent) => {\n if (current.find === false) return;\n const name = editorKeyName(event);\n const replace = name === (isMacPlatform() ? 'Mod-Alt-f' : 'Mod-h');\n if (name !== 'Mod-f' && !replace) return;\n event.preventDefault();\n findBar.open({ replace });\n };\n element.addEventListener('keydown', onFindKey);\n\n // ---- where a popup hangs from ---------------------------------------------------------------\n\n /** The caret's own rectangle, as an element popups can be anchored to. */\n function placeCaret() {\n if (!caretEl || !contentEl) return;\n const rect = view?.selectionRect();\n if (!rect) return;\n const host = element.getBoundingClientRect();\n caretEl.style.top = `${rect.top - host.top}px`;\n caretEl.style.left = `${rect.left - host.left}px`;\n caretEl.style.width = `${Math.max(1, rect.width)}px`;\n caretEl.style.height = `${rect.height}px`;\n }\n\n function openPanel(overlay: Overlay, name: string, event?: MouseEvent) {\n if (event) anchors.set(name, event.currentTarget as HTMLElement);\n else anchors.delete(name);\n closePanels(overlay);\n overlay.open();\n overlay.update();\n }\n\n const panels = () => [linkPanel, imagePanel, tablePanel, colorPanel];\n const closePanels = (except?: Overlay) => panels().forEach((overlay) => overlay !== except && overlay.close());\n const renderPanels = () => panels().forEach((overlay) => overlay.update());\n\n // ---- the toolbar -----------------------------------------------------------------------------\n\n function toolbarContext(): ToolbarContext {\n return {\n locale: locale(),\n part,\n editable: editable(),\n can,\n isActive: (name, attrs) => editor.isActive(name, attrs as never),\n shortcut: (name, args) => {\n const binding = editorShortcutFor(name, args);\n return binding ? { label: formatEditorShortcut(binding), aria: ariaEditorShortcut(binding) } : undefined;\n },\n colors: { text: colorOf('color'), highlight: colorOf('highlight') },\n ref: (name) => (el) => {\n if (el) anchors.set(name, el as HTMLElement);\n else anchors.delete(name);\n },\n on: {\n tip: (element, text) => tooltips.attach(element, text),\n command: (name, args, event) => {\n run(name, ...args);\n if (event.detail > 0) focus();\n },\n openLink: (event) => openLinkPanel(event),\n openFind: () => (findBar.isOpen ? findBar.close() : findBar.open()),\n openImage: (event) => openPanel(imagePanel, 'image', event),\n openTable: (event) => openPanel(tablePanel, 'table', event),\n openMath: (event) => {\n closePanels();\n // On a formula it hangs from the formula; for a new one, from the button.\n mathTools.open(editor.isActive('math') ? null : (event.currentTarget as HTMLElement));\n },\n openColor: (kind, event) => {\n colorKind = kind;\n openPanel(colorPanel, kind, event);\n },\n blockSelect: (el) => {\n blockSelectHost = (el as HTMLElement | null) ?? null;\n syncBlockSelect();\n }\n }\n };\n }\n\n /** The block type, drawn by the control kit's select. */\n function syncBlockSelect() {\n if (!blockSelectHost) return;\n const words = locale().editor;\n const options = [\n { label: words.paragraph, value: 'paragraph' },\n { label: words.heading1, value: 'heading1' },\n { label: words.heading2, value: 'heading2' },\n { label: words.heading3, value: 'heading3' },\n { label: words.codeBlock, value: 'codeBlock' }\n ];\n const active = activeEditorBlockType(editor.state);\n const settings = {\n options,\n optionValue: 'value',\n value: active,\n size: 'small' as const,\n ariaLabel: words.blockType,\n disabled: !editable(),\n locale: locale(),\n unstyled: current.unstyled,\n overlayTarget: current.overlayTarget,\n zIndex: current.zIndex,\n nonce: current.nonce,\n cssLayer: current.cssLayer\n };\n if (blockSelect) blockSelect.update(settings);\n else\n blockSelect = createSelect(blockSelectHost, {\n ...settings,\n onChange: (value) => {\n if (value === 'paragraph') run('setParagraph');\n else if (value === 'codeBlock') run('toggleCodeBlock');\n else run('toggleHeading', Number(String(value).slice(-1)));\n focus();\n }\n });\n }\n\n // ---- drawing --------------------------------------------------------------------------------\n\n /** The groups of the toolbar, without the formula button where formulas are off. */\n const toolbarGroups = (): EditorToolbarItem[][] => {\n const groups = Array.isArray(current.toolbar) ? current.toolbar : defaultToolbar;\n return mathOn() ? groups : groups.map((group) => group.filter((item) => item !== 'math')).filter((group) => group.length);\n };\n\n function countText(): string {\n const words = locale().editor;\n const count = editor.characterCount();\n const characters = current.maxLength\n ? formatMessage(words.charactersLimit, { count, limit: current.maxLength })\n : formatMessage(count === 1 ? words.character : words.characters, { count });\n const mode = current.showCount === true ? 'characters' : current.showCount;\n if (mode === 'characters' || !mode) return characters;\n const wordCount = editor.wordCount();\n const wordText = formatMessage(wordCount === 1 ? words.word : words.words, { count: wordCount });\n return mode === 'words' ? wordText : `${wordText} · ${characters}`;\n }\n\n function contentView(): Child {\n return h(\n 'div',\n mergeAttrs({ key: 'content', id: ids.content }, part('content'), {\n class: isEmptyEditorDoc(editor.state.doc) ? 'vt-editor-content-empty' : undefined,\n role: 'textbox',\n 'aria-multiline': 'true',\n 'aria-label': current.ariaLabelledby ? undefined : current.ariaLabel,\n 'aria-labelledby': current.ariaLabelledby,\n 'aria-describedby': ids.help,\n 'aria-readonly': current.readonly ? 'true' : undefined,\n 'aria-disabled': current.disabled ? 'true' : undefined,\n 'aria-invalid': current.invalid ? 'true' : undefined,\n 'aria-placeholder': current.placeholder || undefined,\n 'data-placeholder': current.placeholder || undefined,\n // How a formula answers a press, which is what its look under the pointer follows.\n 'data-math-edit': mathOn() && editable() ? (mathOptions().inlineEdit === false ? 'panel' : 'inline') : undefined,\n contenteditable: editable() ? 'true' : 'false',\n tabindex: current.disabled ? '-1' : '0',\n spellcheck: 'true',\n translate: 'no',\n ref: (el: Element | null) => {\n const next = el as HTMLElement | null;\n if (next === contentEl) return;\n contentEl = next;\n attachView();\n },\n onFocus: (event: FocusEvent) => current.on?.focus?.(event),\n onBlur: (event: FocusEvent) => current.on?.blur?.(event)\n })\n );\n }\n\n function render() {\n const drawn = toolbarContext();\n root.attrs(part('root', { readonly: current.readonly, disabled: current.disabled, invalid: current.invalid }));\n root.render([\n current.hooks?.toolbar ? (current.hooks.toolbar() as Child) : current.toolbar === false ? null : toolbarView(drawn, toolbarGroups()),\n findBar.view(),\n contentView(),\n h('span', mergeAttrs({ key: 'caret', 'aria-hidden': 'true' }, part('caret'), { ref: (el: Element | null) => (caretEl = el as HTMLElement | null) })),\n h('span', { key: 'help', id: ids.help, style: visuallyHidden }, locale().editor.keyboardHelp),\n current.hooks?.footer\n ? (current.hooks.footer() as Child)\n : current.showCount\n ? h('div', mergeAttrs({ key: 'footer' }, part('footer')), h('span', part('count', { limit: !!current.maxLength }), countText()))\n : null\n ]);\n bars.sync([contentEl]);\n syncBlockSelect();\n syncBubble();\n renderPanels();\n blockHandle.sync();\n mathTools.sync();\n }\n\n function attachView() {\n view?.destroy();\n view = null;\n if (!contentEl) return;\n view = createEditorView(contentEl, editor, {\n editable,\n taskLabel: locale().editor.taskDone,\n selectedClass: 'vt-editor-node-selected',\n emptyClass: 'vt-editor-content-empty',\n chipClass: (kind) => (current.unstyled ? undefined : ['vt-editor-chip', kind ? `vt-editor-chip-${kind}` : ''].filter(Boolean).join(' ')),\n mathClass: ({ display, pending }) => (current.unstyled ? undefined : ['vt-editor-math', display ? 'vt-editor-math-display' : '', pending ? 'vt-editor-math-pending' : ''].filter(Boolean).join(' ')),\n // Ctrl/⌘+K opens the link editor, over the caret.\n handleKey: (_name, binding) => {\n if (binding?.[0] !== 'link' || !editable()) return false;\n openLinkPanel();\n return true;\n },\n linkHint: (href) => ({ ...tooltips.options(editorLinkHint(href, locale().editor.followLink)), placement: 'top' })\n });\n if (current.autofocus) view.focus();\n }\n\n const focus = () => view?.focus();\n\n render();\n\n const handle: TextEditorHandle = {\n element,\n update(next) {\n const content = 'content' in next;\n current = { ...current, ...next };\n if (content) editor.setContent(current.content ?? '', { emit: false });\n if ('maxLength' in next) editor.maxLength = current.maxLength ?? null;\n if ('math' in next) editor.mathOutput = mathOptions().output ?? 'drawing';\n render();\n },\n getHTML: (options) => editor.getHTML(options),\n getJSON: () => editor.getJSON(),\n getText: () => editor.getText(),\n getMarkdown: () => editor.getMarkdown(),\n typeText: (text) => {\n const typed = editor.typeText(text);\n render();\n return typed;\n },\n setContent: (value) => {\n editor.setContent(value);\n render();\n },\n run: (name, ...args) => {\n const applied = run(name, ...args);\n render();\n return applied;\n },\n can,\n isActive: (name, attrs) => editor.isActive(name, attrs as never),\n focus,\n openFind: (options) => findBar.open(options),\n closeFind: () => findBar.close({ focusEditor: false }),\n refresh: render,\n destroy() {\n stop();\n element.removeEventListener('keydown', onFindKey);\n findBar.destroy();\n slashMenu.destroy();\n chipMenu.destroy();\n mathTools.destroy();\n blockHandle.destroy();\n [...panels(), bubble].forEach((overlay) => overlay.destroy());\n blockSelect?.destroy();\n tooltips.destroy();\n bars.destroy();\n view?.destroy();\n root.clear();\n }\n };\n\n return handle;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkDA,IAAI,UAAU;AAEd,SAAgB,iBAAiB,SAAsB,SAA2B,CAAC,GAAqB;CACpG,IAAI,UAA4B,EAAE,GAAG,OAAO;CAC5C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ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type EditorInstance, type EditorView, type Locale } from '@vitral/core';
2
2
  import { type OverlayTarget } from '@vitral/controls';
3
- import { type Props } from '@vitral/dom';
3
+ import { type Props, type ScrollbarSlotOptions } from '@vitral/dom';
4
4
  import type { MathTemplate } from './types';
5
5
  /**
6
6
  * Formulas, as a piece that attaches to any editor, the way the slash menu
@@ -42,6 +42,8 @@ export interface MathToolsOptions {
42
42
  id?: string;
43
43
  overlayTarget?: OverlayTarget;
44
44
  zIndex?: number;
45
+ /** Drawn scrollbars on the list of ready-made formulas: `{ mode, style: scrollpanelStyle, unstyled }`. */
46
+ scrollbars?: () => ScrollbarSlotOptions;
45
47
  }
46
48
  export interface MathTools {
47
49
  readonly isOpen: boolean;
package/dist/math.js CHANGED
@@ -70,6 +70,8 @@ function createMathTools(options) {
70
70
  target: () => options.overlayTarget,
71
71
  zIndex: options.zIndex,
72
72
  restoreFocus: false,
73
+ scrollbars: options.scrollbars,
74
+ scrollers: (drawn) => drawn.querySelectorAll("[data-vt-math-templates]"),
73
75
  onOpen: (drawn) => {
74
76
  const box = drawn.querySelector(`[${SOURCE}]`);
75
77
  if (!box) return;
@@ -139,7 +141,10 @@ function createMathTools(options) {
139
141
  }), h("span", null, words.mathDisplay)), templates().length ? h("div", mergeAttrs({
140
142
  key: "templates",
141
143
  role: "group"
142
- }, part("mathTemplates"), { "aria-label": words.mathTemplates }), templates().map((template) => drawn("button", mergeAttrs({
144
+ }, part("mathTemplates"), {
145
+ "aria-label": words.mathTemplates,
146
+ "data-vt-math-templates": ""
147
+ }), templates().map((template) => drawn("button", mergeAttrs({
143
148
  key: template.id,
144
149
  type: "button"
145
150
  }, part("mathTemplate"), {
package/dist/math.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"math.js","names":[],"sources":["../src/math.ts"],"sourcesContent":["import { drawMath, editorMathAt, en, isMathLoaded, loadMath, overlayContainerOf, paintMath, type EditorInstance, type EditorPosition, type EditorView, type Locale } from '@vitral/core';\nimport { createOverlay, type OverlayTarget } from '@vitral/controls';\nimport { h, mergeAttrs, type Props, type VElement } from '@vitral/dom';\nimport type { MathTemplate } from './types';\n\n/**\n * Formulas, as a piece that attaches to any editor, the way the slash menu\n * does. A formula is held as LaTeX and drawn from it, and there are two ways\n * to change one:\n *\n * - the panel, which the toolbar's button and the slash menu open: the source\n * in a box, the formula drawn above it as it is typed, and the usual\n * formulas ready-made on buttons;\n * - pressing it in the text. A number, a letter or a sign is edited where it\n * stands, in a box over it, and the formula is drawn again around it with\n * every key; Tab goes on to the next value. A press anywhere else on the\n * formula opens the panel with that piece of the source selected.\n *\n * Either way the document only ever holds the source, and the drawing is made\n * from it again, so there is no drawing to get out of step. What is typed is\n * never trusted to be a formula: a piece that cannot be read is drawn as\n * written, where it stands, and the rest of the formula around it.\n */\n\nexport interface MathToolsOptions {\n editor: EditorInstance;\n view: () => EditorView | null;\n /** The `contenteditable` element, where a press on a formula is heard. */\n content: () => HTMLElement | null;\n /** What the panel hangs from when it is opened by no button and on no formula: an element over the caret. */\n anchor: () => HTMLElement | null;\n /** Puts that element where the caret is, before the panel opens. */\n place?: () => void;\n /** The ready-made formulas on offer; read every time the panel opens. */\n templates: () => MathTemplate[];\n /** Whether a value is edited where it stands. */\n inlineEdit?: () => boolean;\n part: (name: string, state?: unknown) => Props;\n locale?: () => Locale;\n /** Off while the editor is read-only, or has formulas turned off. */\n enabled?: () => boolean;\n /** Puts the keyboard back in the text. */\n focus?: () => void;\n id?: string;\n overlayTarget?: OverlayTarget;\n zIndex?: number;\n}\n\nexport interface MathTools {\n readonly isOpen: boolean;\n /**\n * Opens the panel: on the formula the selection is on, to change it, or\n * for a new one where the caret is. `anchor` is what it hangs from, a\n * toolbar button say; the formula itself, or the caret, otherwise.\n */\n open(anchor?: HTMLElement | null): void;\n /** Looks again for the element the text is in: called when the host has drawn. */\n sync(): void;\n close(): void;\n destroy(): void;\n}\n\n/** The formulas the panel offers when an application names none. */\nexport function defaultMathTemplates(locale: Locale): MathTemplate[] {\n const names = locale.editor.mathTemplateNames;\n const entry = (id: string, latex: string): MathTemplate => ({ id, label: names[id] ?? id, latex });\n return [\n entry('fraction', '\\\\frac{a}{b}'),\n entry('squareRoot', '\\\\sqrt{x}'),\n entry('root', '\\\\sqrt[n]{x}'),\n entry('power', 'x^{2}'),\n entry('subscript', 'x_{i}'),\n entry('sum', '\\\\sum_{i=1}^{n} i'),\n entry('product', '\\\\prod_{k=1}^{n} k'),\n entry('integral', '\\\\int_{a}^{b} x \\\\, dx'),\n entry('limit', '\\\\lim_{x \\\\to 0} f(x)'),\n entry('parentheses', '\\\\left( \\\\frac{a}{b} \\\\right)'),\n entry('matrix', '\\\\begin{pmatrix} a & b \\\\\\\\ c & d \\\\end{pmatrix}'),\n entry('cases', '\\\\begin{cases} a & x > 0 \\\\\\\\ b & x \\\\leq 0 \\\\end{cases}'),\n entry('quadratic', 'x = \\\\frac{-b \\\\pm \\\\sqrt{b^2 - 4ac}}{2a}'),\n entry('times', '\\\\times'),\n entry('divide', '\\\\div'),\n entry('plusMinus', '\\\\pm'),\n entry('lessEqual', '\\\\leq'),\n entry('greaterEqual', '\\\\geq'),\n entry('notEqual', '\\\\neq'),\n entry('approximately', '\\\\approx'),\n entry('pi', '\\\\pi'),\n entry('infinity', '\\\\infty')\n ];\n}\n\ninterface PanelState {\n /** The formula being changed; none when a new one is being written. */\n at: EditorPosition | null;\n latex: string;\n display: boolean;\n}\n\ninterface InlineState {\n at: EditorPosition;\n /** The formula's element in the text. */\n host: HTMLElement;\n /** The formula as it was when the box opened. */\n source: string;\n display: boolean;\n /** The piece of the source the box stands for. */\n start: number;\n end: number;\n input: HTMLInputElement;\n}\n\nconst SOURCE = 'data-vt-math-source';\n\nexport function createMathTools(options: MathToolsOptions): MathTools {\n let panel: PanelState | null = null;\n let anchorEl: HTMLElement | null = null;\n /** A piece of the source to select when the panel's box is first drawn. */\n let select: [number, number] | null = null;\n let inline: InlineState | null = null;\n let element: HTMLElement | null = null;\n\n const locale = () => options.locale?.() ?? en;\n const enabled = () => options.enabled?.() ?? true;\n const id = options.id ?? 'vt-math';\n const run = (name: string, ...args: unknown[]) => (options.editor.run as (n: string, ...a: unknown[]) => boolean)(name, ...args);\n\n // ---- where a formula is ------------------------------------------------------------------\n\n /** The formula's position from its element: the view reads a point inside one as just after it. */\n function positionOf(host: HTMLElement): EditorPosition | null {\n const after = options.view()?.posFromDOM(host, 0);\n return after && after.offset > 0 ? { path: after.path, offset: after.offset - 1 } : null;\n }\n\n function elementAt(at: EditorPosition): HTMLElement | null {\n const formulas = options.content()?.querySelectorAll<HTMLElement>('[data-math]') ?? [];\n for (const host of Array.from(formulas)) {\n const position = positionOf(host);\n if (position && position.offset === at.offset && position.path.join('.') === at.path.join('.')) return host;\n }\n return null;\n }\n\n // ---- the panel -----------------------------------------------------------------------------\n\n const overlay = createOverlay({\n anchor: () => anchorEl,\n render: () => (panel ? panelView(panel) : null),\n placement: 'bottom-start',\n target: () => options.overlayTarget,\n zIndex: options.zIndex,\n restoreFocus: false,\n onOpen: (drawn) => {\n const box = drawn.querySelector<HTMLInputElement>(`[${SOURCE}]`);\n if (!box) return;\n box.focus({ preventScroll: true });\n if (select) box.setSelectionRange(select[0], select[1]);\n else box.select();\n select = null;\n },\n onClose: (reason) => {\n panel = null;\n if (reason === 'escape') options.focus?.();\n }\n });\n\n /**\n * What the panel draws a formula with: the drawing, or the source while\n * there is nothing to draw with. The panel centres it, so where it would\n * hang from a baseline does not come into it.\n */\n const drawn = (tag: string, props: Props, latex: string, display: boolean): VElement => {\n const drawing = drawMath(latex, { display });\n return (drawing ? h(tag, mergeAttrs(props, { innerHTML: drawing.svg })) : h(tag, props, latex)) as VElement;\n };\n\n function panelView(state: PanelState): VElement {\n const words = locale().editor;\n const { part } = options;\n const button = (key: string, label: string, onClick: () => void, quiet = true) =>\n h('button', mergeAttrs({ key, type: 'button', class: quiet ? 'vt-button vt-button-text vt-button-secondary vt-button-sm' : 'vt-button vt-button-sm' }, { onClick }), label);\n const source = state.latex.trim();\n return h(\n 'div',\n mergeAttrs({ role: 'dialog', id }, part('panel'), part('mathPanel'), { 'aria-label': words.math }),\n source\n ? drawn('div', mergeAttrs({ key: 'preview' }, part('mathPreview')), source, state.display)\n : h('div', mergeAttrs({ key: 'empty' }, part('mathPreview', { empty: true })), words.mathEmpty),\n h(\n 'label',\n mergeAttrs({ key: 'source' }, part('field')),\n h('span', part('fieldLabel'), words.mathSource),\n h(\n 'span',\n { class: 'vt-field vt-field-sm vt-field-fluid' },\n h('input', {\n type: 'text',\n class: 'vt-field-input',\n spellcheck: 'false',\n autocomplete: 'off',\n autocapitalize: 'off',\n [SOURCE]: '',\n value: state.latex,\n onInput: (event: Event) => {\n if (!panel) return;\n panel = { ...panel, latex: (event.target as HTMLInputElement).value };\n overlay.update();\n },\n onKeydown: (event: KeyboardEvent) => {\n if (event.key !== 'Enter') return;\n event.preventDefault();\n apply();\n }\n })\n )\n ),\n h(\n 'label',\n mergeAttrs({ key: 'display' }, part('check')),\n h('input', {\n type: 'checkbox',\n checked: state.display,\n onChange: (event: Event) => {\n if (!panel) return;\n panel = { ...panel, display: (event.target as HTMLInputElement).checked };\n overlay.update();\n }\n }),\n h('span', null, words.mathDisplay)\n ),\n templates().length\n ? h(\n 'div',\n mergeAttrs({ key: 'templates', role: 'group' }, part('mathTemplates'), { 'aria-label': words.mathTemplates }),\n templates().map((template) =>\n drawn(\n 'button',\n mergeAttrs({ key: template.id, type: 'button' }, part('mathTemplate'), { 'aria-label': template.label, title: template.label, onClick: () => write(template.latex) }),\n template.latex,\n false\n )\n )\n )\n : null,\n h(\n 'div',\n mergeAttrs({ key: 'actions' }, part('actions')),\n state.at ? button('remove', words.removeMath, remove) : null,\n button('cancel', locale().cancel, cancel),\n button('apply', state.at ? words.apply : words.insert, apply, false)\n )\n ) as VElement;\n }\n\n let offered: MathTemplate[] = [];\n const templates = () => offered;\n\n /** Writes a ready-made formula into the box, over what is selected there, and leaves the caret after it. */\n function write(latex: string) {\n if (!panel) return;\n const box = overlay.element()?.querySelector<HTMLInputElement>(`[${SOURCE}]`);\n const start = box?.selectionStart ?? panel.latex.length;\n const end = box?.selectionEnd ?? start;\n // A space keeps a command from running into the letters after it: `\\pi x`, not `\\pix`.\n const before = panel.latex.slice(0, start);\n const glue = /\\\\[a-zA-Z]+$/.test(before) && /^[a-zA-Z]/.test(latex) ? ' ' : '';\n const after = panel.latex.slice(end);\n const tail = /\\\\[a-zA-Z]+$/.test(latex) && /^[a-zA-Z]/.test(after) ? ' ' : '';\n panel = { ...panel, latex: before + glue + latex + tail + after };\n overlay.update();\n const caret = before.length + glue.length + latex.length + tail.length;\n box?.focus({ preventScroll: true });\n box?.setSelectionRange(caret, caret);\n }\n\n function apply() {\n if (!panel) return;\n const { at, display } = panel;\n const latex = panel.latex.trim();\n overlay.close();\n if (at) run('setMath', at, { latex, display });\n else if (latex) run('insertMath', { latex, display });\n options.focus?.();\n }\n\n function remove() {\n if (!panel?.at) return;\n const { at } = panel;\n overlay.close();\n run('setMath', at, { latex: '' });\n options.focus?.();\n }\n\n function cancel() {\n overlay.close();\n options.focus?.();\n }\n\n function openPanel(state: PanelState, anchor: HTMLElement | null | undefined, range?: [number, number]) {\n endInline(true);\n offered = options.templates();\n panel = state;\n select = range ?? null;\n anchorEl = anchor ?? (state.at ? elementAt(state.at) : null);\n if (!anchorEl) {\n options.place?.();\n anchorEl = options.anchor();\n }\n if (overlay.isOpen) overlay.close();\n overlay.open();\n overlay.update();\n // Nothing to draw with yet, in a document that had no formula in it: the panel draws again when there is.\n if (!isMathLoaded()) loadMath().then(() => overlay.update());\n }\n\n function open(anchor?: HTMLElement | null) {\n if (!enabled()) return;\n const on = editorMathAt(options.editor.state);\n openPanel(on ? { at: { path: on.path, offset: on.offset }, latex: on.latex, display: on.display } : { at: null, latex: '', display: false }, anchor);\n }\n\n // ---- a value, edited where it stands ---------------------------------------------------------\n\n /** The box is put over the piece it stands for, and is at least wide enough for what is in it. */\n function placeInline() {\n if (!inline) return;\n const { host, input, start } = inline;\n const end = start + input.value.length;\n const piece = host.querySelector(`[data-at=\"${start},${end}\"]`) ?? host;\n const rect = piece.getBoundingClientRect();\n const size = Number.parseFloat(getComputedStyle(host).fontSize) || 16;\n // Wide enough for what is typed in its own face, and never narrower than the piece it covers.\n const width = Math.max(rect.width + size * 0.35, (input.value.length + 0.8) * size * 0.62);\n const height = Math.max(rect.height, size * 1.3);\n input.style.fontSize = `${size}px`;\n input.style.width = `${width}px`;\n input.style.height = `${height}px`;\n input.style.left = `${rect.left + rect.width / 2 - width / 2}px`;\n input.style.top = `${rect.top + rect.height / 2 - height / 2}px`;\n }\n\n const inlineSource = (state: InlineState) => state.source.slice(0, state.start) + state.input.value + state.source.slice(state.end);\n\n function startInline(host: HTMLElement, at: EditorPosition, start: number, end: number) {\n endInline(true);\n if (overlay.isOpen) overlay.close();\n const source = host.getAttribute('data-math') ?? '';\n const input = document.createElement('input');\n input.type = 'text';\n input.value = source.slice(start, end);\n input.spellcheck = false;\n input.autocomplete = 'off';\n input.setAttribute('autocapitalize', 'off');\n input.setAttribute('aria-label', locale().editor.mathValue);\n for (const [key, value] of Object.entries(options.part('mathInput'))) if (typeof value === 'string') input.setAttribute(key, value);\n input.style.position = 'fixed';\n input.style.zIndex = String(options.zIndex ?? 1000);\n inline = { at, host, source, display: host.getAttribute('data-display') === 'true', start, end, input };\n input.addEventListener('input', onInlineInput);\n input.addEventListener('keydown', onInlineKeydown);\n input.addEventListener('blur', onInlineBlur);\n // Beside the other popups, so it wears the theme they wear.\n (overlayContainerOf(host) ?? host.ownerDocument.body).appendChild(input);\n host.setAttribute('data-editing', '');\n placeInline();\n input.focus({ preventScroll: true });\n input.select();\n window.addEventListener('scroll', onInlineScroll, true);\n window.addEventListener('resize', onInlineScroll);\n }\n\n /** The formula follows the typing: drawn again from what the source would be, before any of it is kept. */\n function onInlineInput() {\n if (!inline) return;\n paintMath(inline.host, inlineSource(inline), { display: inline.display, interactive: true });\n placeInline();\n }\n\n function onInlineKeydown(event: KeyboardEvent) {\n if (!inline) return;\n if (event.key === 'Enter') {\n event.preventDefault();\n endInline(true);\n options.focus?.();\n } else if (event.key === 'Escape') {\n event.preventDefault();\n event.stopPropagation();\n endInline(false);\n options.focus?.();\n } else if (event.key === 'Tab') {\n // On to the next value, or back to the one before; off the end, the keyboard goes back to the text.\n event.preventDefault();\n const { at, start } = inline;\n const length = inline.input.value.length;\n const forward = !event.shiftKey;\n endInline(true);\n const host = elementAt(at);\n const leaves = host ? Array.from(host.querySelectorAll<SVGElement>('[data-leaf]')).map((leaf) => leaf.getAttribute('data-at')!.split(',').map(Number) as [number, number]) : [];\n leaves.sort((a, b) => a[0] - b[0]);\n const next = forward ? leaves.find(([from]) => from >= start + length) : leaves.reverse().find(([, to]) => to <= start);\n if (host && next) startInline(host, at, next[0], next[1]);\n else options.focus?.();\n }\n }\n\n const onInlineBlur = () => endInline(true);\n // The box is placed by the page's coordinates, so it is placed again when the page moves under it.\n // (Not closed: a field scrolls its own text as it is typed into, and that is a scroll too.)\n const onInlineScroll = (event: Event) => {\n if (event.target !== inline?.input) placeInline();\n };\n\n /** Closes the box. `keep` writes what was typed into the document, as one change; otherwise the formula is drawn as it was. */\n function endInline(keep: boolean) {\n const state = inline;\n if (!state) return;\n inline = null;\n const { input, host, at } = state;\n input.removeEventListener('blur', onInlineBlur);\n input.removeEventListener('input', onInlineInput);\n input.removeEventListener('keydown', onInlineKeydown);\n window.removeEventListener('scroll', onInlineScroll, true);\n window.removeEventListener('resize', onInlineScroll);\n input.remove();\n host.removeAttribute('data-editing');\n const next = inlineSource(state);\n if (keep && next !== state.source) {\n // The element is put back as the document has it first, so that the change is the view's to draw.\n paintMath(host, state.source, { display: state.display, interactive: true });\n run('setMath', at, { latex: next });\n } else if (host.isConnected) paintMath(host, state.source, { display: state.display, interactive: true });\n }\n\n // ---- a press on a formula in the text --------------------------------------------------------\n\n function onClick(event: MouseEvent) {\n const target = event.target as Element | null;\n const host = target?.closest?.('[data-math]') as HTMLElement | null;\n if (!host || !element?.contains(host) || !enabled() || inline?.host === host) return;\n const at = positionOf(host);\n if (!at) return;\n event.preventDefault();\n const piece = target!.closest('[data-at]');\n const range = piece && host.contains(piece) ? (piece.getAttribute('data-at')!.split(',').map(Number) as [number, number]) : null;\n if (range && piece!.hasAttribute('data-leaf') && (options.inlineEdit?.() ?? true) && isMathLoaded()) {\n startInline(host, at, range[0], range[1]);\n return;\n }\n openPanel({ at, latex: host.getAttribute('data-math') ?? '', display: host.getAttribute('data-display') === 'true' }, host, range ?? undefined);\n }\n\n function listen() {\n const next = options.content();\n if (next === element) return;\n element?.removeEventListener('click', onClick);\n element = next;\n element?.addEventListener('click', onClick);\n }\n\n const stop = options.editor.subscribe(() => {\n listen();\n if (!enabled()) {\n endInline(false);\n if (overlay.isOpen) overlay.close();\n return;\n }\n // The document changed under an open box or panel (an undo, the application): what it was\n // editing may be gone. Looked at once the view has drawn the change, which it does after this.\n if (inline || panel?.at) queueMicrotask(settle);\n });\n\n function settle() {\n if (inline && !inline.host.isConnected) endInline(false);\n if (panel?.at && !elementAt(panel.at)) overlay.close();\n }\n listen();\n\n return {\n get isOpen() {\n return overlay.isOpen;\n },\n open,\n sync: listen,\n close() {\n endInline(true);\n if (overlay.isOpen) overlay.close();\n },\n destroy() {\n stop();\n endInline(false);\n element?.removeEventListener('click', onClick);\n element = null;\n overlay.destroy();\n }\n };\n}\n"],"mappings":";;;;;AA+DA,SAAgB,qBAAqB,QAAgC;CACjE,MAAM,QAAQ,OAAO,OAAO;CAC5B,MAAM,SAAS,IAAY,WAAiC;EAAE;EAAI,OAAO,MAAM,OAAO;EAAI;CAAM;CAChG,OAAO;EACH,MAAM,YAAY,cAAc;EAChC,MAAM,cAAc,WAAW;EAC/B,MAAM,QAAQ,cAAc;EAC5B,MAAM,SAAS,OAAO;EACtB,MAAM,aAAa,OAAO;EAC1B,MAAM,OAAO,mBAAmB;EAChC,MAAM,WAAW,oBAAoB;EACr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S,MAAO,aAAa,WAAW,MAAM,QAAQ,aAAa,KAAK,SAAS,aAAa,GAAG;GACjG,YAAY,MAAM,IAAI,MAAM,IAAI,MAAM,EAAE;GACxC;EACJ;EACA,UAAU;GAAE;GAAI,OAAO,KAAK,aAAa,WAAW,KAAK;GAAI,SAAS,KAAK,aAAa,cAAc,MAAM;EAAO,GAAG,MAAM,SAAS,KAAA,CAAS;CAClJ;CAEA,SAAS,SAAS;EACd,MAAM,OAAO,QAAQ,QAAQ;EAC7B,IAAI,SAAS,SAAS;EACtB,SAAS,oBAAoB,SAAS,OAAO;EAC7C,UAAU;EACV,SAAS,iBAAiB,SAAS,OAAO;CAC9C;CAEA,MAAM,OAAO,QAAQ,OAAO,gBAAgB;EACxC,OAAO;EACP,IAAI,CAAC,QAAQ,GAAG;GACZ,UAAU,KAAK;GACf,IAAI,QAAQ,QAAQ,QAAQ,MAAM;GAClC;EACJ;EAGA,IAAI,UAAU,OAAO,IAAI,eAAe,MAAM;CAClD,CAAC;CAED,SAAS,SAAS;EACd,IAAI,UAAU,CAAC,OAAO,KAAK,aAAa,UAAU,KAAK;EACvD,IAAI,OAAO,MAAM,CAAC,UAAU,MAAM,EAAE,GAAG,QAAQ,MAAM;CACzD;CACA,OAAO;CAEP,OAAO;EACH,IAAI,SAAS;GACT,OAAO,QAAQ;EACnB;EACA;EACA,MAAM;EACN,QAAQ;GACJ,UAAU,IAAI;GACd,IAAI,QAAQ,QAAQ,QAAQ,MAAM;EACtC;EACA,UAAU;GACN,KAAK;GACL,UAAU,KAAK;GACf,SAAS,oBAAoB,SAAS,OAAO;GAC7C,UAAU;GACV,QAAQ,QAAQ;EACpB;CACJ;AACJ"}
1
+ {"version":3,"file":"math.js","names":[],"sources":["../src/math.ts"],"sourcesContent":["import { drawMath, editorMathAt, en, isMathLoaded, loadMath, overlayContainerOf, paintMath, type EditorInstance, type EditorPosition, type EditorView, type Locale } from '@vitral/core';\nimport { createOverlay, type OverlayTarget } from '@vitral/controls';\nimport { h, mergeAttrs, type Props, type ScrollbarSlotOptions, type VElement } from '@vitral/dom';\nimport type { MathTemplate } from './types';\n\n/**\n * Formulas, as a piece that attaches to any editor, the way the slash menu\n * does. A formula is held as LaTeX and drawn from it, and there are two ways\n * to change one:\n *\n * - the panel, which the toolbar's button and the slash menu open: the source\n * in a box, the formula drawn above it as it is typed, and the usual\n * formulas ready-made on buttons;\n * - pressing it in the text. A number, a letter or a sign is edited where it\n * stands, in a box over it, and the formula is drawn again around it with\n * every key; Tab goes on to the next value. A press anywhere else on the\n * formula opens the panel with that piece of the source selected.\n *\n * Either way the document only ever holds the source, and the drawing is made\n * from it again, so there is no drawing to get out of step. What is typed is\n * never trusted to be a formula: a piece that cannot be read is drawn as\n * written, where it stands, and the rest of the formula around it.\n */\n\nexport interface MathToolsOptions {\n editor: EditorInstance;\n view: () => EditorView | null;\n /** The `contenteditable` element, where a press on a formula is heard. */\n content: () => HTMLElement | null;\n /** What the panel hangs from when it is opened by no button and on no formula: an element over the caret. */\n anchor: () => HTMLElement | null;\n /** Puts that element where the caret is, before the panel opens. */\n place?: () => void;\n /** The ready-made formulas on offer; read every time the panel opens. */\n templates: () => MathTemplate[];\n /** Whether a value is edited where it stands. */\n inlineEdit?: () => boolean;\n part: (name: string, state?: unknown) => Props;\n locale?: () => Locale;\n /** Off while the editor is read-only, or has formulas turned off. */\n enabled?: () => boolean;\n /** Puts the keyboard back in the text. */\n focus?: () => void;\n id?: string;\n overlayTarget?: OverlayTarget;\n zIndex?: number;\n /** Drawn scrollbars on the list of ready-made formulas: `{ mode, style: scrollpanelStyle, unstyled }`. */\n scrollbars?: () => ScrollbarSlotOptions;\n}\n\nexport interface MathTools {\n readonly isOpen: boolean;\n /**\n * Opens the panel: on the formula the selection is on, to change it, or\n * for a new one where the caret is. `anchor` is what it hangs from, a\n * toolbar button say; the formula itself, or the caret, otherwise.\n */\n open(anchor?: HTMLElement | null): void;\n /** Looks again for the element the text is in: called when the host has drawn. */\n sync(): void;\n close(): void;\n destroy(): void;\n}\n\n/** The formulas the panel offers when an application names none. */\nexport function defaultMathTemplates(locale: Locale): MathTemplate[] {\n const names = locale.editor.mathTemplateNames;\n const entry = (id: string, latex: string): MathTemplate => ({ id, label: names[id] ?? id, latex });\n return [\n entry('fraction', '\\\\frac{a}{b}'),\n entry('squareRoot', '\\\\sqrt{x}'),\n entry('root', '\\\\sqrt[n]{x}'),\n entry('power', 'x^{2}'),\n entry('subscript', 'x_{i}'),\n entry('sum', '\\\\sum_{i=1}^{n} i'),\n entry('product', '\\\\prod_{k=1}^{n} k'),\n entry('integral', '\\\\int_{a}^{b} x \\\\, dx'),\n entry('limit', '\\\\lim_{x \\\\to 0} f(x)'),\n entry('parentheses', '\\\\left( \\\\frac{a}{b} \\\\right)'),\n entry('matrix', '\\\\begin{pmatrix} a & b \\\\\\\\ c & d \\\\end{pmatrix}'),\n entry('cases', '\\\\begin{cases} a & x > 0 \\\\\\\\ b & x \\\\leq 0 \\\\end{cases}'),\n entry('quadratic', 'x = \\\\frac{-b \\\\pm \\\\sqrt{b^2 - 4ac}}{2a}'),\n entry('times', '\\\\times'),\n entry('divide', '\\\\div'),\n entry('plusMinus', '\\\\pm'),\n entry('lessEqual', '\\\\leq'),\n entry('greaterEqual', '\\\\geq'),\n entry('notEqual', '\\\\neq'),\n entry('approximately', '\\\\approx'),\n entry('pi', '\\\\pi'),\n entry('infinity', '\\\\infty')\n ];\n}\n\ninterface PanelState {\n /** The formula being changed; none when a new one is being written. */\n at: EditorPosition | null;\n latex: string;\n display: boolean;\n}\n\ninterface InlineState {\n at: EditorPosition;\n /** The formula's element in the text. */\n host: HTMLElement;\n /** The formula as it was when the box opened. */\n source: string;\n display: boolean;\n /** The piece of the source the box stands for. */\n start: number;\n end: number;\n input: HTMLInputElement;\n}\n\nconst SOURCE = 'data-vt-math-source';\n\nexport function createMathTools(options: MathToolsOptions): MathTools {\n let panel: PanelState | null = null;\n let anchorEl: HTMLElement | null = null;\n /** A piece of the source to select when the panel's box is first drawn. */\n let select: [number, number] | null = null;\n let inline: InlineState | null = null;\n let element: HTMLElement | null = null;\n\n const locale = () => options.locale?.() ?? en;\n const enabled = () => options.enabled?.() ?? true;\n const id = options.id ?? 'vt-math';\n const run = (name: string, ...args: unknown[]) => (options.editor.run as (n: string, ...a: unknown[]) => boolean)(name, ...args);\n\n // ---- where a formula is ------------------------------------------------------------------\n\n /** The formula's position from its element: the view reads a point inside one as just after it. */\n function positionOf(host: HTMLElement): EditorPosition | null {\n const after = options.view()?.posFromDOM(host, 0);\n return after && after.offset > 0 ? { path: after.path, offset: after.offset - 1 } : null;\n }\n\n function elementAt(at: EditorPosition): HTMLElement | null {\n const formulas = options.content()?.querySelectorAll<HTMLElement>('[data-math]') ?? [];\n for (const host of Array.from(formulas)) {\n const position = positionOf(host);\n if (position && position.offset === at.offset && position.path.join('.') === at.path.join('.')) return host;\n }\n return null;\n }\n\n // ---- the panel -----------------------------------------------------------------------------\n\n const overlay = createOverlay({\n anchor: () => anchorEl,\n render: () => (panel ? panelView(panel) : null),\n placement: 'bottom-start',\n target: () => options.overlayTarget,\n zIndex: options.zIndex,\n restoreFocus: false,\n scrollbars: options.scrollbars,\n scrollers: (drawn) => drawn.querySelectorAll('[data-vt-math-templates]'),\n onOpen: (drawn) => {\n const box = drawn.querySelector<HTMLInputElement>(`[${SOURCE}]`);\n if (!box) return;\n box.focus({ preventScroll: true });\n if (select) box.setSelectionRange(select[0], select[1]);\n else box.select();\n select = null;\n },\n onClose: (reason) => {\n panel = null;\n if (reason === 'escape') options.focus?.();\n }\n });\n\n /**\n * What the panel draws a formula with: the drawing, or the source while\n * there is nothing to draw with. The panel centres it, so where it would\n * hang from a baseline does not come into it.\n */\n const drawn = (tag: string, props: Props, latex: string, display: boolean): VElement => {\n const drawing = drawMath(latex, { display });\n return (drawing ? h(tag, mergeAttrs(props, { innerHTML: drawing.svg })) : h(tag, props, latex)) as VElement;\n };\n\n function panelView(state: PanelState): VElement {\n const words = locale().editor;\n const { part } = options;\n const button = (key: string, label: string, onClick: () => void, quiet = true) =>\n h('button', mergeAttrs({ key, type: 'button', class: quiet ? 'vt-button vt-button-text vt-button-secondary vt-button-sm' : 'vt-button vt-button-sm' }, { onClick }), label);\n const source = state.latex.trim();\n return h(\n 'div',\n mergeAttrs({ role: 'dialog', id }, part('panel'), part('mathPanel'), { 'aria-label': words.math }),\n source\n ? drawn('div', mergeAttrs({ key: 'preview' }, part('mathPreview')), source, state.display)\n : h('div', mergeAttrs({ key: 'empty' }, part('mathPreview', { empty: true })), words.mathEmpty),\n h(\n 'label',\n mergeAttrs({ key: 'source' }, part('field')),\n h('span', part('fieldLabel'), words.mathSource),\n h(\n 'span',\n { class: 'vt-field vt-field-sm vt-field-fluid' },\n h('input', {\n type: 'text',\n class: 'vt-field-input',\n spellcheck: 'false',\n autocomplete: 'off',\n autocapitalize: 'off',\n [SOURCE]: '',\n value: state.latex,\n onInput: (event: Event) => {\n if (!panel) return;\n panel = { ...panel, latex: (event.target as HTMLInputElement).value };\n overlay.update();\n },\n onKeydown: (event: KeyboardEvent) => {\n if (event.key !== 'Enter') return;\n event.preventDefault();\n apply();\n }\n })\n )\n ),\n h(\n 'label',\n mergeAttrs({ key: 'display' }, part('check')),\n h('input', {\n type: 'checkbox',\n checked: state.display,\n onChange: (event: Event) => {\n if (!panel) return;\n panel = { ...panel, display: (event.target as HTMLInputElement).checked };\n overlay.update();\n }\n }),\n h('span', null, words.mathDisplay)\n ),\n templates().length\n ? h(\n 'div',\n mergeAttrs({ key: 'templates', role: 'group' }, part('mathTemplates'), { 'aria-label': words.mathTemplates, 'data-vt-math-templates': '' }),\n templates().map((template) =>\n drawn(\n 'button',\n mergeAttrs({ key: template.id, type: 'button' }, part('mathTemplate'), { 'aria-label': template.label, title: template.label, onClick: () => write(template.latex) }),\n template.latex,\n false\n )\n )\n )\n : null,\n h(\n 'div',\n mergeAttrs({ key: 'actions' }, part('actions')),\n state.at ? button('remove', words.removeMath, remove) : null,\n button('cancel', locale().cancel, cancel),\n button('apply', state.at ? words.apply : words.insert, apply, false)\n )\n ) as VElement;\n }\n\n let offered: MathTemplate[] = [];\n const templates = () => offered;\n\n /** Writes a ready-made formula into the box, over what is selected there, and leaves the caret after it. */\n function write(latex: string) {\n if (!panel) return;\n const box = overlay.element()?.querySelector<HTMLInputElement>(`[${SOURCE}]`);\n const start = box?.selectionStart ?? panel.latex.length;\n const end = box?.selectionEnd ?? start;\n // A space keeps a command from running into the letters after it: `\\pi x`, not `\\pix`.\n const before = panel.latex.slice(0, start);\n const glue = /\\\\[a-zA-Z]+$/.test(before) && /^[a-zA-Z]/.test(latex) ? ' ' : '';\n const after = panel.latex.slice(end);\n const tail = /\\\\[a-zA-Z]+$/.test(latex) && /^[a-zA-Z]/.test(after) ? ' ' : '';\n panel = { ...panel, latex: before + glue + latex + tail + after };\n overlay.update();\n const caret = before.length + glue.length + latex.length + tail.length;\n box?.focus({ preventScroll: true });\n box?.setSelectionRange(caret, caret);\n }\n\n function apply() {\n if (!panel) return;\n const { at, display } = panel;\n const latex = panel.latex.trim();\n overlay.close();\n if (at) run('setMath', at, { latex, display });\n else if (latex) run('insertMath', { latex, display });\n options.focus?.();\n }\n\n function remove() {\n if (!panel?.at) return;\n const { at } = panel;\n overlay.close();\n run('setMath', at, { latex: '' });\n options.focus?.();\n }\n\n function cancel() {\n overlay.close();\n options.focus?.();\n }\n\n function openPanel(state: PanelState, anchor: HTMLElement | null | undefined, range?: [number, number]) {\n endInline(true);\n offered = options.templates();\n panel = state;\n select = range ?? null;\n anchorEl = anchor ?? (state.at ? elementAt(state.at) : null);\n if (!anchorEl) {\n options.place?.();\n anchorEl = options.anchor();\n }\n if (overlay.isOpen) overlay.close();\n overlay.open();\n overlay.update();\n // Nothing to draw with yet, in a document that had no formula in it: the panel draws again when there is.\n if (!isMathLoaded()) loadMath().then(() => overlay.update());\n }\n\n function open(anchor?: HTMLElement | null) {\n if (!enabled()) return;\n const on = editorMathAt(options.editor.state);\n openPanel(on ? { at: { path: on.path, offset: on.offset }, latex: on.latex, display: on.display } : { at: null, latex: '', display: false }, anchor);\n }\n\n // ---- a value, edited where it stands ---------------------------------------------------------\n\n /** The box is put over the piece it stands for, and is at least wide enough for what is in it. */\n function placeInline() {\n if (!inline) return;\n const { host, input, start } = inline;\n const end = start + input.value.length;\n const piece = host.querySelector(`[data-at=\"${start},${end}\"]`) ?? host;\n const rect = piece.getBoundingClientRect();\n const size = Number.parseFloat(getComputedStyle(host).fontSize) || 16;\n // Wide enough for what is typed in its own face, and never narrower than the piece it covers.\n const width = Math.max(rect.width + size * 0.35, (input.value.length + 0.8) * size * 0.62);\n const height = Math.max(rect.height, size * 1.3);\n input.style.fontSize = `${size}px`;\n input.style.width = `${width}px`;\n input.style.height = `${height}px`;\n input.style.left = `${rect.left + rect.width / 2 - width / 2}px`;\n input.style.top = `${rect.top + rect.height / 2 - height / 2}px`;\n }\n\n const inlineSource = (state: InlineState) => state.source.slice(0, state.start) + state.input.value + state.source.slice(state.end);\n\n function startInline(host: HTMLElement, at: EditorPosition, start: number, end: number) {\n endInline(true);\n if (overlay.isOpen) overlay.close();\n const source = host.getAttribute('data-math') ?? '';\n const input = document.createElement('input');\n input.type = 'text';\n input.value = source.slice(start, end);\n input.spellcheck = false;\n input.autocomplete = 'off';\n input.setAttribute('autocapitalize', 'off');\n input.setAttribute('aria-label', locale().editor.mathValue);\n for (const [key, value] of Object.entries(options.part('mathInput'))) if (typeof value === 'string') input.setAttribute(key, value);\n input.style.position = 'fixed';\n input.style.zIndex = String(options.zIndex ?? 1000);\n inline = { at, host, source, display: host.getAttribute('data-display') === 'true', start, end, input };\n input.addEventListener('input', onInlineInput);\n input.addEventListener('keydown', onInlineKeydown);\n input.addEventListener('blur', onInlineBlur);\n // Beside the other popups, so it wears the theme they wear.\n (overlayContainerOf(host) ?? host.ownerDocument.body).appendChild(input);\n host.setAttribute('data-editing', '');\n placeInline();\n input.focus({ preventScroll: true });\n input.select();\n window.addEventListener('scroll', onInlineScroll, true);\n window.addEventListener('resize', onInlineScroll);\n }\n\n /** The formula follows the typing: drawn again from what the source would be, before any of it is kept. */\n function onInlineInput() {\n if (!inline) return;\n paintMath(inline.host, inlineSource(inline), { display: inline.display, interactive: true });\n placeInline();\n }\n\n function onInlineKeydown(event: KeyboardEvent) {\n if (!inline) return;\n if (event.key === 'Enter') {\n event.preventDefault();\n endInline(true);\n options.focus?.();\n } else if (event.key === 'Escape') {\n event.preventDefault();\n event.stopPropagation();\n endInline(false);\n options.focus?.();\n } else if (event.key === 'Tab') {\n // On to the next value, or back to the one before; off the end, the keyboard goes back to the text.\n event.preventDefault();\n const { at, start } = inline;\n const length = inline.input.value.length;\n const forward = !event.shiftKey;\n endInline(true);\n const host = elementAt(at);\n const leaves = host ? Array.from(host.querySelectorAll<SVGElement>('[data-leaf]')).map((leaf) => leaf.getAttribute('data-at')!.split(',').map(Number) as [number, number]) : [];\n leaves.sort((a, b) => a[0] - b[0]);\n const next = forward ? leaves.find(([from]) => from >= start + length) : leaves.reverse().find(([, to]) => to <= start);\n if (host && next) startInline(host, at, next[0], next[1]);\n else options.focus?.();\n }\n }\n\n const onInlineBlur = () => endInline(true);\n // The box is placed by the page's coordinates, so it is placed again when the page moves under it.\n // (Not closed: a field scrolls its own text as it is typed into, and that is a scroll too.)\n const onInlineScroll = (event: Event) => {\n if (event.target !== inline?.input) placeInline();\n };\n\n /** Closes the box. `keep` writes what was typed into the document, as one change; otherwise the formula is drawn as it was. */\n function endInline(keep: boolean) {\n const state = inline;\n if (!state) return;\n inline = null;\n const { input, host, at } = state;\n input.removeEventListener('blur', onInlineBlur);\n input.removeEventListener('input', onInlineInput);\n input.removeEventListener('keydown', onInlineKeydown);\n window.removeEventListener('scroll', onInlineScroll, true);\n window.removeEventListener('resize', onInlineScroll);\n input.remove();\n host.removeAttribute('data-editing');\n const next = inlineSource(state);\n if (keep && next !== state.source) {\n // The element is put back as the document has it first, so that the change is the view's to draw.\n paintMath(host, state.source, { display: state.display, interactive: true });\n run('setMath', at, { latex: next });\n } else if (host.isConnected) paintMath(host, state.source, { display: state.display, interactive: true });\n }\n\n // ---- a press on a formula in the text --------------------------------------------------------\n\n function onClick(event: MouseEvent) {\n const target = event.target as Element | null;\n const host = target?.closest?.('[data-math]') as HTMLElement | null;\n if (!host || !element?.contains(host) || !enabled() || inline?.host === host) return;\n const at = positionOf(host);\n if (!at) return;\n event.preventDefault();\n const piece = target!.closest('[data-at]');\n const range = piece && host.contains(piece) ? (piece.getAttribute('data-at')!.split(',').map(Number) as [number, number]) : null;\n if (range && piece!.hasAttribute('data-leaf') && (options.inlineEdit?.() ?? true) && isMathLoaded()) {\n startInline(host, at, range[0], range[1]);\n return;\n }\n openPanel({ at, latex: host.getAttribute('data-math') ?? '', display: host.getAttribute('data-display') === 'true' }, host, range ?? undefined);\n }\n\n function listen() {\n const next = options.content();\n if (next === element) return;\n element?.removeEventListener('click', onClick);\n element = next;\n element?.addEventListener('click', onClick);\n }\n\n const stop = options.editor.subscribe(() => {\n listen();\n if (!enabled()) {\n endInline(false);\n if (overlay.isOpen) overlay.close();\n return;\n }\n // The document changed under an open box or panel (an undo, the application): what it was\n // editing may be gone. Looked at once the view has drawn the change, which it does after this.\n if (inline || panel?.at) queueMicrotask(settle);\n });\n\n function settle() {\n if (inline && !inline.host.isConnected) endInline(false);\n if (panel?.at && !elementAt(panel.at)) overlay.close();\n }\n listen();\n\n return {\n get isOpen() {\n return overlay.isOpen;\n },\n open,\n sync: listen,\n close() {\n endInline(true);\n if (overlay.isOpen) overlay.close();\n },\n destroy() {\n stop();\n endInline(false);\n element?.removeEventListener('click', onClick);\n element = null;\n overlay.destroy();\n }\n };\n}\n"],"mappings":";;;;;AAiEA,SAAgB,qBAAqB,QAAgC;CACjE,MAAM,QAAQ,OAAO,OAAO;CAC5B,MAAM,SAAS,IAAY,WAAiC;EAAE;EAAI,OAAO,MAAM,OAAO;EAAI;CAAM;CAChG,OAAO;EACH,MAAM,YAAY,cAAc;EAChC,MAAM,cAAc,WAAW;EA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ACJ;AACJ"}
package/dist/slash.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type EditorInstance, type Locale } from '@vitral/core';
2
2
  import { type OverlayTarget } from '@vitral/controls';
3
- import type { Props } from '@vitral/dom';
3
+ import type { Props, ScrollbarSlotOptions } from '@vitral/dom';
4
4
  import type { SlashCommand } from './types';
5
5
  /**
6
6
  * The menu a `/` opens, as a piece that attaches to any editor: the
@@ -29,6 +29,8 @@ export interface SlashMenuOptions {
29
29
  };
30
30
  overlayTarget?: OverlayTarget;
31
31
  zIndex?: number;
32
+ /** Drawn scrollbars on the panel: `{ mode, style: scrollpanelStyle, unstyled }`. */
33
+ scrollbars?: () => ScrollbarSlotOptions;
32
34
  /** What to do with the command the reader chose; it runs itself by default. */
33
35
  onRun?: (command: SlashCommand) => void;
34
36
  }
package/dist/slash.js CHANGED
@@ -37,6 +37,7 @@ function createSlashMenu(options) {
37
37
  target: () => options.overlayTarget,
38
38
  zIndex: options.zIndex,
39
39
  restoreFocus: false,
40
+ scrollbars: options.scrollbars,
40
41
  onClose: () => open = null
41
42
  });
42
43
  /** The text of the block the caret is in, and where the caret is in it. */
package/dist/slash.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"slash.js","names":[],"sources":["../src/slash.ts"],"sourcesContent":["import { editorSelectionRange, editorTextblocks, en, type EditorInstance, type EditorNode, type Locale } from '@vitral/core';\nimport { createOverlay, type OverlayTarget } from '@vitral/controls';\nimport type { Props } from '@vitral/dom';\nimport { slashMenuView } from './render/menus';\nimport type { CommandRunner, SlashCommand } from './types';\n\n/**\n * The menu a `/` opens, as a piece that attaches to any editor: the\n * framework-free one uses it, and so does a framework component that draws its\n * own toolbar. It watches the document, opens when a slash starts a word,\n * filters as it is typed, and takes the keys it needs while it is open.\n */\n\nexport interface SlashMenuOptions {\n editor: EditorInstance;\n /** The `contenteditable` element, where the keys are heard. */\n content: () => HTMLElement | null;\n /** What the menu hangs from: an element over the caret. */\n anchor: () => HTMLElement | null;\n /** The commands on offer; a function is read every time it opens. */\n commands: () => SlashCommand[];\n /** The classes and pass-through of the menu's parts. */\n part: (name: string, state?: unknown) => Props;\n locale?: () => Locale;\n /** Off while the editor is read-only. */\n enabled?: () => boolean;\n /** Puts the anchor where the caret is, before the menu opens. */\n place?: () => void;\n ids?: { slash: string; block: string };\n overlayTarget?: OverlayTarget;\n zIndex?: number;\n /** What to do with the command the reader chose; it runs itself by default. */\n onRun?: (command: SlashCommand) => void;\n}\n\nexport interface SlashMenu {\n readonly isOpen: boolean;\n /** Reads the document again: called on every change. */\n sync(): void;\n close(): void;\n destroy(): void;\n}\n\nexport function createSlashMenu(options: SlashMenuOptions): SlashMenu {\n let open: { query: string; active: number } | null = null;\n let element: HTMLElement | null = null;\n\n const locale = () => options.locale?.() ?? en;\n const ids = options.ids ?? { slash: 'vt-slash', block: 'vt-block' };\n const enabled = () => options.enabled?.() ?? true;\n\n /** What the query after the slash matches, by label, id and keyword. */\n function matches(query: string): SlashCommand[] {\n const needle = query.trim().toLocaleLowerCase(locale().code);\n const all = options.commands();\n if (!needle) return all;\n return all.filter((item) => [item.label, item.id, ...(item.keywords ?? [])].some((word) => word.toLocaleLowerCase(locale().code).includes(needle)));\n }\n\n const overlay = createOverlay({\n anchor: options.anchor,\n render: () =>\n open\n ? (slashMenuView({ locale: locale(), part: options.part, ids }, { query: open.query, items: matches(open.query), active: open.active }, { choose: run }) as never)\n : null,\n placement: 'bottom-start',\n target: () => options.overlayTarget,\n zIndex: options.zIndex,\n restoreFocus: false,\n onClose: () => (open = null)\n });\n\n /** The text of the block the caret is in, and where the caret is in it. */\n function caretText(): { text: string; offset: number } | null {\n const state = options.editor.state;\n if (!editorSelectionRange(state.selection).empty) return null;\n const blocks = editorTextblocks(state.doc);\n const path = state.selection.head.path;\n const block = blocks.find((entry) => entry.path.join('.') === path.join('.'))?.node ?? (path[0] === undefined ? undefined : (state.doc.content?.[path[0]] as EditorNode | undefined));\n if (!block) return null;\n const text = (block.content ?? []).map((child) => (typeof child === 'string' ? child : (child.text ?? ''))).join('');\n return { text, offset: state.selection.head.offset };\n }\n\n function sync() {\n if (!enabled()) return close();\n const caret = caretText();\n if (!caret) return close();\n const before = caret.text.slice(0, caret.offset);\n const at = before.lastIndexOf('/');\n const starts = at === 0 || (at > 0 && /\\s/.test(before[at - 1] ?? ''));\n if (at < 0 || !starts) return close();\n const query = before.slice(at + 1);\n if (/\\s/.test(query)) return close();\n open = { query, active: open && open.query === query ? open.active : 0 };\n options.place?.();\n overlay.open();\n overlay.update();\n }\n\n function close() {\n if (!overlay.isOpen) {\n open = null;\n return;\n }\n overlay.close();\n }\n\n /** Runs what the menu was pointing at, after taking the slash and its query out. */\n function run(index: number) {\n const items = matches(open?.query ?? '');\n const item = items[index];\n if (!item || !open) return;\n const remove = open.query.length + 1;\n close();\n for (let n = 0; n < remove; n++) options.editor.backspace('char');\n if (options.onRun) options.onRun(item);\n // An entry's own `run` is what an application writes a command of its\n // own with: without this it was only ever called by a host that passed\n // `onRun`, so a slash command with a `run` did nothing in Vue.\n else if (item.run) item.run(options.editor as unknown as CommandRunner);\n else if (item.command) (options.editor.run as (name: string, ...args: unknown[]) => boolean)(item.command[0], ...item.command.slice(1));\n }\n\n /**\n * While the menu is open those keys are the menu's. The listener is a\n * capturing one: the editor's own view listens on the same element, and an\n * Enter it heard would split the block the command is about to change.\n */\n function onKeydown(event: KeyboardEvent) {\n if (!open) return;\n const items = matches(open.query);\n const take = () => {\n event.preventDefault();\n event.stopImmediatePropagation();\n };\n if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {\n take();\n const step = event.key === 'ArrowDown' ? 1 : -1;\n open = { ...open, active: (open.active + step + items.length) % Math.max(1, items.length) };\n overlay.update();\n return;\n }\n if (event.key === 'Home' || event.key === 'End') {\n take();\n open = { ...open, active: event.key === 'Home' ? 0 : Math.max(0, items.length - 1) };\n overlay.update();\n return;\n }\n if (event.key === 'Enter' || event.key === 'Tab') {\n if (!items.length) return;\n take();\n run(open.active);\n return;\n }\n if (event.key === 'Escape') {\n take();\n close();\n }\n }\n\n function listen() {\n const next = options.content();\n if (next === element) return;\n element?.removeEventListener('keydown', onKeydown, true);\n element = next;\n element?.addEventListener('keydown', onKeydown, true);\n }\n\n const stop = options.editor.subscribe(() => {\n listen();\n sync();\n });\n listen();\n // The document may already be mid-word: a menu attached after a slash was\n // typed (a re-attach, a component that mounted late) opens straight away.\n sync();\n\n return {\n get isOpen() {\n return overlay.isOpen;\n },\n sync() {\n listen();\n sync();\n },\n close,\n destroy() {\n stop();\n element?.removeEventListener('keydown', onKeydown, true);\n element = null;\n overlay.destroy();\n }\n };\n}\n\n/** The blocks a slash offers when an application names none. */\nexport function defaultSlashCommands(locale: Locale): SlashCommand[] {\n const words = locale.editor;\n const entry = (id: string, icon: string, command: readonly [string, ...unknown[]]): SlashCommand => ({\n id,\n icon,\n label: words.slashCommands[id] ?? id,\n description: words.slashHints[id],\n command\n });\n return [\n entry('paragraph', 'pilcrow', ['setParagraph']),\n entry('heading1', 'heading1', ['toggleHeading', 1]),\n entry('heading2', 'heading2', ['toggleHeading', 2]),\n entry('heading3', 'heading3', ['toggleHeading', 3]),\n entry('bulletList', 'list', ['toggleBulletList']),\n entry('orderedList', 'listOrdered', ['toggleOrderedList']),\n entry('taskList', 'listChecks', ['toggleTaskList']),\n entry('blockquote', 'quote', ['toggleBlockquote']),\n entry('codeBlock', 'codeBlock', ['toggleCodeBlock']),\n entry('horizontalRule', 'horizontalRule', ['insertHorizontalRule']),\n entry('table', 'table', ['insertTable', 3, 3, true]),\n entry('image', 'image', ['insertImage', { src: '' }]),\n // Not a command of the document's: the host opens its formula panel for it, and leaves it out where formulas are off.\n entry('math', 'sigma', ['math'])\n ];\n}\n"],"mappings":";;;;AA2CA,SAAgB,gBAAgB,SAAsC;CAClE,IAAI,OAAiD;CACrD,IAAI,UAA8B;CAElC,MAAM,eAAe,QAAQ,SAAS,KAAK;CAC3C,MAAM,MAAM,QAAQ,OAAO;EAAE,OAAO;EAAY,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BAAqB,QAAgC;CACjE,MAAM,QAAQ,OAAO;CACrB,MAAM,SAAS,IAAY,MAAc,aAA4D;EACjG;EACA;EACA,OAAO,MAAM,cAAc,OAAO;EAClC,aAAa,MAAM,WAAW;EAC9B;CACJ;CACA,OAAO;EACH,MAAM,aAAa,WAAW,CAAC,cAAc,CAAC;EAC9C,MAAM,YAAY,YAAY,CAAC,iBAAiB,CAAC,CAAC;EAClD,MAAM,YAAY,YAAY,CAAC,iBAAiB,CAAC,CAAC;EAClD,MAAM,YAAY,YAAY,CAAC,iBAAiB,CAAC,CAAC;EAClD,MAAM,cAAc,QAAQ,CAAC,kBAAkB,CAAC;EAChD,MAAM,eAAe,eAAe,CAAC,mBAAmB,CAAC;EACzD,MAAM,YAAY,cAAc,CAAC,gBAAgB,CAAC;EAClD,MAAM,cAAc,SAAS,CAAC,kBAAkB,CAAC;EACjD,MAAM,aAAa,aAAa,CAAC,iBAAiB,CAAC;EACnD,MAAM,kBAAkB,kBAAkB,CAAC,sBAAsB,CAAC;EAClE,MAAM,SAAS,SAAS;GAAC;GAAe;GAAG;GAAG;EAAI,CAAC;EACnD,MAAM,SAAS,SAAS,CAAC,eAAe,EAAE,KAAK,GAAG,CAAC,CAAC;EAEpD,MAAM,QAAQ,SAAS,CAAC,MAAM,CAAC;CACnC;AACJ"}
1
+ {"version":3,"file":"slash.js","names":[],"sources":["../src/slash.ts"],"sourcesContent":["import { editorSelectionRange, editorTextblocks, en, type EditorInstance, type EditorNode, type Locale } from '@vitral/core';\nimport { createOverlay, type OverlayTarget } from '@vitral/controls';\nimport type { Props, ScrollbarSlotOptions } from '@vitral/dom';\nimport { slashMenuView } from './render/menus';\nimport type { CommandRunner, SlashCommand } from './types';\n\n/**\n * The menu a `/` opens, as a piece that attaches to any editor: the\n * framework-free one uses it, and so does a framework component that draws its\n * own toolbar. It watches the document, opens when a slash starts a word,\n * filters as it is typed, and takes the keys it needs while it is open.\n */\n\nexport interface SlashMenuOptions {\n editor: EditorInstance;\n /** The `contenteditable` element, where the keys are heard. */\n content: () => HTMLElement | null;\n /** What the menu hangs from: an element over the caret. */\n anchor: () => HTMLElement | null;\n /** The commands on offer; a function is read every time it opens. */\n commands: () => SlashCommand[];\n /** The classes and pass-through of the menu's parts. */\n part: (name: string, state?: unknown) => Props;\n locale?: () => Locale;\n /** Off while the editor is read-only. */\n enabled?: () => boolean;\n /** Puts the anchor where the caret is, before the menu opens. */\n place?: () => void;\n ids?: { slash: string; block: string };\n overlayTarget?: OverlayTarget;\n zIndex?: number;\n /** Drawn scrollbars on the panel: `{ mode, style: scrollpanelStyle, unstyled }`. */\n scrollbars?: () => ScrollbarSlotOptions;\n /** What to do with the command the reader chose; it runs itself by default. */\n onRun?: (command: SlashCommand) => void;\n}\n\nexport interface SlashMenu {\n readonly isOpen: boolean;\n /** Reads the document again: called on every change. */\n sync(): void;\n close(): void;\n destroy(): void;\n}\n\nexport function createSlashMenu(options: SlashMenuOptions): SlashMenu {\n let open: { query: string; active: number } | null = null;\n let element: HTMLElement | null = null;\n\n const locale = () => options.locale?.() ?? en;\n const ids = options.ids ?? { slash: 'vt-slash', block: 'vt-block' };\n const enabled = () => options.enabled?.() ?? true;\n\n /** What the query after the slash matches, by label, id and keyword. */\n function matches(query: string): SlashCommand[] {\n const needle = query.trim().toLocaleLowerCase(locale().code);\n const all = options.commands();\n if (!needle) return all;\n return all.filter((item) => [item.label, item.id, ...(item.keywords ?? [])].some((word) => word.toLocaleLowerCase(locale().code).includes(needle)));\n }\n\n const overlay = createOverlay({\n anchor: options.anchor,\n render: () =>\n open\n ? (slashMenuView({ locale: locale(), part: options.part, ids }, { query: open.query, items: matches(open.query), active: open.active }, { choose: run }) as never)\n : null,\n placement: 'bottom-start',\n target: () => options.overlayTarget,\n zIndex: options.zIndex,\n restoreFocus: false,\n scrollbars: options.scrollbars,\n onClose: () => (open = null)\n });\n\n /** The text of the block the caret is in, and where the caret is in it. */\n function caretText(): { text: string; offset: number } | null {\n const state = options.editor.state;\n if (!editorSelectionRange(state.selection).empty) return null;\n const blocks = editorTextblocks(state.doc);\n const path = state.selection.head.path;\n const block = blocks.find((entry) => entry.path.join('.') === path.join('.'))?.node ?? (path[0] === undefined ? undefined : (state.doc.content?.[path[0]] as EditorNode | undefined));\n if (!block) return null;\n const text = (block.content ?? []).map((child) => (typeof child === 'string' ? child : (child.text ?? ''))).join('');\n return { text, offset: state.selection.head.offset };\n }\n\n function sync() {\n if (!enabled()) return close();\n const caret = caretText();\n if (!caret) return close();\n const before = caret.text.slice(0, caret.offset);\n const at = before.lastIndexOf('/');\n const starts = at === 0 || (at > 0 && /\\s/.test(before[at - 1] ?? ''));\n if (at < 0 || !starts) return close();\n const query = before.slice(at + 1);\n if (/\\s/.test(query)) return close();\n open = { query, active: open && open.query === query ? open.active : 0 };\n options.place?.();\n overlay.open();\n overlay.update();\n }\n\n function close() {\n if (!overlay.isOpen) {\n open = null;\n return;\n }\n overlay.close();\n }\n\n /** Runs what the menu was pointing at, after taking the slash and its query out. */\n function run(index: number) {\n const items = matches(open?.query ?? '');\n const item = items[index];\n if (!item || !open) return;\n const remove = open.query.length + 1;\n close();\n for (let n = 0; n < remove; n++) options.editor.backspace('char');\n if (options.onRun) options.onRun(item);\n // An entry's own `run` is what an application writes a command of its\n // own with: without this it was only ever called by a host that passed\n // `onRun`, so a slash command with a `run` did nothing in Vue.\n else if (item.run) item.run(options.editor as unknown as CommandRunner);\n else if (item.command) (options.editor.run as (name: string, ...args: unknown[]) => boolean)(item.command[0], ...item.command.slice(1));\n }\n\n /**\n * While the menu is open those keys are the menu's. The listener is a\n * capturing one: the editor's own view listens on the same element, and an\n * Enter it heard would split the block the command is about to change.\n */\n function onKeydown(event: KeyboardEvent) {\n if (!open) return;\n const items = matches(open.query);\n const take = () => {\n event.preventDefault();\n event.stopImmediatePropagation();\n };\n if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {\n take();\n const step = event.key === 'ArrowDown' ? 1 : -1;\n open = { ...open, active: (open.active + step + items.length) % Math.max(1, items.length) };\n overlay.update();\n return;\n }\n if (event.key === 'Home' || event.key === 'End') {\n take();\n open = { ...open, active: event.key === 'Home' ? 0 : Math.max(0, items.length - 1) };\n overlay.update();\n return;\n }\n if (event.key === 'Enter' || event.key === 'Tab') {\n if (!items.length) return;\n take();\n run(open.active);\n return;\n }\n if (event.key === 'Escape') {\n take();\n close();\n }\n }\n\n function listen() {\n const next = options.content();\n if (next === element) return;\n element?.removeEventListener('keydown', onKeydown, true);\n element = next;\n element?.addEventListener('keydown', onKeydown, true);\n }\n\n const stop = options.editor.subscribe(() => {\n listen();\n sync();\n });\n listen();\n // The document may already be mid-word: a menu attached after a slash was\n // typed (a re-attach, a component that mounted late) opens straight away.\n sync();\n\n return {\n get isOpen() {\n return overlay.isOpen;\n },\n sync() {\n listen();\n sync();\n },\n close,\n destroy() {\n stop();\n element?.removeEventListener('keydown', onKeydown, true);\n element = null;\n overlay.destroy();\n }\n };\n}\n\n/** The blocks a slash offers when an application names none. */\nexport function defaultSlashCommands(locale: Locale): SlashCommand[] {\n const words = locale.editor;\n const entry = (id: string, icon: string, command: readonly [string, ...unknown[]]): SlashCommand => ({\n id,\n icon,\n label: words.slashCommands[id] ?? id,\n description: words.slashHints[id],\n command\n });\n return [\n entry('paragraph', 'pilcrow', ['setParagraph']),\n entry('heading1', 'heading1', ['toggleHeading', 1]),\n entry('heading2', 'heading2', ['toggleHeading', 2]),\n entry('heading3', 'heading3', ['toggleHeading', 3]),\n entry('bulletList', 'list', ['toggleBulletList']),\n entry('orderedList', 'listOrdered', ['toggleOrderedList']),\n entry('taskList', 'listChecks', ['toggleTaskList']),\n entry('blockquote', 'quote', ['toggleBlockquote']),\n entry('codeBlock', 'codeBlock', ['toggleCodeBlock']),\n entry('horizontalRule', 'horizontalRule', ['insertHorizontalRule']),\n entry('table', 'table', ['insertTable', 3, 3, true]),\n entry('image', 'image', ['insertImage', { src: '' }]),\n // Not a command of the document's: the host opens its formula panel for it, and leaves it out where formulas are off.\n entry('math', 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AAO;EACH,IAAI,SAAS;GACT,OAAO,QAAQ;EACnB;EACA,OAAO;GACH,OAAO;GACP,KAAK;EACT;EACA;EACA,UAAU;GACN,KAAK;GACL,SAAS,oBAAoB,WAAW,WAAW,IAAI;GACvD,UAAU;GACV,QAAQ,QAAQ;EACpB;CACJ;AACJ;;AAGA,SAAgB,qBAAqB,QAAgC;CACjE,MAAM,QAAQ,OAAO;CACrB,MAAM,SAAS,IAAY,MAAc,aAA4D;EACjG;EACA;EACA,OAAO,MAAM,cAAc,OAAO;EAClC,aAAa,MAAM,WAAW;EAC9B;CACJ;CACA,OAAO;EACH,MAAM,aAAa,WAAW,CAAC,cAAc,CAAC;EAC9C,MAAM,YAAY,YAAY,CAAC,iBAAiB,CAAC,CAAC;EAClD,MAAM,YAAY,YAAY,CAAC,iBAAiB,CAAC,CAAC;EAClD,MAAM,YAAY,YAAY,CAAC,iBAAiB,CAAC,CAAC;EAClD,MAAM,cAAc,QAAQ,CAAC,kBAAkB,CAAC;EAChD,MAAM,eAAe,eAAe,CAAC,mBAAmB,CAAC;EACzD,MAAM,YAAY,cAAc,CAAC,gBAAgB,CAAC;EAClD,MAAM,cAAc,SAAS,CAAC,kBAAkB,CAAC;EACjD,MAAM,aAAa,aAAa,CAAC,iBAAiB,CAAC;EACnD,MAAM,kBAAkB,kBAAkB,CAAC,sBAAsB,CAAC;EAClE,MAAM,SAAS,SAAS;GAAC;GAAe;GAAG;GAAG;EAAI,CAAC;EACnD,MAAM,SAAS,SAAS,CAAC,eAAe,EAAE,KAAK,GAAG,CAAC,CAAC;EAEpD,MAAM,QAAQ,SAAS,CAAC,MAAM,CAAC;CACnC;AACJ"}
package/dist/types.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ClassEntry, EditorColor, EditorContent, EditorNode, Locale } from '@vitral/core';
2
2
  import type { OverlayTarget } from '@vitral/controls';
3
- import type { PassThrough } from '@vitral/dom';
3
+ import type { PassThrough, ScrollbarMode } from '@vitral/dom';
4
4
  /**
5
5
  * What an editor is told, as plain data. The document, the commands and the
6
6
  * history are `@vitral/core`'s; this is the interface around them — which
@@ -156,6 +156,12 @@ export interface TextEditorConfig {
156
156
  ariaLabelledby?: string;
157
157
  locale?: Locale;
158
158
  unstyled?: boolean;
159
+ /**
160
+ * The bars of the text area, when a height makes it scroll: the theme's
161
+ * drawn bars, shown under the pointer (`'hover'`, the default) or always
162
+ * (`'always'`), or the browser's own (`'native'`).
163
+ */
164
+ scrollbar?: ScrollbarMode;
159
165
  classes?: Partial<Record<string, ClassEntry>>;
160
166
  pt?: PassThrough;
161
167
  /** What the host draws itself. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitral/editor",
3
- "version": "0.2.12",
3
+ "version": "0.2.14",
4
4
  "description": "Framework-free rich text editor for Vitral: the toolbar, the panels and the content area over @vitral/core's editor engine, which the Vue, React and Angular components wrap.",
5
5
  "keywords": [
6
6
  "vitral",
@@ -44,11 +44,11 @@
44
44
  "access": "public"
45
45
  },
46
46
  "dependencies": {
47
- "@vitral/controls": "0.2.12",
48
- "@vitral/core": "0.2.12",
49
- "@vitral/dom": "0.2.12",
50
- "@vitral/icons": "0.2.12",
51
- "@vitral/styles": "0.2.12"
47
+ "@vitral/core": "0.2.14",
48
+ "@vitral/styles": "0.2.14",
49
+ "@vitral/controls": "0.2.14",
50
+ "@vitral/dom": "0.2.14",
51
+ "@vitral/icons": "0.2.14"
52
52
  },
53
53
  "scripts": {
54
54
  "build": "vite build && tsc -p tsconfig.build.json"