wysio 0.0.1 → 0.2.0-alpha.0

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.
Files changed (90) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/LICENSE +21 -0
  3. package/README.md +241 -3
  4. package/dist/auto-init.d.ts +12 -0
  5. package/dist/auto-init.d.ts.map +1 -0
  6. package/dist/cdn-full.d.ts +3 -0
  7. package/dist/cdn-full.d.ts.map +1 -0
  8. package/dist/cdn.d.ts +2 -0
  9. package/dist/cdn.d.ts.map +1 -0
  10. package/dist/commands.d.ts +19 -0
  11. package/dist/commands.d.ts.map +1 -0
  12. package/dist/content.d.ts +31 -0
  13. package/dist/content.d.ts.map +1 -0
  14. package/dist/editor.d.ts +158 -0
  15. package/dist/editor.d.ts.map +1 -0
  16. package/dist/emitter.d.ts +9 -0
  17. package/dist/emitter.d.ts.map +1 -0
  18. package/dist/format-html.d.ts +7 -0
  19. package/dist/format-html.d.ts.map +1 -0
  20. package/dist/i18n.d.ts +16 -0
  21. package/dist/i18n.d.ts.map +1 -0
  22. package/dist/icons.d.ts +34 -0
  23. package/dist/icons.d.ts.map +1 -0
  24. package/dist/index.d.ts +17 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/locales/nl.d.ts +81 -0
  27. package/dist/locales/nl.d.ts.map +1 -0
  28. package/dist/markdown/index.d.ts +17 -0
  29. package/dist/markdown/index.d.ts.map +1 -0
  30. package/dist/markdown.js +179 -0
  31. package/dist/markdown.js.map +1 -0
  32. package/dist/messages.d.ts +83 -0
  33. package/dist/messages.d.ts.map +1 -0
  34. package/dist/plugin.d.ts +94 -0
  35. package/dist/plugin.d.ts.map +1 -0
  36. package/dist/plugins/alignment.d.ts +10 -0
  37. package/dist/plugins/alignment.d.ts.map +1 -0
  38. package/dist/plugins/base.d.ts +7 -0
  39. package/dist/plugins/base.d.ts.map +1 -0
  40. package/dist/plugins/blocks.d.ts +4 -0
  41. package/dist/plugins/blocks.d.ts.map +1 -0
  42. package/dist/plugins/clear-formatting.d.ts +10 -0
  43. package/dist/plugins/clear-formatting.d.ts.map +1 -0
  44. package/dist/plugins/color.d.ts +36 -0
  45. package/dist/plugins/color.d.ts.map +1 -0
  46. package/dist/plugins/heading.d.ts +3 -0
  47. package/dist/plugins/heading.d.ts.map +1 -0
  48. package/dist/plugins/history.d.ts +2 -0
  49. package/dist/plugins/history.d.ts.map +1 -0
  50. package/dist/plugins/image.d.ts +56 -0
  51. package/dist/plugins/image.d.ts.map +1 -0
  52. package/dist/plugins/index.d.ts +29 -0
  53. package/dist/plugins/index.d.ts.map +1 -0
  54. package/dist/plugins/link.d.ts +15 -0
  55. package/dist/plugins/link.d.ts.map +1 -0
  56. package/dist/plugins/lists.d.ts +2 -0
  57. package/dist/plugins/lists.d.ts.map +1 -0
  58. package/dist/plugins/marks.d.ts +7 -0
  59. package/dist/plugins/marks.d.ts.map +1 -0
  60. package/dist/plugins/paste.d.ts +9 -0
  61. package/dist/plugins/paste.d.ts.map +1 -0
  62. package/dist/plugins/placeholder.d.ts +3 -0
  63. package/dist/plugins/placeholder.d.ts.map +1 -0
  64. package/dist/plugins/source.d.ts +5 -0
  65. package/dist/plugins/source.d.ts.map +1 -0
  66. package/dist/plugins/table.d.ts +14 -0
  67. package/dist/plugins/table.d.ts.map +1 -0
  68. package/dist/registry-BfhH2s8N.js +19 -0
  69. package/dist/registry-BfhH2s8N.js.map +1 -0
  70. package/dist/registry.d.ts +10 -0
  71. package/dist/registry.d.ts.map +1 -0
  72. package/dist/schema.d.ts +5 -0
  73. package/dist/schema.d.ts.map +1 -0
  74. package/dist/style.css +824 -0
  75. package/dist/toolbar/toolbar.d.ts +56 -0
  76. package/dist/toolbar/toolbar.d.ts.map +1 -0
  77. package/dist/ui/menu.d.ts +20 -0
  78. package/dist/ui/menu.d.ts.map +1 -0
  79. package/dist/ui/popover.d.ts +29 -0
  80. package/dist/ui/popover.d.ts.map +1 -0
  81. package/dist/url.d.ts +23 -0
  82. package/dist/url.d.ts.map +1 -0
  83. package/dist/web-component.d.ts +21 -0
  84. package/dist/web-component.d.ts.map +1 -0
  85. package/dist/wysio.full.iife.js +72 -0
  86. package/dist/wysio.iife.js +49 -0
  87. package/dist/wysio.js +2668 -0
  88. package/dist/wysio.js.map +1 -0
  89. package/package.json +68 -6
  90. package/index.js +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wysio.js","names":["DOMParser","PMNode","isMac","historyPlugin","baseKeymap","chainCommands","exitCode","lift","setBlockType","toggleMark","wrapIn","InputRule","inputRules","textblockTypeInputRule","undoInputRule","wrappingInputRule","keymap","EditorState","NodeSelection","Plugin","PluginKey","TextSelection","Decoration","DecorationSet","EditorView","DOMParser$1","DOMSerializer","Node$1","Schema","resolvePluginNames","definePlugin","registerPlugin","dropCursor","gapCursor","liftListItem","sinkListItem","splitListItem","wrapInList","history$1","redo","undo","addColumnAfter","addColumnBefore","addRowAfter","addRowBefore","deleteColumn","deleteRow","deleteTable","goToNextCell","isInTable","tableEditing","getDocument","doc","d","parseHTML","schema","html","body","serializeHTML","node","container","normalizeDoc","parseJSON","json","createDoc","content","isDocEmpty","first","Emitter","event","listener","set","args","nl","defaultMessages","locales","registerLocale","code","messages","availableLocales","findLocale","normalized","candidate","interpolate","text","params","match","name","svg","icons","popoverCount","Popover","editor","label","next","pos","focus","restoreFocus","open","view","coords","box","left","registry","getPopover","key","create","map","created","popover","createForm","uid","template","form","query","root","selector","el","MenuPopover","items","list","item","button","state","enabled","b","buttons","index","ALIGNMENTS","ALIGNABLE","toStored","value","readAlign","dom","align","addClass","out","className","tag","second","rest","attrs","withAlign","spec","toDOM","rule","tagRule","base","alignableBlocks","blocks","$from","$to","setAlignment","dispatch","tr","isAlignmentActive","SHORTCUTS","itemName","openAlignmentMenu","ed","alignment","current","a","isMarkActive","type","from","to","empty","findAncestor","types","depth","toggleList","listType","itemType","listTypes","toggleWrap","getMarkRange","$pos","parent","found","mark","start","startIndex","endIndex","blockquote","horizontalRule","_match","end","$start","hr","hardBreak","cmd","FORMATTING_ATTRIBUTES","KEEP_MARKS","clearFormatting","changed","marks","resetBlock","reset","attr","stored","m","clearFormattingPlugin","DEFAULT_TEXT_COLORS","DEFAULT_HIGHLIGHT_COLORS","hex2","n","normalizeColor","v","parts","NAME","createPalette","colors","entries","c","byName","byValue","prefix","cls","paletteCSS","kind","showColor","palette","setColorMark","color","removeColorMark","activeColor","mixed","colorLabel","COLUMNS","PalettePopover","removeLabel","swatchStyle","grid","remove","swatch","on","s","moves","i","textColor","options","highlight","fallback","HEADING_LEVELS","clampLevel","level","heading","keys","paragraph","block","command","isMac$1","history","ALLOWED_SCHEMES","IGNORED_IN_SCHEME","CONTROL_CHARS","sanitizeUrl","raw","url","compact","scheme","colon","separator","normalizeUserUrl","input","hasScheme","isRelative","safe","DATA_IMAGE","sanitizeImageUrl","allowDataUrls","trimmed","IMAGE_ALIGNMENTS","DEFAULT_IMAGE_TYPES","toDimension","toText","toAlign","parseAlign","float","editorOptions","optionsFor","cleanAttrs","src","uploadKey","uploads","findPlaceholder","id","createPlaceholder","file","img","bar","uploadImages","files","upload","controllers","active","placeholder","at","controller","result","fraction","error","imageFiles","uploadPlugin","meta","_view","data","_slice","moved","selectedImage","selection","insertImage","clean","existing","removeImage","openImageDialog","ImageDialog","image","typed","show","config","width","height","linkRange","range","setLink","href","removeLink","openLinkDialog","LinkDialog","cancel","size","link","_state","toStart","lists","bullet","ordered","inList","markPlugin","shortcut","hasDecoration","decoration","bold","italic","underline","strike","REMOVE","BLOCK","KEEP_ATTRIBUTES","HEADING","unwrap","wrapChildren","tags","outer","inner","formattingTags","style","weight","isWordListParagraph","isMarkerSpan","convertWordLists","p","markerSpan","marker","li","isBlockLevelBreak","br","sibling","dir","isBlank","isBlockOrEdge","cleanPastedHTML","parsed","comments","walker","ownClasses","paste","CONTAINERS","BLOCKS","hasBlockChildren","openTag","shallow","close","formatHTML","indent","lines","print","pad","child","sourceKey","SourceView","views","sourceView","toggleSourceView","source","MAX_TABLE_SIZE","MAX_SPAN","toSpan","spanAttrs","cellSpec","tableRole","colspan","rowspan","createTable","rows","cols","header","table","row","cell","th","clamp","_","r","insertTable","allowed","tablePos","toggleHeaderRow","td","toHeader","offset","nextCell","tableActions","openTableMenu","TablePopover","action","inTable","target","inTableOnly","defaultPlugins","buildSchema","plugins","nodes","plugin","extend","isMac","formatShortcut","mac","part","fitCount","rightEdges","limit","count","CARET","toolbarCount","Toolbar","names","warnUnknown","mode","lastWasSeparator","sep","control","icon","blank","option","opt","editable","wysiwyg","more","panel","focused","gap","focusMore","defaultToolbar","editorCount","Editor","element","locale","resolveMessages","resolvePlugins","initial","initialFormat","ctx","handler","mount","top","rules","format","emitChange","info","removed","extra","builtIn","createEditor","editors","getEditor","autoInit","defaults","BOOLEAN_ATTRS","createElementClass","#editor","#internals","#value","#formDisabled","#format","#formAssociated","#syncForm","toolbar","#isEditable","oldValue","newValue","disabled","defineWysioElement","tagName","version"],"sources":["../src/content.ts","../src/emitter.ts","../src/locales/nl.ts","../src/messages.ts","../src/i18n.ts","../src/icons.ts","../src/ui/popover.ts","../src/ui/menu.ts","../src/plugins/alignment.ts","../src/plugins/base.ts","../src/commands.ts","../src/plugins/blocks.ts","../src/plugins/clear-formatting.ts","../src/plugins/color.ts","../src/plugins/heading.ts","../src/plugins/history.ts","../src/url.ts","../src/plugins/image.ts","../src/plugins/link.ts","../src/plugins/lists.ts","../src/plugins/marks.ts","../src/plugins/paste.ts","../src/plugins/placeholder.ts","../src/format-html.ts","../src/plugins/source.ts","../src/plugins/table.ts","../src/plugins/index.ts","../src/schema.ts","../src/toolbar/toolbar.ts","../src/editor.ts","../src/auto-init.ts","../src/web-component.ts","../src/index.ts"],"sourcesContent":["import { DOMParser, DOMSerializer, Node as PMNode, type Schema } from 'prosemirror-model';\n\n/** ProseMirror JSON document. */\nexport interface JSONContent {\n type: string;\n attrs?: Record<string, unknown>;\n content?: JSONContent[];\n marks?: { type: string; attrs?: Record<string, unknown> }[];\n text?: string;\n}\n\n/** Content accepted by the editor: an HTML string or a ProseMirror JSON document. */\nexport type Content = string | JSONContent | null | undefined;\n\nfunction getDocument(doc?: Document): Document {\n const d = doc ?? globalThis.document;\n if (!d) throw new Error('[wysio] A DOM document is required.');\n return d;\n}\n\n/**\n * Parses HTML into a document. The HTML is parsed in an inert document (no scripts run,\n * no resources load); only what the schema's parse rules accept is kept.\n */\nexport function parseHTML(schema: Schema, html: string, doc?: Document): PMNode {\n const d = getDocument(doc);\n const view = d.defaultView;\n const Parser = view?.DOMParser ?? globalThis.DOMParser;\n const body = new Parser().parseFromString(html, 'text/html').body;\n return DOMParser.fromSchema(schema).parse(body);\n}\n\nexport function serializeHTML(schema: Schema, node: PMNode, doc?: Document): string {\n const d = getDocument(doc);\n const container = d.createElement('div');\n container.appendChild(\n DOMSerializer.fromSchema(schema).serializeFragment(node.content, { document: d }),\n );\n return container.innerHTML;\n}\n\n/**\n * Passes a document through the HTML serializer and parser, so content that did not\n * come from HTML (JSON, Markdown) is held to exactly the same rules as HTML input\n * (e.g. unsafe link URLs are dropped).\n */\nexport function normalizeDoc(schema: Schema, node: PMNode, doc?: Document): PMNode {\n const d = getDocument(doc);\n const container = d.createElement('div');\n container.appendChild(\n DOMSerializer.fromSchema(schema).serializeFragment(node.content, { document: d }),\n );\n return DOMParser.fromSchema(schema).parse(container);\n}\n\n/** Loads a JSON document, sanitised like HTML input. */\nexport function parseJSON(schema: Schema, json: JSONContent, doc?: Document): PMNode {\n const node = PMNode.fromJSON(schema, json);\n node.check();\n return normalizeDoc(schema, node, doc);\n}\n\nexport function createDoc(schema: Schema, content: Content, doc?: Document): PMNode {\n if (content == null || content === '') return schema.topNodeType.createAndFill()!;\n if (typeof content === 'string') return parseHTML(schema, content, doc);\n return parseJSON(schema, content, doc);\n}\n\nexport function isDocEmpty(node: PMNode): boolean {\n const first = node.firstChild;\n return (\n node.childCount === 0 ||\n (node.childCount === 1 && !!first?.isTextblock && first.content.size === 0)\n );\n}\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyListener = (...args: any[]) => void;\n\nexport class Emitter<Events extends Record<string, unknown[]>> {\n private listeners = new Map<keyof Events, Set<AnyListener>>();\n\n on<E extends keyof Events>(event: E, listener: (...args: Events[E]) => void): () => void {\n let set = this.listeners.get(event);\n if (!set) this.listeners.set(event, (set = new Set()));\n set.add(listener);\n return () => this.off(event, listener);\n }\n\n off<E extends keyof Events>(event: E, listener: (...args: Events[E]) => void): void {\n this.listeners.get(event)?.delete(listener);\n }\n\n emit<E extends keyof Events>(event: E, ...args: Events[E]): void {\n for (const listener of [...(this.listeners.get(event) ?? [])]) listener(...args);\n }\n\n has(event: keyof Events): boolean {\n return (this.listeners.get(event)?.size ?? 0) > 0;\n }\n\n clear(): void {\n this.listeners.clear();\n }\n}\n","import type { MessageKey } from '../messages';\n\n/** Dutch. Terminology follows the Dutch versions of Word and Google Docs. */\nexport const nl = {\n toolbar: 'Opmaak',\n 'toolbar.more': 'Meer',\n editor: 'Teksteditor',\n bold: 'Vet',\n italic: 'Cursief',\n underline: 'Onderstrepen',\n strike: 'Doorhalen',\n code: 'Code',\n heading: 'Tekststijl',\n paragraph: 'Alinea',\n heading1: 'Kop 1',\n heading2: 'Kop 2',\n heading3: 'Kop 3',\n heading4: 'Kop 4',\n bulletList: 'Opsommingslijst',\n orderedList: 'Genummerde lijst',\n blockquote: 'Citaat',\n horizontalRule: 'Horizontale lijn',\n link: 'Link',\n unlink: 'Link verwijderen',\n image: 'Afbeelding',\n 'image.dialog': 'Afbeelding',\n 'image.url': 'Afbeeldings-URL',\n 'image.alt': 'Alternatieve tekst',\n 'image.altHint':\n 'Beschrijf de afbeelding voor wie ze niet kan zien. Laat leeg als ze enkel decoratief is.',\n 'image.upload': 'Uploaden vanaf computer…',\n 'image.uploading': 'Bezig met uploaden van {name}',\n 'image.invalid': 'Voer een geldige afbeeldings-URL in (http of https).',\n 'image.align': 'Uitlijning',\n 'image.alignNone': 'Geen',\n 'image.alignLeft': 'Links',\n 'image.alignCenter': 'Gecentreerd',\n 'image.alignRight': 'Rechts',\n 'image.remove': 'Afbeelding verwijderen',\n table: 'Tabel',\n 'table.insert': 'Tabel invoegen',\n 'table.size': 'Tabelgrootte',\n 'table.cells': '{rows} × {cols}',\n 'table.header': 'Kopregel',\n 'table.addRowBefore': 'Rij erboven invoegen',\n 'table.addRowAfter': 'Rij eronder invoegen',\n 'table.addColumnBefore': 'Kolom links invoegen',\n 'table.addColumnAfter': 'Kolom rechts invoegen',\n 'table.deleteRow': 'Rij verwijderen',\n 'table.deleteColumn': 'Kolom verwijderen',\n 'table.toggleHeaderRow': 'Kopregel aan/uit',\n 'table.delete': 'Tabel verwijderen',\n align: 'Uitlijning',\n alignLeft: 'Links uitlijnen',\n alignCenter: 'Centreren',\n alignRight: 'Rechts uitlijnen',\n alignJustify: 'Uitvullen',\n textColor: 'Tekstkleur',\n highlight: 'Markeren',\n 'color.remove': 'Kleur verwijderen',\n 'highlight.remove': 'Markering verwijderen',\n 'color.gray': 'Grijs',\n 'color.red': 'Rood',\n 'color.orange': 'Oranje',\n 'color.yellow': 'Geel',\n 'color.green': 'Groen',\n 'color.teal': 'Blauwgroen',\n 'color.blue': 'Blauw',\n 'color.violet': 'Violet',\n 'color.pink': 'Roze',\n clearFormatting: 'Opmaak wissen',\n source: 'Broncode',\n 'source.label': 'HTML-broncode',\n undo: 'Ongedaan maken',\n redo: 'Opnieuw',\n 'link.dialog': 'Link bewerken',\n 'link.url': 'URL',\n 'link.newTab': 'Openen in nieuw tabblad',\n 'dialog.apply': 'Toepassen',\n 'dialog.cancel': 'Annuleren',\n 'link.remove': 'Verwijderen',\n 'link.invalid': 'Voer een geldige URL in (http, https, mailto of tel).',\n} satisfies Record<MessageKey, string>;\n","/** English UI strings: the default and the fallback for missing keys in other locales. */\nexport const defaultMessages = {\n toolbar: 'Formatting',\n 'toolbar.more': 'More',\n editor: 'Rich text editor',\n bold: 'Bold',\n italic: 'Italic',\n underline: 'Underline',\n strike: 'Strikethrough',\n code: 'Inline code',\n heading: 'Text style',\n paragraph: 'Paragraph',\n heading1: 'Heading 1',\n heading2: 'Heading 2',\n heading3: 'Heading 3',\n heading4: 'Heading 4',\n bulletList: 'Bulleted list',\n orderedList: 'Numbered list',\n blockquote: 'Quote',\n horizontalRule: 'Horizontal line',\n link: 'Link',\n unlink: 'Remove link',\n image: 'Image',\n 'image.dialog': 'Image',\n 'image.url': 'Image URL',\n 'image.alt': 'Alternative text',\n 'image.altHint':\n 'Describe the image for people who cannot see it. Leave empty if it is decorative.',\n 'image.upload': 'Upload from computer…',\n 'image.uploading': 'Uploading {name}',\n 'image.invalid': 'Enter a valid image URL (http or https).',\n 'image.align': 'Alignment',\n 'image.alignNone': 'None',\n 'image.alignLeft': 'Left',\n 'image.alignCenter': 'Center',\n 'image.alignRight': 'Right',\n 'image.remove': 'Remove image',\n table: 'Table',\n 'table.insert': 'Insert table',\n 'table.size': 'Table size',\n 'table.cells': '{rows} × {cols}',\n 'table.header': 'Header row',\n 'table.addRowBefore': 'Insert row above',\n 'table.addRowAfter': 'Insert row below',\n 'table.addColumnBefore': 'Insert column left',\n 'table.addColumnAfter': 'Insert column right',\n 'table.deleteRow': 'Delete row',\n 'table.deleteColumn': 'Delete column',\n 'table.toggleHeaderRow': 'Toggle header row',\n 'table.delete': 'Delete table',\n align: 'Alignment',\n alignLeft: 'Align left',\n alignCenter: 'Align center',\n alignRight: 'Align right',\n alignJustify: 'Justify',\n textColor: 'Text color',\n highlight: 'Highlight',\n 'color.remove': 'Remove color',\n 'highlight.remove': 'Remove highlight',\n 'color.gray': 'Gray',\n 'color.red': 'Red',\n 'color.orange': 'Orange',\n 'color.yellow': 'Yellow',\n 'color.green': 'Green',\n 'color.teal': 'Teal',\n 'color.blue': 'Blue',\n 'color.violet': 'Violet',\n 'color.pink': 'Pink',\n clearFormatting: 'Clear formatting',\n source: 'Source code',\n 'source.label': 'HTML source',\n undo: 'Undo',\n redo: 'Redo',\n 'link.dialog': 'Edit link',\n 'link.url': 'URL',\n 'link.newTab': 'Open in new tab',\n 'dialog.apply': 'Apply',\n 'dialog.cancel': 'Cancel',\n 'link.remove': 'Remove',\n 'link.invalid': 'Enter a valid URL (http, https, mailto or tel).',\n};\n\nexport type MessageKey = keyof typeof defaultMessages;\nexport type Messages = Partial<Record<MessageKey, string>> & Record<string, string>;\n","import { nl } from './locales/nl';\nimport { defaultMessages, type Messages } from './messages';\n\nconst locales = new Map<string, Messages>([\n ['en', defaultMessages],\n ['nl', nl],\n]);\n\n/** Makes a locale available by code (e.g. `de`, or `pt-br` for a regional variant). */\nexport function registerLocale(code: string, messages: Messages): void {\n locales.set(code.toLowerCase(), messages);\n}\n\n/** Built-in and registered locale codes. */\nexport function availableLocales(): string[] {\n return [...locales.keys()];\n}\n\n/**\n * Finds messages for a code: the exact code first (`nl-be`), then its language\n * (`nl`). Returns the code that matched, or `null` when nothing did.\n */\nexport function findLocale(code: string): { code: string; messages: Messages } | null {\n const normalized = code.toLowerCase().replace('_', '-');\n for (const candidate of [normalized, normalized.split('-')[0]!]) {\n const messages = locales.get(candidate);\n if (messages) return { code: candidate, messages };\n }\n return null;\n}\n\n/** Replaces `{name}` placeholders with values; unknown placeholders are left as-is. */\nexport function interpolate(text: string, params?: Record<string, string | number>): string {\n if (!params) return text;\n return text.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n name in params ? String(params[name]) : match,\n );\n}\n","// Icons are trusted, static markup rendered into toolbar buttons.\nconst svg = (body: string) =>\n `<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\" focusable=\"false\">${body}</svg>`;\n\nexport const icons = {\n bold: '<span class=\"wysio-glyph\" style=\"font-weight:700\">B</span>',\n italic: '<span class=\"wysio-glyph\" style=\"font-style:italic;font-family:Georgia,serif\">I</span>',\n underline: '<span class=\"wysio-glyph\" style=\"text-decoration:underline\">U</span>',\n strike: '<span class=\"wysio-glyph\" style=\"text-decoration:line-through\">S</span>',\n code: svg('<path d=\"m8 7-5 5 5 5M16 7l5 5-5 5\"/>'),\n bulletList: svg(\n '<path d=\"M9 6h11M9 12h11M9 18h11\"/><circle cx=\"4.5\" cy=\"6\" r=\"1\" fill=\"currentColor\"/><circle cx=\"4.5\" cy=\"12\" r=\"1\" fill=\"currentColor\"/><circle cx=\"4.5\" cy=\"18\" r=\"1\" fill=\"currentColor\"/>',\n ),\n orderedList: svg(\n '<path d=\"M10 6h10M10 12h10M10 18h10\"/><path d=\"M4 4h1.5v5M4 9h3\" stroke-width=\"1.5\"/><path d=\"M4 14.5c.4-.8 2.8-.9 2.8.6 0 1.2-2.8 2.2-2.8 3.4h3\" stroke-width=\"1.5\"/>',\n ),\n blockquote: svg('<path d=\"M4 7h5v5c0 3-2 4.5-4 5M14 7h5v5c0 3-2 4.5-4 5\"/>'),\n horizontalRule: svg('<path d=\"M3 12h18\"/>'),\n link: svg(\n '<path d=\"M10 14a4 4 0 0 0 5.66 0l3-3a4 4 0 0 0-5.66-5.66l-1 1\"/><path d=\"M14 10a4 4 0 0 0-5.66 0l-3 3a4 4 0 0 0 5.66 5.66l1-1\"/>',\n ),\n unlink: svg(\n '<path d=\"M10 14a4 4 0 0 0 5.66 0l3-3a4 4 0 0 0-5.66-5.66l-1 1\"/><path d=\"M14 10a4 4 0 0 0-5.66 0l-3 3a4 4 0 0 0 5.66 5.66l1-1\"/><path d=\"M3 3l18 18\"/>',\n ),\n image: svg(\n '<rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\"/><circle cx=\"9\" cy=\"10\" r=\"2\"/><path d=\"m21 16-5-5-9 9\"/>',\n ),\n table: svg(\n '<rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\"/><path d=\"M3 10h18M3 15h18M9 4v16M15 4v16\"/>',\n ),\n tableRowBefore: svg('<path d=\"M3 14h18v6H3zM3 17h18M12 3v7M8.5 6.5h7\"/>'),\n tableRowAfter: svg('<path d=\"M3 4h18v6H3zM3 7h18M12 14v7M8.5 17.5h7\"/>'),\n tableColumnBefore: svg('<path d=\"M14 3h6v18h-6zM17 3v18M3 12h7M6.5 8.5v7\"/>'),\n tableColumnAfter: svg('<path d=\"M4 3h6v18H4zM7 3v18M14 12h7M17.5 8.5v7\"/>'),\n tableDeleteRow: svg('<path d=\"M3 9h18v6H3zM9 9v6M15 9v6M8 4l8 0M8 20h8\"/>'),\n tableDeleteColumn: svg('<path d=\"M9 3h6v18H9zM9 9h6M9 15h6M4 8v8M20 8v8\"/>'),\n tableHeaderRow: svg(\n '<rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\"/><path d=\"M3 10h18M9 10v10M15 10v10\"/><path d=\"M3 6h18\" stroke-width=\"4\"/>',\n ),\n tableDelete: svg(\n '<rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\"/><path d=\"m9 9 6 6M15 9l-6 6\"/>',\n ),\n alignLeft: svg('<path d=\"M4 6h16M4 10h10M4 14h16M4 18h10\"/>'),\n alignCenter: svg('<path d=\"M4 6h16M7 10h10M4 14h16M7 18h10\"/>'),\n alignRight: svg('<path d=\"M4 6h16M10 10h10M4 14h16M10 18h10\"/>'),\n alignJustify: svg('<path d=\"M4 6h16M4 10h16M4 14h16M4 18h16\"/>'),\n textColor: svg(\n '<path d=\"m6 16 6-12 6 12M8.5 11h7\"/><path d=\"M4 20h16\" stroke-width=\"3\" stroke=\"var(--wysio-icon-accent, currentColor)\"/>',\n ),\n highlight: svg(\n '<path d=\"m9 11-5 5v3h3l5-5M9 11l4-4 4 4-4 4zM13 7l2-2a1.4 1.4 0 0 1 2 0l2 2a1.4 1.4 0 0 1 0 2l-2 2\"/><path d=\"M14 20h6\" stroke-width=\"3\" stroke=\"var(--wysio-icon-accent, currentColor)\"/>',\n ),\n clearFormatting: svg('<path d=\"M6 5h11M11.5 5 8 19M4 4l16 16\"/><path d=\"M12 19h3\"/>'),\n source: svg(\n '<rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\"/><path d=\"m10 9-3 3 3 3M14 9l3 3-3 3\"/>',\n ),\n undo: svg('<path d=\"M9 14 4 9l5-5\"/><path d=\"M4 9h10.5a5.5 5.5 0 0 1 0 11H11\"/>'),\n redo: svg('<path d=\"m15 14 5-5-5-5\"/><path d=\"M20 9H9.5a5.5 5.5 0 0 0 0 11H13\"/>'),\n};\n","import type { Editor } from '../editor';\n\nlet popoverCount = 0;\n\n/**\n * Small dialog anchored to a document position inside the editor. Handles Escape,\n * clicks outside, focus restore and positioning; subclasses provide the content.\n */\nexport class Popover {\n readonly dom: HTMLElement;\n /** Set by `getPopover`; toolbar buttons with the same `popover` key track it. */\n key = '';\n /** Unique prefix for element ids inside this popover. */\n protected readonly uid = `wysio-pop-${++popoverCount}`;\n\n constructor(\n protected readonly editor: Editor,\n label: string,\n ) {\n this.dom = editor.dom.ownerDocument.createElement('div');\n this.dom.className = 'wysio-popover';\n this.dom.setAttribute('role', 'dialog');\n if (editor.locale) this.dom.lang = editor.locale;\n this.dom.setAttribute('aria-label', label);\n this.dom.hidden = true;\n // Non-modal: tabbing (or clicking) out of the popover closes it.\n this.dom.addEventListener('focusout', (e) => {\n const next = e.relatedTarget as Node | null;\n if (next && !this.dom.contains(next)) this.close(false);\n });\n this.dom.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') {\n e.preventDefault();\n e.stopPropagation();\n this.close();\n }\n });\n editor.dom.appendChild(this.dom);\n }\n\n get isOpen(): boolean {\n return !this.dom.hidden;\n }\n\n /** Shows the popover below document position `pos` and focuses `focus`. */\n protected show(pos: number, focus: HTMLElement): void {\n this.dom.hidden = false;\n this.notify(true);\n this.position(pos);\n this.editor.dom.ownerDocument.addEventListener('mousedown', this.onOutside, true);\n focus.focus();\n }\n\n close(restoreFocus = true): void {\n if (!this.isOpen) return;\n this.dom.hidden = true;\n this.editor.dom.ownerDocument.removeEventListener('mousedown', this.onOutside, true);\n this.notify(false);\n // Back to the text, also when the popover was opened from the toolbar.\n if (restoreFocus) this.editor.focus();\n }\n\n /** Announces open/close on the editor root (`wysio:popover`), e.g. for aria-expanded. */\n private notify(open: boolean): void {\n this.editor.dom.dispatchEvent(\n new CustomEvent('wysio:popover', { detail: { key: this.key, open } }),\n );\n }\n\n destroy(): void {\n this.close(false);\n this.dom.remove();\n }\n\n private position(pos: number): void {\n const { view } = this.editor;\n try {\n const coords = view.coordsAtPos(Math.min(pos, view.state.doc.content.size));\n const box = this.editor.dom.getBoundingClientRect();\n const left = Math.max(0, Math.min(coords.left - box.left, box.width - this.dom.offsetWidth));\n this.dom.style.left = `${left}px`;\n this.dom.style.top = `${coords.bottom - box.top + 6}px`;\n } catch {\n // Layout is unavailable (e.g. jsdom); keep the CSS default position.\n }\n }\n\n private onOutside = (e: MouseEvent) => {\n if (!this.dom.contains(e.target as Node)) this.close(false);\n };\n}\n\nconst registry = new WeakMap<Editor, Map<string, Popover>>();\n\n/** One popover instance per editor and key, destroyed together with the editor. */\nexport function getPopover<T extends Popover>(editor: Editor, key: string, create: () => T): T {\n let map = registry.get(editor);\n if (!map) {\n const created = new Map<string, Popover>();\n registry.set(editor, (map = created));\n editor.on('destroy', () => {\n for (const popover of created.values()) popover.destroy();\n registry.delete(editor);\n });\n }\n let popover = map.get(key) as T | undefined;\n if (!popover) {\n popover = create();\n popover.key = key;\n map.set(key, popover);\n }\n return popover;\n}\n\n/** Builds a form from trusted markup; `{id}` in the template is replaced by the popover uid. */\nexport function createForm(doc: Document, uid: string, template: string): HTMLFormElement {\n const form = doc.createElement('form');\n form.noValidate = true;\n form.innerHTML = template.replaceAll('{id}', uid);\n return form;\n}\n\nexport function query<T extends Element>(root: ParentNode, selector: string): T {\n const el = root.querySelector<T>(selector);\n if (!el) throw new Error(`[wysio] Missing element ${selector}`);\n return el;\n}\n","import type { EditorState } from 'prosemirror-state';\nimport type { Editor } from '../editor';\nimport { Popover } from './popover';\n\nexport interface MenuItem {\n id: string;\n label: string;\n /** Trusted HTML. */\n icon?: string;\n run: (editor: Editor) => void;\n isActive?: (state: EditorState) => boolean;\n isEnabled?: (state: EditorState) => boolean;\n}\n\n/** A vertical list of actions in a popover, navigable with the arrow keys. */\nexport class MenuPopover extends Popover {\n private buttons: { button: HTMLButtonElement; item: MenuItem }[] = [];\n\n constructor(editor: Editor, label: string, items: MenuItem[]) {\n super(editor, label);\n const doc = editor.dom.ownerDocument;\n const list = doc.createElement('div');\n list.className = 'wysio-menu';\n for (const item of items) {\n const button = doc.createElement('button');\n button.type = 'button';\n button.className = 'wysio-menu-item';\n button.dataset.action = item.id;\n button.innerHTML = item.icon ?? '';\n button.append(doc.createTextNode(item.label));\n if (item.isActive) button.setAttribute('aria-pressed', 'false');\n button.addEventListener('click', () => {\n this.close(false);\n item.run(this.editor);\n });\n list.appendChild(button);\n this.buttons.push({ button, item });\n }\n list.addEventListener('keydown', this.onKey);\n this.dom.appendChild(list);\n }\n\n open(): void {\n const { state } = this.editor.view;\n for (const { button, item } of this.buttons) {\n button.disabled = item.isEnabled ? !item.isEnabled(state) : false;\n if (item.isActive) button.setAttribute('aria-pressed', String(item.isActive(state)));\n }\n const enabled = this.buttons.filter((b) => !b.button.disabled);\n const focus =\n enabled.find((b) => b.button.getAttribute('aria-pressed') === 'true') ?? enabled[0];\n this.show(state.selection.from, focus?.button ?? this.dom);\n }\n\n private onKey = (e: KeyboardEvent) => {\n const buttons = this.buttons.map((b) => b.button).filter((b) => !b.disabled);\n const index = buttons.indexOf(e.target as HTMLButtonElement);\n let next: number | null = null;\n if (e.key === 'ArrowDown') next = (index + 1) % buttons.length;\n else if (e.key === 'ArrowUp') next = (index - 1 + buttons.length) % buttons.length;\n else if (e.key === 'Home') next = 0;\n else if (e.key === 'End') next = buttons.length - 1;\n if (next === null) return;\n e.preventDefault();\n buttons[next]?.focus();\n };\n}\n","import type { DOMOutputSpec, Node as PMNode, NodeSpec, TagParseRule } from 'prosemirror-model';\nimport type { Command, EditorState } from 'prosemirror-state';\nimport type { Editor } from '../editor';\nimport { icons } from '../icons';\nimport { definePlugin, type ToolbarButton } from '../plugin';\nimport { MenuPopover } from '../ui/menu';\nimport { getPopover } from '../ui/popover';\n\nexport const ALIGNMENTS = ['left', 'center', 'right', 'justify'] as const;\nexport type Alignment = (typeof ALIGNMENTS)[number];\n\n/** Nodes that get an `align` attribute. */\nconst ALIGNABLE = ['paragraph', 'heading'];\n\n/** Stored value: left is the default and stored as `null`. */\nconst toStored = (value: unknown): Exclude<Alignment, 'left'> | null =>\n value === 'center' || value === 'right' || value === 'justify' ? value : null;\n\n/** Reads alignment from our class, an inline `text-align` (TinyMCE) or the legacy `align` attribute. */\nfunction readAlign(dom: HTMLElement): Alignment | null {\n for (const align of ALIGNMENTS) {\n if (dom.classList.contains(`wysio-align-${align}`)) return align;\n }\n const value = (dom.style.textAlign || dom.getAttribute('align') || '').toLowerCase();\n return ALIGNMENTS.includes(value as Alignment) ? (value as Alignment) : null;\n}\n\nfunction addClass(out: DOMOutputSpec, className: string): DOMOutputSpec {\n if (!Array.isArray(out)) return out;\n const [tag, second, ...rest] = out as unknown[];\n const isAttrs =\n second !== null &&\n typeof second === 'object' &&\n !Array.isArray(second) &&\n !(typeof Node !== 'undefined' && second instanceof Node);\n if (isAttrs) {\n const attrs = { ...(second as Record<string, string>) };\n attrs.class = attrs.class ? `${attrs.class} ${className}` : className;\n return [tag, attrs, ...rest] as unknown as DOMOutputSpec;\n }\n return [\n tag,\n { class: className },\n ...(second === undefined ? [] : [second]),\n ...rest,\n ] as unknown as DOMOutputSpec;\n}\n\n/** Adds an `align` attribute to a textblock spec: parsed from HTML, output as a class. */\nfunction withAlign(spec: NodeSpec): NodeSpec {\n const toDOM = spec.toDOM;\n return {\n ...spec,\n attrs: { ...spec.attrs, align: { default: null, validate: 'string|null' } },\n parseDOM: spec.parseDOM?.map((rule) => {\n if (!('tag' in rule)) return rule;\n const tagRule = rule as TagParseRule;\n return {\n ...tagRule,\n attrs: undefined,\n getAttrs: (dom: HTMLElement) => {\n const base = tagRule.getAttrs ? tagRule.getAttrs(dom) : null;\n if (base === false) return false;\n return { ...tagRule.attrs, ...base, align: toStored(readAlign(dom)) };\n },\n } as TagParseRule;\n }),\n toDOM: toDOM\n ? (node: PMNode) => {\n const out = toDOM(node);\n const align = toStored(node.attrs.align);\n return align ? addClass(out, `wysio-align-${align}`) : out;\n }\n : undefined,\n };\n}\n\n/** Textblocks in the selection that support alignment, with their positions. */\nfunction alignableBlocks(state: EditorState): { node: PMNode; pos: number }[] {\n const blocks: { node: PMNode; pos: number }[] = [];\n for (const { $from, $to } of state.selection.ranges) {\n state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {\n if (node.isTextblock && 'align' in node.type.spec.attrs!) blocks.push({ node, pos });\n return !node.isTextblock;\n });\n }\n return blocks;\n}\n\nexport function setAlignment(align: Alignment): Command {\n return (state, dispatch) => {\n const blocks = alignableBlocks(state);\n if (!blocks.length) return false;\n if (dispatch) {\n const tr = state.tr;\n const value = toStored(align);\n for (const { node, pos } of blocks)\n tr.setNodeMarkup(pos, undefined, { ...node.attrs, align: value });\n dispatch(tr.scrollIntoView());\n }\n return true;\n };\n}\n\nexport function isAlignmentActive(state: EditorState, align: Alignment): boolean {\n const blocks = alignableBlocks(state);\n return (\n blocks.length > 0 &&\n blocks.every(({ node }) => (toStored(node.attrs.align) ?? 'left') === align)\n );\n}\n\nconst SHORTCUTS: Record<Alignment, string> = {\n left: 'Mod-Shift-l',\n center: 'Mod-Shift-e',\n right: 'Mod-Shift-r',\n justify: 'Mod-Shift-j',\n};\n\nconst itemName = (align: Alignment) => `align${align[0]!.toUpperCase()}${align.slice(1)}`;\n\n/** Opens the alignment menu. */\nexport function openAlignmentMenu(editor: Editor): void {\n if (!editor.isEditable) return;\n getPopover(\n editor,\n 'alignment',\n () =>\n new MenuPopover(\n editor,\n editor.t('align'),\n ALIGNMENTS.map((align) => ({\n id: itemName(align),\n label: editor.t(itemName(align)),\n icon: icons[itemName(align) as keyof typeof icons],\n run: (ed) => ed.exec(setAlignment(align)),\n isActive: (state) => isAlignmentActive(state, align),\n isEnabled: (state) => setAlignment(align)(state),\n })),\n ),\n ).open();\n}\n\nexport const alignment = definePlugin({\n name: 'alignment',\n schema: {\n extendNodes: Object.fromEntries(ALIGNABLE.map((name) => [name, withAlign])),\n },\n keymap: () =>\n Object.fromEntries(ALIGNMENTS.map((align) => [SHORTCUTS[align], setAlignment(align)])),\n toolbarItems: ({ editor }) => {\n const items: Record<string, ToolbarButton> = {\n align: {\n label: editor.t('align'),\n icon: icons.alignLeft,\n run: openAlignmentMenu,\n popover: 'alignment',\n dropdown: true,\n // Show the current alignment, like word processors do.\n render: (state, button) => {\n const current = ALIGNMENTS.find((a) => isAlignmentActive(state, a)) ?? 'left';\n button.setIcon(icons[itemName(current) as keyof typeof icons]);\n },\n isActive: (state) => ALIGNMENTS.slice(1).some((a) => isAlignmentActive(state, a)),\n isEnabled: (state) => setAlignment('left')(state),\n },\n };\n for (const align of ALIGNMENTS) {\n items[itemName(align)] = {\n label: editor.t(itemName(align)),\n icon: icons[itemName(align) as keyof typeof icons],\n shortcut: SHORTCUTS[align],\n command: setAlignment(align),\n isActive: (state) => isAlignmentActive(state, align),\n };\n }\n return items;\n },\n});\n","import { dropCursor } from 'prosemirror-dropcursor';\nimport { gapCursor } from 'prosemirror-gapcursor';\nimport { definePlugin } from '../plugin';\n\n/**\n * The document, paragraphs and text. Always first: paragraph is the default block.\n * Also adds the gap cursor (to reach positions next to tables, rules and images)\n * and the drop cursor.\n */\nexport const base = definePlugin({\n name: 'base',\n schema: {\n nodes: {\n doc: { content: 'block+' },\n paragraph: {\n content: 'inline*',\n group: 'block',\n parseDOM: [{ tag: 'p' }],\n toDOM: () => ['p', 0],\n },\n text: { group: 'inline' },\n },\n },\n prosemirrorPlugins: () => [gapCursor(), dropCursor({ class: 'wysio-dropcursor' })],\n});\n","import type { Mark, MarkType, NodeType, ResolvedPos } from 'prosemirror-model';\nimport { lift, wrapIn } from 'prosemirror-commands';\nimport { liftListItem, wrapInList } from 'prosemirror-schema-list';\nimport type { Command, EditorState } from 'prosemirror-state';\n\nexport function isMarkActive(state: EditorState, type: MarkType): boolean {\n const { from, to, empty, $from } = state.selection;\n if (empty) return !!type.isInSet(state.storedMarks ?? $from.marks());\n return state.doc.rangeHasMark(from, to, type);\n}\n\n/** Nearest ancestor of the selection start whose type is one of `types`. */\nexport function findAncestor(state: EditorState, types: readonly NodeType[]) {\n const { $from } = state.selection;\n for (let depth = $from.depth; depth > 0; depth--) {\n const node = $from.node(depth);\n if (types.includes(node.type)) return { node, depth, pos: $from.before(depth) };\n }\n return null;\n}\n\n/** Toggles between `listType`, the other list type(s) and no list. */\nexport function toggleList(listType: NodeType, itemType: NodeType, listTypes: NodeType[]): Command {\n return (state, dispatch) => {\n const list = findAncestor(state, listTypes);\n if (!list) return wrapInList(listType)(state, dispatch);\n if (list.node.type === listType) return liftListItem(itemType)(state, dispatch);\n if (dispatch) dispatch(state.tr.setNodeMarkup(list.pos, listType).scrollIntoView());\n return true;\n };\n}\n\nexport function toggleWrap(type: NodeType): Command {\n return (state, dispatch) =>\n findAncestor(state, [type]) ? lift(state, dispatch) : wrapIn(type)(state, dispatch);\n}\n\n/** The full extent of the mark of `type` around `$pos`, if any. */\nexport function getMarkRange(\n $pos: ResolvedPos,\n type: MarkType,\n): { from: number; to: number; mark: Mark } | null {\n const parent = $pos.parent;\n let found = parent.childAfter($pos.parentOffset);\n let mark = found.node ? type.isInSet(found.node.marks) : undefined;\n if (!mark) {\n found = parent.childBefore($pos.parentOffset);\n mark = found.node ? type.isInSet(found.node.marks) : undefined;\n if (!mark || !found.node) return null;\n }\n const start = $pos.start();\n let startIndex = found.index;\n let from = start + found.offset;\n while (startIndex > 0 && mark.isInSet(parent.child(startIndex - 1).marks)) {\n startIndex--;\n from -= parent.child(startIndex).nodeSize;\n }\n let endIndex = found.index + 1;\n let to = start + found.offset + parent.child(found.index).nodeSize;\n while (endIndex < parent.childCount && mark.isInSet(parent.child(endIndex).marks)) {\n to += parent.child(endIndex).nodeSize;\n endIndex++;\n }\n return { from, to, mark };\n}\n","import { chainCommands, exitCode } from 'prosemirror-commands';\nimport { InputRule, wrappingInputRule } from 'prosemirror-inputrules';\nimport type { Command } from 'prosemirror-state';\nimport { findAncestor, toggleWrap } from '../commands';\nimport { icons } from '../icons';\nimport { definePlugin } from '../plugin';\n\nexport const blockquote = definePlugin({\n name: 'blockquote',\n schema: {\n nodes: {\n blockquote: {\n content: 'block+',\n group: 'block',\n defining: true,\n parseDOM: [{ tag: 'blockquote' }],\n toDOM: () => ['blockquote', 0],\n },\n },\n },\n keymap: ({ schema }) => ({ 'Mod-Shift-b': toggleWrap(schema.nodes.blockquote!) }),\n inputRules: ({ schema }) => [wrappingInputRule(/^\\s*>\\s$/, schema.nodes.blockquote!)],\n toolbarItems: ({ schema, editor }) => {\n const type = schema.nodes.blockquote!;\n return {\n blockquote: {\n label: editor.t('blockquote'),\n icon: icons.blockquote,\n shortcut: 'Mod-Shift-b',\n command: toggleWrap(type),\n isActive: (state) => !!findAncestor(state, [type]),\n },\n };\n },\n});\n\nexport const horizontalRule = definePlugin({\n name: 'horizontalRule',\n schema: {\n nodes: {\n horizontal_rule: {\n group: 'block',\n parseDOM: [{ tag: 'hr' }],\n toDOM: () => ['hr'],\n },\n },\n },\n inputRules: ({ schema }) => [\n new InputRule(/^(?:---|___|\\*\\*\\*)$/, (state, _match, start, end) => {\n const $start = state.doc.resolve(start);\n const hr = schema.nodes.horizontal_rule!.create();\n if (!$start.parent.isTextblock || $start.parent.content.size !== end - start + 1) return null;\n return state.tr.replaceRangeWith($start.before(), $start.after(), hr).scrollIntoView();\n }),\n ],\n toolbarItems: ({ schema, editor }) => {\n const type = schema.nodes.horizontal_rule!;\n const insert: Command = (state, dispatch) => {\n if (\n !state.selection.$from.parent.canReplaceWith(0, 0, type) &&\n !state.selection.$from.parent.isTextblock\n ) {\n return false;\n }\n if (dispatch) dispatch(state.tr.replaceSelectionWith(type.create()).scrollIntoView());\n return true;\n };\n return {\n horizontalRule: {\n label: editor.t('horizontalRule'),\n icon: icons.horizontalRule,\n command: insert,\n },\n };\n },\n});\n\nexport const hardBreak = definePlugin({\n name: 'hardBreak',\n schema: {\n nodes: {\n hard_break: {\n inline: true,\n group: 'inline',\n selectable: false,\n parseDOM: [{ tag: 'br' }],\n toDOM: () => ['br'],\n },\n },\n },\n keymap: ({ schema }) => {\n const type = schema.nodes.hard_break!;\n const insert: Command = (state, dispatch) => {\n if (dispatch) dispatch(state.tr.replaceSelectionWith(type.create()).scrollIntoView());\n return true;\n };\n const cmd = chainCommands(exitCode, insert);\n return { 'Shift-Enter': cmd, 'Mod-Enter': cmd };\n },\n});\n","import type { Command } from 'prosemirror-state';\nimport { icons } from '../icons';\nimport { definePlugin } from '../plugin';\n\n/** Block attributes that count as formatting and are reset by {@link clearFormatting}. */\nexport const FORMATTING_ATTRIBUTES = ['align'];\n\n/** Marks that are content rather than formatting and are kept. */\nconst KEEP_MARKS = new Set(['link']);\n\n/**\n * Removes all formatting marks (links are kept) and resets formatting attributes such\n * as alignment on the blocks in the selection. Returns false when there is nothing to clear.\n */\nexport const clearFormatting: Command = (state, dispatch) => {\n const tr = state.tr;\n let changed = false;\n const marks = Object.values(state.schema.marks).filter((type) => !KEEP_MARKS.has(type.name));\n\n const resetBlock = (pos: number) => {\n const node = tr.doc.nodeAt(pos);\n if (!node) return;\n const reset: Record<string, unknown> = {};\n for (const attr of FORMATTING_ATTRIBUTES) {\n if (attr in node.type.spec.attrs! && node.attrs[attr] != null) reset[attr] = null;\n }\n if (Object.keys(reset).length) {\n tr.setNodeMarkup(pos, undefined, { ...node.attrs, ...reset });\n changed = true;\n }\n };\n\n for (const { $from, $to } of state.selection.ranges) {\n const from = $from.pos;\n const to = $to.pos;\n for (const type of marks) {\n if (from < to && state.doc.rangeHasMark(from, to, type)) {\n tr.removeMark(from, to, type);\n changed = true;\n }\n }\n if (from === to) {\n if ($from.depth > 0) resetBlock($from.before());\n } else {\n state.doc.nodesBetween(from, to, (node, pos) => {\n if (node.isTextblock) resetBlock(pos);\n return !node.isTextblock;\n });\n }\n }\n\n if (state.selection.empty) {\n const stored = state.storedMarks ?? state.selection.$from.marks();\n if (stored.some((m) => !KEEP_MARKS.has(m.type.name))) {\n tr.setStoredMarks(stored.filter((m) => KEEP_MARKS.has(m.type.name)));\n changed = true;\n }\n }\n\n if (!changed) return false;\n if (dispatch) dispatch(tr.scrollIntoView());\n return true;\n};\n\nexport const clearFormattingPlugin = definePlugin({\n name: 'clearFormatting',\n keymap: () => ({ 'Mod-\\\\': clearFormatting }),\n toolbarItems: ({ editor }) => ({\n clearFormatting: {\n label: editor.t('clearFormatting'),\n icon: icons.clearFormatting,\n shortcut: 'Mod-\\\\',\n command: clearFormatting,\n },\n }),\n});\n","import { toggleMark } from 'prosemirror-commands';\nimport type { MarkType } from 'prosemirror-model';\nimport type { Command, EditorState } from 'prosemirror-state';\nimport type { Editor } from '../editor';\nimport { icons } from '../icons';\nimport { definePlugin, type WysioPlugin } from '../plugin';\nimport { getPopover, Popover } from '../ui/popover';\n\nexport interface PaletteColor {\n /**\n * Identifier (`a-z`, digits, `-`): used in the class (`wysio-color-{name}`) and for the\n * label (`color.{name}` message, or the name itself).\n */\n name: string;\n /** Hex colour: `#rgb` or `#rrggbb`. */\n value: string;\n /** Label override. */\n label?: string;\n}\n\nexport interface ColorOptions {\n /** The only colours that are accepted, in picker order. */\n colors?: readonly PaletteColor[];\n}\n\nexport const DEFAULT_TEXT_COLORS: readonly PaletteColor[] = [\n { name: 'gray', value: '#868e96' },\n { name: 'red', value: '#e03131' },\n { name: 'orange', value: '#e8590c' },\n { name: 'green', value: '#2f9e44' },\n { name: 'teal', value: '#0c8599' },\n { name: 'blue', value: '#1971c2' },\n { name: 'violet', value: '#6741d9' },\n { name: 'pink', value: '#c2255c' },\n];\n\nexport const DEFAULT_HIGHLIGHT_COLORS: readonly PaletteColor[] = [\n { name: 'yellow', value: '#ffec99' },\n { name: 'green', value: '#b2f2bb' },\n { name: 'blue', value: '#a5d8ff' },\n { name: 'pink', value: '#fcc2d7' },\n { name: 'orange', value: '#ffd8a8' },\n { name: 'violet', value: '#d0bfff' },\n { name: 'red', value: '#ffc9c9' },\n { name: 'gray', value: '#e9ecef' },\n];\n\nconst hex2 = (n: number) => n.toString(16).padStart(2, '0');\n\n/** `#abc`, `#aabbcc` or `rgb(…)`/`rgba(…, 1)` → `#aabbcc`; anything else → `null`. */\nexport function normalizeColor(value: unknown): string | null {\n if (typeof value !== 'string') return null;\n const v = value.trim().toLowerCase();\n let m = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(v);\n if (m) return `#${m[1]}${m[1]}${m[2]}${m[2]}${m[3]}${m[3]}`;\n if (/^#[0-9a-f]{6}$/.test(v)) return v;\n m = /^rgba?\\(\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*(?:,\\s*(1|1\\.0+)\\s*)?\\)$/.exec(v);\n if (m) {\n const parts = [m[1], m[2], m[3]].map(Number);\n if (parts.every((n) => n <= 255)) return `#${parts.map(hex2).join('')}`;\n }\n return null;\n}\n\nconst NAME = /^[a-z][a-z0-9-]*$/;\n\nfunction createPalette(colors: readonly PaletteColor[]) {\n const entries = colors.map((c) => {\n const value = normalizeColor(c.value);\n if (!value || !NAME.test(c.name)) {\n throw new Error(`[wysio] Invalid palette colour \"${c.name}\" (${c.value}).`);\n }\n return { ...c, value };\n });\n const byName = new Map(entries.map((c) => [c.name, c]));\n const byValue = new Map(entries.map((c) => [c.value, c.name]));\n return {\n colors: entries,\n /** The palette name for a stored name, or null. */\n name: (value: unknown) => (typeof value === 'string' && byName.has(value) ? value : null),\n /** The palette name for a CSS colour value, or null when it is not in the palette. */\n fromCSS: (value: unknown) => byValue.get(normalizeColor(value) ?? '') ?? null,\n /** The palette name in a `{prefix}{name}` class on the element, or null. */\n fromClass: (el: HTMLElement, prefix: string) => {\n for (const cls of el.classList) {\n if (cls.startsWith(prefix) && byName.has(cls.slice(prefix.length))) {\n return cls.slice(prefix.length);\n }\n }\n return null;\n },\n value: (name: string) => byName.get(name)?.value ?? null,\n };\n}\n\n/**\n * CSS rules for a custom palette, for pages that display editor content (and for the\n * editor itself). The default palettes are already in `wysio/style.css`.\n */\nexport function paletteCSS(kind: 'text' | 'highlight', colors: readonly PaletteColor[]): string {\n const palette = createPalette(colors);\n return palette.colors\n .map((c) =>\n kind === 'text'\n ? `.wysio-color-${c.name} { color: ${c.value}; }`\n : `.wysio-highlight-${c.name} { background-color: ${c.value}; }`,\n )\n .join('\\n');\n}\n\ntype Palette = ReturnType<typeof createPalette>;\n\n/** Colours the bar under the toolbar icon with the colour at the selection. */\nfunction showColor(el: HTMLElement, palette: Palette, name: string | null): void {\n const value = name ? palette.value(name) : null;\n if (value) el.style.setProperty('--wysio-icon-accent', value);\n else el.style.removeProperty('--wysio-icon-accent');\n}\n\nexport function setColorMark(type: MarkType, color: string): Command {\n return (state, dispatch) => {\n if (!toggleMark(type)(state)) return false;\n if (dispatch) {\n const mark = type.create({ color });\n const tr = state.tr;\n if (state.selection.empty) tr.addStoredMark(mark);\n else\n for (const { $from, $to } of state.selection.ranges) tr.addMark($from.pos, $to.pos, mark);\n dispatch(tr.scrollIntoView());\n }\n return true;\n };\n}\n\nexport function removeColorMark(type: MarkType): Command {\n return (state, dispatch) => {\n if (dispatch) {\n const tr = state.tr;\n if (state.selection.empty) tr.removeStoredMark(type);\n else\n for (const { $from, $to } of state.selection.ranges)\n tr.removeMark($from.pos, $to.pos, type);\n dispatch(tr.scrollIntoView());\n }\n return true;\n };\n}\n\n/** The colour name of `type` at the selection, when it is the same everywhere. */\nexport function activeColor(state: EditorState, type: MarkType): string | null {\n const { empty, $from, from, to } = state.selection;\n if (empty)\n return (type.isInSet(state.storedMarks ?? $from.marks())?.attrs.color as string) ?? null;\n let color: string | null | undefined;\n let mixed = false;\n state.doc.nodesBetween(from, to, (node) => {\n if (!node.isText) return;\n const c = (type.isInSet(node.marks)?.attrs.color as string | undefined) ?? null;\n if (color === undefined) color = c;\n else if (color !== c) mixed = true;\n });\n return mixed ? null : (color ?? null);\n}\n\nconst colorLabel = (editor: Editor, color: PaletteColor) => {\n if (color.label) return color.label;\n const key = `color.${color.name}`;\n const text = editor.t(key);\n return text === key ? color.name : text;\n};\n\nconst COLUMNS = 4;\n\nclass PalettePopover extends Popover {\n private swatches: { button: HTMLButtonElement; value: string }[] = [];\n\n constructor(\n editor: Editor,\n label: string,\n private type: MarkType,\n palette: Palette,\n removeLabel: string,\n swatchStyle: 'text' | 'background',\n ) {\n super(editor, label);\n const doc = editor.dom.ownerDocument;\n const grid = doc.createElement('div');\n grid.className = 'wysio-palette';\n grid.setAttribute('role', 'group');\n grid.setAttribute('aria-label', label);\n for (const color of palette.colors) {\n const button = doc.createElement('button');\n button.type = 'button';\n button.className = `wysio-swatch wysio-swatch-${swatchStyle}`;\n button.style.setProperty('--wysio-swatch', color.value);\n button.setAttribute('aria-label', colorLabel(editor, color));\n button.title = colorLabel(editor, color);\n button.setAttribute('aria-pressed', 'false');\n button.tabIndex = -1;\n if (swatchStyle === 'text') button.textContent = 'A';\n button.addEventListener('click', () => this.apply(color.name));\n grid.appendChild(button);\n this.swatches.push({ button, value: color.name });\n }\n grid.addEventListener('keydown', this.onKey);\n\n const remove = doc.createElement('button');\n remove.type = 'button';\n remove.className = 'wysio-button wysio-palette-remove';\n remove.dataset.action = 'remove';\n remove.textContent = removeLabel;\n remove.addEventListener('click', () => {\n this.close(false);\n this.editor.exec(removeColorMark(this.type));\n });\n this.dom.append(grid, remove);\n }\n\n open(): void {\n const { state } = this.editor.view;\n const current = activeColor(state, this.type);\n let focus = this.swatches[0];\n for (const swatch of this.swatches) {\n const on = swatch.value === current;\n swatch.button.setAttribute('aria-pressed', String(on));\n if (on) focus = swatch;\n }\n for (const swatch of this.swatches) swatch.button.tabIndex = swatch === focus ? 0 : -1;\n this.show(state.selection.from, focus?.button ?? this.dom);\n }\n\n private apply(name: string): void {\n this.close(false);\n this.editor.exec(setColorMark(this.type, name));\n }\n\n private onKey = (e: KeyboardEvent) => {\n const buttons = this.swatches.map((s) => s.button);\n const index = buttons.indexOf(e.target as HTMLButtonElement);\n if (index === -1) return;\n const moves: Record<string, number> = {\n ArrowRight: 1,\n ArrowLeft: -1,\n ArrowDown: COLUMNS,\n ArrowUp: -COLUMNS,\n };\n let next: number | null = null;\n if (e.key in moves) next = Math.min(buttons.length - 1, Math.max(0, index + moves[e.key]!));\n else if (e.key === 'Home') next = 0;\n else if (e.key === 'End') next = buttons.length - 1;\n if (next === null) return;\n e.preventDefault();\n buttons.forEach((b, i) => (b.tabIndex = i === next ? 0 : -1));\n buttons[next]?.focus();\n };\n}\n\n/** Text colour, limited to a palette. Output: `<span class=\"wysio-color-{name}\">`. */\nexport function textColor(options: ColorOptions = {}): WysioPlugin {\n const palette = createPalette(options.colors ?? DEFAULT_TEXT_COLORS);\n return definePlugin({\n name: 'textColor',\n schema: {\n marks: {\n text_color: {\n attrs: { color: { validate: 'string' } },\n parseDOM: [\n {\n tag: 'span',\n getAttrs: (dom) => {\n const color = palette.fromClass(dom as HTMLElement, 'wysio-color-');\n return color ? { color } : false;\n },\n },\n {\n style: 'color',\n getAttrs: (value) => {\n const color = palette.fromCSS(value);\n return color ? { color } : false;\n },\n },\n ],\n toDOM: (mark) => {\n const color = palette.name(mark.attrs.color);\n return ['span', color ? { class: `wysio-color-${color}` } : {}, 0];\n },\n },\n },\n },\n toolbarItems: ({ schema, editor }) => {\n const type = schema.marks.text_color!;\n return {\n textColor: {\n label: editor.t('textColor'),\n icon: icons.textColor,\n popover: 'textColor',\n dropdown: true,\n render: (state, button) => showColor(button.el, palette, activeColor(state, type)),\n run: (ed) =>\n getPopover(\n ed,\n 'textColor',\n () =>\n new PalettePopover(\n ed,\n ed.t('textColor'),\n type,\n palette,\n ed.t('color.remove'),\n 'text',\n ),\n ).open(),\n isActive: (state) => activeColor(state, type) !== null,\n isEnabled: (state) => toggleMark(type)(state),\n },\n };\n },\n });\n}\n\n/** Highlight, limited to a palette. Output: `<mark class=\"wysio-highlight-{name}\">`. */\nexport function highlight(options: ColorOptions = {}): WysioPlugin {\n const palette = createPalette(options.colors ?? DEFAULT_HIGHLIGHT_COLORS);\n const fallback = palette.colors[0]?.name;\n return definePlugin({\n name: 'highlight',\n schema: {\n marks: {\n highlight: {\n attrs: { color: { validate: 'string' } },\n parseDOM: [\n {\n tag: 'mark',\n getAttrs: (dom) => {\n const el = dom as HTMLElement;\n const color =\n palette.fromClass(el, 'wysio-highlight-') ??\n palette.fromCSS(el.style.backgroundColor) ??\n fallback;\n return color ? { color } : false;\n },\n },\n {\n style: 'background-color',\n getAttrs: (value) => {\n const color = palette.fromCSS(value);\n return color ? { color } : false;\n },\n },\n ],\n toDOM: (mark) => {\n const color = palette.name(mark.attrs.color);\n return ['mark', color ? { class: `wysio-highlight-${color}` } : {}, 0];\n },\n },\n },\n },\n toolbarItems: ({ schema, editor }) => {\n const type = schema.marks.highlight!;\n return {\n highlight: {\n label: editor.t('highlight'),\n icon: icons.highlight,\n popover: 'highlight',\n dropdown: true,\n render: (state, button) => showColor(button.el, palette, activeColor(state, type)),\n run: (ed) =>\n getPopover(\n ed,\n 'highlight',\n () =>\n new PalettePopover(\n ed,\n ed.t('highlight'),\n type,\n palette,\n ed.t('highlight.remove'),\n 'background',\n ),\n ).open(),\n isActive: (state) => activeColor(state, type) !== null,\n isEnabled: (state) => toggleMark(type)(state),\n },\n };\n },\n });\n}\n","import { setBlockType } from 'prosemirror-commands';\nimport { textblockTypeInputRule } from 'prosemirror-inputrules';\nimport type { Command } from 'prosemirror-state';\nimport { definePlugin } from '../plugin';\n\nexport const HEADING_LEVELS = [1, 2, 3, 4] as const;\n\nconst clampLevel = (level: unknown) => Math.min(4, Math.max(1, Math.trunc(Number(level)) || 1));\n\nexport const heading = definePlugin({\n name: 'heading',\n schema: {\n nodes: {\n heading: {\n attrs: { level: { default: 1, validate: 'number' } },\n content: 'inline*',\n group: 'block',\n defining: true,\n parseDOM: [\n ...HEADING_LEVELS.map((level) => ({ tag: `h${level}`, attrs: { level } })),\n { tag: 'h5', attrs: { level: 4 } },\n { tag: 'h6', attrs: { level: 4 } },\n ],\n toDOM: (node) => [`h${clampLevel(node.attrs.level)}`, 0],\n },\n },\n },\n keymap: ({ schema }) => {\n const keys: Record<string, Command> = { 'Mod-Alt-0': setBlockType(schema.nodes.paragraph!) };\n for (const level of HEADING_LEVELS) {\n keys[`Mod-Alt-${level}`] = setBlockType(schema.nodes.heading!, { level });\n }\n return keys;\n },\n inputRules: ({ schema }) => [\n textblockTypeInputRule(/^(#{1,4})\\s$/, schema.nodes.heading!, (match) => ({\n level: match[1]!.length,\n })),\n ],\n toolbarItems: ({ schema, editor }) => {\n const { paragraph, heading } = schema.nodes as Required<typeof schema.nodes>;\n return {\n heading: {\n type: 'select',\n label: editor.t('heading'),\n options: [\n { value: 'p', label: editor.t('paragraph') },\n ...HEADING_LEVELS.map((level) => ({\n value: `h${level}`,\n label: editor.t(`heading${level}`),\n })),\n ],\n getValue: (state) => {\n const { $from, $to } = state.selection;\n const block = $from.parent;\n if (!$from.sameParent($to) && block !== $to.parent) return '';\n if (block.type === paragraph) return 'p';\n if (block.type === heading) return `h${block.attrs.level}`;\n return '';\n },\n isEnabled: (state) =>\n setBlockType(paragraph!)(state) || setBlockType(heading!, { level: 1 })(state),\n onSelect: (ed, value) => {\n const command =\n value === 'p'\n ? setBlockType(paragraph!)\n : setBlockType(heading!, { level: clampLevel(value.slice(1)) });\n ed.exec(command);\n },\n },\n };\n },\n});\n","import { history as historyPlugin, redo, undo } from 'prosemirror-history';\nimport { icons } from '../icons';\nimport { definePlugin } from '../plugin';\n\nconst isMac = () =>\n typeof navigator !== 'undefined' && /Mac|iP(hone|[oa]d)/.test(navigator.platform);\n\nexport const history = definePlugin({\n name: 'history',\n prosemirrorPlugins: () => [historyPlugin()],\n keymap: () => ({\n 'Mod-z': undo,\n 'Mod-Shift-z': redo,\n ...(isMac() ? {} : { 'Mod-y': redo }),\n }),\n toolbarItems: ({ editor }) => ({\n undo: { label: editor.t('undo'), icon: icons.undo, shortcut: 'Mod-z', command: undo },\n redo: { label: editor.t('redo'), icon: icons.redo, shortcut: 'Mod-Shift-z', command: redo },\n }),\n});\n","const ALLOWED_SCHEMES = new Set(['http', 'https', 'mailto', 'tel']);\n\n// Characters browsers ignore or strip when they read a URL scheme (`java\\tscript:`).\n// eslint-disable-next-line no-control-regex\nconst IGNORED_IN_SCHEME = /[\\u0000- \\u007f-\\u009f]/g;\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARS = /[\\u0000-\\u001f\\u007f-\\u009f]/g;\n\n/**\n * Returns a URL that is safe to put in an `href`, or `null` when it is not.\n *\n * Only http(s), mailto and tel are allowed, plus scheme-less (relative, `#fragment`,\n * `?query`, `//host`) URLs. Everything else, including `javascript:`, `data:` and\n * `vbscript:`, is rejected.\n */\nexport function sanitizeUrl(raw: unknown): string | null {\n if (typeof raw !== 'string') return null;\n const url = raw.trim().replace(CONTROL_CHARS, '');\n if (!url) return null;\n\n const compact = url.replace(IGNORED_IN_SCHEME, '');\n const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(compact);\n if (scheme) {\n return ALLOWED_SCHEMES.has(scheme[1]!.toLowerCase()) ? url : null;\n }\n // No valid scheme. A colon before the first path/query/fragment separator would still\n // be read as (part of) a scheme by some parsers, so reject that.\n const colon = compact.indexOf(':');\n if (colon !== -1) {\n const separator = compact.search(/[/?#]/);\n if (separator === -1 || colon < separator) return null;\n }\n return url;\n}\n\n/**\n * Turns what a user typed into a link dialog into a URL: adds `https://` to bare\n * domains and `mailto:` to e-mail addresses. Returns `null` when the result is unsafe\n * or clearly not a URL.\n */\nexport function normalizeUserUrl(input: string): string | null {\n let url = input.trim();\n if (!url) return null;\n const hasScheme = /^[a-z][a-z0-9+.-]*:/i.test(url);\n const isRelative = /^([/?#.]|\\/\\/)/.test(url);\n if (!hasScheme && !isRelative) {\n if (/^[^\\s@/]+@[^\\s@/]+\\.[^\\s@/]+$/.test(url)) url = `mailto:${url}`;\n else if (/^[^\\s/]+\\.[^\\s/]+/.test(url)) url = `https://${url}`;\n else return null;\n }\n const safe = sanitizeUrl(url);\n if (!safe) return null;\n if (/^https?:/i.test(safe)) {\n try {\n if (!new URL(safe).hostname) return null;\n } catch {\n return null;\n }\n }\n return safe;\n}\n\nconst DATA_IMAGE = /^data:image\\/(png|gif|jpe?g|webp|avif|bmp);base64,[a-z0-9+/=\\s]+$/i;\n\n/**\n * Like {@link sanitizeUrl} for image sources: http(s) and scheme-less URLs.\n * Base64 raster `data:image/*` URLs only with `allowDataUrls`; SVG data URLs,\n * `mailto:` and `tel:` are always rejected.\n */\nexport function sanitizeImageUrl(raw: unknown, { allowDataUrls = false } = {}): string | null {\n if (typeof raw !== 'string') return null;\n const trimmed = raw.trim();\n if (/^data:/i.test(trimmed.replace(IGNORED_IN_SCHEME, ''))) {\n return allowDataUrls && DATA_IMAGE.test(trimmed) ? trimmed : null;\n }\n const url = sanitizeUrl(trimmed);\n if (!url || /^(mailto|tel):/i.test(url.replace(IGNORED_IN_SCHEME, ''))) return null;\n return url;\n}\n","import type { Node as PMNode, NodeType } from 'prosemirror-model';\nimport { NodeSelection, Plugin, PluginKey, type EditorState } from 'prosemirror-state';\nimport { Decoration, DecorationSet, type EditorView } from 'prosemirror-view';\nimport type { Editor } from '../editor';\nimport { icons } from '../icons';\nimport { definePlugin, type WysioPlugin } from '../plugin';\nimport { createForm, getPopover, Popover, query } from '../ui/popover';\nimport { normalizeUserUrl, sanitizeImageUrl } from '../url';\n\nexport const IMAGE_ALIGNMENTS = ['left', 'center', 'right'] as const;\nexport type ImageAlign = (typeof IMAGE_ALIGNMENTS)[number];\n\nexport interface ImageAttrs {\n src: string;\n alt?: string | null;\n title?: string | null;\n width?: number | null;\n height?: number | null;\n /** Rendered as the class `wysio-image-{align}`. */\n align?: ImageAlign | null;\n}\n\nexport interface ImageOptions {\n /**\n * Allow base64 raster `data:image/*` URLs as `src` (pasted HTML, upload results).\n * Off by default: they bloat the stored HTML.\n */\n allowDataUrls?: boolean;\n /** MIME types accepted for upload. Defaults to PNG, JPEG, GIF, WebP and AVIF. */\n types?: readonly string[];\n}\n\nexport interface UploadContext {\n editor: Editor;\n /** Aborted when the upload is cancelled (e.g. the editor is destroyed). */\n signal: AbortSignal;\n /** Report progress between 0 and 1. */\n onProgress: (fraction: number) => void;\n}\n\nexport type UploadResult =\n string | { url: string; alt?: string; title?: string; width?: number; height?: number };\n\n/** Uploads a file and resolves with its public URL. Rejecting removes the placeholder and emits `error`. */\nexport type UploadHandler = (file: File, context: UploadContext) => Promise<UploadResult>;\n\nexport const DEFAULT_IMAGE_TYPES: readonly string[] = [\n 'image/png',\n 'image/jpeg',\n 'image/gif',\n 'image/webp',\n 'image/avif',\n];\n\nconst toDimension = (value: unknown): number | null => {\n const text =\n typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : '';\n if (!/^\\d+$/.test(text)) return null;\n const n = Number(text);\n return n > 0 && n <= 10000 ? n : null;\n};\n\nconst toText = (value: unknown): string | null => (typeof value === 'string' ? value : null);\n\nconst toAlign = (value: unknown): ImageAlign | null =>\n IMAGE_ALIGNMENTS.includes(value as ImageAlign) ? (value as ImageAlign) : null;\n\n/** Reads alignment from our class, TinyMCE-style inline styles or the legacy `align` attribute. */\nfunction parseAlign(el: HTMLElement): ImageAlign | null {\n for (const align of IMAGE_ALIGNMENTS) {\n if (el.classList.contains(`wysio-image-${align}`)) return align;\n }\n const float = el.style.cssFloat || el.style.getPropertyValue('float');\n if (float === 'left' || float === 'right') return float;\n if (\n el.style.display === 'block' &&\n el.style.marginLeft === 'auto' &&\n el.style.marginRight === 'auto'\n ) {\n return 'center';\n }\n const attr = el.getAttribute('align')?.toLowerCase();\n if (attr === 'left' || attr === 'right') return attr;\n if (attr === 'middle' || attr === 'center') return 'center';\n return null;\n}\n\ninterface ResolvedOptions {\n allowDataUrls: boolean;\n types: readonly string[];\n}\n\nconst editorOptions = new WeakMap<Editor, ResolvedOptions>();\nconst optionsFor = (editor: Editor): ResolvedOptions =>\n editorOptions.get(editor) ?? { allowDataUrls: false, types: DEFAULT_IMAGE_TYPES };\n\nfunction cleanAttrs(input: ImageAttrs, options: ResolvedOptions): Record<string, unknown> | null {\n const src = sanitizeImageUrl(input.src, options);\n if (!src) return null;\n return {\n src,\n alt: toText(input.alt),\n title: toText(input.title),\n width: toDimension(input.width),\n height: toDimension(input.height),\n align: toAlign(input.align),\n };\n}\n\n// --- Uploads ------------------------------------------------------------------\n\ninterface UploadMeta {\n add?: { id: object; pos: number; dom: HTMLElement };\n remove?: { id: object };\n}\n\nconst uploadKey = new PluginKey<DecorationSet>('wysio-upload');\nconst uploads = new WeakMap<Editor, Set<AbortController>>();\n\nfunction findPlaceholder(state: EditorState, id: object): number | null {\n const found = uploadKey.getState(state)?.find(undefined, undefined, (spec) => spec.id === id);\n return found?.length ? found[0]!.from : null;\n}\n\nfunction createPlaceholder(editor: Editor, file: File): { dom: HTMLElement; revoke: () => void } {\n const doc = editor.dom.ownerDocument;\n const dom = doc.createElement('span');\n dom.className = 'wysio-upload';\n dom.setAttribute('role', 'status');\n dom.setAttribute('aria-label', editor.t('image.uploading', { name: file.name }));\n dom.style.setProperty('--wysio-progress', '0');\n let url = '';\n if (typeof URL.createObjectURL === 'function') {\n url = URL.createObjectURL(file);\n const img = doc.createElement('img');\n img.src = url;\n img.alt = '';\n dom.appendChild(img);\n }\n const bar = doc.createElement('span');\n bar.className = 'wysio-upload-bar';\n dom.appendChild(bar);\n return { dom, revoke: () => url && URL.revokeObjectURL(url) };\n}\n\n/**\n * Uploads image files through the `upload` option and inserts them at `pos`\n * (default: the selection), showing a placeholder while uploading.\n */\nexport function uploadImages(editor: Editor, files: Iterable<File>, pos?: number): Promise<void>[] {\n const upload = editor.options.upload;\n const type = editor.schema.nodes.image;\n if (!upload || !type || !editor.isEditable) return [];\n const options = optionsFor(editor);\n let controllers = uploads.get(editor);\n if (!controllers) {\n const created = new Set<AbortController>();\n uploads.set(editor, (controllers = created));\n editor.on('destroy', () => created.forEach((c) => c.abort()));\n }\n const active = controllers;\n\n return [...files].map(async (file) => {\n if (!options.types.includes(file.type)) {\n editor.reportError(new Error(`Unsupported image type: ${file.type || 'unknown'}`), {\n source: 'upload',\n file,\n });\n return;\n }\n const { view } = editor;\n const id = {};\n const placeholder = createPlaceholder(editor, file);\n const tr = view.state.tr;\n if (pos === undefined && !tr.selection.empty) tr.deleteSelection();\n const at = pos ?? tr.selection.from;\n view.dispatch(\n tr\n .setMeta(uploadKey, { add: { id, pos: at, dom: placeholder.dom } } satisfies UploadMeta)\n .setMeta('addToHistory', false),\n );\n const controller = new AbortController();\n active.add(controller);\n try {\n const result = await upload(file, {\n editor,\n signal: controller.signal,\n onProgress: (fraction) =>\n placeholder.dom.style.setProperty(\n '--wysio-progress',\n String(Math.min(1, Math.max(0, fraction))),\n ),\n });\n if (controller.signal.aborted) return;\n const { url, ...rest } = typeof result === 'string' ? { url: result } : result;\n const attrs = cleanAttrs({ ...rest, src: url }, options);\n if (!attrs) throw new Error('Upload handler returned an unsafe or empty URL');\n const at = findPlaceholder(editor.view.state, id);\n if (at === null) return; // The placeholder was deleted while uploading.\n editor.view.dispatch(\n editor.view.state.tr\n .insert(at, type.create(attrs))\n .setMeta(uploadKey, { remove: { id } } satisfies UploadMeta),\n );\n } catch (error) {\n if (controller.signal.aborted) return;\n if (findPlaceholder(editor.view.state, id) !== null) {\n editor.view.dispatch(\n editor.view.state.tr\n .setMeta(uploadKey, { remove: { id } } satisfies UploadMeta)\n .setMeta('addToHistory', false),\n );\n }\n editor.reportError(error, { source: 'upload', file });\n } finally {\n active.delete(controller);\n placeholder.revoke();\n }\n });\n}\n\nfunction imageFiles(editor: Editor, list: FileList | null | undefined): File[] {\n const { types } = optionsFor(editor);\n return [...(list ?? [])].filter((file) => types.includes(file.type));\n}\n\nfunction uploadPlugin(editor: Editor): Plugin {\n return new Plugin<DecorationSet>({\n key: uploadKey,\n state: {\n init: () => DecorationSet.empty,\n apply(tr, set) {\n let next = set.map(tr.mapping, tr.doc);\n const meta = tr.getMeta(uploadKey) as UploadMeta | undefined;\n if (meta?.add) {\n next = next.add(tr.doc, [\n Decoration.widget(meta.add.pos, meta.add.dom, { id: meta.add.id }),\n ]);\n }\n if (meta?.remove) {\n const { id } = meta.remove;\n next = next.remove(next.find(undefined, undefined, (spec) => spec.id === id));\n }\n return next;\n },\n },\n props: {\n decorations: (state) => uploadKey.getState(state),\n handlePaste: (_view, event) => {\n if (!editor.options.upload) return false;\n const data = event.clipboardData;\n // Office and browsers put an image rendering next to the HTML; prefer the HTML.\n if (!data || data.getData('text/html') || data.getData('text/plain')) return false;\n const files = imageFiles(editor, data.files);\n if (!files.length) return false;\n event.preventDefault();\n void uploadImages(editor, files);\n return true;\n },\n handleDrop: (view: EditorView, event, _slice, moved) => {\n if (moved || !editor.options.upload) return false;\n const files = imageFiles(editor, event.dataTransfer?.files);\n if (!files.length) return false;\n event.preventDefault();\n const pos = view.posAtCoords({ left: event.clientX, top: event.clientY })?.pos;\n void uploadImages(editor, files, pos ?? view.state.selection.from);\n return true;\n },\n },\n });\n}\n\n// --- Commands -----------------------------------------------------------------\n\nfunction selectedImage(state: EditorState, type: NodeType): PMNode | null {\n const { selection } = state;\n return selection instanceof NodeSelection && selection.node.type === type ? selection.node : null;\n}\n\n/**\n * Inserts an image at the selection, or updates the selected image (only the\n * attributes given). Returns false when `src` is unsafe.\n */\nexport function insertImage(editor: Editor, attrs: ImageAttrs): boolean {\n const type = editor.schema.nodes.image;\n const clean = type && cleanAttrs(attrs, optionsFor(editor));\n if (!type || !clean) return false;\n return editor.exec((state, dispatch) => {\n const existing = selectedImage(state, type);\n if (dispatch) {\n const changed = Object.fromEntries(\n Object.entries(clean).filter(([key]) => attrs[key as keyof ImageAttrs] !== undefined),\n );\n const tr = existing\n ? state.tr.setNodeMarkup(state.selection.from, undefined, { ...existing.attrs, ...changed })\n : state.tr.replaceSelectionWith(type.create(clean));\n dispatch(tr.scrollIntoView());\n }\n return true;\n });\n}\n\n/** Deletes the selected image. */\nexport function removeImage(editor: Editor): boolean {\n const type = editor.schema.nodes.image;\n return editor.exec((state, dispatch) => {\n if (!type || !selectedImage(state, type)) return false;\n if (dispatch) dispatch(state.tr.deleteSelection().scrollIntoView());\n return true;\n });\n}\n\n// --- Dialog -------------------------------------------------------------------\n\n/** Opens the image popover (insert, or edit the selected image). */\nexport function openImageDialog(editor: Editor): void {\n if (!editor.isEditable || !editor.schema.nodes.image) return;\n getPopover(editor, 'image', () => new ImageDialog(editor)).open();\n}\n\nclass ImageDialog extends Popover {\n private src: HTMLInputElement;\n private alt: HTMLInputElement;\n private align: HTMLSelectElement;\n private error: HTMLElement;\n private file: HTMLInputElement;\n private uploadRow: HTMLElement;\n private removeButton: HTMLButtonElement;\n private pos = 0;\n private original = '';\n\n constructor(editor: Editor) {\n super(editor, editor.t('image.dialog'));\n const form = createForm(\n editor.dom.ownerDocument,\n this.uid,\n `<label class=\"wysio-field\" for=\"{id}-src\" data-text=\"image.url\"></label>\n <input class=\"wysio-input\" id=\"{id}-src\" name=\"src\" type=\"text\" inputmode=\"url\" autocomplete=\"off\" spellcheck=\"false\" aria-describedby=\"{id}-error\">\n <p class=\"wysio-error\" id=\"{id}-error\" role=\"alert\" hidden></p>\n <div class=\"wysio-upload-row\">\n <button type=\"button\" class=\"wysio-button\" data-action=\"upload\" data-text=\"image.upload\"></button>\n <input type=\"file\" name=\"file\" hidden>\n </div>\n <label class=\"wysio-field\" for=\"{id}-alt\" data-text=\"image.alt\"></label>\n <input class=\"wysio-input\" id=\"{id}-alt\" name=\"alt\" type=\"text\" aria-describedby=\"{id}-alt-hint\">\n <p class=\"wysio-hint\" id=\"{id}-alt-hint\" data-text=\"image.altHint\"></p>\n <label class=\"wysio-field\" for=\"{id}-align\" data-text=\"image.align\"></label>\n <select class=\"wysio-input\" id=\"{id}-align\" name=\"align\">\n <option value=\"\" data-text=\"image.alignNone\"></option>\n <option value=\"left\" data-text=\"image.alignLeft\"></option>\n <option value=\"center\" data-text=\"image.alignCenter\"></option>\n <option value=\"right\" data-text=\"image.alignRight\"></option>\n </select>\n <div class=\"wysio-actions\">\n <button type=\"submit\" class=\"wysio-button wysio-button-primary\" data-text=\"dialog.apply\"></button>\n <button type=\"button\" class=\"wysio-button\" data-action=\"remove\" data-text=\"image.remove\"></button>\n <button type=\"button\" class=\"wysio-button\" data-action=\"cancel\" data-text=\"dialog.cancel\"></button>\n </div>`,\n );\n for (const el of form.querySelectorAll<HTMLElement>('[data-text]')) {\n el.textContent = editor.t(el.dataset.text!);\n }\n this.src = query(form, 'input[name=src]');\n this.alt = query(form, 'input[name=alt]');\n this.align = query(form, 'select[name=align]');\n this.error = query(form, '.wysio-error');\n this.file = query(form, 'input[name=file]');\n this.file.accept = optionsFor(editor).types.join(',');\n this.file.multiple = true;\n this.uploadRow = query(form, '.wysio-upload-row');\n this.removeButton = query(form, '[data-action=remove]');\n\n form.addEventListener('submit', (e) => {\n e.preventDefault();\n this.apply();\n });\n query(form, '[data-action=cancel]').addEventListener('click', () => this.close());\n this.removeButton.addEventListener('click', () => {\n this.close(false);\n removeImage(this.editor);\n });\n query(form, '[data-action=upload]').addEventListener('click', () => this.file.click());\n this.file.addEventListener('change', () => {\n const files = [...(this.file.files ?? [])];\n this.file.value = '';\n if (!files.length) return;\n this.close(false);\n this.editor.focus();\n void uploadImages(this.editor, files, this.pos);\n });\n this.src.addEventListener('input', () => this.setError(false));\n this.dom.appendChild(form);\n }\n\n open(): void {\n const { state } = this.editor.view;\n const image = selectedImage(state, this.editor.schema.nodes.image!);\n this.pos = state.selection.from;\n this.original = (image?.attrs.src as string | undefined) ?? '';\n this.src.value = this.original;\n this.alt.value = (image?.attrs.alt as string | null | undefined) ?? '';\n this.align.value = (image?.attrs.align as string | null | undefined) ?? '';\n // Uploading inserts a new image, so offer it only when inserting.\n this.uploadRow.hidden = !this.editor.options.upload || !!image;\n this.removeButton.hidden = !image;\n this.setError(false);\n this.show(this.pos, this.src);\n this.src.select();\n }\n\n private apply(): void {\n const typed = this.src.value.trim();\n const options = optionsFor(this.editor);\n const src =\n // Unchanged, a data URL, or a bare file name (\"cat.png\") is used as-is; anything\n // else goes through the same normalisation as links (\"example.com/a.png\" → https).\n typed === this.original ||\n /^data:/i.test(typed) ||\n /^[^/:]+\\.(png|jpe?g|gif|webp|avif|svg|bmp)$/i.test(typed)\n ? sanitizeImageUrl(typed, options)\n : sanitizeImageUrl(normalizeUserUrl(typed), options);\n if (!src) {\n this.setError(true);\n this.src.focus();\n return;\n }\n this.close(false);\n insertImage(this.editor, {\n src,\n alt: this.alt.value.trim(),\n align: toAlign(this.align.value),\n });\n }\n\n private setError(show: boolean): void {\n this.error.hidden = !show;\n this.error.textContent = show ? this.editor.t('image.invalid') : '';\n this.src.setAttribute('aria-invalid', String(show));\n }\n}\n\n// --- Plugin -------------------------------------------------------------------\n\n/** Image support. Use `image({ ... })` in `plugins` to replace the default configuration. */\nexport function image(config: ImageOptions = {}): WysioPlugin {\n const options: ResolvedOptions = {\n allowDataUrls: config.allowDataUrls ?? false,\n types: config.types ?? DEFAULT_IMAGE_TYPES,\n };\n return definePlugin({\n name: 'image',\n schema: {\n nodes: {\n image: {\n inline: true,\n group: 'inline',\n draggable: true,\n attrs: {\n src: { validate: 'string' },\n alt: { default: null, validate: 'string|null' },\n title: { default: null, validate: 'string|null' },\n width: { default: null, validate: 'number|null' },\n height: { default: null, validate: 'number|null' },\n align: { default: null, validate: 'string|null' },\n },\n parseDOM: [\n {\n tag: 'img[src]',\n getAttrs: (dom) => {\n const el = dom as HTMLElement;\n return (\n cleanAttrs(\n {\n src: el.getAttribute('src') ?? '',\n alt: el.getAttribute('alt'),\n title: el.getAttribute('title'),\n width: toDimension(el.getAttribute('width')),\n height: toDimension(el.getAttribute('height')),\n align: parseAlign(el),\n },\n options,\n ) ?? false\n );\n },\n },\n ],\n toDOM: (node) => {\n const attrs: Record<string, string> = {};\n const src = sanitizeImageUrl(node.attrs.src, options);\n if (src) attrs.src = src;\n if (typeof node.attrs.alt === 'string') attrs.alt = node.attrs.alt;\n if (typeof node.attrs.title === 'string') attrs.title = node.attrs.title;\n const width = toDimension(node.attrs.width);\n const height = toDimension(node.attrs.height);\n if (width) attrs.width = String(width);\n if (height) attrs.height = String(height);\n const align = toAlign(node.attrs.align);\n if (align) attrs.class = `wysio-image-${align}`;\n return ['img', attrs];\n },\n },\n },\n },\n prosemirrorPlugins: ({ editor }) => {\n editorOptions.set(editor, options);\n return [uploadPlugin(editor)];\n },\n toolbarItems: ({ schema, editor }) => {\n const type = schema.nodes.image!;\n return {\n image: {\n label: editor.t('image'),\n icon: icons.image,\n run: openImageDialog,\n popover: 'image',\n isActive: (state) => !!selectedImage(state, type),\n isEnabled: (state) =>\n !!selectedImage(state, type) || state.selection.$from.parent.inlineContent,\n },\n };\n },\n });\n}\n","import type { MarkType } from 'prosemirror-model';\nimport type { Command, EditorState } from 'prosemirror-state';\nimport { getMarkRange, isMarkActive } from '../commands';\nimport type { Editor } from '../editor';\nimport { icons } from '../icons';\nimport { definePlugin } from '../plugin';\nimport { createForm, getPopover, Popover, query } from '../ui/popover';\nimport { normalizeUserUrl, sanitizeUrl } from '../url';\n\nexport interface LinkAttrs {\n href: string;\n /** `'_blank'` to open in a new tab, otherwise `null`. */\n target?: string | null;\n}\n\n/** The range a link command acts on: the selection, or the whole link around the cursor. */\nfunction linkRange(state: EditorState, type: MarkType) {\n const { from, to, empty, $from } = state.selection;\n if (!empty) return { from, to };\n const range = getMarkRange($from, type);\n return range ? { from: range.from, to: range.to } : null;\n}\n\n/** Sets a link on the selection (or the link around the cursor); inserts the URL as text when nothing is selected. */\nexport function setLink(type: MarkType, attrs: LinkAttrs): Command {\n return (state, dispatch) => {\n const href = sanitizeUrl(attrs.href);\n if (!href) return false;\n const mark = type.create({ href, target: attrs.target === '_blank' ? '_blank' : null });\n const range = linkRange(state, type);\n if (dispatch) {\n const tr = state.tr;\n if (range) {\n tr.removeMark(range.from, range.to, type).addMark(range.from, range.to, mark);\n } else {\n const { from } = state.selection;\n tr.insertText(href, from).addMark(from, from + href.length, mark);\n }\n dispatch(tr.scrollIntoView());\n }\n return true;\n };\n}\n\nexport function removeLink(type: MarkType): Command {\n return (state, dispatch) => {\n const range = linkRange(state, type);\n if (!range || !state.doc.rangeHasMark(range.from, range.to, type)) return false;\n if (dispatch) dispatch(state.tr.removeMark(range.from, range.to, type).scrollIntoView());\n return true;\n };\n}\n\n/** Opens the link popover for this editor. */\nexport function openLinkDialog(editor: Editor): void {\n const type = editor.schema.marks.link;\n if (!editor.isEditable || !type) return;\n getPopover(editor, 'link', () => new LinkDialog(editor, type)).open();\n}\n\nclass LinkDialog extends Popover {\n private input: HTMLInputElement;\n private newTab: HTMLInputElement;\n private error: HTMLElement;\n private removeButton: HTMLButtonElement;\n private range: { from: number; to: number } | null = null;\n\n constructor(\n editor: Editor,\n private type: MarkType,\n ) {\n super(editor, editor.t('link.dialog'));\n const form = createForm(\n editor.dom.ownerDocument,\n this.uid,\n `<label class=\"wysio-field\" for=\"{id}-url\"></label>\n <input class=\"wysio-input\" id=\"{id}-url\" name=\"href\" type=\"text\" inputmode=\"url\" autocomplete=\"off\" spellcheck=\"false\" aria-describedby=\"{id}-error\">\n <p class=\"wysio-error\" id=\"{id}-error\" role=\"alert\" hidden></p>\n <label class=\"wysio-check\"><input type=\"checkbox\" name=\"newTab\"> <span></span></label>\n <div class=\"wysio-actions\">\n <button type=\"submit\" class=\"wysio-button wysio-button-primary\" data-action=\"apply\"></button>\n <button type=\"button\" class=\"wysio-button\" data-action=\"remove\"></button>\n <button type=\"button\" class=\"wysio-button\" data-action=\"cancel\"></button>\n </div>`,\n );\n query(form, '.wysio-field').textContent = editor.t('link.url');\n query(form, '.wysio-check span').textContent = editor.t('link.newTab');\n query(form, '[data-action=apply]').textContent = editor.t('dialog.apply');\n const cancel = query<HTMLButtonElement>(form, '[data-action=cancel]');\n cancel.textContent = editor.t('dialog.cancel');\n this.removeButton = query(form, '[data-action=remove]');\n this.removeButton.textContent = editor.t('link.remove');\n this.input = query(form, 'input[name=href]');\n this.newTab = query(form, 'input[name=newTab]');\n this.error = query(form, '.wysio-error');\n\n form.addEventListener('submit', (e) => {\n e.preventDefault();\n this.apply();\n });\n this.removeButton.addEventListener('click', () => this.remove());\n cancel.addEventListener('click', () => this.close());\n this.input.addEventListener('input', () => this.setError(false));\n this.dom.appendChild(form);\n }\n\n open(): void {\n const { state } = this.editor.view;\n const { from, to } = state.selection;\n const existing = getMarkRange(state.selection.$from, this.type);\n this.range =\n existing && (state.selection.empty || (existing.from <= from && existing.to >= to))\n ? { from: existing.from, to: existing.to }\n : { from, to };\n const mark = existing?.mark;\n this.input.value = (mark?.attrs.href as string | undefined) ?? '';\n this.newTab.checked = mark?.attrs.target === '_blank';\n this.removeButton.hidden = !mark && !isMarkActive(state, this.type);\n this.setError(false);\n this.show(this.range.from, this.input);\n this.input.select();\n }\n\n private apply(): void {\n const href = normalizeUserUrl(this.input.value);\n if (!href) {\n this.setError(true);\n this.input.focus();\n return;\n }\n const { view } = this.editor;\n const range = this.clampRange();\n const mark = this.type.create({ href, target: this.newTab.checked ? '_blank' : null });\n const tr = view.state.tr;\n if (range.from === range.to) {\n tr.insertText(href, range.from).addMark(range.from, range.from + href.length, mark);\n } else {\n tr.removeMark(range.from, range.to, this.type).addMark(range.from, range.to, mark);\n }\n view.dispatch(tr.scrollIntoView());\n this.close(false);\n this.editor.focus();\n }\n\n private remove(): void {\n const range = this.clampRange();\n const { view } = this.editor;\n view.dispatch(view.state.tr.removeMark(range.from, range.to, this.type));\n this.close(false);\n this.editor.focus();\n }\n\n /** The document may have changed while the dialog was open. */\n private clampRange() {\n const size = this.editor.view.state.doc.content.size;\n const from = Math.min(this.range?.from ?? 0, size);\n const to = Math.min(this.range?.to ?? from, size);\n return { from, to };\n }\n\n private setError(show: boolean): void {\n this.error.hidden = !show;\n this.error.textContent = show ? this.editor.t('link.invalid') : '';\n this.input.setAttribute('aria-invalid', String(show));\n }\n}\n\nexport const link = definePlugin({\n name: 'link',\n schema: {\n marks: {\n link: {\n attrs: {\n href: { validate: 'string' },\n target: { default: null, validate: 'string|null' },\n },\n inclusive: false,\n parseDOM: [\n {\n tag: 'a[href]',\n getAttrs: (dom) => {\n const el = dom as HTMLElement;\n const href = sanitizeUrl(el.getAttribute('href'));\n if (!href) return false;\n return { href, target: el.getAttribute('target') === '_blank' ? '_blank' : null };\n },\n },\n ],\n toDOM: (mark) => {\n const href = sanitizeUrl(mark.attrs.href);\n const attrs: Record<string, string> = {};\n if (href) attrs.href = href;\n if (mark.attrs.target === '_blank') {\n attrs.target = '_blank';\n attrs.rel = 'noopener noreferrer';\n }\n return ['a', attrs, 0];\n },\n },\n },\n },\n keymap: ({ editor }) => ({\n 'Mod-k': (_state, dispatch) => {\n if (!editor.isEditable) return false;\n if (dispatch) openLinkDialog(editor);\n return true;\n },\n }),\n toolbarItems: ({ schema, editor }) => {\n const type = schema.marks.link!;\n return {\n link: {\n label: editor.t('link'),\n icon: icons.link,\n shortcut: 'Mod-k',\n run: openLinkDialog,\n popover: 'link',\n isActive: (state) => isMarkActive(state, type),\n isEnabled: () => true,\n },\n unlink: {\n label: editor.t('unlink'),\n icon: icons.unlink,\n command: removeLink(type),\n },\n };\n },\n});\n","import { wrappingInputRule } from 'prosemirror-inputrules';\nimport { liftListItem, sinkListItem, splitListItem } from 'prosemirror-schema-list';\nimport { findAncestor, toggleList } from '../commands';\nimport { icons } from '../icons';\nimport { definePlugin } from '../plugin';\n\nconst toStart = (value: unknown) => {\n const n = Math.trunc(Number(value));\n return Number.isFinite(n) ? n : 1;\n};\n\nexport const lists = definePlugin({\n name: 'lists',\n schema: {\n nodes: {\n bullet_list: {\n content: 'list_item+',\n group: 'block',\n parseDOM: [{ tag: 'ul' }],\n toDOM: () => ['ul', 0],\n },\n ordered_list: {\n attrs: { start: { default: 1, validate: 'number' } },\n content: 'list_item+',\n group: 'block',\n parseDOM: [\n {\n tag: 'ol',\n getAttrs: (dom) => ({\n start: toStart((dom as HTMLElement).getAttribute('start') ?? 1),\n }),\n },\n ],\n toDOM: (node) => {\n const start = toStart(node.attrs.start);\n return start === 1 ? ['ol', 0] : ['ol', { start: String(start) }, 0];\n },\n },\n list_item: {\n content: 'paragraph block*',\n defining: true,\n parseDOM: [{ tag: 'li' }],\n toDOM: () => ['li', 0],\n },\n },\n },\n keymap: ({ schema }) => {\n const item = schema.nodes.list_item!;\n const types = [schema.nodes.bullet_list!, schema.nodes.ordered_list!];\n return {\n Enter: splitListItem(item),\n Tab: sinkListItem(item),\n 'Shift-Tab': liftListItem(item),\n 'Mod-Shift-8': toggleList(types[0]!, item, types),\n 'Mod-Shift-7': toggleList(types[1]!, item, types),\n };\n },\n inputRules: ({ schema }) => [\n wrappingInputRule(/^\\s*([-+*])\\s$/, schema.nodes.bullet_list!),\n wrappingInputRule(\n /^(\\d+)\\.\\s$/,\n schema.nodes.ordered_list!,\n (match) => ({ start: toStart(match[1]) }),\n (match, node) => node.childCount + (node.attrs.start as number) === toStart(match[1]),\n ),\n ],\n toolbarItems: ({ schema, editor }) => {\n const item = schema.nodes.list_item!;\n const bullet = schema.nodes.bullet_list!;\n const ordered = schema.nodes.ordered_list!;\n const types = [bullet, ordered];\n const inList = (type: typeof bullet) => (state: Parameters<typeof findAncestor>[0]) =>\n findAncestor(state, types)?.node.type === type;\n return {\n bulletList: {\n label: editor.t('bulletList'),\n icon: icons.bulletList,\n shortcut: 'Mod-Shift-8',\n command: toggleList(bullet, item, types),\n isActive: inList(bullet),\n },\n orderedList: {\n label: editor.t('orderedList'),\n icon: icons.orderedList,\n shortcut: 'Mod-Shift-7',\n command: toggleList(ordered, item, types),\n isActive: inList(ordered),\n },\n };\n },\n});\n","import { toggleMark } from 'prosemirror-commands';\nimport type { MarkSpec } from 'prosemirror-model';\nimport { isMarkActive } from '../commands';\nimport { icons } from '../icons';\nimport { definePlugin, type WysioPlugin } from '../plugin';\n\n/** Defines a plugin for a simple formatting mark with a toggle button and shortcut. */\nfunction markPlugin(name: keyof typeof icons, spec: MarkSpec, shortcut: string): WysioPlugin {\n return definePlugin({\n name,\n schema: { marks: { [name]: spec } },\n keymap: ({ schema }) => ({ [shortcut]: toggleMark(schema.marks[name]!) }),\n toolbarItems: ({ schema, editor }) => {\n const type = schema.marks[name]!;\n return {\n [name]: {\n label: editor.t(name),\n icon: icons[name],\n shortcut,\n command: toggleMark(type),\n isActive: (state) => isMarkActive(state, type),\n },\n };\n },\n });\n}\n\nconst hasDecoration = (value: string, decoration: string) => value.includes(decoration) && null;\n\nexport const bold = markPlugin(\n 'bold',\n {\n parseDOM: [\n { tag: 'strong' },\n // Google Docs wraps everything in <b style=\"font-weight:normal\">.\n { tag: 'b', getAttrs: (node) => (node as HTMLElement).style.fontWeight !== 'normal' && null },\n { style: 'font-weight=400', clearMark: (m) => m.type.name === 'bold' },\n {\n style: 'font-weight',\n getAttrs: (v) => /^(bold(er)?|[5-9]\\d{2,})$/.test(v as string) && null,\n },\n ],\n toDOM: () => ['strong', 0],\n },\n 'Mod-b',\n);\n\nexport const italic = markPlugin(\n 'italic',\n {\n parseDOM: [\n { tag: 'em' },\n { tag: 'i' },\n { style: 'font-style=italic' },\n { style: 'font-style=normal', clearMark: (m) => m.type.name === 'italic' },\n ],\n toDOM: () => ['em', 0],\n },\n 'Mod-i',\n);\n\nexport const underline = markPlugin(\n 'underline',\n {\n parseDOM: [\n { tag: 'u' },\n { style: 'text-decoration', getAttrs: (v) => hasDecoration(v as string, 'underline') },\n { style: 'text-decoration-line', getAttrs: (v) => hasDecoration(v as string, 'underline') },\n ],\n toDOM: () => ['u', 0],\n },\n 'Mod-u',\n);\n\nexport const strike = markPlugin(\n 'strike',\n {\n parseDOM: [\n { tag: 's' },\n { tag: 'del' },\n { tag: 'strike' },\n { style: 'text-decoration', getAttrs: (v) => hasDecoration(v as string, 'line-through') },\n {\n style: 'text-decoration-line',\n getAttrs: (v) => hasDecoration(v as string, 'line-through'),\n },\n ],\n toDOM: () => ['s', 0],\n },\n 'Mod-Shift-x',\n);\n\nexport const code = markPlugin(\n 'code',\n {\n code: true,\n parseDOM: [{ tag: 'code' }],\n toDOM: () => ['code', 0],\n },\n 'Mod-e',\n);\n","import { Plugin } from 'prosemirror-state';\nimport { definePlugin } from '../plugin';\n\n/** Elements removed together with their content. */\nconst REMOVE = [\n 'script, style, meta, link, title, xml, template, noscript',\n 'object, embed, iframe, svg, canvas, video, audio',\n // Page UI that comes along when copying from websites.\n 'button, input, select, textarea',\n].join(', ');\n\nconst BLOCK = new Set(\n 'P H1 H2 H3 H4 H5 H6 UL OL LI TABLE DIV BLOCKQUOTE HR PRE FIGURE SECTION ARTICLE HEADER FOOTER'.split(\n ' ',\n ),\n);\n\n/** Attributes the schema's parse rules may read. Everything else is dropped before parsing. */\nconst KEEP_ATTRIBUTES = new Set([\n 'href',\n 'target',\n 'src',\n 'alt',\n 'title',\n 'width',\n 'height',\n 'colspan',\n 'rowspan',\n 'start',\n]);\n\nconst HEADING = 'h1, h2, h3, h4, h5, h6';\n\nfunction unwrap(el: Element): void {\n el.replaceWith(...el.childNodes);\n}\n\n/** Wraps the children of `el` in the given tags (outermost first). */\nfunction wrapChildren(el: Element, tags: string[]): void {\n if (!tags.length) return;\n const doc = el.ownerDocument;\n const outer = doc.createElement(tags[0]!);\n let inner = outer;\n for (const tag of tags.slice(1)) inner = inner.appendChild(doc.createElement(tag));\n inner.append(...el.childNodes);\n el.appendChild(outer);\n}\n\n/**\n * Formatting that Google Docs and browsers express only through inline styles,\n * turned into tags so it survives dropping `style`.\n */\nfunction formattingTags(el: HTMLElement): string[] {\n const style = el.style;\n const tags: string[] = [];\n const weight = style.fontWeight;\n // Headings are bold already; links are underlined already.\n if (/^(bold(er)?|[6-9]\\d\\d)$/.test(weight) && !el.closest(HEADING)) tags.push('strong');\n if (style.fontStyle === 'italic' || style.fontStyle === 'oblique') tags.push('em');\n const decoration = `${style.textDecoration} ${style.getPropertyValue('text-decoration-line')}`;\n if (decoration.includes('underline') && !el.closest('a')) tags.push('u');\n if (decoration.includes('line-through')) tags.push('s');\n return tags;\n}\n\nconst isWordListParagraph = (el: Element) =>\n /mso-list\\s*:\\s*l\\d+/i.test(el.getAttribute('style') ?? '');\n\nconst isMarkerSpan = (el: Element) => /mso-list\\s*:\\s*ignore/i.test(el.getAttribute('style') ?? '');\n\n/**\n * Word writes lists as paragraphs with `mso-list` styles and a marker span. Consecutive\n * ones become a flat <ul> or <ol> (numbered when the marker looks like \"1.\" or \"a)\").\n * Nesting levels are not kept: free paste is clean, not faithful.\n */\nfunction convertWordLists(body: HTMLElement): void {\n let list: HTMLElement | null = null;\n for (const p of [...body.querySelectorAll<HTMLElement>('p')].filter(isWordListParagraph)) {\n const markerSpan = [...p.querySelectorAll('span')].find(isMarkerSpan);\n const marker = (markerSpan?.textContent ?? '').replace(/[\\s\\u00a0]+/g, '');\n const tag = /^\\(?(\\d+|[a-z]{1,3})[.)]$/i.test(marker) ? 'OL' : 'UL';\n markerSpan?.remove();\n if (!list || list.tagName !== tag || p.previousElementSibling !== list) {\n list = p.ownerDocument.createElement(tag);\n p.before(list);\n }\n const li = p.ownerDocument.createElement('li');\n li.appendChild(p);\n list.appendChild(li);\n }\n}\n\n/** A <br> between blocks (Google Docs uses these for spacing), not inside text. */\nfunction isBlockLevelBreak(br: Element): boolean {\n const sibling = (node: Node | null, dir: 'previousSibling' | 'nextSibling'): Node | null => {\n while (node && node.nodeType === Node.TEXT_NODE && isBlank(node.textContent)) node = node[dir];\n return node;\n };\n const isBlockOrEdge = (node: Node | null) => !node || BLOCK.has((node as Element).tagName);\n return (\n isBlockOrEdge(sibling(br.previousSibling, 'previousSibling')) &&\n isBlockOrEdge(sibling(br.nextSibling, 'nextSibling'))\n );\n}\n\nconst isBlank = (text: string | null) => !(text ?? '').replace(/[\\s\\u00a0\\u200b]/g, '');\n\n/**\n * Cleans pasted HTML from Word, Google Docs and web pages before the schema parses it:\n * removes comments, Office markup, scripts and styles; turns style-only bold/italic/\n * underline/strike into tags; drops `style`, `class`, `id` and other attributes; unwraps\n * `span`/`font`; removes empty paragraphs. The result is clean, not a faithful copy.\n */\nexport function cleanPastedHTML(html: string, doc: Document = document): string {\n // Copied from a ProseMirror editor (ours, or another one): already clean, and the\n // data-pm-slice attribute must survive for correct open-ended slices. The schema\n // still sanitises it.\n if (/<[^>]+\\sdata-pm-slice=/.test(html)) return html;\n\n const Parser = doc.defaultView?.DOMParser ?? DOMParser;\n const parsed = new Parser().parseFromString(html, 'text/html');\n const body = parsed.body;\n\n // Comments, including Office conditional comments (<!--[if ...]> and <![if ...]>).\n const comments: Node[] = [];\n const walker = parsed.createTreeWalker(body, NodeFilter.SHOW_COMMENT);\n while (walker.nextNode()) comments.push(walker.currentNode);\n comments.forEach((c) => c.parentNode?.removeChild(c));\n\n body.querySelectorAll(REMOVE).forEach((el) => el.remove());\n body.querySelectorAll('br.Apple-interchange-newline').forEach((el) => el.remove());\n\n convertWordLists(body);\n\n // Remaining Word list markers (e.g. numbered headings) become plain text (\"1. \").\n body.querySelectorAll<HTMLElement>('span[style]').forEach((el) => {\n if (isMarkerSpan(el)) {\n const marker = (el.textContent ?? '').replace(/[\\s\\u00a0]+/g, ' ').trim();\n el.replaceWith(parsed.createTextNode(marker ? `${marker} ` : ''));\n }\n });\n\n // Google Docs wraps everything in <b style=\"font-weight:normal\" id=\"docs-internal-guid-…\">.\n body.querySelectorAll<HTMLElement>('b, strong').forEach((el) => {\n if (/^(normal|[1-4]00)$/.test(el.style.fontWeight) || el.id.startsWith('docs-internal-guid')) {\n unwrap(el);\n }\n });\n\n // Browsers write spaces next to inline elements as <span>&nbsp;</span>.\n body.querySelectorAll('span').forEach((el) => {\n if (el.textContent && /^[\\s\\u00a0]+$/.test(el.textContent) && !el.children.length) {\n el.replaceWith(parsed.createTextNode(' '));\n }\n });\n\n // Style-only formatting → tags (deepest first, so wrapping doesn't disturb the walk).\n [...body.querySelectorAll<HTMLElement>('span[style], font[style]')]\n .reverse()\n .forEach((el) => wrapChildren(el, formattingTags(el)));\n\n for (const el of [...body.querySelectorAll('*')]) {\n // Keep images intact: their class/style/align carry alignment the image plugin reads.\n if (el.tagName === 'IMG') continue;\n // Our own formatting classes (alignment, colours) survive, e.g. when pasting from a\n // page that displays Wysio content.\n const ownClasses = [...el.classList].filter((c) => c.startsWith('wysio-'));\n for (const attr of [...el.attributes]) {\n if (!KEEP_ATTRIBUTES.has(attr.name.toLowerCase())) el.removeAttribute(attr.name);\n }\n if (ownClasses.length) el.setAttribute('class', ownClasses.join(' '));\n }\n\n // Wrappers without meaning: span, font and Office namespaced tags (<o:p>, <w:sdt>, …).\n [...body.querySelectorAll('*')].reverse().forEach((el) => {\n // Spans that still carry one of our classes (e.g. a colour) are kept.\n const plain = el.tagName === 'SPAN' || el.tagName === 'FONT';\n if ((plain && !el.hasAttribute('class')) || el.tagName.includes(':')) unwrap(el);\n });\n\n body.querySelectorAll('br').forEach((br) => {\n if (isBlockLevelBreak(br)) br.remove();\n });\n\n // Empty paragraphs (Word's <p><o:p>&nbsp;</o:p></p>, stray spacing).\n body.querySelectorAll('p').forEach((p) => {\n if (isBlank(p.textContent) && !p.querySelector('img, br, table, hr')) p.remove();\n });\n\n return body.innerHTML;\n}\n\nexport const paste = definePlugin({\n name: 'paste',\n prosemirrorPlugins: ({ editor }) => [\n new Plugin({\n props: {\n transformPastedHTML: (html) => cleanPastedHTML(html, editor.dom.ownerDocument),\n },\n }),\n ],\n});\n","import { Plugin } from 'prosemirror-state';\nimport { Decoration, DecorationSet } from 'prosemirror-view';\nimport { isDocEmpty } from '../content';\nimport { definePlugin } from '../plugin';\n\n/** Shows `options.placeholder` while the document is empty. */\nexport const placeholder = definePlugin({\n name: 'placeholder',\n prosemirrorPlugins: ({ editor }) => [\n new Plugin({\n props: {\n decorations: (state) => {\n const text = editor.options.placeholder;\n const first = state.doc.firstChild;\n if (!text || !first || !isDocEmpty(state.doc)) return null;\n return DecorationSet.create(state.doc, [\n Decoration.node(0, first.nodeSize, {\n class: 'wysio-placeholder',\n 'data-placeholder': text,\n }),\n ]);\n },\n attributes: (): Record<string, string> => {\n const text = editor.options.placeholder;\n return text ? { 'aria-placeholder': text } : {};\n },\n },\n }),\n ],\n});\n","/** Elements that may contain other blocks and are printed with indented children. */\nconst CONTAINERS = new Set([\n 'UL',\n 'OL',\n 'LI',\n 'BLOCKQUOTE',\n 'TABLE',\n 'THEAD',\n 'TBODY',\n 'TR',\n 'TD',\n 'TH',\n]);\nconst BLOCKS = new Set([\n ...CONTAINERS,\n 'P',\n 'H1',\n 'H2',\n 'H3',\n 'H4',\n 'H5',\n 'H6',\n 'HR',\n 'PRE',\n 'DIV',\n]);\n\nconst hasBlockChildren = (el: Element) => [...el.children].some((c) => BLOCKS.has(c.tagName));\n\n/** `<tag attr=\"…\">` for an element, using the browser's own serialisation. */\nfunction openTag(el: Element): string {\n const shallow = (el.cloneNode(false) as Element).outerHTML;\n const close = shallow.lastIndexOf('</');\n return close === -1 ? shallow : shallow.slice(0, close);\n}\n\n/**\n * Pretty-prints editor HTML for the source view: one block per line, children of\n * lists, quotes and tables indented. Inline content is left untouched, so the\n * result parses back to the same document.\n */\nexport function formatHTML(html: string, indent = ' ', doc: Document = document): string {\n const container = doc.createElement('div');\n container.innerHTML = html;\n const lines: string[] = [];\n\n const print = (node: Node, depth: number) => {\n const pad = indent.repeat(depth);\n if (node.nodeType === Node.TEXT_NODE) {\n const text = (node.textContent ?? '').trim();\n // Text directly inside a container (unusual in editor output): keep it.\n if (text) lines.push(pad + (node as Text).data.trim());\n return;\n }\n if (node.nodeType !== Node.ELEMENT_NODE) return;\n const el = node as Element;\n if (CONTAINERS.has(el.tagName) && hasBlockChildren(el)) {\n lines.push(pad + openTag(el));\n el.childNodes.forEach((child) => print(child, depth + 1));\n lines.push(`${pad}</${el.tagName.toLowerCase()}>`);\n } else {\n lines.push(pad + el.outerHTML);\n }\n };\n\n container.childNodes.forEach((child) => print(child, 0));\n return lines.join('\\n');\n}\n","import { Plugin, PluginKey } from 'prosemirror-state';\nimport type { Node as PMNode } from 'prosemirror-model';\nimport { createDoc } from '../content';\nimport type { Editor } from '../editor';\nimport { formatHTML } from '../format-html';\nimport { icons } from '../icons';\nimport { definePlugin } from '../plugin';\n\nconst sourceKey = new PluginKey('wysio-source');\n\n/** Shows the HTML in a textarea and applies edits to the document as they are typed. */\nclass SourceView {\n readonly textarea: HTMLTextAreaElement;\n /** The last document produced from the textarea, to tell our own updates apart. */\n private ownDoc: PMNode | null = null;\n /** True while our own edit is being dispatched. */\n private applying = false;\n\n constructor(private editor: Editor) {\n const doc = editor.dom.ownerDocument;\n this.textarea = doc.createElement('textarea');\n this.textarea.className = 'wysio-source';\n this.textarea.spellcheck = false;\n this.textarea.hidden = true;\n this.textarea.setAttribute('aria-label', editor.t('source.label'));\n this.textarea.setAttribute('autocapitalize', 'off');\n this.textarea.setAttribute('autocomplete', 'off');\n this.textarea.addEventListener('input', () => this.apply());\n editor.view.dom.parentElement!.after(this.textarea);\n }\n\n private get body(): HTMLElement {\n return this.editor.view.dom.parentElement!;\n }\n\n open(): void {\n this.ownDoc = this.editor.view.state.doc;\n this.textarea.value = formatHTML(this.editor.getHTML(), ' ', this.editor.dom.ownerDocument);\n this.textarea.readOnly = !this.editor.isEditable;\n // Same height as the editing area, so the layout doesn't jump.\n const height = this.body.offsetHeight;\n if (height) this.textarea.style.height = `${height}px`;\n this.body.hidden = true;\n this.textarea.hidden = false;\n this.editor.setMode('source');\n this.textarea.focus();\n this.textarea.setSelectionRange(0, 0);\n this.textarea.scrollTop = 0;\n }\n\n close(): void {\n this.textarea.hidden = true;\n this.body.hidden = false;\n this.editor.setMode('wysiwyg');\n this.editor.focus();\n }\n\n /** Parses the textarea through the schema (same sanitising as setContent) and applies it. */\n private apply(): void {\n const { view, schema } = this.editor;\n const doc = createDoc(schema, this.textarea.value, this.editor.dom.ownerDocument);\n if (doc.eq(view.state.doc)) return;\n this.applying = true;\n try {\n view.dispatch(\n view.state.tr\n .replaceWith(0, view.state.doc.content.size, doc.content)\n .setMeta(sourceKey, true),\n );\n } finally {\n this.applying = false;\n }\n this.ownDoc = view.state.doc;\n }\n\n /** Called on every view update: reflect outside changes (setContent, read-only). */\n sync(): void {\n if (this.editor.mode !== 'source' || this.applying) return;\n this.textarea.readOnly = !this.editor.isEditable;\n const { doc } = this.editor.view.state;\n if (doc !== this.ownDoc) {\n this.ownDoc = doc;\n this.textarea.value = formatHTML(this.editor.getHTML(), ' ', this.editor.dom.ownerDocument);\n }\n }\n}\n\nconst views = new WeakMap<Editor, SourceView>();\n\nfunction sourceView(editor: Editor): SourceView {\n let view = views.get(editor);\n if (!view) views.set(editor, (view = new SourceView(editor)));\n return view;\n}\n\n/** Switches between the WYSIWYG editor and the HTML source view. */\nexport function toggleSourceView(editor: Editor): void {\n if (!editor.hasPlugin('source')) return;\n const view = sourceView(editor);\n if (editor.mode === 'source') view.close();\n else view.open();\n}\n\nexport const source = definePlugin({\n name: 'source',\n prosemirrorPlugins: ({ editor }) => [\n new Plugin({\n key: sourceKey,\n view: () => {\n // setContent() creates a new state, which recreates plugin views: sync then too.\n views.get(editor)?.sync();\n return { update: () => views.get(editor)?.sync() };\n },\n }),\n ],\n toolbarItems: ({ editor }) => ({\n source: {\n label: editor.t('source'),\n icon: icons.source,\n run: toggleSourceView,\n isActive: () => editor.mode === 'source',\n isEnabled: () => true,\n availableInSourceMode: true,\n },\n }),\n});\n","import type { Node as PMNode, NodeSpec, Schema } from 'prosemirror-model';\nimport { TextSelection, type Command, type EditorState } from 'prosemirror-state';\nimport {\n addColumnAfter,\n addColumnBefore,\n addRowAfter,\n addRowBefore,\n deleteColumn,\n deleteRow,\n deleteTable,\n goToNextCell,\n isInTable,\n tableEditing,\n} from 'prosemirror-tables';\nimport { findAncestor } from '../commands';\nimport type { Editor } from '../editor';\nimport { icons } from '../icons';\nimport { definePlugin, type ToolbarButton } from '../plugin';\nimport { createForm, getPopover, Popover, query } from '../ui/popover';\n\nexport const MAX_TABLE_SIZE = 10;\nconst MAX_SPAN = 50;\n\nconst toSpan = (value: unknown): number => {\n const n = Number(value);\n return Number.isInteger(n) && n >= 1 && n <= MAX_SPAN ? n : 1;\n};\n\nconst spanAttrs = {\n colspan: { default: 1, validate: 'number' },\n rowspan: { default: 1, validate: 'number' },\n // Used by prosemirror-tables; never read from or written to HTML (resizing is not free).\n colwidth: { default: null },\n};\n\nfunction cellSpec(tag: 'td' | 'th', tableRole: 'cell' | 'header_cell'): NodeSpec {\n return {\n content: 'block+',\n attrs: spanAttrs,\n tableRole,\n isolating: true,\n parseDOM: [\n {\n tag,\n getAttrs: (dom) => {\n const el = dom as HTMLElement;\n return {\n colspan: toSpan(el.getAttribute('colspan') ?? 1),\n rowspan: toSpan(el.getAttribute('rowspan') ?? 1),\n };\n },\n },\n ],\n toDOM: (node) => {\n const attrs: Record<string, string> = {};\n const colspan = toSpan(node.attrs.colspan);\n const rowspan = toSpan(node.attrs.rowspan);\n if (colspan !== 1) attrs.colspan = String(colspan);\n if (rowspan !== 1) attrs.rowspan = String(rowspan);\n return [tag, attrs, 0];\n },\n };\n}\n\n/** Builds a `rows` × `cols` table; the first row uses header cells when `header` is set. */\nexport function createTable(schema: Schema, rows: number, cols: number, header = true): PMNode {\n const { table, table_row: row, table_cell: cell, table_header: th } = schema.nodes;\n if (!table || !row || !cell || !th) throw new Error('[wysio] The table plugin is not enabled.');\n const clamp = (n: number) => Math.min(MAX_TABLE_SIZE, Math.max(1, Math.trunc(n) || 1));\n return table.create(\n null,\n Array.from({ length: clamp(rows) }, (_, r) =>\n row.create(\n null,\n Array.from({ length: clamp(cols) }, () => (header && r === 0 ? th : cell).createAndFill()!),\n ),\n ),\n );\n}\n\n/** Inserts a table at the selection and puts the cursor in its first cell. */\nexport function insertTable(rows: number, cols: number, header = true): Command {\n return (state, dispatch) => {\n if (!state.schema.nodes.table || isInTable(state)) return false;\n const table = createTable(state.schema, rows, cols, header);\n const { $from } = state.selection;\n let allowed = false;\n for (let depth = $from.depth; depth >= 0 && !allowed; depth--) {\n const index = $from.index(depth);\n allowed = $from.node(depth).canReplaceWith(index, index, table.type);\n }\n if (!allowed) return false;\n if (dispatch) {\n const tr = state.tr.replaceSelectionWith(table);\n let tablePos = -1;\n tr.doc.descendants((node, pos) => {\n if (node === table) tablePos = pos;\n return tablePos === -1;\n });\n // table > row > cell > paragraph: the first text position is 4 positions in.\n if (tablePos !== -1) tr.setSelection(TextSelection.near(tr.doc.resolve(tablePos + 4)));\n dispatch(tr.scrollIntoView());\n }\n return true;\n };\n}\n\n/** Turns the table's first row into header cells, or back into normal cells. */\nexport const toggleHeaderRow: Command = (state, dispatch) => {\n const { table, table_cell: td, table_header: th } = state.schema.nodes;\n const found = table && td && th ? findAncestor(state, [table]) : null;\n const row = found?.node.firstChild;\n if (!found || !row || !td || !th) return false;\n if (dispatch) {\n const toHeader = row.content.content.some((cell) => cell.type !== th);\n const tr = state.tr;\n // Positions: table open (+1), row open (+1), then each cell.\n row.forEach((cell, offset) => {\n tr.setNodeMarkup(found.pos + 2 + offset, toHeader ? th : td, cell.attrs);\n });\n dispatch(tr);\n }\n return true;\n};\n\n/** Tab: next cell; in the last cell, add a row first (like TinyMCE). */\nconst nextCell: Command = (state, dispatch, view) => {\n if (!isInTable(state)) return false;\n if (goToNextCell(1)(state, dispatch, view)) return true;\n if (!dispatch || !view) return addRowAfter(state);\n addRowAfter(state, dispatch);\n return goToNextCell(1)(view.state, dispatch, view);\n};\n\ninterface TableAction {\n name: string;\n label: string;\n command: Command;\n icon: string;\n}\n\nfunction tableActions(editor: Editor): TableAction[] {\n return [\n {\n name: 'tableAddRowBefore',\n label: 'table.addRowBefore',\n command: addRowBefore,\n icon: icons.tableRowBefore,\n },\n {\n name: 'tableAddRowAfter',\n label: 'table.addRowAfter',\n command: addRowAfter,\n icon: icons.tableRowAfter,\n },\n {\n name: 'tableAddColumnBefore',\n label: 'table.addColumnBefore',\n command: addColumnBefore,\n icon: icons.tableColumnBefore,\n },\n {\n name: 'tableAddColumnAfter',\n label: 'table.addColumnAfter',\n command: addColumnAfter,\n icon: icons.tableColumnAfter,\n },\n {\n name: 'tableDeleteRow',\n label: 'table.deleteRow',\n command: deleteRow,\n icon: icons.tableDeleteRow,\n },\n {\n name: 'tableDeleteColumn',\n label: 'table.deleteColumn',\n command: deleteColumn,\n icon: icons.tableDeleteColumn,\n },\n {\n name: 'tableToggleHeaderRow',\n label: 'table.toggleHeaderRow',\n command: toggleHeaderRow,\n icon: icons.tableHeaderRow,\n },\n { name: 'tableDelete', label: 'table.delete', command: deleteTable, icon: icons.tableDelete },\n ].map((a) => ({ ...a, label: editor.t(a.label) }));\n}\n\n// --- Popover: size picker when outside a table, actions when inside ---------\n\n/** Opens the table popover: a size picker, or the table actions when the cursor is in a table. */\nexport function openTableMenu(editor: Editor): void {\n if (!editor.isEditable || !editor.schema.nodes.table) return;\n getPopover(editor, 'table', () => new TablePopover(editor)).open();\n}\n\nclass TablePopover extends Popover {\n private picker: HTMLElement;\n private actions: HTMLElement;\n private cells: HTMLButtonElement[] = [];\n private size: HTMLElement;\n private header: HTMLInputElement;\n private actionButtons: { button: HTMLButtonElement; action: TableAction }[] = [];\n\n constructor(editor: Editor) {\n super(editor, editor.t('table'));\n const doc = editor.dom.ownerDocument;\n this.dom.classList.add('wysio-popover-table');\n\n const form = createForm(\n doc,\n this.uid,\n `<div class=\"wysio-table-picker\">\n <div class=\"wysio-table-grid\" role=\"group\"></div>\n <p class=\"wysio-table-size\" aria-live=\"polite\"></p>\n <label class=\"wysio-check\"><input type=\"checkbox\" name=\"header\" checked> <span></span></label>\n </div>\n <div class=\"wysio-table-actions\"></div>`,\n );\n this.picker = query(form, '.wysio-table-picker');\n this.actions = query(form, '.wysio-table-actions');\n this.size = query(form, '.wysio-table-size');\n this.header = query(form, 'input[name=header]');\n query(form, '.wysio-check span').textContent = editor.t('table.header');\n\n const grid = query<HTMLElement>(form, '.wysio-table-grid');\n grid.setAttribute('aria-label', editor.t('table.size'));\n for (let r = 1; r <= MAX_TABLE_SIZE; r++) {\n for (let c = 1; c <= MAX_TABLE_SIZE; c++) {\n const cell = doc.createElement('button');\n cell.type = 'button';\n cell.className = 'wysio-table-cell';\n cell.tabIndex = -1;\n cell.dataset.rows = String(r);\n cell.dataset.cols = String(c);\n cell.setAttribute('aria-label', this.sizeLabel(r, c));\n cell.addEventListener('mouseenter', () => this.highlight(r, c));\n cell.addEventListener('focus', () => this.highlight(r, c));\n cell.addEventListener('click', () => this.insert(r, c));\n grid.appendChild(cell);\n this.cells.push(cell);\n }\n }\n grid.addEventListener('keydown', this.onGridKey);\n\n for (const action of tableActions(editor)) {\n const button = doc.createElement('button');\n button.type = 'button';\n button.className = 'wysio-menu-item';\n button.dataset.action = action.name;\n button.innerHTML = action.icon;\n button.append(doc.createTextNode(action.label));\n button.addEventListener('click', () => {\n this.close(false);\n this.editor.exec(action.command);\n });\n this.actions.appendChild(button);\n this.actionButtons.push({ button, action });\n }\n this.actions.addEventListener('keydown', this.onActionsKey);\n this.dom.appendChild(form);\n }\n\n open(): void {\n const { state } = this.editor.view;\n const inTable = isInTable(state);\n this.picker.hidden = inTable;\n this.actions.hidden = !inTable;\n this.dom.setAttribute('aria-label', this.editor.t(inTable ? 'table' : 'table.insert'));\n if (inTable) {\n for (const { button, action } of this.actionButtons) button.disabled = !action.command(state);\n const first = this.actionButtons.find((b) => !b.button.disabled)?.button;\n this.show(state.selection.from, first ?? this.actions);\n } else {\n this.highlight(1, 1);\n this.show(state.selection.from, this.cell(1, 1)!);\n }\n }\n\n private sizeLabel(rows: number, cols: number): string {\n return this.editor.t('table.cells', { rows, cols });\n }\n\n private cell(rows: number, cols: number): HTMLButtonElement | undefined {\n return this.cells[(rows - 1) * MAX_TABLE_SIZE + (cols - 1)];\n }\n\n private highlight(rows: number, cols: number): void {\n for (const cell of this.cells) {\n const on = Number(cell.dataset.rows) <= rows && Number(cell.dataset.cols) <= cols;\n cell.classList.toggle('wysio-active', on);\n cell.tabIndex =\n Number(cell.dataset.rows) === rows && Number(cell.dataset.cols) === cols ? 0 : -1;\n }\n this.size.textContent = this.sizeLabel(rows, cols);\n }\n\n private insert(rows: number, cols: number): void {\n this.close(false);\n this.editor.exec(insertTable(rows, cols, this.header.checked));\n }\n\n private onGridKey = (e: KeyboardEvent) => {\n const target = e.target as HTMLElement;\n let rows = Number(target.dataset.rows);\n let cols = Number(target.dataset.cols);\n if (!rows || !cols) return;\n if (e.key === 'ArrowRight') cols++;\n else if (e.key === 'ArrowLeft') cols--;\n else if (e.key === 'ArrowDown') rows++;\n else if (e.key === 'ArrowUp') rows--;\n else if (e.key === 'Home') cols = 1;\n else if (e.key === 'End') cols = MAX_TABLE_SIZE;\n else return;\n e.preventDefault();\n rows = Math.min(MAX_TABLE_SIZE, Math.max(1, rows));\n cols = Math.min(MAX_TABLE_SIZE, Math.max(1, cols));\n this.cell(rows, cols)?.focus();\n };\n\n private onActionsKey = (e: KeyboardEvent) => {\n const buttons = this.actionButtons.map((b) => b.button).filter((b) => !b.disabled);\n const index = buttons.indexOf(e.target as HTMLButtonElement);\n let next: number | null = null;\n if (e.key === 'ArrowDown') next = (index + 1) % buttons.length;\n else if (e.key === 'ArrowUp') next = (index - 1 + buttons.length) % buttons.length;\n else if (e.key === 'Home') next = 0;\n else if (e.key === 'End') next = buttons.length - 1;\n if (next === null) return;\n e.preventDefault();\n buttons[next]?.focus();\n };\n}\n\n// --- Plugin -------------------------------------------------------------------\n\nconst inTableOnly = (command: Command) => (state: EditorState) =>\n isInTable(state) && command(state);\n\nexport const table = definePlugin({\n name: 'table',\n schema: {\n nodes: {\n table: {\n content: 'table_row+',\n tableRole: 'table',\n isolating: true,\n group: 'block',\n parseDOM: [{ tag: 'table' }],\n toDOM: () => ['table', ['tbody', 0]],\n },\n table_row: {\n content: '(table_cell | table_header)*',\n tableRole: 'row',\n parseDOM: [{ tag: 'tr' }],\n toDOM: () => ['tr', 0],\n },\n table_cell: cellSpec('td', 'cell'),\n table_header: cellSpec('th', 'header_cell'),\n },\n },\n keymap: () => ({\n Tab: nextCell,\n 'Shift-Tab': goToNextCell(-1),\n }),\n prosemirrorPlugins: () => [tableEditing()],\n toolbarItems: ({ editor }) => {\n const items: Record<string, ToolbarButton> = {\n table: {\n label: editor.t('table'),\n icon: icons.table,\n run: openTableMenu,\n popover: 'table',\n isActive: (state) => isInTable(state),\n isEnabled: (state) => isInTable(state) || insertTable(1, 1)(state),\n },\n };\n for (const action of tableActions(editor)) {\n items[action.name] = {\n label: action.label,\n icon: action.icon,\n command: action.command,\n isEnabled: inTableOnly(action.command),\n };\n }\n return items;\n },\n});\n","import { alignment } from './alignment';\nimport { base } from './base';\nimport { blockquote, hardBreak, horizontalRule } from './blocks';\nimport { clearFormattingPlugin } from './clear-formatting';\nimport { highlight, textColor } from './color';\nimport { heading } from './heading';\nimport { history } from './history';\nimport { image } from './image';\nimport { link } from './link';\nimport { lists } from './lists';\nimport { bold, code, italic, strike, underline } from './marks';\nimport { paste } from './paste';\nimport { placeholder } from './placeholder';\nimport { source } from './source';\nimport { table } from './table';\n\nexport {\n alignment,\n base,\n blockquote,\n bold,\n code,\n hardBreak,\n heading,\n highlight,\n history,\n horizontalRule,\n image,\n italic,\n link,\n lists,\n paste,\n placeholder,\n source,\n strike,\n table,\n textColor,\n underline,\n};\nexport {\n DEFAULT_IMAGE_TYPES,\n IMAGE_ALIGNMENTS,\n insertImage,\n openImageDialog,\n removeImage,\n uploadImages,\n type ImageAlign,\n type ImageAttrs,\n type ImageOptions,\n type UploadContext,\n type UploadHandler,\n type UploadResult,\n} from './image';\nexport { createTable, insertTable, MAX_TABLE_SIZE, openTableMenu, toggleHeaderRow } from './table';\nexport { cleanPastedHTML } from './paste';\nexport { toggleSourceView } from './source';\nexport {\n ALIGNMENTS,\n isAlignmentActive,\n openAlignmentMenu,\n setAlignment,\n type Alignment,\n} from './alignment';\nexport {\n activeColor,\n DEFAULT_HIGHLIGHT_COLORS,\n DEFAULT_TEXT_COLORS,\n normalizeColor,\n paletteCSS,\n removeColorMark,\n setColorMark,\n type ColorOptions,\n type PaletteColor,\n} from './color';\nexport { clearFormatting, clearFormattingPlugin, FORMATTING_ATTRIBUTES } from './clear-formatting';\nexport { openLinkDialog, removeLink, setLink, type LinkAttrs } from './link';\n\n/**\n * Built-in plugins, in schema order. Mark order decides nesting in the output:\n * link is outermost, code innermost.\n */\nexport const defaultPlugins = [\n base,\n heading,\n blockquote,\n lists,\n horizontalRule,\n table,\n hardBreak,\n image(),\n link,\n bold,\n italic,\n underline,\n strike,\n code,\n textColor(),\n highlight(),\n alignment,\n clearFormattingPlugin,\n paste,\n source,\n history,\n placeholder,\n];\n","import { Schema, type MarkSpec, type NodeSpec } from 'prosemirror-model';\nimport type { WysioPlugin } from './plugin';\n\n/** Builds a schema from the nodes and marks of all plugins, in plugin order. */\nexport function buildSchema(plugins: readonly WysioPlugin[]): Schema {\n const nodes: Record<string, NodeSpec> = {};\n const marks: Record<string, MarkSpec> = {};\n for (const plugin of plugins) {\n for (const [name, spec] of Object.entries(plugin.schema?.nodes ?? {})) {\n if (name in nodes)\n throw new Error(`[wysio] Node \"${name}\" is defined twice (plugin \"${plugin.name}\").`);\n nodes[name] = spec;\n }\n for (const [name, spec] of Object.entries(plugin.schema?.marks ?? {})) {\n if (name in marks)\n throw new Error(`[wysio] Mark \"${name}\" is defined twice (plugin \"${plugin.name}\").`);\n marks[name] = spec;\n }\n }\n for (const plugin of plugins) {\n for (const [name, extend] of Object.entries(plugin.schema?.extendNodes ?? {})) {\n const spec = nodes[name];\n if (spec) nodes[name] = extend(spec);\n }\n }\n return new Schema({ nodes, marks });\n}\n","import type { EditorState } from 'prosemirror-state';\nimport type { Editor } from '../editor';\nimport type { ToolbarButton, ToolbarItem, ToolbarSelect } from '../plugin';\n\nexport const SEPARATOR = '|';\n\n/** `overflow`: items that don't fit go into a \"More\" panel. `wrap`: items wrap to more rows. */\nexport type ToolbarMode = 'overflow' | 'wrap';\n\ntype Control =\n | { kind: 'button'; item: ToolbarButton; el: HTMLButtonElement; icon: HTMLElement }\n | { kind: 'select'; item: ToolbarSelect; el: HTMLSelectElement };\n\nconst isMac = () =>\n typeof navigator !== 'undefined' && /Mac|iP(hone|[oa]d)/.test(navigator.platform);\n\n/** `Mod-Shift-z` → `Ctrl+Shift+Z` (or `⌘⇧Z` on macOS). */\nexport function formatShortcut(shortcut: string): string {\n const mac = isMac();\n const parts = shortcut.split('-').map((part) => {\n switch (part) {\n case 'Mod':\n return mac ? '⌘' : 'Ctrl';\n case 'Shift':\n return mac ? '⇧' : 'Shift';\n case 'Alt':\n return mac ? '⌥' : 'Alt';\n case 'Ctrl':\n return mac ? '⌃' : 'Ctrl';\n default:\n return part.length === 1 ? part.toUpperCase() : part;\n }\n });\n return parts.join(mac ? '' : '+');\n}\n\n/**\n * How many items fit in a row: the number of leading items whose right edge\n * (offsetLeft + offsetWidth) is within `limit`.\n */\nexport function fitCount(rightEdges: readonly number[], limit: number): number {\n let count = 0;\n while (count < rightEdges.length && rightEdges[count]! <= limit) count++;\n return count;\n}\n\nconst CARET =\n '<svg class=\"wysio-caret\" viewBox=\"0 0 10 10\" width=\"8\" height=\"8\" aria-hidden=\"true\" focusable=\"false\"><path d=\"m2 3.5 3 3 3-3\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>';\n\nlet toolbarCount = 0;\n\n/**\n * Accessible toolbar: role=\"toolbar\", a single tab stop with arrow-key navigation\n * (roving tabindex), aria-pressed on toggles, aria-disabled on unavailable items and\n * aria-expanded on buttons that open popovers. In `overflow` mode, items that don't\n * fit move into a \"More\" disclosure panel.\n */\nexport class Toolbar {\n readonly dom: HTMLElement;\n private controls: Control[] = [];\n /** Controls and separators in configured order. */\n private entries: HTMLElement[] = [];\n private more: HTMLButtonElement | null = null;\n private panel: HTMLElement | null = null;\n private observer: ResizeObserver | null = null;\n\n constructor(\n private editor: Editor,\n names: readonly string[],\n registry: ReadonlyMap<string, ToolbarItem>,\n { warnUnknown = true, mode = 'overflow' as ToolbarMode } = {},\n ) {\n const doc = editor.dom.ownerDocument;\n this.dom = doc.createElement('div');\n this.dom.className = 'wysio-toolbar';\n this.dom.dataset.mode = mode;\n this.dom.setAttribute('role', 'toolbar');\n // UI language, so screen readers pronounce the labels correctly on any page.\n if (editor.locale) this.dom.lang = editor.locale;\n this.dom.setAttribute('aria-label', editor.t('toolbar'));\n this.dom.setAttribute('aria-controls', editor.view.dom.id);\n\n let lastWasSeparator = true;\n for (const name of names) {\n if (name === SEPARATOR) {\n if (lastWasSeparator) continue;\n const sep = doc.createElement('span');\n sep.className = 'wysio-separator';\n sep.setAttribute('role', 'separator');\n sep.setAttribute('aria-orientation', 'vertical');\n this.entries.push(sep);\n lastWasSeparator = true;\n continue;\n }\n const item = registry.get(name);\n if (!item) {\n if (warnUnknown) console.warn(`[wysio] Unknown toolbar item \"${name}\".`);\n continue;\n }\n const control =\n item.type === 'select' ? this.createSelect(name, item) : this.createButton(name, item);\n this.controls.push(control);\n this.entries.push(control.el);\n lastWasSeparator = false;\n }\n if (this.entries.at(-1)?.classList.contains('wysio-separator')) this.entries.pop();\n this.dom.append(...this.entries);\n\n if (mode === 'overflow') this.setUpOverflow();\n\n this.dom.addEventListener('keydown', this.onKeyDown);\n this.dom.addEventListener('focusin', this.onFocusIn);\n editor.dom.addEventListener('wysio:popover', this.onPopover);\n this.controls[0]?.el.setAttribute('tabindex', '0');\n }\n\n private label(name: string, item: ToolbarItem): string {\n return item.labelKey ? this.editor.t(item.labelKey) : (item.label ?? name);\n }\n\n private createButton(name: string, item: ToolbarButton): Control {\n const doc = this.editor.dom.ownerDocument;\n const el = doc.createElement('button');\n const label = this.label(name, item);\n el.type = 'button';\n el.className = 'wysio-tool';\n el.dataset.item = name;\n el.tabIndex = -1;\n const icon = doc.createElement('span');\n icon.className = 'wysio-icon';\n icon.innerHTML = item.icon;\n el.appendChild(icon);\n if (item.dropdown) el.insertAdjacentHTML('beforeend', CARET);\n el.setAttribute('aria-label', label);\n el.title = item.shortcut ? `${label} (${formatShortcut(item.shortcut)})` : label;\n if (item.isActive) el.setAttribute('aria-pressed', 'false');\n if (item.popover) {\n el.setAttribute('aria-haspopup', 'dialog');\n el.setAttribute('aria-expanded', 'false');\n }\n // Keep the editor selection (and focus) when clicking with the mouse.\n el.addEventListener('mousedown', (e) => e.preventDefault());\n el.addEventListener('click', () => {\n if (el.getAttribute('aria-disabled') === 'true') return;\n if (item.run) item.run(this.editor);\n else if (item.command) this.editor.exec(item.command);\n });\n return { kind: 'button', item, el, icon };\n }\n\n private createSelect(name: string, item: ToolbarSelect): Control {\n const doc = this.editor.dom.ownerDocument;\n const el = doc.createElement('select');\n const label = this.label(name, item);\n el.className = 'wysio-select';\n el.dataset.item = name;\n el.tabIndex = -1;\n el.setAttribute('aria-label', label);\n el.title = label;\n const blank = doc.createElement('option');\n blank.value = '';\n blank.hidden = true;\n blank.textContent = '—';\n el.appendChild(blank);\n for (const option of item.options) {\n const opt = doc.createElement('option');\n opt.value = option.value;\n opt.textContent = option.label;\n el.appendChild(opt);\n }\n el.addEventListener('change', () => {\n if (el.value) item.onSelect(this.editor, el.value);\n });\n return { kind: 'select', item, el };\n }\n\n update(state: EditorState): void {\n const editable = this.editor.isEditable;\n const wysiwyg = this.editor.mode === 'wysiwyg';\n for (const control of this.controls) {\n const { item, el } = control;\n let enabled = item.availableInSourceMode || (editable && wysiwyg);\n if (enabled) {\n if (item.isEnabled) enabled = item.isEnabled(state, this.editor);\n else if (control.kind === 'button' && control.item.command)\n enabled = control.item.command(state);\n }\n if (control.kind === 'select') {\n control.el.disabled = !enabled;\n control.el.value = control.item.getValue(state);\n continue;\n }\n el.setAttribute('aria-disabled', String(!enabled));\n if (control.item.isActive) {\n // In source mode only items that work there show a pressed state.\n const active = (wysiwyg || !!item.availableInSourceMode) && control.item.isActive(state);\n el.setAttribute('aria-pressed', String(active));\n }\n const { icon } = control;\n control.item.render?.(state, {\n el: control.el,\n setIcon: (html) => {\n if (icon.innerHTML !== html) icon.innerHTML = html;\n },\n });\n }\n }\n\n /** Moves focus into the toolbar (Alt+F10 from the editor). */\n focus(): void {\n const items = this.focusable();\n (items.find((el) => el.tabIndex === 0) ?? items[0])?.focus();\n }\n\n destroy(): void {\n this.observer?.disconnect();\n this.closePanel(false);\n this.editor.dom.removeEventListener('wysio:popover', this.onPopover);\n this.dom.remove();\n }\n\n // --- Overflow -----------------------------------------------------------------\n\n private setUpOverflow(): void {\n const doc = this.editor.dom.ownerDocument;\n const id = `wysio-toolbar-more-${++toolbarCount}`;\n this.more = doc.createElement('button');\n this.more.type = 'button';\n this.more.className = 'wysio-tool wysio-more';\n this.more.tabIndex = -1;\n this.more.hidden = true;\n this.more.innerHTML =\n '<svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" aria-hidden=\"true\" focusable=\"false\"><circle cx=\"5\" cy=\"12\" r=\"1.75\" fill=\"currentColor\"/><circle cx=\"12\" cy=\"12\" r=\"1.75\" fill=\"currentColor\"/><circle cx=\"19\" cy=\"12\" r=\"1.75\" fill=\"currentColor\"/></svg>';\n this.more.setAttribute('aria-label', this.editor.t('toolbar.more'));\n this.more.title = this.editor.t('toolbar.more');\n this.more.setAttribute('aria-expanded', 'false');\n this.more.setAttribute('aria-controls', id);\n this.more.addEventListener('mousedown', (e) => e.preventDefault());\n this.more.addEventListener('click', () => {\n if (this.panel?.hidden) this.openPanel();\n else this.closePanel(true);\n });\n\n this.panel = doc.createElement('div');\n this.panel.id = id;\n this.panel.className = 'wysio-toolbar-panel';\n this.panel.hidden = true;\n this.panel.setAttribute('role', 'group');\n this.panel.setAttribute('aria-label', this.editor.t('toolbar.more'));\n this.panel.addEventListener('keydown', this.onPanelKey);\n // Using an item closes the panel (select: after choosing).\n this.panel.addEventListener('click', (e) => {\n const target = (e.target as HTMLElement).closest('button');\n if (target && target.getAttribute('aria-disabled') !== 'true') this.closePanel(false);\n });\n this.panel.addEventListener('change', () => this.closePanel(false));\n\n this.dom.append(this.more, this.panel);\n if (typeof ResizeObserver !== 'undefined') {\n this.observer = new ResizeObserver(() => this.layout());\n this.observer.observe(this.dom);\n }\n }\n\n /** Moves the items that don't fit into the \"More\" panel. Runs on every resize. */\n layout(): void {\n const { more, panel } = this;\n if (!more || !panel) return;\n const focused = this.editor.dom.ownerDocument.activeElement;\n for (const el of this.entries) this.dom.insertBefore(el, more);\n more.hidden = true;\n if (this.dom.scrollWidth <= this.dom.clientWidth) {\n this.closePanel(false);\n this.ensureTabStop();\n return;\n }\n more.hidden = false;\n const style = getComputedStyle(this.dom);\n const gap = parseFloat(style.columnGap) || 0;\n const limit =\n this.dom.clientWidth - (parseFloat(style.paddingRight) || 0) - more.offsetWidth - gap;\n let count = fitCount(\n this.entries.map((el) => el.offsetLeft + el.offsetWidth),\n limit,\n );\n // Don't end the row with a separator.\n while (count > 0 && this.entries[count - 1]!.classList.contains('wysio-separator')) count--;\n for (const el of this.entries.slice(count)) panel.appendChild(el);\n this.ensureTabStop();\n if (focused instanceof HTMLElement && this.dom.contains(focused)) focused.focus();\n }\n\n private openPanel(): void {\n const { more, panel } = this;\n if (!more || !panel) return;\n panel.hidden = false;\n more.setAttribute('aria-expanded', 'true');\n this.editor.dom.ownerDocument.addEventListener('mousedown', this.onOutside, true);\n this.panelItems()[0]?.focus();\n }\n\n private closePanel(focusMore: boolean): void {\n const { more, panel } = this;\n if (!more || !panel || panel.hidden) return;\n panel.hidden = true;\n more.setAttribute('aria-expanded', 'false');\n this.editor.dom.ownerDocument.removeEventListener('mousedown', this.onOutside, true);\n if (focusMore) more.focus();\n }\n\n private panelItems(): HTMLElement[] {\n if (!this.panel) return [];\n return this.controls\n .map((c) => c.el)\n .filter(\n (el) => this.panel!.contains(el) && !(el instanceof HTMLSelectElement && el.disabled),\n );\n }\n\n private onOutside = (e: MouseEvent) => {\n const target = e.target as Node;\n if (!this.panel?.contains(target) && !this.more?.contains(target)) this.closePanel(false);\n };\n\n private onPanelKey = (e: KeyboardEvent) => {\n e.stopPropagation();\n if (e.key === 'Escape') {\n e.preventDefault();\n this.closePanel(true);\n return;\n }\n if (e.target instanceof HTMLSelectElement && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) {\n return; // Let the select change its value.\n }\n const items = this.panelItems();\n const index = items.indexOf(e.target as HTMLElement);\n let next: number | null = null;\n if (e.key === 'ArrowRight' || e.key === 'ArrowDown') next = (index + 1) % items.length;\n else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp')\n next = (index - 1 + items.length) % items.length;\n else if (e.key === 'Home') next = 0;\n else if (e.key === 'End') next = items.length - 1;\n if (next === null) return;\n e.preventDefault();\n items[next]?.focus();\n };\n\n // --- Focus and popovers -----------------------------------------------------\n\n /** Row items plus the \"More\" button, in order. */\n private focusable(): HTMLElement[] {\n const row = this.controls\n .map((c) => c.el)\n .filter(\n (el) => el.parentElement === this.dom && !(el instanceof HTMLSelectElement && el.disabled),\n );\n return this.more && !this.more.hidden ? [...row, this.more] : row;\n }\n\n /** Keeps exactly one tab stop in the row, also after items moved into the panel. */\n private ensureTabStop(): void {\n const items = this.focusable();\n if (items.some((el) => el.tabIndex === 0)) return;\n for (const c of this.controls) c.el.tabIndex = -1;\n if (this.more) this.more.tabIndex = -1;\n if (items[0]) items[0].tabIndex = 0;\n }\n\n private onFocusIn = (e: FocusEvent) => {\n const target = e.target as HTMLElement;\n if (!this.focusable().includes(target)) return;\n for (const c of this.controls) c.el.tabIndex = c.el === target ? 0 : -1;\n if (this.more) this.more.tabIndex = this.more === target ? 0 : -1;\n };\n\n private onKeyDown = (e: KeyboardEvent) => {\n if (e.key === 'Escape') {\n e.preventDefault();\n this.editor.focus();\n return;\n }\n const items = this.focusable();\n if (!items.length) return;\n const index = items.indexOf(e.target as HTMLElement);\n if (index === -1) return;\n let next: number | null = null;\n if (e.key === 'ArrowRight') next = (index + 1) % items.length;\n else if (e.key === 'ArrowLeft') next = (index - 1 + items.length) % items.length;\n else if (e.key === 'Home') next = 0;\n else if (e.key === 'End') next = items.length - 1;\n if (next === null) return;\n e.preventDefault();\n items[next]?.focus();\n };\n\n private onPopover = (e: Event) => {\n const { key, open } = (e as CustomEvent<{ key: string; open: boolean }>).detail;\n for (const c of this.controls) {\n if (c.kind === 'button' && c.item.popover === key) {\n c.el.setAttribute('aria-expanded', String(open));\n }\n }\n };\n}\n","import { baseKeymap } from 'prosemirror-commands';\nimport { inputRules, undoInputRule } from 'prosemirror-inputrules';\nimport { keymap } from 'prosemirror-keymap';\nimport type { Node as PMNode, Schema } from 'prosemirror-model';\nimport { EditorState, type Command, type Plugin, type Transaction } from 'prosemirror-state';\nimport { EditorView } from 'prosemirror-view';\nimport {\n createDoc,\n isDocEmpty,\n normalizeDoc,\n serializeHTML,\n type Content,\n type JSONContent,\n} from './content';\nimport { Emitter } from './emitter';\nimport { findLocale, interpolate } from './i18n';\nimport { defaultMessages, type Messages } from './messages';\nimport type { ContentFormatHandler, PluginContext, ToolbarItem, WysioPlugin } from './plugin';\nimport { defaultPlugins } from './plugins';\nimport type { UploadHandler } from './plugins/image';\nimport { resolvePluginNames } from './registry';\nimport { buildSchema } from './schema';\nimport { Toolbar, type ToolbarMode } from './toolbar/toolbar';\n\nexport const defaultToolbar = [\n 'heading',\n '|',\n 'bold',\n 'italic',\n 'underline',\n 'strike',\n 'code',\n '|',\n 'textColor',\n 'highlight',\n 'clearFormatting',\n '|',\n 'align',\n 'bulletList',\n 'orderedList',\n 'blockquote',\n 'horizontalRule',\n 'table',\n '|',\n 'link',\n 'image',\n '|',\n 'undo',\n 'redo',\n];\n\n/** Text formats for content: HTML, a ProseMirror JSON string, or one added by a plugin (`markdown`). */\nexport type ContentFormat = 'html' | 'json' | 'markdown' | (string & {});\n\nexport interface EditorOptions {\n /**\n * Initial content: a string in `format` (HTML by default) or a ProseMirror JSON object.\n * Defaults to the element's HTML (or a textarea's value).\n */\n content?: Content;\n /**\n * How string content (the `content` option, a textarea's value) is read, and what is\n * written to a textarea or the `name` input. `markdown` needs the markdown plugin.\n * Default `html`.\n */\n format?: ContentFormat;\n /**\n * Form field name. The editor keeps a hidden input with this name in sync (in\n * `format`), so it works in plain HTML forms. For a textarea target, this sets the\n * textarea's name instead. Resetting the form restores the initial content.\n */\n name?: string;\n /** Toolbar item names, with `'|'` as separator. `false` hides the toolbar. */\n toolbar?: readonly string[] | false;\n /**\n * Extra plugins, added after the built-in ones. A plugin with the same name as a\n * built-in replaces it (e.g. `image({ allowDataUrls: true })`). Strings are looked up\n * among registered plugins (see `registerPlugin`), e.g. `'markdown'`.\n */\n plugins?: readonly (WysioPlugin | string)[];\n /** Names of built-in plugins to leave out, e.g. `['image', 'horizontalRule']`. */\n removePlugins?: readonly string[];\n placeholder?: string;\n editable?: boolean;\n /** Accessible name of the editing area. */\n ariaLabel?: string;\n /**\n * `overflow` (default): items that don't fit move into a \"More\" menu.\n * `wrap`: the toolbar wraps onto more rows.\n */\n toolbarMode?: ToolbarMode;\n /**\n * Keep the toolbar visible while scrolling long content. A number sets the distance\n * from the top of the viewport in pixels (e.g. below a fixed site header).\n */\n sticky?: boolean | number;\n /**\n * UI language: a code such as `nl` or `nl-BE` (built in: `en`, `nl`; add more with\n * `registerLocale`), or a messages object. Missing strings fall back to English.\n */\n locale?: string | Messages;\n /** Overrides for individual UI strings, applied on top of `locale`. */\n messages?: Messages;\n onChange?: (editor: Editor) => void;\n /**\n * Upload adapter for image files (dialog file picker, paste, drop). Resolves with the\n * public URL. Without it, images can only be added by URL.\n */\n upload?: UploadHandler;\n}\n\nexport interface EditorErrorInfo {\n /** What failed. */\n source: 'upload';\n file?: File;\n}\n\n/** `wysiwyg` is normal editing; `source` is the HTML source view. */\nexport type EditorMode = 'wysiwyg' | 'source';\n\nexport interface EditorEvents extends Record<string, unknown[]> {\n /** The editor switched between WYSIWYG and source view. */\n mode: [editor: Editor, mode: EditorMode];\n change: [editor: Editor];\n focus: [editor: Editor, event: FocusEvent];\n blur: [editor: Editor, event: FocusEvent];\n /** Every state update, including selection changes. */\n transaction: [editor: Editor, transaction: Transaction];\n destroy: [editor: Editor];\n /** Something failed in the background (e.g. an upload). Logged to the console when nobody listens. */\n error: [editor: Editor, error: unknown, info: EditorErrorInfo];\n}\n\nlet editorCount = 0;\n\nexport class Editor {\n /** Root element (gets the `wysio` class). */\n readonly dom: HTMLElement;\n readonly view: EditorView;\n readonly schema: Schema;\n readonly options: Readonly<EditorOptions>;\n private readonly emitter = new Emitter<EditorEvents>();\n private readonly toolbar: Toolbar | null = null;\n private readonly textarea: HTMLTextAreaElement | null = null;\n private readonly input: HTMLInputElement | null = null;\n private readonly form: HTMLFormElement | null = null;\n private initialContent: JSONContent | null = null;\n private readonly plugins: readonly WysioPlugin[];\n private readonly messages: Messages;\n /** Resolved UI language code (e.g. `nl`), or `null` for a custom messages object. */\n readonly locale: string | null;\n private readonly formats = new Map<string, ContentFormatHandler>();\n private editable: boolean;\n private currentMode: EditorMode = 'wysiwyg';\n private destroyed = false;\n\n constructor(target: HTMLElement | string, options: EditorOptions = {}) {\n const element =\n typeof target === 'string' ? document.querySelector<HTMLElement>(target) : target;\n if (!element) throw new Error(`[wysio] Element not found: ${String(target)}`);\n this.options = options;\n const { locale, messages } = resolveMessages(options.locale);\n this.locale = locale;\n this.messages = { ...defaultMessages, ...messages, ...options.messages };\n this.editable = options.editable ?? true;\n this.plugins = resolvePlugins(options);\n this.schema = buildSchema(this.plugins);\n\n let initial: Content = options.content;\n let initialFormat = options.format;\n if (element instanceof HTMLTextAreaElement) {\n this.textarea = element;\n initial ??= element.value;\n this.dom = element.ownerDocument.createElement('div');\n element.insertAdjacentElement('afterend', this.dom);\n element.hidden = true;\n } else {\n this.dom = element;\n if (initial === undefined) {\n // An element's existing content is HTML, whatever the storage format.\n initial = element.innerHTML.trim();\n initialFormat = 'html';\n }\n element.innerHTML = '';\n }\n this.dom.classList.add('wysio');\n const doc = this.dom.ownerDocument;\n\n const ctx: PluginContext = { schema: this.schema, editor: this };\n for (const plugin of this.plugins) {\n for (const [name, handler] of Object.entries(plugin.formats?.(ctx) ?? {})) {\n this.formats.set(name, handler);\n }\n }\n const mount = doc.createElement('div');\n mount.className = 'wysio-body';\n this.dom.appendChild(mount);\n\n const id = `wysio-${++editorCount}`;\n this.view = new EditorView(mount, {\n state: EditorState.create({\n doc: this.parseContent(initial, initialFormat),\n plugins: this.createProseMirrorPlugins(ctx),\n }),\n editable: () => this.editable,\n attributes: {\n id,\n class: 'wysio-content',\n role: 'textbox',\n 'aria-multiline': 'true',\n 'aria-label': options.ariaLabel ?? this.t('editor'),\n },\n dispatchTransaction: (tr) => this.dispatch(tr),\n handleDOMEvents: {\n focus: (_view, event) => {\n this.emitter.emit('focus', this, event);\n return false;\n },\n blur: (_view, event) => {\n this.emitter.emit('blur', this, event);\n return false;\n },\n },\n });\n\n if (options.toolbar !== false) {\n const registry = new Map<string, ToolbarItem>();\n for (const plugin of this.plugins) {\n for (const [name, item] of Object.entries(plugin.toolbarItems?.(ctx) ?? {}))\n registry.set(name, item);\n }\n this.toolbar = new Toolbar(this, options.toolbar ?? defaultToolbar, registry, {\n warnUnknown: !!options.toolbar,\n mode: options.toolbarMode ?? 'overflow',\n });\n if (options.sticky) {\n this.dom.classList.add('wysio-sticky');\n const top = typeof options.sticky === 'number' ? options.sticky : 0;\n this.dom.style.setProperty('--wysio-sticky-top', `${top}px`);\n }\n this.dom.insertBefore(this.toolbar.dom, mount);\n this.toolbar.update(this.view.state);\n }\n\n // Plain HTML form support: a named textarea, or a hidden input next to the editor.\n if (options.name && this.textarea) {\n this.textarea.name = options.name;\n } else if (options.name) {\n this.input = doc.createElement('input');\n this.input.type = 'hidden';\n this.input.name = options.name;\n this.dom.appendChild(this.input);\n }\n this.form = (this.textarea ?? this.input)?.form ?? null;\n this.form?.addEventListener('reset', this.onFormReset);\n this.initialContent = this.isEmpty ? null : this.getJSON();\n this.syncTextarea();\n }\n\n private createProseMirrorPlugins(ctx: PluginContext): Plugin[] {\n const rules = this.plugins.flatMap((p) => p.inputRules?.(ctx) ?? []);\n return [\n inputRules({ rules }),\n keymap({\n Backspace: undoInputRule,\n 'Alt-F10': () => {\n this.toolbar?.focus();\n return !!this.toolbar;\n },\n }),\n ...this.plugins.flatMap((p) => (p.keymap ? [keymap(p.keymap(ctx))] : [])),\n keymap(baseKeymap),\n ...this.plugins.flatMap((p) => p.prosemirrorPlugins?.(ctx) ?? []),\n ];\n }\n\n private dispatch(tr: Transaction): void {\n if (this.destroyed) return;\n this.view.updateState(this.view.state.apply(tr));\n this.toolbar?.update(this.view.state);\n this.emitter.emit('transaction', this, tr);\n if (tr.docChanged) this.changed();\n }\n\n private changed(): void {\n this.syncTextarea();\n this.emitter.emit('change', this);\n this.options.onChange?.(this);\n }\n\n /** Writes the content to the textarea target and/or the `name` input. */\n private syncTextarea(): void {\n if (!this.textarea && !this.input) return;\n const value = this.serialize(this.options.format ?? 'html');\n if (this.textarea) this.textarea.value = value;\n if (this.input) this.input.value = value;\n }\n\n private onFormReset = () => {\n // The reset event fires before the browser resets the fields; restore afterwards.\n queueMicrotask(() => {\n if (!this.destroyed) this.setContent(this.initialContent, { emitChange: true });\n });\n };\n\n get state(): EditorState {\n return this.view.state;\n }\n\n /** Current mode. Plugins (e.g. the source view) switch it with {@link setMode}. */\n get mode(): EditorMode {\n return this.currentMode;\n }\n\n /** Switches the mode flag; the plugin that owns the mode handles the UI. */\n setMode(mode: EditorMode): void {\n if (mode === this.currentMode) return;\n this.currentMode = mode;\n this.dom.dataset.mode = mode;\n this.toolbar?.update(this.view.state);\n this.emitter.emit('mode', this, mode);\n }\n\n get isEditable(): boolean {\n return this.editable;\n }\n\n get isEmpty(): boolean {\n return isDocEmpty(this.view.state.doc);\n }\n\n /** Translated UI string. */\n /** Translated UI string, with `{name}` placeholders filled from `params`. */\n t(key: string, params?: Record<string, string | number>): string {\n return interpolate(this.messages[key] ?? key, params);\n }\n\n /** Sanitised HTML. Contains only elements and attributes the schema allows. Empty string when empty. */\n getHTML(): string {\n if (this.isEmpty) return '';\n return serializeHTML(this.schema, this.view.state.doc, this.dom.ownerDocument);\n }\n\n getJSON(): JSONContent {\n return this.view.state.doc.toJSON() as JSONContent;\n }\n\n /** Markdown (needs the markdown plugin from `wysio/markdown`). Lossy: see its docs. */\n getMarkdown(): string {\n return this.serialize('markdown');\n }\n\n /** The content as a string in the given format. */\n serialize(format: ContentFormat): string {\n if (format === 'html') return this.getHTML();\n if (format === 'json') return this.isEmpty ? '' : JSON.stringify(this.getJSON());\n const handler = this.formatHandler(format);\n return this.isEmpty ? '' : handler.serialize(this.view.state.doc);\n }\n\n private formatHandler(format: string): ContentFormatHandler {\n const handler = this.formats.get(format);\n if (!handler) {\n const hint =\n format === 'markdown'\n ? \" Add it with: import { markdown } from 'wysio/markdown'; plugins: [markdown()]. On a CDN, use wysio.full.iife.js.\"\n : '';\n throw new Error(`[wysio] No plugin provides the \"${format}\" format.${hint}`);\n }\n return handler;\n }\n\n /** Builds a sanitised document from content: an object is JSON, a string is read as `format`. */\n private parseContent(content: Content, format: ContentFormat = 'html'): PMNode {\n const doc = this.dom.ownerDocument;\n if (typeof content !== 'string' || content === '' || format === 'html') {\n return createDoc(this.schema, content, doc);\n }\n if (format === 'json') return createDoc(this.schema, JSON.parse(content) as JSONContent, doc);\n return normalizeDoc(this.schema, this.formatHandler(format).parse(content, this.schema), doc);\n }\n\n getText(): string {\n const { doc } = this.view.state;\n return doc.textBetween(0, doc.content.size, '\\n\\n');\n }\n\n /**\n * Replaces the content and resets undo history. A string is read as `format`\n * (default: the editor's `format` option, else HTML). Emits `change` only when\n * `emitChange` is set.\n */\n setContent(\n content: Content,\n {\n emitChange = false,\n format = this.options.format,\n }: { emitChange?: boolean; format?: ContentFormat } = {},\n ): void {\n const state = EditorState.create({\n doc: this.parseContent(content, format),\n plugins: this.view.state.plugins,\n });\n this.view.updateState(state);\n this.toolbar?.update(state);\n this.syncTextarea();\n if (emitChange) {\n this.emitter.emit('change', this);\n this.options.onChange?.(this);\n }\n }\n\n setEditable(editable: boolean): void {\n this.editable = editable;\n this.view.setProps({});\n this.toolbar?.update(this.view.state);\n }\n\n /** Runs a ProseMirror command and returns focus to the editor. */\n exec(command: Command): boolean {\n if (!this.editable) return false;\n const result = command(this.view.state, this.view.dispatch, this.view);\n this.focus();\n return result;\n }\n\n /** Reports a background error through the `error` event (or the console). */\n reportError(error: unknown, info: EditorErrorInfo): void {\n if (this.emitter.has('error')) this.emitter.emit('error', this, error, info);\n else console.error(`[wysio] ${info.source} failed:`, error);\n }\n\n /** Whether a plugin with this name is active. */\n hasPlugin(name: string): boolean {\n return this.plugins.some((p) => p.name === name);\n }\n\n focus(): void {\n if (!this.destroyed) this.view.focus();\n }\n\n on<E extends keyof EditorEvents>(\n event: E,\n handler: (...args: EditorEvents[E]) => void,\n ): () => void {\n return this.emitter.on(event, handler);\n }\n\n off<E extends keyof EditorEvents>(event: E, handler: (...args: EditorEvents[E]) => void): void {\n this.emitter.off(event, handler);\n }\n\n /** Removes the editor. A div target keeps the final HTML; a textarea is shown again with the final value. */\n destroy(): void {\n if (this.destroyed) return;\n const html = this.getHTML();\n const value = this.serialize(this.options.format ?? 'html');\n this.emitter.emit('destroy', this);\n this.destroyed = true;\n this.emitter.clear();\n this.view.destroy();\n this.toolbar?.destroy();\n this.form?.removeEventListener('reset', this.onFormReset);\n this.input?.remove();\n if (this.textarea) {\n this.textarea.value = value;\n this.textarea.hidden = false;\n this.dom.remove();\n } else {\n this.dom.classList.remove('wysio', 'wysio-sticky');\n this.dom.style.removeProperty('--wysio-sticky-top');\n delete this.dom.dataset.mode;\n this.dom.innerHTML = html;\n }\n }\n}\n\nfunction resolveMessages(locale: EditorOptions['locale']): {\n locale: string | null;\n messages: Messages;\n} {\n if (locale == null) return { locale: 'en', messages: {} };\n if (typeof locale !== 'string') return { locale: null, messages: locale };\n const found = findLocale(locale);\n if (!found) {\n console.warn(\n `[wysio] Unknown locale \"${locale}\", using English. Add it with registerLocale().`,\n );\n return { locale: 'en', messages: {} };\n }\n return { locale: found.code, messages: found.messages };\n}\n\n/** Built-ins minus `removePlugins`, with same-name plugins from `plugins` replacing built-ins. */\nfunction resolvePlugins(options: EditorOptions): WysioPlugin[] {\n const removed = new Set(options.removePlugins ?? []);\n if (removed.has('base')) throw new Error('[wysio] The \"base\" plugin cannot be removed.');\n const extra = resolvePluginNames(options.plugins ?? []);\n const plugins = defaultPlugins\n .filter((p) => !removed.has(p.name))\n .map((builtIn) => {\n const index = extra.findIndex((p) => p.name === builtIn.name);\n return index === -1 ? builtIn : extra.splice(index, 1)[0]!;\n });\n return [...plugins, ...extra];\n}\n\nexport function createEditor(target: HTMLElement | string, options?: EditorOptions): Editor {\n return new Editor(target, options);\n}\n","import { createEditor, type Editor, type EditorOptions } from './editor';\n\nconst editors = new WeakMap<Element, Editor>();\n\n/** The editor created for an element by {@link autoInit} (or `null`). */\nexport function getEditor(element: Element): Editor | null {\n return editors.get(element) ?? null;\n}\n\n/**\n * Creates an editor for every element with a `data-wysio` attribute inside `root`\n * (default: the document). Options come from the element's `data-wysio-options`\n * JSON, on top of `defaults` (use those for what JSON can't hold, like `upload`).\n * Elements that already have an editor are skipped, so it is safe to call again\n * after the page changes. Returns the editors it created.\n */\nexport function autoInit(\n defaults: EditorOptions | ((element: HTMLElement) => EditorOptions) = {},\n root: ParentNode = document,\n): Editor[] {\n const created: Editor[] = [];\n for (const element of root.querySelectorAll<HTMLElement>('[data-wysio]')) {\n if (editors.has(element)) continue;\n let options: EditorOptions;\n try {\n const json = element.dataset.wysioOptions;\n options = json ? (JSON.parse(json) as EditorOptions) : {};\n } catch (error) {\n console.error('[wysio] Invalid JSON in data-wysio-options:', element, error);\n continue;\n }\n const base = typeof defaults === 'function' ? defaults(element) : defaults;\n let editor: Editor;\n try {\n editor = createEditor(element, {\n ...base,\n ...options,\n plugins: [...(base.plugins ?? []), ...(options.plugins ?? [])],\n messages: { ...base.messages, ...options.messages },\n });\n } catch (error) {\n // One broken element must not stop the others on a server-rendered page.\n console.error('[wysio] Could not create an editor for', element, error);\n continue;\n }\n editors.set(element, editor);\n editor.on('destroy', () => editors.delete(element));\n created.push(editor);\n }\n return created;\n}\n","import { createEditor, type Editor } from './editor';\n\n/** Public shape of the `<wysio-editor>` element. */\nexport interface WysioEditorElement extends HTMLElement {\n /**\n * Current content, sanitised, in the `format` attribute's format (default HTML).\n * Setting it replaces the content without emitting `change`.\n */\n value: string;\n /** The underlying editor, available while the element is connected. */\n readonly editor: Editor | null;\n readonly form: HTMLFormElement | null;\n readonly name: string;\n}\n\nconst BOOLEAN_ATTRS = ['readonly', 'disabled'] as const;\n\nfunction createElementClass(): CustomElementConstructor {\n return class extends HTMLElement implements WysioEditorElement {\n static formAssociated = true;\n static observedAttributes = ['value', 'placeholder', ...BOOLEAN_ATTRS];\n\n #editor: Editor | null = null;\n #internals: ElementInternals | null = null;\n #value: string | null = null;\n #formDisabled = false;\n\n constructor() {\n super();\n try {\n this.#internals = this.attachInternals();\n } catch {\n this.#internals = null;\n }\n }\n\n get editor(): Editor | null {\n return this.#editor;\n }\n\n /** Content format of `value` and the submitted form value (`format` attribute). */\n get #format(): string {\n return this.getAttribute('format') || 'html';\n }\n\n /** Whether the browser supports form-associated custom elements. */\n get #formAssociated(): boolean {\n return typeof this.#internals?.setFormValue === 'function';\n }\n\n get value(): string {\n return this.#editor\n ? this.#editor.serialize(this.#format)\n : (this.#value ?? this.getAttribute('value') ?? '');\n }\n\n set value(value: string) {\n const text = value == null ? '' : String(value);\n if (this.#editor) this.#editor.setContent(text);\n else this.#value = text;\n this.#syncForm();\n }\n\n get form(): HTMLFormElement | null {\n return this.#internals?.form ?? this.closest('form');\n }\n\n get name(): string {\n return this.getAttribute('name') ?? '';\n }\n\n connectedCallback(): void {\n if (this.#editor) return;\n const toolbar = this.getAttribute('toolbar');\n const plugins = this.getAttribute('plugins');\n this.#editor = createEditor(this, {\n content: this.#value ?? this.getAttribute('value') ?? '',\n format: this.#format,\n plugins: plugins ? plugins.split(/[\\s,]+/).filter(Boolean) : undefined,\n // Without form-associated custom elements (older browsers), submit through a\n // hidden input instead.\n name: this.#formAssociated ? undefined : this.getAttribute('name') || undefined,\n placeholder: this.getAttribute('placeholder') ?? undefined,\n locale: this.getAttribute('locale') ?? undefined,\n ariaLabel: this.getAttribute('aria-label') ?? undefined,\n toolbar:\n toolbar === 'false'\n ? false\n : toolbar\n ? toolbar.split(/[\\s,]+/).filter(Boolean)\n : undefined,\n editable: this.#isEditable(),\n onChange: () => {\n this.#syncForm();\n this.dispatchEvent(new Event('change', { bubbles: true }));\n },\n });\n this.#value = null;\n this.#syncForm();\n }\n\n disconnectedCallback(): void {\n if (!this.#editor) return;\n // Keep the value so the element can be moved in the DOM.\n this.#value = this.#editor.serialize(this.#format);\n this.#editor.destroy();\n this.#editor = null;\n this.innerHTML = '';\n }\n\n attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {\n if (oldValue === newValue || !this.#editor) return;\n if (name === 'value') {\n if ((newValue ?? '') !== this.value) this.value = newValue ?? '';\n } else if ((BOOLEAN_ATTRS as readonly string[]).includes(name)) {\n this.#editor.setEditable(this.#isEditable());\n }\n }\n\n formResetCallback(): void {\n this.value = this.getAttribute('value') ?? '';\n }\n\n formDisabledCallback(disabled: boolean): void {\n this.#formDisabled = disabled;\n this.#editor?.setEditable(this.#isEditable());\n }\n\n formStateRestoreCallback(state: string | null): void {\n if (typeof state === 'string') this.value = state;\n }\n\n #isEditable(): boolean {\n return !this.#formDisabled && BOOLEAN_ATTRS.every((attr) => !this.hasAttribute(attr));\n }\n\n #syncForm(): void {\n if (this.#formAssociated) this.#internals!.setFormValue(this.value);\n }\n };\n}\n\n/** Registers the `<wysio-editor>` custom element (no-op when already defined or outside a browser). */\nexport function defineWysioElement(tagName = 'wysio-editor'): void {\n if (typeof customElements === 'undefined' || customElements.get(tagName)) return;\n customElements.define(tagName, createElementClass());\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'wysio-editor': WysioEditorElement;\n }\n}\n","export {\n createEditor,\n defaultToolbar,\n Editor,\n type ContentFormat,\n type EditorErrorInfo,\n type EditorEvents,\n type EditorMode,\n type EditorOptions,\n} from './editor';\nexport {\n definePlugin,\n type ContentFormatHandler,\n type PluginContext,\n type ToolbarButton,\n type ToolbarButtonHandle,\n type ToolbarItem,\n type ToolbarSelect,\n type WysioPlugin,\n} from './plugin';\nexport type { Content, JSONContent } from './content';\nexport { defaultMessages, type MessageKey, type Messages } from './messages';\nexport { availableLocales, registerLocale } from './i18n';\nexport { registerPlugin } from './registry';\nexport { autoInit, getEditor } from './auto-init';\nexport { nl } from './locales/nl';\nexport { sanitizeImageUrl, sanitizeUrl } from './url';\nexport { formatHTML } from './format-html';\nexport { fitCount, type ToolbarMode } from './toolbar/toolbar';\nexport { isMarkActive, findAncestor, getMarkRange, toggleList, toggleWrap } from './commands';\nexport * from './plugins';\nexport { defineWysioElement, type WysioEditorElement } from './web-component';\n\n/** Package version, injected at build time. */\nexport const version: string = __WYSIO_VERSION__;\n"],"mappings":";;;;;;;;;;;;;AAcA,SAASmD,EAAYC,GAA0B;CAC7C,IAAMC,IAAID,KAAO,WAAW;CAC5B,IAAI,CAACC,GAAG,MAAU,MAAM,qCAAqC;CAC7D,OAAOA;AACT;AAMA,SAAgBC,GAAUC,GAAgBC,GAAcJ,GAAwB;CAI9E,IAAMK,IAAO,MAHHN,EAAYC,CACT,CAAA,CAAE,aACM,cAAa,WAAW,WACrB,CAAC,CAAC,gBAAgBI,GAAM,WAAW,CAAC,CAAC;CAC7D,OAAOxD,GAAU,WAAWuD,CAAM,CAAC,CAAC,MAAME,CAAI;AAChD;AAEA,SAAgBC,GAAcH,GAAgBI,GAAcP,GAAwB;CAClF,IAAMC,IAAIF,EAAYC,CAAG,GACnBQ,IAAYP,EAAE,cAAc,KAAK;CAIvC,OAHAO,EAAU,YACRlC,GAAc,WAAW6B,CAAM,CAAC,CAAC,kBAAkBI,EAAK,SAAS,EAAE,UAAUN,EAAE,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