@morfira-dev/wysiwyg-core 1.9.0 → 1.10.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.
- package/dist/editor/html-snapshots.d.ts +2 -1
- package/dist/formatting/index.d.ts +1 -1
- package/dist/formatting/links.d.ts +1 -1
- package/dist/formatting/local-inline.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +4 -4
- package/dist/input/inline-source.d.ts +2 -0
- package/dist/input/replacement-blocks.d.ts +4 -0
- package/dist/lists/internal-types.d.ts +0 -1
- package/dist/lists/source-inline.d.ts +2 -0
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/document/security.ts", "../src/document/font-family.ts", "../src/document/list-marker.ts", "../src/document/direction.ts", "../src/document/budget.ts", "../src/document/index.ts", "../src/schema/index.ts", "../src/commands/index.ts", "../src/selection/index.ts", "../src/input/block-boundaries.ts", "../src/input/replace-selection.ts", "../src/input/inline-fragment.ts", "../src/input/paste-replacement.ts", "../src/lists/paste-payload.ts", "../src/lists/quote-selection.ts", "../src/lists/quote-crossing.ts", "../src/lists/selection-boundaries.ts", "../src/lists/replace-selection.ts", "../src/lists/forward-delete.ts", "../src/lists/first-body-backspace.ts", "../src/lists/wrapped-input.ts", "../src/lists/index.ts", "../src/formatting/inline-attributes.ts", "../src/formatting/links.ts", "../src/formatting/inline-document.ts", "../src/formatting/local-inline.ts", "../src/formatting/index.ts", "../src/events/index.ts", "../src/editor/html-snapshots.ts", "../src/localization/index.ts", "../src/editor/create-editor.ts", "../src/ui/toolbar/index.ts"],
|
|
4
|
-
"sourcesContent": ["export const safeURL = (value: string, image: boolean): string | undefined => {\n const trimmed = value.trim();\n if (!trimmed || /[\\u0000-\\u0020\\u007f]/.test(trimmed))\n return;\n // Explicit protocols and relative references only. Never data:, blob:, or script URLs.\n const protocol = /^([a-z][a-z\\d+.-]*):/i.exec(trimmed)?.[1].toLowerCase();\n if (protocol && !(image ? ['http', 'https'] : ['http', 'https', 'mailto', 'tel']).includes(protocol))\n return;\n if (trimmed.startsWith('\\\\') || trimmed.startsWith('//'))\n return;\n return trimmed;\n};\n", "const genericFamilies = new Set(['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded', 'emoji', 'math', 'fangsong']);\nconst wideKeywords = new Set(['inherit', 'initial', 'unset', 'revert', 'revert-layer', 'default']);\nconst identifier = /^-?[a-z_][a-z\\d_-]*$/i;\n\n/** A deliberately small inert CSS subset, shared by HTML and JSON validation. */\nexport const normalizeFontFamily = (input: string): string | undefined => {\n if (!input || input.length > 256 || /[^\\x20-\\x7e]|[\\\\/()*;{}:]/.test(input)) return;\n const parts = input.split(',');\n if (parts.length > 8) return;\n const result: string[] = [];\n for (const part of parts) {\n const value = part.trim();\n const quoted = value.startsWith('\"') || value.startsWith(\"'\");\n if (quoted && (value.length < 3 || value.at(-1) !== value[0])) return;\n const name = (quoted ? value.slice(1, -1) : value).trim().replace(/ +/g, ' ');\n if (!name || !/^[a-z\\d_ -]+$/i.test(name) || wideKeywords.has(name.toLowerCase())) return;\n const generic = genericFamilies.has(name.toLowerCase());\n if (!quoted && name.split(' ').some((word) => !identifier.test(word))) return;\n if (!quoted && generic) result.push(name.toLowerCase());\n else if (!generic && identifier.test(name)) result.push(name);\n else result.push(`\"${name}\"`);\n }\n const normalized = result.join(', ');\n return normalized.length <= 256 ? normalized : undefined;\n};\n", "const markers: Readonly<Record<string, readonly string[]>> = {\n ul: ['disc', 'circle', 'square'],\n ol: ['decimal', 'lower-alpha', 'upper-alpha', 'lower-roman', 'upper-roman'],\n};\n\nexport const normalizeListMarker = (tag: string, value: string): string | undefined => {\n const marker = value.trim().toLowerCase();\n return Object.hasOwn(markers, tag) && markers[tag].includes(marker) ? marker : undefined;\n};\n", "const tags = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'blockquote', 'ul', 'ol', 'li', 'td', 'th']);\n\nexport const normalizeDirection = (tag: string, value: unknown, canonical = false): string | undefined => {\n if (!tags.has(tag) || typeof value !== 'string' || value.length > 20000) return;\n const direction = canonical ? value : value.trim().toLowerCase();\n return direction === 'ltr' || direction === 'rtl' ? direction : undefined;\n};\n\n/** Copy one validated attribute only, never application/schema metadata. */\nexport const copyDirection = (source: HTMLElement, target: HTMLElement): void => {\n const direction = normalizeDirection(source.localName, source.getAttribute('dir'), true);\n if (direction && normalizeDirection(target.localName, direction, true)) target.setAttribute('dir', direction);\n};\n", "import type { DocumentBudget } from './internal-types.js';\n\nexport const maximumHTMLLength = 5000000;\nexport const maximumNodes = 100000;\nexport const maximumDepth = 100;\nconst voidTags = new Set(['br', 'hr', 'img', 'col']);\n\nconst consume = (budget: DocumentBudget, length: number): void => {\n if (length > maximumHTMLLength - budget.htmlLength) throw new RangeError('Document serialized HTML exceeds size limit.');\n budget.htmlLength += length;\n};\nconst escaped = (budget: DocumentBudget, value: string, attribute = false): void => {\n const remaining = maximumHTMLLength - budget.htmlLength;\n let length = value.length;\n if (length > remaining) throw new RangeError('Document serialized HTML exceeds size limit.');\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n length += code === 38 ? 4 : code === 60 || code === 62 ? 3 : code === 160 || (attribute && code === 34) ? 5 : 0;\n if (length > remaining) throw new RangeError('Document serialized HTML exceeds size limit.');\n }\n budget.htmlLength += length;\n};\n\nexport const countText = (budget: DocumentBudget, value: string): void => escaped(budget, value);\nexport const countElement = (budget: DocumentBudget, tag: string, attributes: Record<string, string>): void => {\n consume(budget, voidTags.has(tag) ? tag.length + 2 : 2 * tag.length + 5);\n for (const [name, value] of Object.entries(attributes)) {\n consume(budget, name.length + 4);\n escaped(budget, value, true);\n }\n};\n", "import { safeURL } from './security.js';\nimport { normalizeFontFamily } from './font-family.js';\nimport { normalizeListMarker } from './list-marker.js';\nimport { normalizeDirection } from './direction.js';\nimport { countText, countElement, maximumHTMLLength, maximumNodes, maximumDepth } from './budget.js';\nimport type { DocumentAttributeResolver, DocumentBudget } from './internal-types.js';\nimport type { DocumentTag, TextNode, ElementNode, DocumentNode, EditorDocument } from './types.js';\nexport type { DocumentTag, TextNode, ElementNode, DocumentNode, EditorDocument } from './types.js';\n/** Versioned, framework-independent document tree. Only supported HTML semantics are stored. */\nexport const documentTags = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'code', 'strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'br', 'hr', 'ul', 'ol', 'li', 'img', 'figure', 'figcaption', 'table', 'caption', 'colgroup', 'col', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th'] as const;\nconst tags = new Set<string>(documentTags);\nconst omitted = new Set(['script', 'style', 'iframe', 'object', 'embed', 'svg', 'math', 'template', 'form', 'input', 'button', 'textarea', 'select', 'noscript', 'link', 'meta', 'base']);\nconst aliases: Record<string, string> = { b: 'strong', i: 'em', strike: 's', div: 'p' };\nconst safeStyle = (tag: DocumentTag, value: string): string => {\n const result: string[] = [];\n for (const declaration of value.split(';')) {\n const separator = declaration.indexOf(':');\n if (separator < 0)\n continue;\n const property = declaration.slice(0, separator).trim().toLowerCase();\n if (property === 'list-style-type') {\n const marker = normalizeListMarker(tag, declaration.slice(separator + 1));\n if (marker) result.push(`list-style-type: ${marker}`);\n continue;\n }\n if (property === 'font-family') {\n const family = normalizeFontFamily(declaration.slice(separator + 1).trim());\n if (family) result.push(`font-family: ${family}`);\n continue;\n }\n const content = declaration.slice(separator + 1).trim().toLowerCase();\n const color = /^(#[a-f\\d]{3,8}|[a-z]{1,24}|(?:rgb|rgba|hsl|hsla)\\([\\d\\s.,%+-]+\\))$/;\n const length = /^(?:\\d{1,4}(?:\\.\\d{1,3})?)(?:px|%|em|rem)$/;\n const valid = ['color', 'background-color', 'border-color'].includes(property) ? color.test(content)\n : ['width', 'height', 'font-size'].includes(property) ? length.test(content)\n : property === 'text-align' ? ['left', 'center', 'right', 'justify'].includes(content)\n : property === 'font-weight' ? /^(bold|normal|[1-9]00)$/.test(content)\n : property === 'font-style' ? ['italic', 'normal'].includes(content)\n : property === 'text-decoration' ? /^(underline|line-through|none)$/.test(content)\n : false;\n if (valid)\n result.push(`${property}: ${content}`);\n }\n return result.join('; ');\n};\n/** Keep ordered-list numbering within the signed DOM integer range. */\nconst orderedListStart = (value: unknown): string | undefined => {\n if (typeof value !== 'string' || value.length > 20000 || !/^[+-]?\\d+$/.test(value.trim())) return;\n const number = Number(value);\n if (Number.isSafeInteger(number) && number >= -2147483648 && number <= 2147483647) return String(number);\n};\nconst attributesFor = (tag: DocumentTag, input: Record<string, unknown>, source: 'html' | 'json', resolve?: DocumentAttributeResolver, originalTag?: string): Record<string, string> => {\n const output: Record<string, string> = {};\n for (const [key, value] of Object.entries(input)) {\n if (key === 'dir') {\n const direction = normalizeDirection(tag, value, source === 'json');\n if (direction) output.dir = direction;\n else if (source === 'json') throw new TypeError('Direction must be canonical ltr or rtl on a supported block.');\n continue;\n }\n if (key === 'start') {\n const clean = tag === 'ol' ? orderedListStart(value) : undefined;\n if (clean !== undefined) output.start = clean;\n else if (source === 'json') throw new TypeError('Ordered-list start must be a signed 32-bit decimal integer string on ol.');\n continue;\n }\n if (key === 'reversed') {\n if (tag === 'ol' && (source === 'html' || value === '')) output.reversed = '';\n else if (source === 'json') throw new TypeError('Reversed must be an empty string on ol.');\n continue;\n }\n if (typeof value !== 'string' || value.length > 20000)\n continue;\n if (key === 'style') {\n const clean = safeStyle(tag, value);\n if (clean)\n output.style = clean;\n }\n else if (key === 'title' || (tag === 'img' && key === 'alt'))\n output[key] = value;\n else if ((tag === 'a' && key === 'href') || (tag === 'img' && key === 'src')) {\n const clean = safeURL(value, tag === 'img');\n if (clean)\n output[key] = clean;\n }\n else if ((['td', 'th'].includes(tag) && ['rowspan', 'colspan'].includes(key)) || (['img', 'col', 'table'].includes(tag) && ['width', 'height', 'span'].includes(key))) {\n if (/^\\d{1,4}$/.test(value) && Number(value) > 0 && Number(value) <= 1000)\n output[key] = value;\n }\n else if (tag === 'a' && key === 'target' && ['_self', '_blank'].includes(value))\n output.target = value;\n else if (tag === 'a' && key === 'rel') {\n const tokens = [...new Set(value.toLowerCase().split(/\\s+/).filter((token) => ['noopener', 'noreferrer'].includes(token)))];\n if (tokens.length)\n output.rel = tokens.join(' ');\n }\n else if (tag === 'th' && key === 'scope' && ['row', 'col', 'rowgroup', 'colgroup'].includes(value))\n output[key] = value;\n }\n if (tag === 'img' && (output.width || output.height)) {\n const dimensions = ['width', 'height'].filter((key) => output[key]);\n const styles = (output.style ?? '').split(';').map((part) => part.trim()).filter((part) => part && !dimensions.includes(part.slice(0, part.indexOf(':')).trim()));\n output.style = [...styles, ...dimensions.map((key) => `${key}: ${output[key]}px`)].join('; ');\n }\n if (tag === 'a' && output.target === '_blank')\n output.rel = 'noopener noreferrer';\n if (resolve) Object.assign(output, resolve(tag, input, source, originalTag));\n else if (source === 'json' && Object.hasOwn(input, 'data-mw-node'))\n throw new TypeError('Unregistered schema node.');\n return output;\n};\nconst readDOM = (node: Node, depth: number, budget: DocumentBudget, resolve?: DocumentAttributeResolver): DocumentNode[] => {\n if (++budget.count > maximumNodes || depth > maximumDepth)\n throw new RangeError('Document exceeds structural limits.');\n if (node.nodeType === 3) {\n const text = node.textContent ?? '';\n countText(budget, text);\n return [{ type: 'text', text }];\n }\n if (node.nodeType !== 1)\n return [];\n const element = node as Element;\n const original = element.localName.toLowerCase();\n if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || omitted.has(original))\n return [];\n const children = [...element.childNodes].flatMap((child) => readDOM(child, depth + 1, budget, resolve));\n const tag = aliases[original] ?? original;\n if (!tags.has(tag)) {\n if (resolve && element.hasAttribute('data-mw-node'))\n resolve(tag, Object.fromEntries([...element.attributes].map((attr) => [attr.name, attr.value])), 'html', original);\n return children;\n }\n const attributes = attributesFor(tag as DocumentTag, Object.fromEntries([...element.attributes].map((attr) => [attr.name, attr.value])), 'html', resolve, original);\n if (tag === 'img' && !attributes.src)\n return [];\n countElement(budget, tag, attributes);\n return [{ type: 'element', tag: tag as DocumentTag, attributes, children }];\n};\nexport const parseHTML = (html: string, resolve?: DocumentAttributeResolver): EditorDocument => {\n if (html.length > maximumHTMLLength)\n throw new RangeError('HTML exceeds the document size limit.');\n // A template is inert: script execution and active resource loading are never used for import.\n const template = document.createElement('template');\n template.innerHTML = html;\n const budget: DocumentBudget = { count: 0, htmlLength: 0 };\n return { version: 1, children: [...template.content.childNodes].flatMap((node) => readDOM(node, 0, budget, resolve)) };\n};\nexport const validateDocument = (input: unknown, resolve?: DocumentAttributeResolver): EditorDocument => {\n if (!input || typeof input !== 'object' || !('version' in input) || input.version !== 1 || !('children' in input) || !Array.isArray(input.children))\n throw new TypeError('Expected a version 1 document.');\n const budget: DocumentBudget = { count: 0, htmlLength: 0 };\n const visit = (value: unknown, depth: number): DocumentNode => {\n if (++budget.count > maximumNodes || depth > maximumDepth)\n throw new RangeError('Document exceeds structural limits.');\n if (!value || typeof value !== 'object' || !('type' in value))\n throw new TypeError('Invalid document node.');\n if (value.type === 'text' && 'text' in value && typeof value.text === 'string') {\n countText(budget, value.text);\n return { type: 'text', text: value.text };\n }\n if (value.type !== 'element' || !('tag' in value) || typeof value.tag !== 'string' || !tags.has(value.tag) || !('children' in value) || !Array.isArray(value.children))\n throw new TypeError('Invalid document element.');\n const attrs = 'attributes' in value && value.attributes && typeof value.attributes === 'object' && !Array.isArray(value.attributes) ? value.attributes : {};\n const attributes = attributesFor(value.tag as DocumentTag, attrs as Record<string, unknown>, 'json', resolve);\n countElement(budget, value.tag, attributes);\n return { type: 'element', tag: value.tag as DocumentTag, attributes, children: children(value.children, depth + 1) };\n };\n const children = (values: unknown[], depth: number): DocumentNode[] => {\n if (values.length > maximumNodes) throw new RangeError('Document children exceed node limit.');\n const output: DocumentNode[] = [];\n for (let index = 0; index < values.length; index++) {\n if (!Object.hasOwn(values, index)) throw new TypeError('Document children must be dense arrays.');\n output.push(visit(values[index], depth));\n }\n return output;\n };\n return { version: 1, children: children(input.children, 0) };\n};\nexport const renderDocument = (value: EditorDocument, owner: Document = document): DocumentFragment => {\n const fragment = owner.createDocumentFragment();\n const append = (parent: Node, node: DocumentNode) => {\n if (node.type === 'text') {\n parent.appendChild(owner.createTextNode(node.text));\n return;\n }\n const element = owner.createElement(node.tag);\n for (const [key, value] of Object.entries(node.attributes))\n element.setAttribute(key, value);\n for (const child of node.children)\n append(element, child);\n parent.appendChild(element);\n };\n for (const node of value.children)\n append(fragment, node);\n return fragment;\n};\nexport const documentHTML = (value: EditorDocument): string => {\n const container = document.createElement('template');\n container.content.append(renderDocument(value, container.content.ownerDocument));\n return container.innerHTML;\n};\nexport const sanitizeHTML = (html: string): string => { return documentHTML(parseHTML(html)); };\n", "import { documentTags, parseHTML, validateDocument, renderDocument, documentHTML } from '../document/index.js';\nimport { safeURL } from '../document/security.js';\nimport type { DocumentAttributeResolver } from '../document/internal-types.js';\nimport type { CompiledAttribute, CompiledSchemaNode } from './internal-types.js';\nimport type { DocumentTag, EditorDocument } from '../document/types.js';\nimport type { DocumentSchema, SchemaContribution } from './types.js';\n\nexport type { DocumentSchema, SchemaAttributeSpec, SchemaNodeSpec, SchemaAttributesSpec, SchemaContribution } from './types.js';\n\nconst inlineTags = ['span', 'strong', 'em', 'u', 's', 'sub', 'sup', 'code'];\nconst blockTags = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'figure', 'figcaption'];\nconst supportedTag = (kind: unknown, tag: unknown): tag is DocumentTag => typeof tag === 'string' && (kind === 'block' ? blockTags : kind === 'inline' ? inlineTags : []).includes(tag);\nconst record = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object' && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);\nconst keysWithin = (value: Record<string, unknown>, allowed: readonly string[]) => {\n if (Object.keys(value).some((key) => !allowed.includes(key))) throw new TypeError('Unknown schema definition field.');\n};\nconst compileAttribute = (input: unknown): CompiledAttribute => {\n if (!record(input)) throw new TypeError('Schema attribute must be an object.');\n if (input.required !== undefined && typeof input.required !== 'boolean') throw new TypeError('Schema attribute required must be boolean.');\n const required = input.required === true;\n let read: (value: string) => string;\n if (input.type === 'text') {\n keysWithin(input, ['type', 'required', 'maxLength']);\n const limit = input.maxLength ?? 256;\n if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 0 || limit > 20000) throw new RangeError('Schema text maxLength must be from 0 to 20000.');\n read = (value) => {\n if (value.length > limit) throw new RangeError('Schema text exceeds its maximum length.');\n return value;\n };\n }\n else if (input.type === 'enum') {\n keysWithin(input, ['type', 'required', 'values']);\n if (!Array.isArray(input.values) || !input.values.length || input.values.length > 64 || input.values.some((value) => typeof value !== 'string' || value.length > 20000))\n throw new TypeError('Schema enum needs 1 to 64 bounded string values.');\n const values = new Set(input.values);\n read = (value) => {\n if (!values.has(value)) throw new TypeError('Invalid schema enum value.');\n return value;\n };\n }\n else if (input.type === 'integer') {\n keysWithin(input, ['type', 'required', 'min', 'max']);\n const min = input.min;\n const max = input.max;\n if (typeof min !== 'number' || typeof max !== 'number' || !Number.isSafeInteger(min) || !Number.isSafeInteger(max) || min > max) throw new RangeError('Schema integer bounds must be safe ordered integers.');\n read = (value) => {\n const number = Number(value);\n if (!/^-?\\d+$/.test(value) || !Number.isSafeInteger(number) || number < min || number > max) throw new RangeError('Schema integer is outside its bounds.');\n return String(number);\n };\n }\n else if (input.type === 'url') {\n keysWithin(input, ['type', 'required']);\n read = (value) => {\n const clean = safeURL(value, false);\n if (clean === undefined) throw new TypeError('Unsupported or unsafe schema URL.');\n return clean;\n };\n }\n else throw new TypeError('Unknown schema attribute type.');\n return Object.freeze({\n required,\n read: (value: unknown) => {\n if (typeof value !== 'string' || value.length > 20000) throw new TypeError('Schema attribute must be a bounded string.');\n return read(value);\n },\n });\n};\n\nexport const createDocumentSchema = (nodes: readonly SchemaContribution[] = []): DocumentSchema => {\n if (!Array.isArray(nodes) || nodes.length > 128) throw new TypeError('Schema contributions must be an array of at most 128 definitions.');\n const registry = new Map<string, CompiledSchemaNode>();\n const names = new Set<string>();\n // The document boundary also resolves unsupported source tags to reject semantic mismatches.\n const tagAttributes = new Map<string, Map<string, CompiledAttribute>>();\n const splitPolicies = new Map<DocumentTag, Map<string, string>>();\n for (const node of nodes) {\n if (!record(node)) throw new TypeError('Schema contribution must be an object.');\n keysWithin(node, node.kind === 'attributes' ? ['name', 'kind', 'tag', 'attributes', 'split'] : ['name', 'kind', 'tag', 'attributes']);\n if (typeof node.name !== 'string' || node.name.length > 128 || !/^[a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*)+$/.test(node.name))\n throw new TypeError('Schema names must be bounded namespaced identifiers.');\n if (names.has(node.name)) throw new Error(`Duplicate schema contribution: ${node.name}`);\n names.add(node.name);\n const nonOwning = node.kind === 'attributes';\n if (nonOwning ? !documentTags.includes(node.tag as DocumentTag) : !supportedTag(node.kind, node.tag))\n throw new TypeError('Schema tag must match its supported kind.');\n const tag = node.tag as DocumentTag;\n const rules = node.attributes ?? (nonOwning ? undefined : {});\n if (!record(rules) || Object.keys(rules).length > 64) throw new TypeError('Schema attributes must be a bounded record.');\n const attributes = new Map<string, CompiledAttribute>();\n for (const [name, rule] of Object.entries(rules)) {\n if (!/^data-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name) || name.startsWith('data-mw-'))\n throw new TypeError('Schema attributes must use non-reserved lowercase data-* names.');\n const compiled = compileAttribute(rule);\n if (nonOwning && compiled.required) throw new TypeError('Non-owning attributes must be optional.');\n attributes.set(name, compiled);\n }\n if (!nonOwning) {\n registry.set(node.name, Object.freeze({ tag, attributes }));\n continue;\n }\n const existing = tagAttributes.get(tag) ?? new Map<string, CompiledAttribute>();\n for (const [name, rule] of attributes) {\n if (existing.has(name)) throw new TypeError(`Duplicate schema tag attribute: ${name}`);\n existing.set(name, rule);\n }\n if (existing.size > 64) throw new RangeError('Schema tag attributes exceed their bound.');\n tagAttributes.set(tag, existing);\n if (node.split !== undefined) {\n if (tag !== 'li' || !record(node.split)) throw new TypeError('Schema split policy must be an LI attribute record.');\n const policies = splitPolicies.get(tag) ?? new Map<string, string>();\n for (const [name, reset] of Object.entries(node.split)) {\n const rule = attributes.get(name);\n if (!rule) throw new TypeError('Schema split policy must reference its declared attribute.');\n policies.set(name, rule.read(reset));\n }\n splitPolicies.set(tag, policies);\n }\n }\n for (const node of registry.values()) {\n if ([...node.attributes.keys()].some((name) => tagAttributes.get(node.tag)?.has(name)))\n throw new TypeError('Non-owning and semantic attribute definitions must not overlap.');\n }\n const resolve: DocumentAttributeResolver = (tag, input, source, originalTag) => {\n const output: Record<string, string> = {};\n for (const [name, rule] of tagAttributes.get(tag) ?? []) {\n if (Object.hasOwn(input, name)) {\n if (originalTag !== undefined && originalTag !== tag) throw new TypeError('Schema attribute does not match its original tag.');\n output[name] = rule.read(input[name]);\n }\n }\n if (!Object.hasOwn(input, 'data-mw-node')) return output;\n const marker = input['data-mw-node'];\n const node = typeof marker === 'string' ? registry.get(marker) : undefined;\n if (typeof marker !== 'string' || !node) {\n if (source === 'json') throw new TypeError('Unregistered schema node.');\n return output;\n }\n if (tag !== node.tag || (originalTag !== undefined && originalTag !== node.tag)) throw new TypeError('Schema node marker does not match its tag.');\n output['data-mw-node'] = marker;\n for (const [name, rule] of node.attributes) {\n if (Object.hasOwn(input, name)) output[name] = rule.read(input[name]);\n else if (rule.required) throw new TypeError(`Missing required schema attribute: ${name}`);\n }\n return output;\n };\n const validate: DocumentSchema['validateDocument'] = (input) => validateDocument(input, resolve);\n const parse: DocumentSchema['parseHTML'] = (html) => parseHTML(html, resolve);\n return Object.freeze({\n attributesForSplit: (tag: DocumentTag, input: Readonly<Record<string, string>>) => {\n if (!documentTags.includes(tag) || !record(input)) throw new TypeError('Expected a safe tag and attribute record.');\n const output: Record<string, string> = {};\n for (const [name, reset] of splitPolicies.get(tag) ?? []) {\n if (Object.hasOwn(input, name)) {\n tagAttributes.get(tag)!.get(name)!.read(input[name]);\n output[name] = reset;\n }\n }\n return output;\n },\n parseHTML: parse,\n validateDocument: validate,\n renderDocument: (value: EditorDocument) => renderDocument(validate(value)),\n documentHTML: (value: EditorDocument) => documentHTML(validate(value)),\n sanitizeHTML: (html: string) => documentHTML(parse(html)),\n });\n};\n", "import type { CommandRegistry, CommandRegistryOptions, RegisteredCommand } from './internal-types.js';\nimport type { EditorCommand, EditorCommandDefinition, EditorCommandState, EditorCommands } from './types.js';\n\nexport type { EditorCommand, EditorCommandDefinition, EditorCommandState, EditorCommands } from './types.js';\n\nconst tokens = /* @__PURE__ */ new WeakSet<object>();\n\nexport const createEditorCommand = <T>(name: string): EditorCommand<T> => {\n if (typeof name !== 'string' || !name.trim() || name.length > 200)\n throw new TypeError('Expected a command name with 1\u2013200 characters.');\n const command = Object.freeze({ name }) as EditorCommand<T>;\n tokens.add(command);\n return command;\n};\n\nconst assertToken = (command: unknown): object => {\n if (!command || typeof command !== 'object' || !tokens.has(command))\n throw new TypeError('Expected an editor command token.');\n return command;\n};\n\nconst synchronous = (callback: unknown): void => {\n if (typeof callback !== 'function' || callback.constructor.name === 'AsyncFunction')\n throw new TypeError('Command callbacks must be synchronous functions.');\n};\n\nconst rejectThenable = (value: unknown): void => {\n if (value && (typeof value === 'object' || typeof value === 'function') && typeof (value as { then?: unknown }).then === 'function') {\n if (value instanceof Promise)\n void value.catch(() => {});\n throw new TypeError('Command callbacks must not return a thenable.');\n }\n};\n\nexport const createCommandRegistry = (options: CommandRegistryOptions): CommandRegistry => {\n const entries = new Map<object, RegisteredCommand>();\n let disposed = false;\n const assertActive = () => {\n options.assertActive();\n if (disposed)\n throw new Error('Editor commands have been destroyed.');\n };\n const resolve = <T>(command: EditorCommand<T>): RegisteredCommand => {\n assertActive();\n const entry = entries.get(assertToken(command));\n if (!entry)\n throw new Error(`Command is not registered: ${command.name}`);\n return entry;\n };\n const stateValue = (callback: RegisteredCommand['isEnabled'], fallback: boolean): boolean => {\n if (!callback)\n return fallback;\n const value = callback(options.editor());\n rejectThenable(value);\n if (typeof value !== 'boolean')\n throw new TypeError('Command state callbacks must return a boolean.');\n return value;\n };\n const enabled = (entry: RegisteredCommand): boolean => !options.editor().isReadOnly() && !options.isComposing() && stateValue(entry.isEnabled, true);\n const commands: EditorCommands = {\n register: <T>(command: EditorCommand<T>, definition: EditorCommandDefinition<NoInfer<T>>): (() => void) => {\n assertActive();\n const key = assertToken(command);\n if (entries.has(key))\n throw new Error(`Command is already registered: ${command.name}`);\n if (!definition || typeof definition !== 'object')\n throw new TypeError('Expected a command definition.');\n const { validate, execute, isEnabled, isActive, isMixed } = definition;\n synchronous(validate);\n synchronous(execute);\n for (const callback of [isEnabled, isActive, isMixed]) {\n if (callback !== undefined)\n synchronous(callback);\n }\n const entry: RegisteredCommand = {\n validate,\n execute: (editor, payload) => execute(editor, payload as T),\n isEnabled,\n isActive,\n isMixed,\n };\n entries.set(key, entry);\n return () => {\n if (entries.get(key) === entry)\n entries.delete(key);\n };\n },\n execute: (command, payload): boolean => {\n const entry = resolve(command);\n if (!enabled(entry))\n return false;\n const editor = options.editor();\n editor.transact(() => {\n const validated = entry.validate(payload);\n rejectThenable(validated);\n // Keep the original return value so transact can reject thenables atomically.\n return entry.execute(editor, validated);\n });\n return true;\n },\n getState: (command): EditorCommandState => {\n const entry = resolve(command);\n return {\n enabled: enabled(entry),\n active: stateValue(entry.isActive, false),\n mixed: stateValue(entry.isMixed, false),\n };\n },\n };\n return {\n commands,\n destroy: () => {\n if (disposed)\n return;\n disposed = true;\n entries.clear();\n },\n };\n};\n", "import type { TextSelection, SelectionBookmark } from './types.js';\nexport type { TextSelection, SelectionBookmark } from './types.js';\nexport const activeRange = (root: HTMLElement): Range | undefined => {\n const selection = root.ownerDocument.getSelection();\n if (!selection?.rangeCount)\n return;\n const range = selection.getRangeAt(0);\n if (!root.contains(range.startContainer) || !root.contains(range.endContainer))\n return;\n return range.cloneRange();\n};\nconst nodePath = (root: Node, target: Node): number[] => {\n const result: number[] = [];\n let node = target;\n while (node !== root && node.parentNode) {\n result.unshift([...node.parentNode.childNodes].indexOf(node as ChildNode));\n node = node.parentNode;\n }\n return result;\n};\n// Empty text nodes disappear in HTML snapshots. Persist their parent boundary.\nconst stableBoundary = (node: Node, offset: number): [Node, number] => {\n if (node.nodeType === 3 && node.textContent === '' && node.parentNode)\n return [node.parentNode, [...node.parentNode.childNodes].indexOf(node as ChildNode)];\n return [node, offset];\n};\nexport const bookmark = (root: HTMLElement): SelectionBookmark | undefined => {\n const range = activeRange(root);\n if (!range)\n return;\n const selection = root.ownerDocument.getSelection()!;\n const [start, startOffset] = stableBoundary(range.startContainer, range.startOffset);\n const [end, endOffset] = stableBoundary(range.endContainer, range.endOffset);\n return { start: nodePath(root, start), startOffset, end: nodePath(root, end), endOffset, backward: !range.collapsed && selection.anchorNode === range.endContainer && selection.anchorOffset === range.endOffset };\n};\n/** Resolve a remembered selection without changing focus or the document selection. */\nexport const rangeFromBookmark = (root: HTMLElement, saved: SelectionBookmark | undefined): Range | undefined => {\n if (!saved)\n return;\n const resolve = (path: number[]) => path.reduce<Node>((node, index) => node.childNodes[index] ?? node, root);\n const start = resolve(saved.start);\n const end = resolve(saved.end);\n const limit = (node: Node, offset: number) => Math.min(offset, node.nodeType === 3 ? (node.textContent?.length ?? 0) : node.childNodes.length);\n const startOffset = limit(start, saved.startOffset);\n const endOffset = limit(end, saved.endOffset);\n const range = root.ownerDocument.createRange();\n range.setStart(start, startOffset);\n range.setEnd(end, endOffset);\n return range;\n};\nexport const restoreBookmark = (root: HTMLElement, saved: SelectionBookmark | undefined): void => {\n const range = rangeFromBookmark(root, saved);\n const selection = root.ownerDocument.getSelection();\n if (!range || !saved || !selection) return;\n if (saved.backward)\n selection.setBaseAndExtent(range.endContainer, range.endOffset, range.startContainer, range.startOffset);\n else\n selection.setBaseAndExtent(range.startContainer, range.startOffset, range.endContainer, range.endOffset);\n};\nexport const readTextSelection = (root: HTMLElement): TextSelection | undefined => {\n const range = activeRange(root);\n if (!range)\n return;\n const prefix = root.ownerDocument.createRange();\n prefix.selectNodeContents(root);\n prefix.setEnd(range.startContainer, range.startOffset);\n return { index: prefix.toString().length, length: range.toString().length };\n};\nexport const selectText = (root: HTMLElement, index: number, length = 0): void => {\n if (![index, length].every((value) => Number.isInteger(value) && value >= 0))\n throw new RangeError('Selection offsets must be non-negative integers.');\n const walker = root.ownerDocument.createTreeWalker(root, 4);\n const nodes: Text[] = [];\n let current: Node | null;\n while ((current = walker.nextNode()))\n nodes.push(current as Text);\n const locate = (offset: number): [\n Node,\n number\n ] => {\n for (const node of nodes) {\n if (offset <= node.length)\n return [node, offset];\n offset -= node.length;\n }\n const last = nodes.at(-1);\n return last ? [last, last.length] : [root.querySelector('p,h1,h2,h3,h4,h5,h6,li,blockquote,pre') ?? root, 0];\n };\n const [start, startOffset] = locate(index);\n const [end, endOffset] = locate(index + length);\n const range = root.ownerDocument.createRange();\n range.setStart(start, startOffset);\n range.setEnd(end, endOffset);\n root.focus({ preventScroll: true });\n const selection = root.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n};\nexport const placeCaret = (element: HTMLElement, end = false): void => {\n const range = element.ownerDocument.createRange();\n range.selectNodeContents(element);\n range.collapse(!end);\n const selection = element.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n};\n/** Keep actual DOM positions while moving blocks, including empty list items. */\nexport const preserveRange = (root: HTMLElement, mutate: () => void): void => {\n const range = activeRange(root);\n if (!range)\n return;\n const native = root.ownerDocument.getSelection()!;\n const backward = !range.collapsed && native.anchorNode === range.endContainer && native.anchorOffset === range.endOffset;\n const start = root.ownerDocument.createComment('mw-start');\n const end = range.collapsed ? undefined : root.ownerDocument.createComment('mw-end');\n if (end) {\n const tail = range.cloneRange();\n tail.collapse(false);\n tail.insertNode(end);\n }\n const head = range.cloneRange();\n head.collapse(true);\n head.insertNode(start);\n try {\n mutate();\n if (root.contains(start) && (!end || root.contains(end))) {\n const next = root.ownerDocument.createRange();\n next.setStartBefore(start);\n if (end)\n next.setEndBefore(end);\n else\n next.collapse(true);\n start.remove();\n end?.remove();\n root.normalize();\n if (backward)\n native.setBaseAndExtent(next.endContainer, next.endOffset, next.startContainer, next.startOffset);\n else {\n native.removeAllRanges();\n native.addRange(next);\n }\n }\n }\n finally {\n start.remove();\n end?.remove();\n }\n};\n", "import { activeRange, placeCaret } from '../selection/index.js';\nimport { copyDirection } from '../document/direction.js';\n\nconst blockTags = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\nconst inlineTags = new Set(['strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'code', 'br']);\nconst inlineTree = (element: Element): boolean => [...element.childNodes].every((node) => node.nodeType === 3 || (node instanceof HTMLElement && inlineTags.has(node.localName) && inlineTree(node)));\nconst parentOf = (node: Node): Element | null => node.nodeType === 1 ? node as Element : node.parentElement;\nconst editableBlock = (root: HTMLElement, node: Node): HTMLElement | undefined => {\n const block = parentOf(node)?.closest<HTMLElement>('p,h1,h2,h3,h4,h5,h6');\n if (!(block instanceof HTMLElement) || block.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !root.contains(block) || block.closest('li,figure,pre') || !inlineTree(block)) return;\n const parent = block.parentElement;\n if (parent !== root && !['blockquote', 'td', 'th'].includes(parent?.localName ?? '')) return;\n return block;\n};\nconst hasContent = (fragment: DocumentFragment): boolean => Boolean(fragment.textContent || fragment.querySelector('br'));\nconst selectedBlock = (root: HTMLElement): HTMLElement | undefined => {\n const range = activeRange(root);\n if (!range) return;\n const block = editableBlock(root, range.startContainer);\n return block && editableBlock(root, range.endContainer) === block ? block : undefined;\n};\nconst atEdge = (block: HTMLElement, range: Range, end: boolean): boolean => {\n if (!block.textContent && block.querySelectorAll('br').length <= 1) return true;\n const remainder = block.ownerDocument.createRange();\n remainder.selectNodeContents(block);\n if (end) remainder.setStart(range.endContainer, range.endOffset);\n else remainder.setEnd(range.startContainer, range.startOffset);\n // An actual line break is content even though Range.toString omits it.\n const fragment = remainder.cloneContents();\n return !hasContent(fragment);\n};\nconst siblingBlock = (root: HTMLElement, block: HTMLElement, forward: boolean): HTMLElement | undefined => {\n if (block.hasAttribute('data-mw-node')) return;\n const sibling = forward ? block.nextSibling : block.previousSibling;\n return sibling instanceof HTMLElement && !sibling.hasAttribute('data-mw-node') && blockTags.has(sibling.localName) && editableBlock(root, sibling) === sibling ? sibling : undefined;\n};\n\nexport const handlesBlockInput = (root: HTMLElement, inputType: string): boolean => {\n const block = selectedBlock(root);\n const range = activeRange(root);\n if (!block || !range) return false;\n if (inputType === 'insertParagraph' || inputType === 'insertLineBreak') return true;\n if (!range.collapsed) return false;\n if (inputType === 'deleteContentBackward') return atEdge(block, range, false);\n if (inputType === 'deleteContentForward') return atEdge(block, range, true);\n return false;\n};\n\n/** Called inside the editor's existing transaction after handlesBlockInput succeeds. */\nexport const editBlockInput = (root: HTMLElement, inputType: string): void => {\n const block = selectedBlock(root);\n const range = activeRange(root);\n if (!block || !range || !handlesBlockInput(root, inputType)) return;\n const document = root.ownerDocument;\n if (inputType === 'insertParagraph') {\n range.deleteContents();\n const tailRange = document.createRange();\n tailRange.selectNodeContents(block);\n tailRange.setStart(range.startContainer, range.startOffset);\n const tail = tailRange.extractContents();\n const emptyHeading = block.localName !== 'p' && !block.textContent && !tail.textContent && block.querySelectorAll('br').length + tail.querySelectorAll('br').length <= 1;\n const headingEnd = block.localName !== 'p' && (!hasContent(tail) || emptyHeading);\n if (emptyHeading && !block.hasAttribute('data-mw-node')) {\n const paragraph = document.createElement('p');\n for (const attribute of block.attributes)\n if (attribute.name !== 'dir') paragraph.setAttribute(attribute.name, attribute.value);\n copyDirection(block, paragraph);\n paragraph.append(document.createElement('br'));\n block.replaceWith(paragraph);\n placeCaret(paragraph);\n return;\n }\n const next = headingEnd ? document.createElement('p') : block.cloneNode(false) as HTMLElement;\n if (headingEnd) {\n // A semantic identity is valid only on its declared wrapper, never on an exit paragraph.\n for (const attribute of block.attributes) {\n if (!attribute.name.startsWith('data-') && attribute.name !== 'dir') next.setAttribute(attribute.name, attribute.value);\n }\n copyDirection(block, next);\n }\n next.append(tail);\n if (!next.textContent && !next.querySelector('br')) next.replaceChildren(document.createElement('br'));\n if (!block.textContent && !block.querySelector('br')) block.replaceChildren(document.createElement('br'));\n block.after(next);\n placeCaret(next);\n return;\n }\n if (inputType === 'insertLineBreak') {\n range.deleteContents();\n if (!block.textContent && block.querySelectorAll('br').length <= 1) {\n block.replaceChildren();\n range.selectNodeContents(block);\n range.collapse(true);\n }\n const terminal = atEdge(block, range, true);\n const lineBreak = document.createElement('br');\n range.insertNode(lineBreak);\n if (terminal) lineBreak.after(document.createElement('br'));\n const caret = document.createRange();\n caret.setStartAfter(lineBreak);\n caret.collapse(true);\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n return;\n }\n const forward = inputType === 'deleteContentForward';\n const sibling = siblingBlock(root, block, forward);\n if (!sibling) return;\n const left = forward ? block : sibling;\n const right = forward ? sibling : block;\n if (!left.textContent && left.childNodes.length === 1 && left.firstChild instanceof HTMLBRElement) left.replaceChildren();\n if (!right.textContent && right.childNodes.length === 1 && right.firstChild instanceof HTMLBRElement) right.replaceChildren();\n const join = document.createRange();\n join.selectNodeContents(left);\n join.collapse(false);\n left.append(...right.childNodes);\n right.remove();\n if (!left.childNodes.length) left.append(document.createElement('br'));\n left.normalize();\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(join);\n};\n", "import { activeRange } from '../selection/index.js';\nimport type { SelectionReplacement, CutSelectionReplacement } from './internal-types.js';\n\nconst leafTags = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\nconst inlineTags = new Set(['strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'code', 'br']);\nconst inlineTree = (element: Element): boolean => [...element.childNodes].every((node) => node.nodeType === 3 || (node instanceof HTMLElement && inlineTags.has(node.localName) && inlineTree(node)));\nconst ordinaryLeaf = (root: HTMLElement, node: Node): HTMLElement | undefined => {\n const parent = node.nodeType === 1 ? node as Element : node.parentElement;\n const leaf = parent?.closest<HTMLElement>('p,h1,h2,h3,h4,h5,h6');\n if (!(leaf instanceof HTMLElement) || !root.contains(leaf) || leaf.hasAttribute('data-mw-node') || leaf.closest('li,figure,pre') || !inlineTree(leaf)) return;\n if (leaf.parentElement !== root && !['blockquote', 'td', 'th'].includes(leaf.parentElement?.localName ?? '')) return;\n return leaf;\n};\n\nconst selectedLeaves = (root: HTMLElement, range: Range): HTMLElement[] | undefined => {\n const left = ordinaryLeaf(root, range.startContainer);\n const right = ordinaryLeaf(root, range.endContainer);\n if (!left || !right || left === right || left.parentElement !== right.parentElement) return;\n const leaves = [left];\n let next: ChildNode | null = left.nextSibling;\n while (next) {\n if (!(next instanceof HTMLElement) || !leafTags.has(next.localName) || ordinaryLeaf(root, next) !== next) return;\n leaves.push(next);\n if (next === right) return leaves;\n next = next.nextSibling;\n }\n return;\n};\n\nexport const handlesSelectionReplacement = (root: HTMLElement, inputType: string, data: string | null): boolean => {\n if (inputType !== 'deleteContentBackward' && inputType !== 'deleteContentForward' && !(inputType === 'insertText' && typeof data === 'string')) return false;\n return Boolean(selectionReplacement(root));\n};\n\nexport const selectionReplacement = (root: HTMLElement, range: Range | undefined = activeRange(root)): SelectionReplacement | undefined => {\n const leaves = range && !range.collapsed ? selectedLeaves(root, range) : undefined;\n return range && leaves ? { range, leaves } : undefined;\n};\n\n/** Shared live cut, called only after eligibility and detached import validation. */\nexport const cutSelectionReplacement = ({ range, leaves, contentRoots }: SelectionReplacement): CutSelectionReplacement => {\n const left = contentRoots?.left ?? leaves[0];\n const right = contentRoots?.right ?? leaves[leaves.length - 1];\n const document = left.ownerDocument;\n const emptyLeft = !left.textContent && left.querySelectorAll('br').length <= 1;\n const emptyRight = !right.textContent && right.querySelectorAll('br').length <= 1;\n // deleteContents may collapse its own range outside a partially selected mark.\n // A separate collapsed range retains the actual starting inline context.\n const caret = range.cloneRange();\n caret.collapse(true);\n\n const tailRange = document.createRange();\n tailRange.selectNodeContents(right);\n tailRange.setStart(range.endContainer, range.endOffset);\n const tail = tailRange.extractContents();\n if (emptyRight) {\n for (const placeholder of tail.querySelectorAll('br')) placeholder.remove();\n }\n\n const cut = document.createRange();\n cut.selectNodeContents(left);\n cut.setStart(range.startContainer, range.startOffset);\n cut.deleteContents();\n if (emptyLeft) {\n // Remove only the placeholder, keeping an empty starting mark/link as text affinity.\n for (const placeholder of left.querySelectorAll('br')) placeholder.remove();\n }\n for (const leaf of leaves.slice(1)) leaf.remove();\n return { left, right, tail, caret };\n};\n\nexport const ensureReplacementPlaceholder = (leaf: HTMLElement, caret: Range): void => {\n if (!leaf.textContent && !leaf.querySelector('br,img')) {\n // An empty semantic inline still owns metadata; keep it and its insertion context.\n const placeholder = leaf.ownerDocument.createElement('br');\n caret.insertNode(placeholder);\n caret.setStartBefore(placeholder);\n caret.collapse(true);\n }\n};\n\nexport const finishSelectionReplacement = (leaf: HTMLElement, caret: Range): void => {\n ensureReplacementPlaceholder(leaf, caret);\n leaf.normalize();\n const selection = leaf.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n};\n\n/** Replace only ordinary sibling leaves inside the editor's validated transaction. */\nexport const replaceSelection = (root: HTMLElement, text: string): void => {\n const selected = selectionReplacement(root);\n if (!selected) return;\n const { left, tail, caret } = cutSelectionReplacement(selected);\n if (text) {\n const inserted = root.ownerDocument.createTextNode(text);\n caret.insertNode(inserted);\n caret.setStart(inserted, inserted.length);\n caret.collapse(true);\n }\n left.append(tail);\n finishSelectionReplacement(left, caret);\n};\n", "/** Insert a prepared inline fragment without nesting its anchors in a starting link. */\nexport const insertInlineFragment = (left: HTMLElement, caret: Range, fragment: DocumentFragment): void => {\n const parent = caret.startContainer.nodeType === 1 ? caret.startContainer as Element : caret.startContainer.parentElement;\n const anchor = parent?.closest('a');\n if (fragment.querySelector('a') && anchor && left.contains(anchor)) {\n caret.setStartAfter(anchor);\n caret.collapse(true);\n }\n const last = fragment.lastChild;\n if (!last) return;\n caret.insertNode(fragment);\n if (last.nodeType === 3) caret.setStart(last, last.textContent!.length);\n else caret.setStartAfter(last);\n caret.collapse(true);\n};\n", "import { selectionReplacement, cutSelectionReplacement, ensureReplacementPlaceholder, finishSelectionReplacement } from './replace-selection.js';\nimport { insertInlineFragment } from './inline-fragment.js';\n\nconst inlineTags = new Set(['strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'code', 'br', 'img']);\nconst leafTags = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\nconst blockTags = new Set([...leafTags, 'blockquote', 'pre', 'hr', 'ul', 'ol', 'table', 'figure']);\nconst inlineNode = (node: Node): boolean => node.nodeType === 3 || (node instanceof HTMLElement && inlineTags.has(node.localName));\nconst ordinaryPayloadLeaf = (node: Node): node is HTMLElement => node instanceof HTMLElement && leafTags.has(node.localName) && !node.hasAttribute('data-mw-node') && [...node.childNodes].every(inlineNode);\nconst stripPlaceholder = (element: HTMLElement): void => {\n if (!element.textContent && element.querySelectorAll('br').length <= 1 && !element.querySelector('img')) {\n for (const placeholder of element.querySelectorAll('br')) placeholder.remove();\n }\n};\n\n/** Validate/normalize a detached payload only when the new sibling-range path owns it. */\nexport const prepareSelectionPaste = (root: HTMLElement, fragment: DocumentFragment, range?: Range): void => {\n const selected = selectionReplacement(root, range);\n if (!selected) return;\n if (fragment.querySelector('table table') || (selected.leaves[0].closest('td,th') && fragment.querySelector('table')))\n throw new TypeError('Nested table insertion is unsupported for this selection.');\n for (const node of fragment.childNodes) {\n if (!inlineNode(node) && (!(node instanceof HTMLElement) || !blockTags.has(node.localName)))\n throw new TypeError('Unsupported root structure for sibling selection insertion.');\n }\n for (const element of fragment.querySelectorAll('*')) {\n if ((inlineTags.has(element.localName) || leafTags.has(element.localName)) && ![...element.childNodes].every(inlineNode))\n throw new TypeError('A phrasing wrapper cannot contain pasted blocks.');\n }\n const hasBlocks = [...fragment.childNodes].some((node) => !inlineNode(node));\n if (hasBlocks) {\n for (const node of [...fragment.childNodes]) {\n if (node.nodeType === 3 && /^[\\t\\n\\f\\r ]*$/.test(node.textContent ?? '')) node.remove();\n }\n }\n};\n\nconst placeholderAtStart = (leaf: HTMLElement): Range => {\n const caret = leaf.ownerDocument.createRange();\n caret.selectNodeContents(leaf);\n caret.collapse(true);\n ensureReplacementPlaceholder(leaf, caret);\n return caret;\n};\n\nconst meaningfulTail = (tail: DocumentFragment): boolean => Boolean(tail.textContent) || [...tail.querySelectorAll('*')].some((node) => node.attributes.length || ['br', 'img'].includes(node.localName));\n\n/** A validated fragment replaces only the accepted ordinary sibling range. */\nexport const replaceSelectionWithFragment = (root: HTMLElement, fragment: DocumentFragment): boolean => {\n const selected = selectionReplacement(root);\n if (!selected) return false;\n // Trusted focus listeners may have changed the context since detached preflight.\n prepareSelectionPaste(root, fragment, selected.range);\n const nodes = [...fragment.childNodes];\n const singleParagraph = nodes.length === 1 && ordinaryPayloadLeaf(nodes[0]) && nodes[0].localName === 'p';\n const inline = nodes.every(inlineNode) || singleParagraph;\n const leaves = nodes.length > 1 && nodes.every(ordinaryPayloadLeaf);\n const { left, right, tail, caret } = cutSelectionReplacement(selected);\n if (inline) {\n if (singleParagraph) fragment.replaceChildren(...nodes[0].childNodes);\n insertInlineFragment(left, caret, fragment);\n left.append(tail);\n finishSelectionReplacement(left, caret);\n return true;\n }\n if (leaves) {\n const first = nodes[0] as HTMLElement;\n const last = nodes[nodes.length - 1] as HTMLElement;\n stripPlaceholder(first);\n const prefix = root.ownerDocument.createDocumentFragment();\n prefix.append(...first.childNodes);\n first.remove();\n insertInlineFragment(left, caret, prefix);\n left.after(fragment);\n ensureReplacementPlaceholder(left, caret);\n left.normalize();\n for (const middle of nodes.slice(1, -1)) placeholderAtStart(middle as HTMLElement);\n stripPlaceholder(last);\n const end = root.ownerDocument.createRange();\n end.selectNodeContents(last);\n end.collapse(false);\n last.append(tail);\n finishSelectionReplacement(last, end);\n return true;\n }\n // Mixed root inline runs become proper sibling paragraphs, never children of a mark.\n let paragraph: HTMLParagraphElement | undefined;\n for (const node of [...fragment.childNodes]) {\n if (inlineNode(node)) {\n if (!paragraph) {\n paragraph = root.ownerDocument.createElement('p');\n fragment.insertBefore(paragraph, node);\n }\n paragraph.append(node);\n }\n else paragraph = undefined;\n }\n const last = fragment.lastChild!;\n const inserted = [...fragment.childNodes];\n left.after(fragment);\n ensureReplacementPlaceholder(left, caret);\n left.normalize();\n for (const node of inserted) {\n if (node instanceof HTMLElement && leafTags.has(node.localName)) placeholderAtStart(node);\n }\n const suffix = meaningfulTail(tail) ? right : root.ownerDocument.createElement('p');\n suffix.replaceChildren(tail);\n last.after(suffix);\n finishSelectionReplacement(suffix, placeholderAtStart(suffix));\n return true;\n};\n", "const inlineTags = new Set(['strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'code', 'br', 'img']);\n\nexport const inlinePayloadNode = (node: Node): boolean => node.nodeType === 3 || (node instanceof HTMLElement && node.namespaceURI === 'http://www.w3.org/1999/xhtml' && inlineTags.has(node.localName) && [...node.childNodes].every(inlinePayloadNode));\n\nexport const formattingWhitespace = (node: Node): boolean => node.nodeType === 3 && /^[\\t\\n\\f\\r ]*$/.test(node.textContent ?? '');\n\nexport const ordinaryPayloadBody = (node: Node): node is HTMLElement => node instanceof HTMLElement\n && node.namespaceURI === 'http://www.w3.org/1999/xhtml'\n && /^(p|h[1-6])$/.test(node.localName) && !node.hasAttribute('data-mw-node')\n && [...node.childNodes].every(inlinePayloadNode);\n\nexport const quoteBodyBlocks = (quote: HTMLElement): HTMLElement[] | undefined => {\n const nodes = [...quote.childNodes].filter((node) => !formattingWhitespace(node));\n return nodes.length > 0 && nodes.every(ordinaryPayloadBody) ? nodes : undefined;\n};\n\n/** Read-only validation shared by detached payloads and opaque paste sources. */\nexport const isOrdinaryQuote = (node: Node): node is HTMLElement => node instanceof HTMLElement\n && node.namespaceURI === 'http://www.w3.org/1999/xhtml' && node.localName === 'blockquote'\n && !node.hasAttribute('data-mw-node')\n && ([...node.childNodes].every(inlinePayloadNode) || Boolean(quoteBodyBlocks(node)));\n", "import { formattingWhitespace, isOrdinaryQuote } from './paste-payload.js';\nimport type { QuoteBodyPoint, QuotePasteContext } from './internal-types.js';\n\nconst inlineTags = new Set(['strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'code', 'br']);\nconst sourceInlineNode = (node: Node): boolean => node.nodeType === 3 || (node instanceof HTMLElement\n && node.namespaceURI === 'http://www.w3.org/1999/xhtml' && inlineTags.has(node.localName)\n && [...node.childNodes].every(sourceInlineNode));\nconst sourceBody = (node: Node): node is HTMLElement => node instanceof HTMLElement\n && node.namespaceURI === 'http://www.w3.org/1999/xhtml' && /^(p|h[1-6])$/.test(node.localName)\n && !node.hasAttribute('data-mw-node') && [...node.childNodes].every(sourceInlineNode);\n\n/** A source quote being edited has stricter content than an opaque neighbor. */\nexport const quoteSourceBodies = (quote: HTMLElement): HTMLElement[] | undefined => {\n if (!isOrdinaryQuote(quote)) return;\n const children = [...quote.childNodes];\n if (children.every(sourceInlineNode)) return [quote];\n const blocks = children.filter((node) => !formattingWhitespace(node));\n return blocks.length && blocks.every(sourceBody) ? blocks : undefined;\n};\n\n/** Only a quote owned directly by this item can form the bounded inner scope. */\nexport const directQuoteAt = (item: HTMLElement, node: Node): HTMLElement | undefined => {\n const element = node instanceof Element ? node : node.parentElement;\n const quote = element?.closest('blockquote');\n return quote instanceof HTMLElement && quote.parentElement === item ? quote : undefined;\n};\n\nconst quoteBodyPoint = (quote: HTMLElement, bodies: HTMLElement[], range: Range, end: boolean): QuoteBodyPoint | undefined => {\n const point = range.cloneRange();\n point.collapse(!end);\n const node = point.startContainer;\n if (bodies[0] === quote) return { body: quote, range: point };\n const contained = bodies.find((body) => body === node || body.contains(node));\n if (contained) return { body: contained, range: point };\n const children = [...quote.childNodes];\n let offset: number;\n if (node === quote) offset = point.startOffset;\n else if (node.parentNode === quote && formattingWhitespace(node)) offset = children.indexOf(node as ChildNode);\n else return;\n const next = children.slice(offset).find((child): child is HTMLElement => bodies.includes(child as HTMLElement));\n const previous = children.slice(0, offset).reverse().find((child): child is HTMLElement => bodies.includes(child as HTMLElement));\n const body = end ? previous ?? bodies[0] : next ?? bodies[bodies.length - 1];\n point.selectNodeContents(body);\n point.collapse(end ? !previous : Boolean(next));\n return { body, range: point };\n};\n\n/** Resolve one actual quote endpoint using the same child/gap affinity as inner paste. */\nexport const quoteEndpointPoint = (quote: HTMLElement, range: Range, end: boolean): QuoteBodyPoint | undefined => {\n const node = end ? range.endContainer : range.startContainer;\n if (!quote.contains(node)) return;\n const bodies = quoteSourceBodies(quote);\n return bodies && quoteBodyPoint(quote, bodies, range, end);\n};\n\n/** Inspect without normalizing the actual quote or changing the active selection. */\nexport const quotePasteContext = (quote: HTMLElement, range: Range): QuotePasteContext | undefined => {\n if (!quote.contains(range.startContainer) || !quote.contains(range.endContainer)) return;\n const children = [...quote.childNodes];\n const bodies = quoteSourceBodies(quote);\n if (!bodies) return;\n const start = quoteBodyPoint(quote, bodies, range, false);\n const end = range.collapsed ? start : quoteBodyPoint(quote, bodies, range, true);\n if (!start || !end) return;\n const normalized = range.cloneRange();\n normalized.setStart(start.range.startContainer, start.range.startOffset);\n normalized.setEnd(end.range.startContainer, end.range.startOffset);\n const from = bodies.indexOf(start.body);\n const to = bodies.indexOf(end.body);\n // A noncollapsed formatting-gap selection may resolve to reversed body edges.\n if (from > to || start.range.compareBoundaryPoints(Range.START_TO_START, end.range) > 0) return;\n const gaps = children.filter((node) => {\n if (!formattingWhitespace(node)) return false;\n const gap = quote.ownerDocument.createRange();\n gap.selectNode(node);\n return normalized.compareBoundaryPoints(Range.START_TO_START, gap) <= 0\n && normalized.compareBoundaryPoints(Range.END_TO_END, gap) >= 0;\n });\n return { container: quote, bodies, range: normalized, startBody: start.body, endBody: end.body, gaps };\n};\n", "import { ensureReplacementPlaceholder, finishSelectionReplacement } from '../input/replace-selection.js';\nimport { quoteBodyBlocks } from './paste-payload.js';\nimport { directQuoteAt, quoteEndpointPoint, quoteSourceBodies } from './quote-selection.js';\nimport type { ListItemBoundary, QuoteCrossingContext } from './internal-types.js';\n\n/** Read-only inspection of the selected body interval in consecutive inspected items. */\nexport const quoteCrossingContext = (boundaries: ListItemBoundary[], range: Range, startRoot: HTMLElement, endRoot: HTMLElement,\n start: Range, end: Range, gaps: ChildNode[] = []): QuoteCrossingContext | undefined => {\n if (range.collapsed) return;\n const first = boundaries[0];\n const last = boundaries[boundaries.length - 1];\n const from = first.bodies.indexOf(startRoot);\n const to = last.bodies.indexOf(endRoot);\n if (from < 0 || to < 0 || (first === last && to <= from)) return;\n const affected = boundaries.flatMap((boundary, index) => boundary.bodies.slice(index === 0 ? from : 0,\n index === boundaries.length - 1 ? to + 1 : undefined));\n const quotes = affected.filter((body) => body.localName === 'blockquote');\n if (!quotes.length || !quotes.every((quote) => quoteSourceBodies(quote))) return;\n const startQuoted = startRoot.localName === 'blockquote';\n const endQuoted = endRoot.localName === 'blockquote';\n if ((startQuoted && directQuoteAt(first.item, range.startContainer) !== startRoot)\n || (endQuoted && directQuoteAt(last.item, range.endContainer) !== endRoot)) return;\n const startPoint = startQuoted ? quoteEndpointPoint(startRoot, range, false) : undefined;\n const endPoint = endQuoted ? quoteEndpointPoint(endRoot, range, true) : undefined;\n if ((startQuoted && !startPoint) || (endQuoted && !endPoint)) return;\n const normalized = range.cloneRange();\n const left = startPoint?.range ?? start;\n const right = endPoint?.range ?? end;\n if (left.compareBoundaryPoints(Range.START_TO_START, right) > 0) return;\n normalized.setStart(left.startContainer, left.startOffset);\n normalized.setEnd(right.startContainer, right.startOffset);\n const ordered = boundaries.some((boundary) => boundary.interleaved);\n if (ordered && boundaries.some((boundary) => boundary.nestedLists.some((branch) =>\n branch.namespaceURI !== boundary.item.namespaceURI || branch.hasAttribute('data-mw-node')))) return;\n // Body indices describe editing ownership; actual children retain the source\n // body/list order for the separate ordered profile.\n const intervalBranches = ordered ? boundaries.flatMap((boundary, index) => {\n const children = [...boundary.item.children];\n const begin = index === 0 && startRoot !== boundary.item ? children.indexOf(startRoot) + 1 : 0;\n const finish = index === boundaries.length - 1 ? (endRoot === boundary.item ? 0 : children.indexOf(endRoot)) : children.length;\n return children.slice(begin, finish).filter((node): node is HTMLElement => boundary.nestedLists.includes(node as HTMLElement));\n }) : undefined;\n const following = ordered ? (endRoot === last.item ? last.nestedLists\n : [...last.item.children].slice([...last.item.children].indexOf(endRoot) + 1) as HTMLElement[]) : last.bodies.slice(to + 1);\n const siblings = boundaries.length > 1 || ordered ? {\n container: first.item,\n removedItems: boundaries.slice(1).map((boundary) => boundary.item),\n following,\n branches: intervalBranches ?? boundaries.flatMap((boundary) => boundary.nestedLists),\n gaps,\n directStart: startRoot === first.item,\n directEnd: endRoot === last.item,\n } : undefined;\n return { startRoot, endRoot, startQuoteBody: startPoint?.body, endQuoteBody: endPoint?.body,\n range: normalized, covered: affected.slice(1, -1), siblings, ordered };\n};\n\nconst ensureBody = (body: HTMLElement): void => {\n const point = body.ownerDocument.createRange();\n point.selectNodeContents(body);\n point.collapse(true);\n ensureReplacementPlaceholder(body, point);\n};\n\n/** Move actual retained inline descendants into a body, keeping the source item as owner. */\nconst promoteInlineBody = (item: HTMLElement): HTMLElement => {\n const body = item.ownerDocument.createElement('p');\n body.append(...item.childNodes);\n item.append(body);\n return body;\n};\n\n/** Payload/source were fully validated before this transaction-owned mutation. */\nexport const replaceQuoteCrossing = (context: QuoteCrossingContext, roots: HTMLElement[]): void => {\n const { range, covered, startQuoteBody, endQuoteBody, siblings } = context;\n let { startRoot, endRoot } = context;\n const document = startRoot.ownerDocument;\n // Detach protected branches before trimming direct-inline bodies or removing covered items.\n for (const branch of siblings?.branches ?? []) branch.remove();\n if (context.ordered && siblings?.directEnd) {\n for (const node of siblings.following) node.remove();\n }\n // Separate local ranges preserve both actual endpoint wrappers and all untouched\n // quote children/gaps; a cross-container delete would unwrap selected ancestry.\n const suffixCut = document.createRange();\n suffixCut.selectNodeContents(endRoot);\n suffixCut.setEnd(range.endContainer, range.endOffset);\n const prefixCut = document.createRange();\n prefixCut.selectNodeContents(startRoot);\n prefixCut.setStart(range.startContainer, range.startOffset);\n suffixCut.deleteContents();\n prefixCut.deleteContents();\n for (const body of covered) body.remove();\n if (siblings?.directStart) startRoot = promoteInlineBody(startRoot);\n if (siblings?.directEnd) endRoot = promoteInlineBody(endRoot);\n ensureBody(startQuoteBody ?? startRoot);\n if (endQuoteBody) ensureBody(endQuoteBody);\n for (const root of roots) {\n const quoteBodies = root.localName === 'blockquote' && quoteBodyBlocks(root);\n if (quoteBodies) for (const body of quoteBodies) ensureBody(body);\n else ensureBody(root);\n }\n const caretBody = endQuoteBody ? document.createElement('p') : endRoot;\n if (endQuoteBody) ensureBody(caretBody);\n if (context.ordered && siblings) {\n const suffix = endQuoteBody ? [caretBody, endRoot] : [endRoot];\n startRoot.after(...roots, ...siblings.branches, ...suffix, ...siblings.following);\n } else {\n if (endQuoteBody) startRoot.after(...roots, caretBody);\n else startRoot.after(...roots);\n if (siblings) {\n const destination = endQuoteBody ? caretBody : roots[roots.length - 1];\n destination.after(endRoot);\n siblings.container.append(...siblings.following, ...siblings.branches);\n }\n }\n if (siblings) {\n for (const item of siblings.removedItems) item.remove();\n for (const gap of siblings.gaps) gap.remove();\n }\n const caret = document.createRange();\n caret.selectNodeContents(caretBody);\n caret.collapse(true);\n finishSelectionReplacement(caretBody, caret);\n};\n", "import { activeRange } from '../selection/index.js';\nimport { isOrdinaryQuote } from './paste-payload.js';\nimport { directQuoteAt, quotePasteContext } from './quote-selection.js';\nimport { quoteCrossingContext } from './quote-crossing.js';\nimport type { ListItemBoundary, ListSelectionOptions, ListSelectionResult } from './internal-types.js';\n\nconst inlineTags = new Set(['strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'code', 'br']);\nconst inlineNode = (node: Node): boolean => node.nodeType === 3 || (node instanceof HTMLElement && node.namespaceURI === 'http://www.w3.org/1999/xhtml' && inlineTags.has(node.localName) && [...node.childNodes].every(inlineNode));\nconst isList = (node: Node): node is HTMLElement => node instanceof HTMLElement && /^(ul|ol)$/.test(node.localName);\nconst itemAt = (root: HTMLElement, node: Node): HTMLElement | undefined => {\n const element = node.nodeType === 1 ? node as Element : node.parentElement;\n const item = element?.closest<HTMLElement>('li');\n return item && root.contains(item) ? item : undefined;\n};\n\n/** Inspect direct bodies and optional paste-only interleaved branches without changing DOM. */\nconst inspectItem = (root: HTMLElement, item: HTMLElement, preserveQuotes: boolean): ListItemBoundary | undefined => {\n const list = item.parentElement;\n if (item.localName !== 'li' || item.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !root.contains(item) || !list || !isList(list) || item.hasAttribute('data-mw-node') || list.hasAttribute('data-mw-node')) return;\n const ownNodes: ChildNode[] = [];\n const bodies: HTMLElement[] = [];\n const nestedLists: HTMLElement[] = [];\n let interleaved = false;\n for (const node of item.childNodes) {\n if (isList(node)) nestedLists.push(node);\n else {\n if (nestedLists.length) {\n // Only wrapped paste bodies can form an ordered sequence after a branch.\n if (!preserveQuotes || !bodies.length) return;\n interleaved = true;\n }\n const paragraph = node instanceof HTMLElement && /^(p|h[1-6])$/.test(node.localName)\n && node.namespaceURI === item.namespaceURI && !node.hasAttribute('data-mw-node') && [...node.childNodes].every(inlineNode);\n const quote = preserveQuotes && isOrdinaryQuote(node);\n if (node instanceof HTMLElement && (paragraph || quote) && (!ownNodes.length || bodies.length)) {\n bodies.push(node);\n ownNodes.push(...node.childNodes);\n } else {\n if (bodies.length || !inlineNode(node)) return;\n ownNodes.push(node);\n }\n }\n }\n if (!bodies.length) bodies.push(item);\n const body = bodies[0];\n const ownStart = item.ownerDocument.createRange();\n ownStart.selectNodeContents(body);\n ownStart.collapse(true);\n const ownEnd = item.ownerDocument.createRange();\n ownEnd.selectNodeContents(bodies[bodies.length - 1]);\n if (body === item && nestedLists.length) ownEnd.setEndBefore(nestedLists[0]);\n ownEnd.collapse(false);\n const breaks = ownNodes.reduce((count, node) => count + (node instanceof Element ? node.querySelectorAll('br').length + Number(node.localName === 'br') : 0), 0);\n return { item: item as HTMLLIElement, body, bodies, ownNodes, nestedLists, interleaved, ownStart, ownEnd, ownEmpty: ownNodes.every((node) => !node.textContent) && breaks <= 1 };\n};\n\n/** Native/boundary callers deliberately keep the ordinary inline/p/h profile. */\nexport const inspectListItem = (root: HTMLElement, item: HTMLElement): ListItemBoundary | undefined => inspectItem(root, item, false);\n\nconst blocked = (reason: string): ListSelectionResult => ({ status: 'blocked', reason });\n/** Resolve an inline body or an unambiguous edge between direct body blocks. */\nexport const listBodyAt = (range: Range, boundary: ListItemBoundary, end: boolean): HTMLElement | undefined => {\n const node = end ? range.endContainer : range.startContainer;\n const offset = end ? range.endOffset : range.startOffset;\n if (boundary.body === boundary.item) return boundary.item;\n if (node === boundary.item) {\n if (boundary.interleaved) {\n const children = [...boundary.item.childNodes];\n if (offset > children.length) return;\n const child = children[end ? Math.max(0, offset - 1) : Math.min(offset, children.length - 1)];\n return boundary.bodies.find((body) => body === child);\n }\n if (offset > boundary.bodies.length) return;\n const index = end ? Math.max(0, offset - 1) : Math.min(offset, boundary.bodies.length - 1);\n return boundary.bodies[index];\n }\n return boundary.bodies.find((body) => body === node || body.contains(node));\n};\n/** Translate only unambiguous item-level edges; never mutate the active Range. */\nexport const normalizeListBodyRange = (range: Range, boundary: ListItemBoundary, end: boolean): Range | undefined => {\n const body = listBodyAt(range, boundary, end);\n if (!body) return;\n const point = range.cloneRange();\n point.collapse(!end);\n if (boundary.body !== boundary.item && point.startContainer === boundary.item) {\n const count = boundary.interleaved ? boundary.item.childNodes.length : boundary.bodies.length;\n const atStart = point.startOffset === 0 || (!end && point.startOffset < count);\n point.selectNodeContents(body);\n point.collapse(atStart);\n }\n if (point.compareBoundaryPoints(Range.START_TO_START, boundary.ownStart) < 0 || point.compareBoundaryPoints(Range.START_TO_START, boundary.ownEnd) > 0) return;\n return point;\n};\n\n/** A list-owned unsupported partial shape is blocked rather than natively cut. */\nconst selectionPlan = (root: HTMLElement, range: Range | undefined, options: ListSelectionOptions): ListSelectionResult => {\n const { includeSameBody, includeCollapsed, preserveQuotes } = options;\n if (!range || (range.collapsed && !includeCollapsed) || !root.contains(range.startContainer) || !root.contains(range.endContainer)) return { status: 'unowned' };\n const firstItem = itemAt(root, range.startContainer);\n const lastItem = itemAt(root, range.endContainer);\n if (!firstItem && !lastItem) return { status: 'unowned' };\n if (!firstItem || !lastItem) return blocked('A list selection cannot cross into a different block container.');\n if (firstItem.parentElement !== lastItem.parentElement) return blocked('Select sibling items in one list.');\n const first = inspectItem(root, firstItem, preserveQuotes);\n const last = inspectItem(root, lastItem, preserveQuotes);\n if (preserveQuotes && first && last && first.item === last.item) {\n const quote = directQuoteAt(first.item, range.startContainer);\n const endQuote = directQuoteAt(last.item, range.endContainer);\n if (quote && quote === endQuote) {\n if (first.interleaved && first.nestedLists.some((branch) =>\n branch.namespaceURI !== first.item.namespaceURI || branch.hasAttribute('data-mw-node')))\n return blocked('Insertion inside an interleaved item quote requires ordinary branch roots.');\n const context = quotePasteContext(quote, range);\n if (!context) return blocked('Block insertion inside a quote requires ordinary inline or paragraph/heading source content.');\n return { status: 'eligible', range: context.range, leaves: [first.item], gaps: [], first, last,\n startBody: context.startBody, endBody: context.endBody, quote: context };\n }\n }\n const start = first && normalizeListBodyRange(range, first, false);\n const startBody = first && listBodyAt(range, first, false);\n // A collapsed li-level point between blocks denotes the next body's start.\n // Resolving its end independently would instead pick the preceding body.\n const end = range.collapsed ? start : last && normalizeListBodyRange(range, last, true);\n const endBody = range.collapsed ? startBody : last && listBodyAt(range, last, true);\n if (!first || !last || !start || !end || !startBody || !endBody) {\n // Preserve legacy same-item paths except an explicitly block-shaped source.\n if (!includeSameBody && firstItem === lastItem && ![...firstItem.children].some((node) => /^(p|h[1-6])$/.test(node.localName))) return { status: 'unowned' };\n return blocked('List replacement requires inline content or ordinary paragraph/heading bodies.');\n }\n if (preserveQuotes && first.item === last.item) {\n const from = first.bodies.indexOf(startBody);\n const to = first.bodies.indexOf(endBody);\n if (first.bodies.slice(from, to + 1).some((body) => body.localName === 'blockquote')) {\n const crossing = quoteCrossingContext([first], range, startBody, endBody, start, end);\n if (!crossing) return blocked('A block insertion can cross only ordinary editable quotes within the same item.');\n return { status: 'eligible', range: crossing.range, leaves: [first.item], gaps: [], first, last,\n startBody, endBody, crossing };\n }\n }\n if (preserveQuotes && first.item === last.item && (startBody.localName === 'blockquote' || endBody.localName === 'blockquote'))\n return blocked('A block insertion endpoint cannot enter an existing quote.');\n if (first.item === last.item && first.interleaved) return blocked('An interleaved item requires an affected quote crossing.');\n if (!includeSameBody && firstItem === lastItem && startBody === endBody) return { status: 'unowned' };\n const workingRange = range.cloneRange();\n workingRange.setStart(start.startContainer, start.startOffset);\n workingRange.setEnd(end.startContainer, end.startOffset);\n const leaves: HTMLLIElement[] = [];\n const boundaries: ListItemBoundary[] = [];\n let hasQuote = false;\n const gaps: ChildNode[] = [];\n let node: ChildNode | null = first.item;\n while (node) {\n if (node.nodeType === 3 && /^[\\t\\n\\f\\r ]*$/.test(node.textContent ?? '')) gaps.push(node);\n else {\n if (!(node instanceof HTMLElement)) return blocked('Unsupported content between list items.');\n const item = inspectItem(root, node, preserveQuotes);\n if (!item) return blocked('A selected item contains an unsupported body.');\n if (preserveQuotes) {\n const from = item.item === first.item ? item.bodies.indexOf(startBody) : 0;\n const to = item.item === last.item ? item.bodies.indexOf(endBody) : item.bodies.length - 1;\n if (item.bodies.slice(from, to + 1).some((body) => body.localName === 'blockquote')) hasQuote = true;\n }\n leaves.push(item.item);\n boundaries.push(item);\n if (item.item === last.item) {\n if (hasQuote) {\n const unsupportedBranch = boundaries.slice(0, -1).some((boundary) => boundary.nestedLists.some((branch) =>\n branch.namespaceURI !== boundary.item.namespaceURI || branch.hasAttribute('data-mw-node')));\n if (unsupportedBranch) return blocked('Retained first and intermediate branches require ordinary trailing lists.');\n const crossing = quoteCrossingContext(boundaries, range, startBody, endBody, start, end, gaps);\n if (!crossing) return blocked('Block insertion across sibling items requires ordinary editable quotes and supported endpoints.');\n return { status: 'eligible', range: crossing.range, leaves, gaps, first, last, startBody, endBody, crossing };\n }\n if (boundaries.some((boundary) => boundary.interleaved))\n return blocked('Interleaved items require an affected quote crossing.');\n if (boundaries.slice(0, -1).some((boundary) => boundary.nestedLists.length))\n return blocked('A selected item contains a nested branch outside the quote-crossing profile.');\n return { status: 'eligible', range: workingRange, leaves, gaps, first, last, startBody, endBody };\n }\n }\n node = node.nextSibling;\n }\n return blocked('Select consecutive items in one list.');\n};\n\n/** Existing callers keep their earlier native and ordinary insertion ownership. */\nexport const listSelectionReplacement = (root: HTMLElement, range: Range | undefined = activeRange(root), includeSameBody = false, includeCollapsed = false): ListSelectionResult => selectionPlan(root, range, { includeSameBody, includeCollapsed, preserveQuotes: false });\n\n/** Only block payload candidates may preserve opaque quotes beside their range. */\nexport const listPasteSelection = (root: HTMLElement, range: Range | undefined = activeRange(root), blockCandidate = false): ListSelectionResult => selectionPlan(root, range, {\n includeSameBody: blockCandidate,\n includeCollapsed: blockCandidate,\n preserveQuotes: blockCandidate,\n});\n", "import { cutSelectionReplacement, ensureReplacementPlaceholder, finishSelectionReplacement, insertInlineFragment } from '../input/index.js';\nimport { activeRange } from '../selection/index.js';\nimport { listPasteSelection, listSelectionReplacement } from './selection-boundaries.js';\nimport { formattingWhitespace, inlinePayloadNode, isOrdinaryQuote, ordinaryPayloadBody, quoteBodyBlocks } from './paste-payload.js';\nimport { replaceQuoteCrossing } from './quote-crossing.js';\nimport type { ListSelectionPlan, ListSelectionResult } from './internal-types.js';\n\nconst ordinaryParagraph = (fragment: DocumentFragment): HTMLElement | undefined => {\n const node = fragment.firstChild;\n return fragment.childNodes.length === 1 && node instanceof HTMLElement && node.localName === 'p' && !node.hasAttribute('data-mw-node') && [...node.childNodes].every(inlinePayloadNode) ? node : undefined;\n};\nconst multiBlockCandidate = (fragment: DocumentFragment): boolean => {\n const nodes = [...fragment.childNodes].filter((node) => !formattingWhitespace(node));\n return nodes.length > 1 && nodes.some((node) => !inlinePayloadNode(node));\n};\nconst headingRoot = (fragment: DocumentFragment): Element | undefined => {\n const nodes = [...fragment.childNodes].filter((node) => !formattingWhitespace(node));\n const node = nodes[0];\n return nodes.length === 1 && node instanceof Element && /^h[1-6]$/.test(node.localName) ? node : undefined;\n};\nconst ordinaryHeading = (fragment: DocumentFragment): HTMLElement | undefined => {\n const node = headingRoot(fragment);\n return node instanceof HTMLElement && node.namespaceURI === 'http://www.w3.org/1999/xhtml'\n && !node.hasAttribute('data-mw-node') && [...node.childNodes].every(inlinePayloadNode) ? node : undefined;\n};\nconst quoteRoot = (fragment: DocumentFragment): Element | undefined => {\n const nodes = [...fragment.childNodes].filter((node) => !formattingWhitespace(node));\n const node = nodes[0];\n return nodes.length === 1 && node instanceof Element && node.localName === 'blockquote' ? node : undefined;\n};\nconst ordinaryQuote = (fragment: DocumentFragment): HTMLElement | undefined => {\n const node = quoteRoot(fragment);\n return node && isOrdinaryQuote(node) ? node : undefined;\n};\nconst blockPasteCandidate = (fragment: DocumentFragment): boolean => multiBlockCandidate(fragment)\n || Boolean(headingRoot(fragment) || quoteRoot(fragment));\nconst ordinaryBlocks = (fragment: DocumentFragment): HTMLElement[] | undefined => {\n const nodes = [...fragment.childNodes].filter((node) => !formattingWhitespace(node));\n return nodes.length > 1 && nodes.every(ordinaryPayloadBody) ? nodes : undefined;\n};\nconst stripPlaceholder = (body: HTMLElement): void => {\n if (!body.textContent && !body.querySelector('img') && body.querySelectorAll('br').length <= 1) {\n for (const placeholder of body.querySelectorAll('br')) placeholder.remove();\n }\n};\nconst ensureBodyPlaceholder = (body: HTMLElement): void => {\n const caret = body.ownerDocument.createRange();\n caret.selectNodeContents(body);\n caret.collapse(true);\n ensureReplacementPlaceholder(body, caret);\n};\nconst requireSupported = (selected: ListSelectionResult): ListSelectionPlan | undefined => {\n if (selected.status === 'blocked') throw new RangeError(selected.reason);\n return selected.status === 'eligible' ? selected : undefined;\n};\n\n/** The transaction owner clears old caret formats only for this validated path. */\nexport const handlesCollapsedListBlockPaste = (root: HTMLElement, fragment: DocumentFragment, range: Range | undefined = activeRange(root)): boolean => {\n if (!range?.collapsed) return false;\n const innerPayload = Boolean(ordinaryBlocks(fragment) || ordinaryHeading(fragment));\n if (!innerPayload && !ordinaryQuote(fragment)) return false;\n const selected = listPasteSelection(root, range, true);\n return selected.status === 'eligible' && (!selected.quote || innerPayload);\n};\n\n/** Detached import preflight: an empty sanitized fragment stays a no-op for any source. */\nexport const prepareListSelectionPaste = (root: HTMLElement, fragment: DocumentFragment, range?: Range): void => {\n if (!fragment.childNodes.length) return;\n const blocks = ordinaryBlocks(fragment);\n const heading = ordinaryHeading(fragment);\n const quote = ordinaryQuote(fragment);\n const candidate = blockPasteCandidate(fragment);\n const selected = requireSupported(listPasteSelection(root, range, candidate));\n if (!selected) return;\n if (selected.quote && !blocks && !heading)\n throw new TypeError('Insertion inside a list quote supports multiple ordinary paragraphs/headings or one ordinary heading.');\n if (![...fragment.childNodes].every(inlinePayloadNode) && !ordinaryParagraph(fragment) && !blocks && !heading && !quote)\n throw new TypeError('List selection insertion supports inline HTML, an ordinary paragraph, heading or bounded quote, or multiple ordinary paragraphs/headings.');\n if (blocks || heading || quote) {\n for (const node of [...fragment.childNodes]) if (formattingWhitespace(node)) node.remove();\n }\n if (quote && quoteBodyBlocks(quote)) {\n for (const node of [...quote.childNodes]) if (formattingWhitespace(node)) node.remove();\n }\n};\n\nconst cutListSelection = (selected: ListSelectionPlan, forceParagraph = false) => {\n const context = selected.quote;\n const container = context?.container ?? selected.first.item;\n const sameItem = selected.first.item === selected.last.item;\n const firstBodies = context?.bodies ?? selected.first.bodies;\n const lastBodies = context?.bodies ?? selected.last.bodies;\n const startIndex = firstBodies.indexOf(selected.startBody);\n const endIndex = lastBodies.indexOf(selected.endBody);\n const following: ChildNode[] = context ? [] : lastBodies.slice(endIndex + 1);\n if (context && selected.endBody !== container) {\n let node = selected.endBody.nextSibling;\n while (node) {\n following.push(node);\n node = node.nextSibling;\n }\n }\n const branches = context ? [] : selected.last.nestedLists;\n // Keep unselected branches out of the generic cut: for a direct empty LI,\n // their placeholders must not be mistaken for the own-body placeholder.\n for (const branch of branches) branch.remove();\n for (const body of following) body.remove();\n const leaves = context || sameItem ? firstBodies.slice(startIndex, endIndex + 1) : selected.leaves;\n const cut = cutSelectionReplacement({ range: selected.range, leaves, contentRoots: { left: selected.startBody, right: selected.endBody } });\n if (!context && !sameItem) {\n for (const body of selected.first.bodies.slice(startIndex + 1)) body.remove();\n }\n // A direct-inline start needs a wrapper when surviving or incoming blocks\n // would otherwise create a mixed inline/block item. Keep actual descendants.\n if (cut.left === container && (following.length || forceParagraph)) {\n const caretContainer = cut.caret.startContainer;\n const offset = cut.caret.startOffset;\n const paragraph = cut.left.ownerDocument.createElement('p');\n paragraph.append(...cut.left.childNodes);\n cut.left.append(paragraph);\n cut.caret.setStart(caretContainer === cut.left ? paragraph : caretContainer, offset);\n cut.caret.collapse(true);\n cut.left = paragraph;\n }\n for (const gap of context?.gaps ?? selected.gaps) gap.remove();\n return { ...cut, following, branches, container };\n};\n\n/** Called only inside the editor transaction after native ownership was chosen. */\nexport const replaceListSelection = (root: HTMLElement, text: string): boolean => {\n const selected = requireSupported(listSelectionReplacement(root));\n if (!selected) return false;\n const { left, tail, caret, following, branches, container } = cutListSelection(selected);\n if (text) {\n const inserted = root.ownerDocument.createTextNode(text);\n caret.insertNode(inserted);\n caret.setStart(inserted, inserted.length);\n caret.collapse(true);\n }\n left.append(tail);\n finishSelectionReplacement(left, caret);\n container.append(...following, ...branches);\n return true;\n};\n\n/** Recheck the live range; trusted focus callbacks may have changed ownership. */\nexport const replaceListSelectionWithFragment = (root: HTMLElement, fragment: DocumentFragment): boolean => {\n if (!fragment.childNodes.length) return false;\n const blocks = ordinaryBlocks(fragment);\n const heading = ordinaryHeading(fragment);\n const quote = ordinaryQuote(fragment);\n const standalone = heading ?? quote;\n const candidate = blockPasteCandidate(fragment);\n const selected = requireSupported(listPasteSelection(root, undefined, candidate));\n if (!selected) return false;\n prepareListSelectionPaste(root, fragment, selected.range);\n if (selected.crossing) {\n // Crossing is a standalone structural profile: preserve every payload wrapper.\n const roots = blocks ?? (standalone ? [standalone] : undefined);\n if (!roots) throw new TypeError('Crossing a list quote requires an ordinary block payload.');\n replaceQuoteCrossing(selected.crossing, roots);\n return true;\n }\n const paragraph = ordinaryParagraph(fragment);\n // Keep the original end wrapper before a direct start is promoted by the cut.\n const suffix = standalone ? (selected.endBody === (selected.quote?.container ?? selected.last.item)\n ? root.ownerDocument.createElement('p') : selected.endBody.cloneNode(false) as HTMLElement) : undefined;\n const { left, tail, caret, following, branches, container } = cutListSelection(selected, Boolean(blocks || standalone));\n if (standalone && suffix) {\n left.after(standalone, suffix);\n ensureReplacementPlaceholder(left, caret);\n left.normalize();\n const quoteBlocks = quote && quoteBodyBlocks(quote);\n if (quoteBlocks) {\n for (const body of quoteBlocks) ensureBodyPlaceholder(body);\n }\n else ensureBodyPlaceholder(standalone);\n suffix.append(tail);\n const end = root.ownerDocument.createRange();\n end.selectNodeContents(suffix);\n end.collapse(true);\n finishSelectionReplacement(suffix, end);\n container.append(...following, ...branches);\n return true;\n }\n if (blocks) {\n const first = blocks[0];\n const last = blocks[blocks.length - 1];\n stripPlaceholder(first);\n const prefix = root.ownerDocument.createDocumentFragment();\n prefix.append(...first.childNodes);\n first.remove();\n insertInlineFragment(left, caret, prefix);\n left.after(...blocks.slice(1));\n ensureReplacementPlaceholder(left, caret);\n left.normalize();\n for (const middle of blocks.slice(1, -1)) ensureBodyPlaceholder(middle);\n stripPlaceholder(last);\n const end = root.ownerDocument.createRange();\n end.selectNodeContents(last);\n end.collapse(false);\n last.append(tail);\n finishSelectionReplacement(last, end);\n container.append(...following, ...branches);\n return true;\n }\n if (paragraph) fragment.replaceChildren(...paragraph.childNodes);\n insertInlineFragment(left, caret, fragment);\n left.append(tail);\n finishSelectionReplacement(left, caret);\n container.append(...following, ...branches);\n return true;\n};\n", "import { activeRange } from '../selection/index.js';\nimport { finishSelectionReplacement } from '../input/index.js';\nimport { inspectListItem, listBodyAt, normalizeListBodyRange } from './selection-boundaries.js';\n\nconst isList = (node: Node): node is HTMLElement => node instanceof HTMLElement && (node.localName === 'ul' || node.localName === 'ol');\n\nconst selectedItem = (root: HTMLElement, range: Range): HTMLLIElement | undefined => {\n const element = range.startContainer.nodeType === 1 ? range.startContainer as Element : range.startContainer.parentElement;\n const item = element?.closest('li');\n return item instanceof HTMLLIElement && root.contains(item) && item.parentElement && isList(item.parentElement) ? item : undefined;\n};\n\n/** Find an own-body edge even when the item's shape will be a mutation barrier. */\nconst atOwnEnd = (item: HTMLLIElement, range: Range): boolean => {\n const body = item.ownerDocument.createRange();\n body.selectNodeContents(item);\n const children = [...item.childNodes];\n const branchIndex = children.findIndex(isList);\n const firstBranch = children[branchIndex];\n const ownNodes = branchIndex === -1 ? children : children.slice(0, branchIndex);\n if (firstBranch) body.setEndBefore(firstBranch);\n const end = body.cloneRange();\n end.collapse(false);\n if (range.compareBoundaryPoints(Range.START_TO_START, end) > 0) return false;\n const hasText = ownNodes.some((node) => (node.nodeType === 1 || node.nodeType === 3 || node.nodeType === 4) && Boolean(node.textContent));\n const blockers = 'img,hr,table,figure,pre,blockquote,ul,ol';\n const empty = !hasText\n && ownNodes.every((node) => !(node instanceof Element) || (!node.matches(blockers) && !node.querySelector(blockers)))\n && ownNodes.reduce((count, node) => count + (node instanceof Element ? Number(node.localName === 'br') + node.querySelectorAll('br').length : 0), 0) <= 1;\n if (empty) return true;\n body.setStart(range.startContainer, range.startOffset);\n const suffix = body.cloneContents();\n return !suffix.textContent && !suffix.querySelector('br,img,hr,table,figure,ul,ol');\n};\n\nconst nextItem = (item: HTMLLIElement): HTMLLIElement | undefined => {\n let sibling = item.nextSibling;\n // Formatting whitespace between item elements is retained in the list.\n while (sibling?.nodeType === 3 && /^[\\t\\n\\f\\r ]*$/.test(sibling.textContent ?? '')) sibling = sibling.nextSibling;\n return sibling instanceof HTMLLIElement && sibling.parentElement === item.parentElement ? sibling : undefined;\n};\n\nconst removeOwnPlaceholder = (nodes: readonly ChildNode[]): void => {\n for (const node of nodes) {\n if (node instanceof HTMLBRElement) node.remove();\n else if (node instanceof HTMLElement) {\n for (const placeholder of node.querySelectorAll('br')) placeholder.remove();\n }\n }\n};\n\nconst atBodyEnd = (body: HTMLElement, point: Range): boolean => {\n const suffix = body.ownerDocument.createRange();\n suffix.selectNodeContents(body);\n suffix.setStart(point.startContainer, point.startOffset);\n const content = suffix.cloneContents();\n if (!body.textContent && body.querySelectorAll('br').length <= 1) return true;\n return !content.textContent && !content.querySelector('br,img');\n};\n\nconst removeBodyPlaceholder = (body: HTMLElement): void => {\n if (!body.textContent && body.querySelectorAll('br').length <= 1) removeOwnPlaceholder([...body.childNodes]);\n};\n\n/** Only the validated cancelable beforeinput path calls this handler. */\nexport const handlesListForwardDelete = (root: HTMLElement, inputType: string): boolean => {\n if (inputType !== 'deleteContentForward') return false;\n const range = activeRange(root);\n if (!range?.collapsed) return false;\n const item = selectedItem(root, range);\n if (!item) return false;\n const boundary = inspectListItem(root, item);\n const previousEdge = range.startContainer === item && range.startOffset > 0;\n const body = boundary && listBodyAt(range, boundary, previousEdge);\n const point = boundary && normalizeListBodyRange(range, boundary, previousEdge);\n if (body && point) {\n if (body === item) return atOwnEnd(item, range);\n return atBodyEnd(body, point);\n }\n const element = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement;\n const wrapped = element?.closest<HTMLElement>('p,h1,h2,h3,h4,h5,h6');\n if (wrapped?.parentElement === item && atBodyEnd(wrapped, range)) return true;\n return atOwnEnd(item, range);\n};\n\n/** Join one sibling pair inside the existing editor transaction; barriers are no-ops. */\nexport const editListForwardDelete = (root: HTMLElement): boolean => {\n const range = activeRange(root);\n if (!range?.collapsed) return false;\n const item = selectedItem(root, range);\n if (!item) return false;\n const left = inspectListItem(root, item);\n const previousEdge = range.startContainer === item && range.startOffset > 0;\n const current = left && listBodyAt(range, left, previousEdge);\n const point = left && normalizeListBodyRange(range, left, previousEdge);\n if (!left || !current || !point || !(current === item ? atOwnEnd(item, range) : atBodyEnd(current, point))) return false;\n const following = left.bodies[left.bodies.indexOf(current) + 1];\n if (following) {\n removeBodyPlaceholder(current);\n removeBodyPlaceholder(following);\n const join = root.ownerDocument.createRange();\n join.selectNodeContents(current);\n join.collapse(false);\n current.append(...following.childNodes);\n following.remove();\n finishSelectionReplacement(current, join);\n return true;\n }\n const rightItem = nextItem(item);\n const right = rightItem && inspectListItem(root, rightItem);\n if (!right) return false;\n\n // Branches stay independent: no list scan/coalescing, attribute rewrite or\n // descendant normalization is needed to join the items' own inline bodies.\n for (const branch of left.nestedLists) branch.remove();\n for (const branch of right.nestedLists) branch.remove();\n let target = current;\n const rightBody = right.bodies[0];\n const laterBodies = right.bodies.slice(1);\n if (target === item && laterBodies.length) {\n // A direct-inline item cannot also own block siblings. Promote only when\n // preserving later right bodies requires that representation.\n target = root.ownerDocument.createElement('p');\n target.append(...left.ownNodes);\n item.append(target);\n }\n removeBodyPlaceholder(target);\n removeBodyPlaceholder(rightBody);\n const join = root.ownerDocument.createRange();\n join.selectNodeContents(target);\n join.collapse(false);\n const rightNodes = rightBody === right.item ? right.ownNodes : [...rightBody.childNodes];\n target.append(...rightNodes.filter((node) => node.parentNode === rightBody));\n finishSelectionReplacement(target, join);\n item.append(...laterBodies, ...left.nestedLists, ...right.nestedLists);\n right.item.remove();\n return true;\n};\n", "import { activeRange } from '../selection/index.js';\nimport { copyDirection } from '../document/direction.js';\nimport { editListForwardDelete } from './forward-delete.js';\nimport { inspectListItem } from './selection-boundaries.js';\nimport type { ListItemBoundary } from './internal-types.js';\nimport type { FirstBodyBackspacePlan } from './first-body-backspace.types.js';\n\nconst isList = (node: Element | null): node is HTMLElement => node instanceof HTMLElement\n && node.namespaceURI === 'http://www.w3.org/1999/xhtml' && /^(ul|ol)$/.test(node.localName);\nconst whitespace = (node: Node): boolean => node.nodeType === 3 && /^[\\t\\n\\f\\r ]*$/.test(node.textContent ?? '');\n\nconst supportedList = (root: HTMLElement, list: HTMLElement): boolean => isList(list)\n && !list.hasAttribute('data-mw-node')\n && [...list.childNodes].every((node) => whitespace(node)\n || (node instanceof HTMLLIElement && Boolean(inspectListItem(root, node))));\n\n/** Resolve every changed container before opening the structural mutation. */\nconst firstBodyBackspacePlan = (root: HTMLElement, boundary: ListItemBoundary): FirstBodyBackspacePlan | undefined => {\n const list = boundary.item.parentElement;\n if (boundary.bodies.length < 2 || boundary.body === boundary.item || !list || !supportedList(root, list)) return;\n const previous = boundary.item.previousElementSibling;\n if (previous instanceof HTMLElement) {\n const inspected = inspectListItem(root, previous);\n return inspected ? { kind: 'join', previous: inspected } : undefined;\n }\n const parent = list.parentElement;\n if (!(parent instanceof HTMLElement) || parent.namespaceURI !== 'http://www.w3.org/1999/xhtml') return;\n if (parent === root || ['blockquote', 'td', 'th'].includes(parent.localName)) return { kind: 'unwrap', list };\n if (!(parent instanceof HTMLLIElement) || !inspectListItem(root, parent)) return;\n const outer = parent.parentElement;\n if (!outer || !supportedList(root, outer)) return;\n const laterBranches: HTMLElement[] = [];\n let branch = list.nextSibling;\n while (branch) {\n if (!(branch instanceof HTMLElement) || !supportedList(root, branch)) return;\n laterBranches.push(branch);\n branch = branch.nextSibling;\n }\n const following: ChildNode[] = [];\n let next = boundary.item.nextSibling;\n while (next) {\n following.push(next);\n next = next.nextSibling;\n }\n return { kind: 'lift', list, owner: parent, following, laterBranches };\n};\n\nexport const canEditFirstBodyBackspace = (root: HTMLElement, boundary: ListItemBoundary): boolean => Boolean(firstBodyBackspacePlan(root, boundary));\n\nconst selectRange = (root: HTMLElement, range: Range): void => {\n const selection = root.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n};\n\n/** Invoked only inside the cancelable-beforeinput transaction owner. */\nexport const editFirstBodyBackspace = (root: HTMLElement, boundary: ListItemBoundary, start: Range): boolean => {\n const plan = firstBodyBackspacePlan(root, boundary);\n if (!plan) return false;\n if (plan.kind === 'join') {\n // The outer transaction already captured the original first-body bookmark.\n // Reuse the validated forward join rather than duplicate body/branch rules.\n const original = activeRange(root)?.cloneRange();\n selectRange(root, plan.previous.ownEnd.cloneRange());\n if (editListForwardDelete(root)) return true;\n if (original) selectRange(root, original);\n return false;\n }\n\n // DOM Range coordinates can move to the old parent when an actual subtree is\n // transferred. Preserve the normalized inline node/offset explicitly.\n const container = start.startContainer;\n const offset = start.startOffset;\n if (plan.kind === 'unwrap') {\n for (const body of boundary.bodies)\n if (/^(p|h[1-6])$/.test(body.localName) && !body.hasAttribute('dir')) copyDirection(boundary.item, body);\n plan.list.before(...boundary.bodies, ...boundary.nestedLists);\n boundary.item.remove();\n } else {\n if (plan.following.some((node) => node instanceof HTMLLIElement)) {\n const trailing = plan.list.cloneNode(false) as HTMLElement;\n trailing.append(...plan.following);\n boundary.item.append(trailing);\n }\n // The remaining source siblings precede all later owner branches in the\n // original depth-first order. Keep whole branches separate in that order.\n boundary.item.append(...plan.laterBranches);\n plan.owner.after(boundary.item);\n }\n if (!plan.list.children.length) plan.list.remove();\n const caret = root.ownerDocument.createRange();\n caret.setStart(container, offset);\n caret.collapse(true);\n selectRange(root, caret);\n return true;\n};\n", "import { activeRange, placeCaret } from '../selection/index.js';\nimport { finishSelectionReplacement } from '../input/index.js';\nimport { inspectListItem, listBodyAt, listSelectionReplacement, normalizeListBodyRange } from './selection-boundaries.js';\nimport { replaceListSelection } from './replace-selection.js';\nimport { canEditFirstBodyBackspace, editFirstBodyBackspace } from './first-body-backspace.js';\nimport type { WrappedListInputStatus } from './wrapped-input.types.js';\n\nconst itemAt = (root: HTMLElement, node: Node): HTMLLIElement | undefined => {\n const element = node instanceof Element ? node : node.parentElement;\n const item = element?.closest('li');\n return item instanceof HTMLLIElement && root.contains(item) ? item : undefined;\n};\n\nconst atBodyStart = (body: HTMLElement, range: Range): boolean => {\n if (!body.textContent && body.querySelectorAll('br').length <= 1) return true;\n const prefix = body.ownerDocument.createRange();\n prefix.selectNodeContents(body);\n prefix.setEnd(range.startContainer, range.startOffset);\n const content = prefix.cloneContents();\n return !content.textContent && !content.querySelector('br,img');\n};\n\n/** Own only p/heading-shaped items; ordinary inline-list input stays unchanged. */\nexport const inspectWrappedListInput = (root: HTMLElement, inputType: string): WrappedListInputStatus => {\n if (inputType !== 'insertParagraph' && inputType !== 'insertLineBreak' && inputType !== 'deleteContentBackward') return 'unowned';\n const range = activeRange(root);\n if (!range) return 'unowned';\n const item = itemAt(root, range.startContainer);\n const last = itemAt(root, range.endContainer);\n const wrappedShape = (candidate: HTMLLIElement | undefined): boolean => Boolean(candidate && [...candidate.children].some((node) => /^(p|h[1-6])$/.test(node.localName)));\n if (!wrappedShape(item) && !wrappedShape(last)) return 'unowned';\n if (!item || item !== last) return inputType === 'deleteContentBackward' ? 'unowned' : 'blocked';\n const boundary = inspectListItem(root, item);\n if (!boundary || boundary.body === item) {\n if (inputType !== 'deleteContentBackward') return 'blocked';\n const element = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement;\n const body = element?.closest<HTMLElement>('p,h1,h2,h3,h4,h5,h6');\n if (range.collapsed && range.startContainer === item && range.startOffset === 0) return 'blocked';\n return range.collapsed && body?.parentElement === item && atBodyStart(body, range) ? 'blocked' : 'unowned';\n }\n const body = listBodyAt(range, boundary, false);\n const endBody = range.collapsed ? body : listBodyAt(range, boundary, true);\n const start = normalizeListBodyRange(range, boundary, false);\n const end = range.collapsed ? start : normalizeListBodyRange(range, boundary, true);\n if (!body || !start || !end) return inputType === 'deleteContentBackward' ? 'unowned' : 'blocked';\n if (body !== endBody) {\n if (inputType === 'deleteContentBackward') return 'unowned';\n return listSelectionReplacement(root, range).status === 'eligible' ? 'eligible' : 'blocked';\n }\n if (inputType === 'deleteContentBackward') {\n if (!range.collapsed || !atBodyStart(body, start)) return 'unowned';\n if (boundary.bodies.indexOf(body) > 0) return 'eligible';\n return boundary.bodies.length > 1 ? (canEditFirstBodyBackspace(root, boundary) ? 'eligible' : 'blocked') : 'unowned';\n }\n // Preserve the legacy empty-item exit/lift policy, including whitespace-only\n // bodies; branches make this an ordinary split rather than a list exit.\n if (inputType === 'insertParagraph' && boundary.bodies.length === 1 && !item.textContent?.trim() && !boundary.nestedLists.length) return 'legacy';\n return 'eligible';\n};\n\nconst ensurePlaceholder = (body: HTMLElement): void => {\n if (!body.textContent && !body.querySelector('br')) body.append(body.ownerDocument.createElement('br'));\n};\n\n/** Called only by the guarded cancelable-beforeinput transaction owner. */\nexport const editWrappedListInput = (root: HTMLElement, inputType: string, prepareSplit?: (item: HTMLLIElement) => void): boolean => {\n if (inspectWrappedListInput(root, inputType) !== 'eligible') return false;\n let range = activeRange(root)!;\n let boundary = inspectListItem(root, itemAt(root, range.startContainer)!)!;\n if (!range.collapsed && listBodyAt(range, boundary, false) !== listBodyAt(range, boundary, true)) {\n if (!replaceListSelection(root, '')) return false;\n range = activeRange(root)!;\n boundary = inspectListItem(root, itemAt(root, range.startContainer)!)!;\n }\n const body = listBodyAt(range, boundary, false)!;\n const start = normalizeListBodyRange(range, boundary, false)!;\n const end = range.collapsed ? start : normalizeListBodyRange(range, boundary, true)!;\n if (inputType === 'deleteContentBackward') {\n if (body === boundary.body) return editFirstBodyBackspace(root, boundary, start);\n const previous = boundary.bodies[boundary.bodies.indexOf(body) - 1];\n const empty = (node: HTMLElement) => !node.textContent && node.querySelectorAll('br').length <= 1;\n for (const node of [previous, body]) {\n if (empty(node)) for (const placeholder of node.querySelectorAll('br')) placeholder.remove();\n }\n const join = root.ownerDocument.createRange();\n join.selectNodeContents(previous);\n join.collapse(false);\n previous.append(...body.childNodes);\n body.remove();\n finishSelectionReplacement(previous, join);\n return true;\n }\n const cut = start.cloneRange();\n cut.setEnd(end.startContainer, end.startOffset);\n // Keep a separate live starting point: deleteContents may collapse a range\n // across inline wrappers to a common ancestor and lose starting affinity.\n const caret = start.cloneRange();\n cut.deleteContents();\n\n if (inputType === 'insertLineBreak') {\n // A lone empty-body br is a placeholder, not an existing real line.\n // Removing it keeps live caret affinity and semantic inline wrappers.\n const breaks = body.querySelectorAll('br');\n if (!body.textContent && breaks.length <= 1) {\n for (const placeholder of breaks) placeholder.remove();\n }\n const suffix = root.ownerDocument.createRange();\n suffix.selectNodeContents(body);\n suffix.setStart(caret.startContainer, caret.startOffset);\n const trailing = suffix.cloneContents();\n const lineBreak = root.ownerDocument.createElement('br');\n caret.insertNode(lineBreak);\n if (!trailing.textContent && !trailing.querySelector('br')) lineBreak.after(root.ownerDocument.createElement('br'));\n caret.setStartAfter(lineBreak);\n caret.collapse(true);\n const selection = root.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n return true;\n }\n\n const tail = root.ownerDocument.createRange();\n tail.selectNodeContents(body);\n tail.setStart(caret.startContainer, caret.startOffset);\n const nextItem = boundary.item.cloneNode(false) as HTMLLIElement;\n prepareSplit?.(nextItem);\n const nextBody = body.cloneNode(false) as HTMLElement;\n nextBody.append(tail.extractContents());\n const laterBodies = boundary.bodies.slice(boundary.bodies.indexOf(body) + 1);\n nextItem.append(nextBody, ...laterBodies, ...boundary.nestedLists);\n boundary.item.after(nextItem);\n ensurePlaceholder(body);\n ensurePlaceholder(nextBody);\n const walker = root.ownerDocument.createTreeWalker(nextBody, NodeFilter.SHOW_TEXT);\n let text = walker.nextNode();\n while (text && !text.textContent) text = walker.nextNode();\n if (!text) placeCaret(nextBody);\n else {\n caret.setStart(text, 0);\n caret.collapse(true);\n const selection = root.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n }\n return true;\n};\n", "export { inspectWrappedListInput, editWrappedListInput } from './wrapped-input.js';\nimport { activeRange, placeCaret, preserveRange } from '../selection/index.js';\nimport { normalizeListMarker } from '../document/list-marker.js';\nimport { copyDirection } from '../document/direction.js';\nexport { handlesListForwardDelete, editListForwardDelete } from './forward-delete.js';\nexport { inspectListItem, listSelectionReplacement } from './selection-boundaries.js';\nexport { prepareListSelectionPaste, replaceListSelection, replaceListSelectionWithFragment, handlesCollapsedListBlockPaste } from './replace-selection.js';\nconst blocks = 'p,h1,h2,h3,h4,h5,h6,blockquote,pre,li';\nconst isList = (element: Element | null): element is HTMLUListElement | HTMLOListElement => !!element && /^(ul|ol)$/.test(element.localName);\nconst elementAt = (node: Node): Element | null => node instanceof Element ? node : node.parentElement;\nconst blockAt = (root: HTMLElement, node: Node, preferItem = true): HTMLElement | undefined => {\n const element = elementAt(node);\n const item = element?.closest<HTMLElement>('li');\n const block = (preferItem && item && root.contains(item) ? item : undefined) ?? element?.closest<HTMLElement>(blocks);\n return block && root.contains(block) ? block : undefined;\n};\nconst touches = (range: Range, node: Node): boolean => {\n const content = node.ownerDocument!.createRange();\n if (node.nodeType === 3)\n content.selectNodeContents(node);\n else\n content.selectNode(node);\n const start = range.cloneRange();\n start.collapse(true);\n const end = range.cloneRange();\n end.collapse(false);\n const first = content.cloneRange();\n first.collapse(true);\n const last = content.cloneRange();\n last.collapse(false);\n return start.compareBoundaryPoints(Range.START_TO_START, last) < 0 && end.compareBoundaryPoints(Range.START_TO_START, first) > 0;\n};\nexport const selectedBlocks = (root: HTMLElement, range = activeRange(root), preferItems = true): HTMLElement[] => {\n if (!range)\n return [];\n if (range.collapsed) {\n const block = blockAt(root, range.startContainer, preferItems);\n return block ? [block] : [];\n }\n const found = new Set<HTMLElement>();\n const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);\n let node: Node | null;\n while ((node = walker.nextNode())) {\n if (!(node.nodeType === 3 && node.textContent) && !(node instanceof Element && /^(br|img|hr)$/.test(node.localName)))\n continue;\n if (touches(range, node)) {\n const block = blockAt(root, node, preferItems);\n if (block)\n found.add(block);\n }\n }\n return [...root.querySelectorAll<HTMLElement>(blocks)].filter((block) => found.has(block));\n};\nconst topItems = (items: HTMLElement[]) => items.filter((item) => !items.some((parent) => parent !== item && parent.contains(item)));\nconst itemRange = (root: HTMLElement, range?: Range): HTMLLIElement[] => {\n const items = topItems(selectedBlocks(root, range));\n if (!items.length || items.some((item) => item.localName !== 'li' || !isList(item.parentElement)))\n return [];\n const parent = items[0].parentElement;\n if (items.some((item) => item.parentElement !== parent))\n return [];\n const siblings = [...parent!.children];\n if (siblings.indexOf(items.at(-1)!) - siblings.indexOf(items[0]) + 1 !== items.length)\n return [];\n return items as HTMLLIElement[];\n};\nconst depth = (root: HTMLElement, item: HTMLElement): number => {\n let result = 0; let parent: Element | null = item.parentElement; while (parent && parent !== root) {\n if (isList(parent))\n result++;\n parent = parent.parentElement;\n } return result;\n};\nconst numberedBoundary = (list: Element): boolean => list.localName === 'ol' && (list.hasAttribute('start') || list.hasAttribute('reversed'));\nconst compatible = (a: Element | null, b: Element): a is HTMLElement => !!a && a.localName === b.localName && isList(a)\n && !numberedBoundary(a) && !numberedBoundary(b) && a.getAttribute('dir') === b.getAttribute('dir')\n && a.getAttribute('style') === b.getAttribute('style');\nconst joinLists = (root: HTMLElement): void => {\n for (const list of [...root.querySelectorAll<HTMLElement>('ul,ol')]) {\n if (!root.contains(list))\n continue;\n const previous = list.previousSibling;\n if (previous instanceof Element && compatible(previous, list)) {\n previous.append(...list.childNodes);\n list.remove();\n }\n }\n};\nconst splitAround = (item: HTMLLIElement, replacement: Node[]): void => {\n const list = item.parentElement!;\n const tail = list.cloneNode(false) as HTMLElement;\n while (item.nextSibling)\n tail.append(item.nextSibling);\n item.remove();\n list.after(...replacement, ...(tail.childNodes.length ? [tail] : []));\n if (!list.childNodes.length)\n list.remove();\n};\nconst ownContent = (item: HTMLElement) => [...item.childNodes].filter((node) => !(node instanceof Element && isList(node)));\nconst unwrapRoot = (item: HTMLLIElement, paragraphOnly = false): void => {\n const paragraphNode = () => {\n const node = document.createElement('p');\n if (item.hasAttribute('style')) node.setAttribute('style', item.getAttribute('style')!);\n copyDirection(item, node);\n return node;\n };\n let paragraph = paragraphNode();\n const nested = [...item.children].filter(isList);\n const content = ownContent(item);\n // Imported items may contain paragraphs; retain their block structure rather than nest p in p.\n const output: Node[] = [];\n for (const node of content) {\n if (paragraphOnly && node instanceof HTMLElement && /^(p|h[1-6]|blockquote|pre)$/.test(node.localName)) {\n copyDirection(node, paragraph);\n paragraph.append(...node.childNodes);\n }\n else if (node instanceof HTMLElement && /^(p|h[1-6]|blockquote|pre)$/.test(node.localName)) {\n if (paragraph.childNodes.length)\n output.push(paragraph);\n paragraph = paragraphNode();\n if (/^(p|h[1-6])$/.test(node.localName) && !node.hasAttribute('dir')) copyDirection(item, node);\n output.push(node);\n }\n else\n paragraph.append(node);\n }\n if (paragraph.childNodes.length || !output.length) {\n if (!paragraph.childNodes.length)\n paragraph.append(document.createElement('br'));\n output.push(paragraph);\n }\n splitAround(item, [...output, ...nested]);\n};\nconst lift = (items: HTMLLIElement[]): void => {\n const list = items[0].parentElement!;\n const owner = list.parentElement;\n if (owner?.localName !== 'li' || !isList(owner.parentElement)) {\n for (const item of items)\n unwrapRoot(item);\n return;\n }\n const trailing = list.cloneNode(false) as HTMLElement;\n while (items.at(-1)!.nextSibling)\n trailing.append(items.at(-1)!.nextSibling!);\n if (trailing.childNodes.length)\n items.at(-1)!.append(trailing);\n owner.after(...items);\n if (!list.childNodes.length)\n list.remove();\n};\nexport const listState = (root: HTMLElement, range?: Range) => {\n const items = itemRange(root, range);\n const canIndent = !!items.length && items[0].previousElementSibling?.localName === 'li' && items.every((item) => [item, ...item.querySelectorAll<HTMLElement>('li')].every((child) => depth(root, child) < 8));\n return { listDepth: items.length ? depth(root, items[0]) : 0, canIndent, canOutdent: !!items.length };\n};\nexport const indentList = (root: HTMLElement, direction: unknown): void => {\n if (direction !== 1 && direction !== -1)\n throw new TypeError('List indentation requires 1 or -1.');\n const items = itemRange(root);\n if (!items.length)\n throw new RangeError('Select consecutive items in the same list.');\n if (direction === 1 && !listState(root).canIndent)\n return;\n preserveRange(root, () => {\n if (direction === -1)\n lift(items);\n else {\n const list = items[0].parentElement!;\n const previous = items[0].previousElementSibling!;\n let nested = previous.lastElementChild;\n if (!compatible(nested, list)) {\n nested = list.cloneNode(false) as HTMLElement;\n previous.append(nested);\n }\n nested!.append(...items);\n }\n joinLists(root);\n });\n};\nexport const applyList = (root: HTMLElement, value: unknown): void => {\n if (value !== false && value !== 'bullet' && value !== 'ordered')\n throw new TypeError('Expected bullet, ordered or false.');\n const selected = topItems(selectedBlocks(root));\n if (selected.some((block) => block.localName === 'li' && !isList(block.parentElement)))\n throw new RangeError('A list item must belong to a list.');\n preserveRange(root, () => {\n for (const block of selected) {\n if (!value) {\n if (block.localName === 'li')\n lift([block as HTMLLIElement]);\n continue;\n }\n const tag = value === 'bullet' ? 'ul' : 'ol';\n if (block.localName === 'li') {\n if (block.parentElement!.localName === tag)\n continue;\n const list = document.createElement(tag);\n if (block.parentElement!.hasAttribute('style'))\n list.setAttribute('style', block.parentElement!.getAttribute('style')!);\n copyDirection(block.parentElement!, list);\n const marker = list.style.getPropertyValue('list-style-type');\n if (marker && !normalizeListMarker(tag, marker)) {\n list.style.removeProperty('list-style-type');\n if (!list.style.length) list.removeAttribute('style');\n }\n splitAround(block as HTMLLIElement, [list]);\n list.append(block);\n }\n else {\n const list = document.createElement(tag);\n const item = document.createElement('li');\n if (block.hasAttribute('style'))\n item.setAttribute('style', block.getAttribute('style')!);\n copyDirection(block, item);\n item.append(...block.childNodes);\n list.append(item);\n block.replaceWith(list);\n }\n }\n joinLists(root);\n });\n};\nconst empty = (item: HTMLElement) => !item.textContent?.trim() && !item.querySelector('img,hr,ul,ol');\nconst placeholder = (item: HTMLElement): void => {\n const own = ownContent(item);\n const meaningful = own.some((node) => node.textContent || (node instanceof Element && (node.matches('br,img,hr') || node.querySelector('br,img,hr'))));\n if (!meaningful) {\n if ([...item.children].some(isList))\n item.prepend(Object.assign(document.createElement('p'), { innerHTML: '<br>' }));\n else\n item.append(document.createElement('br'));\n }\n};\nconst atStart = (item: HTMLElement, range: Range) => {\n const prefix = range.cloneRange();\n prefix.selectNodeContents(item);\n prefix.setEnd(range.startContainer, range.startOffset);\n return !prefix.toString() && !prefix.cloneContents().querySelector('img,hr,br');\n};\nexport const handlesListInput = (root: HTMLElement, inputType: string): boolean => {\n const range = activeRange(root);\n if (!range)\n return false;\n const item = blockAt(root, range.startContainer);\n if (item?.localName !== 'li' || !isList(item.parentElement) || blockAt(root, range.endContainer) !== item)\n return false;\n return ['insertParagraph', 'insertLineBreak'].includes(inputType) || (inputType === 'deleteContentBackward' && range.collapsed && atStart(item, range));\n};\nexport const editListInput = (root: HTMLElement, inputType: string, prepareSplit?: (item: HTMLLIElement) => void): void => {\n const range = activeRange(root)!;\n const item = blockAt(root, range.startContainer) as HTMLLIElement;\n if (inputType === 'insertParagraph') {\n if (empty(item)) {\n preserveRange(root, () => {\n const owner = item.parentElement!.parentElement; if (owner?.localName === 'li' && isList(owner.parentElement))\n lift([item]);\n else\n unwrapRoot(item, true);\n });\n joinLists(root);\n return;\n }\n range.deleteContents();\n const tail = range.cloneRange();\n tail.selectNodeContents(item);\n tail.setStart(range.startContainer, range.startOffset);\n const next = item.cloneNode(false) as HTMLLIElement;\n prepareSplit?.(next);\n next.append(tail.extractContents());\n item.after(next);\n placeholder(item);\n placeholder(next);\n const walker = document.createTreeWalker(next, NodeFilter.SHOW_TEXT);\n let first: Node | null;\n do {\n first = walker.nextNode();\n } while (first && (!first.textContent || first.parentElement?.closest('li') !== next));\n if (first) {\n const caret = document.createRange();\n caret.setStart(first, 0);\n caret.collapse(true);\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n }\n else\n placeCaret(next.querySelector<HTMLElement>('p,h1,h2,h3,h4,h5,h6,pre') ?? next);\n }\n else if (inputType === 'insertLineBreak') {\n range.deleteContents();\n const br = document.createElement('br');\n range.insertNode(br);\n if (!br.nextSibling)\n br.after(document.createElement('br'));\n range.setStartAfter(br);\n range.collapse(true);\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n }\n else {\n const previous = item.previousElementSibling as HTMLLIElement | null;\n if (previous && previous.localName !== 'li')\n return;\n if (!previous) {\n preserveRange(root, () => lift([item]));\n joinLists(root);\n return;\n }\n if (!ownContent(previous).some((node) => node.textContent || (node instanceof Element && (node.localName === 'img' || node.querySelector('img'))))) {\n for (const br of [...previous.querySelectorAll('br')])\n if (br.closest('li') === previous)\n br.remove();\n }\n const marker = document.createComment('mw-join');\n const previousContent = ownContent(previous);\n const last = previousContent.at(-1);\n const target = last instanceof HTMLElement && /^(p|h[1-6]|blockquote|pre)$/.test(last.localName) ? last : previous;\n if (target === previous)\n previous.insertBefore(marker, [...previous.children].find(isList) ?? null);\n else\n target.append(marker);\n const content = ownContent(item);\n if (content[0] instanceof HTMLElement && /^(p|h[1-6])$/.test(content[0].localName))\n content.splice(0, 1, ...content[0].childNodes);\n marker.after(...content);\n for (const nested of [...item.children].filter(isList))\n previous.append(nested);\n item.remove();\n joinLists(root);\n const caret = document.createRange();\n caret.setStartBefore(marker);\n caret.collapse(true);\n marker.remove();\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n }\n};\n", "import type { LinkFormat, Attributes, Operation, Piece } from './inline-attributes.types.js';\nexport type { LinkFormat } from './inline-attributes.types.js';\nimport { validateDocument } from '../document/index.js';\nimport { normalizeFontFamily } from '../document/font-family.js';\nimport type { DocumentNode, EditorDocument, ElementNode } from '../document/index.js';\nexport const inlineStyles: Record<string, string> = { color: 'color', background: 'background-color', fontFamily: 'font-family', fontSize: 'font-size' };\nconst blocks = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'caption', 'colgroup', 'figure', 'figcaption']);\nconst checkedAttributes = (tag: 'span' | 'a', attributes: Attributes): Attributes => (validateDocument({ version: 1, children: [{ type: 'element', tag, attributes, children: [] }] }).children[0] as ElementNode).attributes;\nexport const normalizeInlineStyle = (name: string, value: unknown): string | false => {\n if (value === false)\n return false;\n if (name === 'fontFamily') {\n const family = typeof value === 'string' ? normalizeFontFamily(value) : undefined;\n if (!family) throw new TypeError('Expected a supported font family or false.');\n return family;\n }\n if (typeof value !== 'string' || !value.trim() || value.length > 128 || /[;{}]/.test(value))\n throw new TypeError('Expected a supported CSS inline style or false.');\n const property = inlineStyles[name];\n const attrs = checkedAttributes('span', { style: `${property}: ${value}` });\n const probe = document.createElement('span');\n probe.setAttribute('style', attrs.style ?? '');\n const normalized = probe.style.getPropertyValue(property);\n if (!normalized)\n throw new TypeError('Unsupported or invalid CSS inline style.');\n return normalized;\n};\nexport const normalizeLink = (value: unknown): {\n attributes: Attributes;\n text?: string;\n} | false => {\n if (value === false)\n return false;\n const input = typeof value === 'string' ? { href: value } : value;\n if (!input || typeof input !== 'object' || Array.isArray(input) || !('href' in input) || typeof input.href !== 'string')\n throw new TypeError('Expected a link URL, LinkFormat or false.');\n const link = input as Record<string, unknown>;\n const attributes: Attributes = { href: input.href };\n if (link.title !== undefined) {\n if (typeof link.title !== 'string' || link.title.length > 1024)\n throw new TypeError('Link title must be a string up to 1024 characters.');\n attributes.title = link.title;\n }\n if (link.target !== undefined) {\n if (link.target !== '_self' && link.target !== '_blank')\n throw new TypeError('Link target must be _self or _blank.');\n attributes.target = link.target;\n }\n if (link.text !== undefined && (typeof link.text !== 'string' || !link.text.length || link.text.length > 20000))\n throw new TypeError('New link text must contain 1\u201320000 characters.');\n const clean = checkedAttributes('a', attributes);\n if (!clean.href)\n throw new TypeError('Unsupported or unsafe link URL.');\n return { attributes: clean, ...(typeof link.text === 'string' ? { text: link.text } : {}) };\n};\nexport const mergeLinkAttributes = (previous: Attributes, patch: Attributes): Attributes => {\n const attrs = { ...previous, ...patch };\n if (!attrs.title)\n delete attrs.title;\n if (patch.target === '_self')\n delete attrs.rel;\n return checkedAttributes('a', attrs);\n};\nconst equalAttributes = (a?: Attributes, b?: Attributes) => JSON.stringify(Object.entries(a ?? {}).sort()) === JSON.stringify(Object.entries(b ?? {}).sort());\nconst withoutProperty = (attributes: Attributes, property: string): Attributes => {\n const attrs = { ...attributes };\n const style = (attrs.style ?? '').split(';').map((part) => part.trim()).filter((part) => part && part.slice(0, part.indexOf(':')).trim() !== property).join('; ');\n if (style)\n attrs.style = style;\n else\n delete attrs.style;\n return attrs;\n};\nconst groupPieces = (pieces: Piece[]): {\n pieces: Piece[];\n selected: boolean;\n link?: Attributes;\n}[] => {\n const result: {\n pieces: Piece[];\n selected: boolean;\n link?: Attributes;\n }[] = [];\n for (const piece of pieces) {\n const last = result.at(-1);\n if (last && last.selected === piece.selected && equalAttributes(last.link, piece.link))\n last.pieces.push(piece);\n else\n result.push({ pieces: [piece], selected: piece.selected, link: piece.link });\n }\n return result;\n};\nconst compact = (nodes: DocumentNode[]): DocumentNode[] => {\n const result: DocumentNode[] = [];\n for (const node of nodes) {\n const next = node.type === 'element' ? { ...node, children: compact(node.children) } : node;\n const previous = result.at(-1);\n if (next.type === 'text' && previous?.type === 'text')\n previous.text += next.text;\n else if (next.type === 'element' && previous?.type === 'element' && !blocks.has(next.tag) && !next.attributes['data-mw-node'] && !['img', 'br', 'hr'].includes(next.tag) && previous.tag === next.tag && equalAttributes(previous.attributes, next.attributes))\n previous.children = compact([...previous.children, ...next.children]);\n else\n result.push(next);\n }\n return result;\n};\nexport const transformInlineAttributes = (document: EditorDocument, from: number, to: number, operation: Operation): EditorDocument => {\n let position = 0;\n const wrap = (pieces: Piece[]): DocumentNode[] => groupPieces(pieces).flatMap((group) => {\n const children = group.pieces.map((piece) => piece.node);\n if (operation.kind === 'style')\n return group.selected && operation.value !== false ? [{ type: 'element', tag: 'span', attributes: { style: `${operation.property}: ${operation.value}` }, children } as ElementNode] : children;\n const attrs = group.selected ? operation.attributes === false ? undefined : mergeLinkAttributes(group.link ?? {}, operation.attributes) : group.link;\n return attrs ? [{ type: 'element', tag: 'a', attributes: attrs, children } as ElementNode] : children;\n });\n const visit = (node: DocumentNode, inheritedLink?: Attributes): Piece[] => {\n if (node.type === 'text') {\n const start = position;\n position += node.text.length;\n const left = Math.max(0, Math.min(node.text.length, from - start));\n const right = Math.max(left, Math.min(node.text.length, to - start));\n return [[0, left, false], [left, right, true], [right, node.text.length, false]].flatMap(([begin, end, selected]) => {\n const text = node.text.slice(begin as number, end as number);\n return text ? [{ node: { type: 'text', text } as DocumentNode, selected: Boolean(selected), link: inheritedLink }] : [];\n });\n }\n const link = operation.kind === 'link' && node.tag === 'a' ? node.attributes : inheritedLink;\n if (!node.children.length)\n return [{ node, selected: position >= from && position < to, link }];\n const children = node.children.flatMap((child) => visit(child, link));\n if (operation.kind === 'link' && node.tag === 'a')\n return children;\n if (blocks.has(node.tag) || node.attributes['data-mw-node'])\n return [{ node: { ...node, children: wrap(children) }, selected: false }];\n return groupPieces(children).flatMap<Piece>((group) => {\n const attrs = operation.kind === 'style' && group.selected ? withoutProperty(node.attributes, operation.property) : node.attributes;\n const content = group.pieces.map((piece) => piece.node);\n if (node.tag === 'span' && !Object.keys(attrs).length)\n return group.pieces;\n return [{ node: { ...node, attributes: attrs, children: content }, selected: group.selected, link: group.link }];\n });\n };\n return { version: 1, children: compact(wrap(document.children.flatMap((node) => visit(node)))) };\n};\n", "import type { DocumentSchema } from '../schema/types.js';\nimport { documentHTML, parseHTML } from '../document/index.js';\nimport { normalizeLink, mergeLinkAttributes, transformInlineAttributes } from './inline-attributes.js';\nimport { activeRange, readTextSelection, selectText, preserveRange } from '../selection/index.js';\nexport const applyLink = (root: HTMLElement, value: unknown, schema?: DocumentSchema): void => {\n const link = normalizeLink(value);\n const range = activeRange(root);\n if (!range)\n return;\n const selection = readTextSelection(root)!;\n const element = range.startContainer.nodeType === 1 ? range.startContainer as Element : range.startContainer.parentElement;\n const anchor = element?.closest('a');\n const existing = anchor && root.contains(anchor) ? anchor : undefined;\n if (link && link.text !== undefined && (!range.collapsed || existing))\n throw new TypeError('Link text is only supported for insertion at a caret outside links.');\n if (!range.collapsed) {\n root.innerHTML = (schema?.documentHTML ?? documentHTML)(transformInlineAttributes((schema?.parseHTML ?? parseHTML)(root.innerHTML), selection.index, selection.index + selection.length, { kind: 'link', attributes: link && link.attributes }));\n selectText(root, selection.index, selection.length);\n return;\n }\n if (existing) {\n const attrs = link && mergeLinkAttributes(Object.fromEntries([...existing.attributes].map((attr) => [attr.name, attr.value])), link.attributes);\n preserveRange(root, () => {\n if (!attrs)\n existing.replaceWith(...existing.childNodes);\n else {\n for (const attr of [...existing.attributes])\n existing.removeAttribute(attr.name);\n for (const [key, val] of Object.entries(attrs))\n existing.setAttribute(key, val);\n }\n });\n return;\n }\n if (!link || link.text === undefined)\n return;\n const created = root.ownerDocument.createElement('a');\n for (const [key, val] of Object.entries(link.attributes))\n created.setAttribute(key, val);\n created.textContent = link.text;\n const parent = element?.closest('p,li,h1,h2,h3,h4,h5,h6,blockquote,pre,td,th');\n if (parent?.childNodes.length === 1 && parent.firstChild instanceof HTMLBRElement) {\n parent.firstChild.remove();\n range.setStart(parent, 0);\n }\n range.insertNode(created);\n const tail = root.ownerDocument.createTextNode('');\n created.after(tail);\n range.setStart(tail, 0);\n range.collapse(true);\n const native = root.ownerDocument.getSelection();\n native?.removeAllRanges();\n native?.addRange(range);\n};\n", "import type { DocumentNode, DocumentTag, EditorDocument, ElementNode } from '../document/index.js';\nimport type { InlineGroup, Piece } from './types.js';\n\nconst blockTags = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'caption', 'colgroup', 'figure', 'figcaption']);\n\nconst textLength = (node: DocumentNode): number => node.type === 'text'\n ? node.text.length\n : node.children.reduce((length, child) => length + textLength(child), 0);\n\nexport const inlineDocument = (value: EditorDocument, from: number, to: number, tag: DocumentTag, enabled: boolean): EditorDocument => {\n let position = 0;\n const visit = (node: DocumentNode): Piece[] => {\n if (node.type === 'text') {\n const start = position;\n position += node.text.length;\n const left = Math.max(0, Math.min(node.text.length, from - start));\n const right = Math.max(left, Math.min(node.text.length, to - start));\n return [[0, left, false], [left, right, true], [right, node.text.length, false]].flatMap(([begin, end, selected]) => {\n const text = node.text.slice(begin as number, end as number);\n if (!text)\n return [];\n const leaf: DocumentNode = { type: 'text', text };\n return [{ node: selected && enabled ? { type: 'element', tag, attributes: {}, children: [leaf] } as ElementNode : leaf, selected: Boolean(selected) }];\n });\n }\n // Descendants already inherit this mark. Keep their validated wrapper shape unchanged.\n if (enabled && node.tag === tag) {\n position += textLength(node);\n return [{ node, selected: false }];\n }\n const children = node.children.flatMap(visit);\n if (blockTags.has(node.tag) || node.attributes['data-mw-node'])\n return [{ node: { ...node, children: children.map((piece) => piece.node) }, selected: false }];\n if (!children.length)\n return [{ node, selected: false }];\n const groups: InlineGroup[] = [];\n for (const piece of children) {\n const last = groups.at(-1);\n if (last?.selected === piece.selected)\n last.children.push(piece.node);\n else\n groups.push({ selected: piece.selected, children: [piece.node] });\n }\n return groups.flatMap<Piece>((group) => node.tag === tag && !enabled && group.selected\n ? group.children.map((child) => ({ node: child, selected: true }))\n : [{ node: { ...node, children: group.children }, selected: group.selected }]);\n };\n return { version: 1, children: value.children.flatMap(visit).map((piece) => piece.node) };\n};\n", "import type { DocumentSchema } from '../schema/types.js';\nimport type { DocumentTag } from '../document/index.js';\nimport { parseHTML, renderDocument } from '../document/index.js';\nimport { selectText } from '../selection/index.js';\nimport { inlineDocument } from './inline-document.js';\n\nconst leaves = 'p,h1,h2,h3,h4,h5,h6';\nconst inlineTags = new Set(['strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'code']);\nconst structuralAncestors = new Set(['blockquote', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th']);\nconst elementAt = (node: Node): Element | null => node.nodeType === 1 ? node as Element : node.parentElement;\nconst isInlineTree = (parent: Element): boolean => {\n for (const node of parent.childNodes) {\n if (node.nodeType === 3) continue;\n if (node.nodeType !== 1) return false;\n const element = node as Element;\n if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !inlineTags.has(element.localName) || !isInlineTree(element)) return false;\n }\n return true;\n};\n\n/** Transform one schema-validated leaf while keeping unrelated editor DOM connected. */\nexport const applyLocalInline = (root: HTMLElement, range: Range, tag: DocumentTag, enabled: boolean, schema?: DocumentSchema): boolean => {\n const block = elementAt(range.startContainer)?.closest<HTMLElement>(leaves);\n if (!block || !root.contains(block) || block.namespaceURI !== 'http://www.w3.org/1999/xhtml') return false;\n if (elementAt(range.endContainer)?.closest(leaves) !== block || !isInlineTree(block)) return false;\n for (let parent = block.parentElement; parent && parent !== root; parent = parent.parentElement) {\n if (parent.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !structuralAncestors.has(parent.localName)) return false;\n }\n\n const prefix = root.ownerDocument.createRange();\n prefix.selectNodeContents(block);\n prefix.setEnd(range.startContainer, range.startOffset);\n const from = prefix.toString().length;\n const length = range.toString().length;\n if (!length || from + length > (block.textContent?.length ?? 0)) return false;\n const native = root.ownerDocument.getSelection();\n const backward = native?.anchorNode === range.endContainer && native.anchorOffset === range.endOffset;\n const content = inlineDocument((schema?.parseHTML ?? parseHTML)(block.outerHTML), from, from + length, tag, enabled);\n const fragment = (schema?.renderDocument ?? renderDocument)(content);\n const replacement = fragment.firstElementChild;\n if (fragment.childNodes.length !== 1 || !(replacement instanceof HTMLElement) || replacement.localName !== block.localName) return false;\n\n // HTML history replay merges adjacent text nodes; capture the same local node shape.\n replacement.normalize();\n if (replacement.outerHTML === block.outerHTML) return true;\n\n block.replaceWith(fragment);\n selectText(replacement, from, length);\n root.focus({ preventScroll: true });\n if (backward && native?.rangeCount) {\n const selected = native.getRangeAt(0);\n native.setBaseAndExtent(selected.endContainer, selected.endOffset, selected.startContainer, selected.startOffset);\n }\n return true;\n};\n", "import type { DocumentSchema } from '../schema/types.js';\nimport type { DocumentTag } from '../document/index.js';\nimport { documentHTML, parseHTML } from '../document/index.js';\nimport { normalizeFontFamily } from '../document/font-family.js';\nimport { copyDirection } from '../document/direction.js';\nimport { activeRange, readTextSelection, selectText, preserveRange } from '../selection/index.js';\nimport { inlineStyles, normalizeInlineStyle, transformInlineAttributes } from './inline-attributes.js';\nimport { applyLink } from './links.js';\nimport { inlineDocument } from './inline-document.js';\nimport { applyLocalInline } from './local-inline.js';\nimport { applyList, indentList, listState, selectedBlocks } from '../lists/index.js';\nexport const inlineFormats: Record<string, DocumentTag> = { bold: 'strong', italic: 'em', underline: 'u', strike: 's', code: 'code', subscript: 'sub', superscript: 'sup' };\n\nconst closestElement = (node: Node): Element | null => { return node.nodeType === 1 ? node as Element : node.parentElement; };\nconst formatsAt = (root: HTMLElement, node: Node): Record<string, unknown> => {\n let element = closestElement(node);\n const formats: Record<string, unknown> = {};\n while (element && element !== root) {\n for (const [name, tag] of Object.entries(inlineFormats))\n if (element.localName === tag)\n formats[name] = true;\n if (/^h[1-6]$/.test(element.localName) && formats.header === undefined)\n formats.header = Number(element.localName[1]);\n if (element.localName === 'blockquote')\n formats.blockquote = true;\n if (element.localName === 'pre')\n formats['code-block'] = true;\n if ((element.localName === 'ul' || element.localName === 'ol') && formats.list === undefined)\n formats.list = element.localName === 'ul' ? 'bullet' : 'ordered';\n if (element.localName === 'a' && formats.link === undefined) {\n formats.link = element.getAttribute('href');\n formats.linkTitle = element.getAttribute('title') ?? '';\n formats.linkTarget = element.getAttribute('target') ?? '_self';\n }\n if (element instanceof HTMLElement)\n for (const [name, property] of Object.entries(inlineStyles)) {\n const value = element.style.getPropertyValue(property);\n if (formats[name] === undefined && value)\n formats[name] = name === 'fontFamily' ? normalizeFontFamily(value) ?? value : value;\n }\n if (element instanceof HTMLElement && element.style.textAlign && formats.align === undefined)\n formats.align = element.style.textAlign;\n element = element.parentElement;\n }\n return formats;\n};\nexport const readFormats = (root: HTMLElement, projection?: Range): Record<string, unknown> => {\n let range: Range | undefined;\n if (projection === undefined) range = activeRange(root);\n else {\n try { range = root.ownerDocument.defaultView!.Range.prototype.cloneRange.call(projection); }\n catch { throw new TypeError('Expected a native Range for format projection.'); }\n if (!root.contains(range.startContainer) || !root.contains(range.endContainer)) return {};\n }\n if (!range)\n return {};\n let formats = formatsAt(root, range.startContainer);\n const mixed = new Set<string>();\n if (!range.collapsed) {\n const prefix = root.ownerDocument.createRange();\n prefix.selectNodeContents(root);\n prefix.setEnd(range.startContainer, range.startOffset);\n const index = prefix.toString().length;\n const length = range.toString().length;\n const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT);\n let position = 0;\n let node: Node | null;\n const samples: Record<string, unknown>[] = [];\n while ((node = walker.nextNode())) {\n const end = position + node.textContent!.length;\n if (end > index && position < index + length)\n samples.push(formatsAt(root, node));\n position = end;\n }\n if (samples.length)\n formats = samples[0];\n const keys = [...Object.keys(inlineFormats), ...Object.keys(inlineStyles), 'header', 'list', 'blockquote', 'code-block', 'link', 'linkTitle', 'linkTarget', 'align'];\n const normalized = (sample: Record<string, unknown>, key: string) => sample[key] ?? (key === 'align' ? 'left' : key === 'header' ? 0 : false);\n for (const key of keys)\n if (samples.some((sample) => normalized(sample, key) !== normalized(samples[0], key)))\n mixed.add(key);\n }\n return { ...formats, align: formats.align ?? 'left', mixed: [...mixed], ...listState(root, range) };\n};\nexport const applyFormat = (root: HTMLElement, name: string, value: unknown, schema?: DocumentSchema): void => {\n const range = activeRange(root);\n if (!range)\n return;\n const tag = inlineFormats[name];\n if (tag && !range.collapsed && applyLocalInline(root, range, tag, Boolean(value), schema))\n return;\n const selection = readTextSelection(root)!;\n if (name === 'list') {\n applyList(root, value);\n return;\n }\n if (name === 'indent') {\n indentList(root, value);\n return;\n }\n if (name === 'clear') {\n if (value !== true || !selection.length)\n return;\n let content = (schema?.parseHTML ?? parseHTML)(root.innerHTML);\n for (const tag of [...Object.values(inlineFormats), 'a', 'span'] as DocumentTag[])\n content = inlineDocument(content, selection.index, selection.index + selection.length, tag, false);\n root.innerHTML = (schema?.documentHTML ?? documentHTML)(content);\n selectText(root, selection.index, selection.length);\n return;\n }\n if (tag) {\n if (range.collapsed)\n return;\n root.innerHTML = (schema?.documentHTML ?? documentHTML)(inlineDocument((schema?.parseHTML ?? parseHTML)(root.innerHTML), selection.index, selection.index + selection.length, tag, Boolean(value)));\n selectText(root, selection.index, selection.length);\n return;\n }\n if (name === 'link') {\n applyLink(root, value, schema);\n return;\n }\n if (Object.hasOwn(inlineStyles, name)) {\n const style = normalizeInlineStyle(name, value);\n if (!selection.length)\n return;\n root.innerHTML = (schema?.documentHTML ?? documentHTML)(transformInlineAttributes((schema?.parseHTML ?? parseHTML)(root.innerHTML), selection.index, selection.index + selection.length, { kind: 'style', property: inlineStyles[name], value: style }));\n selectText(root, selection.index, selection.length);\n return;\n }\n let blocks = selectedBlocks(root, range, false);\n if (!blocks.length) {\n const paragraph = document.createElement('p');\n paragraph.append(range.extractContents());\n if (!paragraph.childNodes.length)\n paragraph.append(document.createElement('br'));\n range.insertNode(paragraph);\n blocks = [paragraph];\n }\n preserveRange(root, () => {\n for (const block of blocks) {\n if (name === 'align' && ['left', 'center', 'right', 'justify', false].includes(value as string | false)) {\n block.style.textAlign = value ? String(value) : '';\n continue;\n }\n const nextTag = name === 'header' ? (Number.isInteger(value) && Number(value) >= 1 && Number(value) <= 6 ? `h${value}` : 'p')\n : name === 'blockquote' ? (value ? 'blockquote' : 'p')\n : name === 'code-block' ? (value ? 'pre' : 'p') : undefined;\n if (nextTag) {\n if (block.hasAttribute('data-mw-node') && block.localName !== nextTag)\n throw new RangeError('Cannot change the tag of a registered semantic node.');\n const replacement = document.createElement(nextTag);\n if (block.localName === 'li') {\n const content = [...block.childNodes].filter((node) => !(node instanceof Element && /^(ul|ol|p|h[1-6]|pre|blockquote)$/.test(node.localName)));\n replacement.append(...content);\n block.prepend(replacement);\n }\n else {\n replacement.append(...block.childNodes);\n replacement.setAttribute('style', block.getAttribute('style') ?? '');\n copyDirection(block, replacement);\n block.replaceWith(replacement);\n }\n }\n }\n });\n};\n", "import type { EditorEventMap, EditorEvents, EventHub, PluginEvent, QueuedEvent, EditorInputCommit } from './types.js';\nexport type { EditorEventMap, EditorEvents, PluginEvent, EditorInputCommit } from './types.js';\nconst tokens = new WeakSet<object>();\nconst coreNames = new Set(['change', 'selectionchange', 'readonlychange', 'localechange', 'inputcommit', 'destroy']);\nexport const createPluginEvent = <T>(name: string): PluginEvent<T> => {\n if (typeof name !== 'string' || !name.trim() || name.length > 200) {\n throw new TypeError('Expected an event name with 1\u2013200 characters.');\n }\n const token = Object.freeze({ name }) as PluginEvent<T>;\n tokens.add(token);\n return token;\n};\nconst assertToken = (event: unknown): object => {\n if (!event || typeof event !== 'object' || !tokens.has(event)) {\n throw new TypeError('Expected a plugin event token. Core events cannot be emitted publicly.');\n }\n return event;\n};\nconst corePayload = (key: string | object, payload: unknown): unknown => {\n if (!payload || typeof payload !== 'object') return payload;\n if (key === 'localechange') {\n const locale = payload as EditorEventMap['localechange'];\n return { ...locale, translations: { ...locale.translations } };\n }\n if (key === 'inputcommit') {\n const receipt = payload as EditorInputCommit;\n const saved = receipt.selection;\n return { ...receipt, selection: saved ? { ...saved, start: [...saved.start], end: [...saved.end] } : undefined };\n }\n return { ...payload };\n};\nexport const createEventHub = (): EventHub => {\n const listeners = new Map<string | object, Map<(payload: unknown) => void, number>>();\n const queue: QueuedEvent[] = [];\n let registration = 0;\n let dispatching = false;\n let closing = false;\n const enqueue = (entry: QueuedEvent) => {\n if (closing && entry.key !== 'destroy')\n return;\n queue.push(entry);\n if (dispatching)\n return;\n dispatching = true;\n const failures: unknown[] = [];\n try {\n while (queue.length) {\n const next = queue.shift()!;\n if (closing && next.key !== 'destroy')\n continue;\n const bucket = listeners.get(next.key);\n for (const [listener, registered] of [...(bucket ?? [])]) {\n if ((closing && next.key !== 'destroy') || bucket?.get(listener) !== registered)\n continue;\n try {\n const payload = next.core ? corePayload(next.key, next.payload) : next.payload;\n listener(payload);\n }\n catch (error) {\n failures.push(error);\n }\n }\n if (next.key === 'destroy') {\n listeners.clear();\n queue.length = 0;\n }\n }\n }\n finally {\n dispatching = false;\n }\n if (failures.length)\n throw new AggregateError(failures, 'Editor event listeners failed.');\n };\n const on = (event: keyof EditorEventMap | PluginEvent<unknown>, listener: (payload: unknown) => void): (() => void) => {\n if (closing)\n throw new Error('Editor events have been destroyed.');\n if (typeof listener !== 'function')\n throw new TypeError('Expected an event listener.');\n const key = typeof event === 'string' && coreNames.has(event) ? event : assertToken(event);\n let bucket = listeners.get(key);\n if (!bucket) {\n bucket = new Map();\n listeners.set(key, bucket);\n }\n if (!bucket.has(listener))\n bucket.set(listener, ++registration);\n const registered = bucket.get(listener);\n return () => {\n if (bucket!.get(listener) !== registered)\n return;\n bucket!.delete(listener);\n if (!bucket!.size && listeners.get(key) === bucket)\n listeners.delete(key);\n };\n };\n const events: EditorEvents = {\n on: on as EditorEvents['on'],\n emit: (event, payload) => {\n if (closing)\n throw new Error('Editor events have been destroyed.');\n enqueue({ key: assertToken(event), payload, core: false });\n },\n };\n return {\n events,\n notify: (event, payload) => enqueue({ key: event, payload, core: true }),\n destroy: () => {\n if (closing)\n return;\n closing = true;\n queue.length = 0;\n enqueue({ key: 'destroy', payload: undefined, core: true });\n },\n };\n};\n", "import { sanitizeHTML } from '../document/index.js';\n\n/** Reuse only a successfully validated string for the exact current serialized DOM. */\nexport const createHTMLSnapshots = (surface: HTMLElement, sanitize = sanitizeHTML) => {\n let previousInput: string | undefined;\n let previousHTML = '';\n\n const read = (): string => {\n const input = surface.innerHTML;\n if (input === previousInput)\n return previousHTML;\n\n // Keep the last successful pair intact when validation rejects a new input.\n const html = sanitize(input);\n previousInput = input;\n previousHTML = html;\n return html;\n };\n\n const clear = (): void => {\n previousInput = undefined;\n previousHTML = '';\n };\n\n return { read, clear };\n};\n", "import type { EditorLocale, EditorTranslations, LocaleDictionaries } from './types.js';\n\nexport type { EditorLocale, EditorTranslations, LocaleDictionaries, EditorTranslationKey } from './types.js';\nexport { editorMessages } from './messages.js';\n\n/** Copy and validate before changing UI state or mounting DOM. */\nexport const createLocale = (locale: string, translations: EditorTranslations = {}): EditorLocale => {\n if (typeof locale !== 'string' || !locale || locale.length > 100)\n throw new TypeError('Expected a language tag with 1\u2013100 characters.');\n const canonical = Intl.getCanonicalLocales(locale)[0];\n if (!canonical)\n throw new RangeError('Expected a valid language tag.');\n if (!translations || typeof translations !== 'object' || Array.isArray(translations))\n throw new TypeError('Translations must be a record of strings.');\n const prototype = Object.getPrototypeOf(translations);\n if (prototype !== Object.prototype && prototype !== null)\n throw new TypeError('Translations must be a plain record of strings.');\n const entries = Object.entries(translations);\n if (entries.some(([key, value]) => !key || typeof value !== 'string'))\n throw new TypeError('Translation keys must be nonempty and values must be strings.');\n return { locale: canonical, translations: Object.fromEntries(entries) };\n};\n\n/** Resolve feature-owned copy without pulling optional feature dictionaries into core. */\nexport const localize = (state: EditorLocale, key: string, dictionaries: LocaleDictionaries): string => {\n const override = Object.hasOwn(state.translations, key) ? state.translations[key] : undefined;\n const exact = Object.hasOwn(dictionaries, state.locale) ? dictionaries[state.locale] : undefined;\n const base = state.locale.split('-')[0];\n const language = Object.hasOwn(dictionaries, base) ? dictionaries[base] : undefined;\n const message = (dictionary: EditorTranslations | undefined) => dictionary && Object.hasOwn(dictionary, key) ? dictionary[key] : undefined;\n const value = override ?? message(exact) ?? message(language) ?? message(dictionaries.en);\n if (typeof value !== 'string')\n throw new Error(`Missing English fallback for translation: ${key}`);\n return value;\n};\n", "import { createDocumentSchema } from '../schema/index.js';\nimport { createCommandRegistry } from '../commands/index.js';\nimport { activeRange, bookmark, placeCaret, rangeFromBookmark, readTextSelection, restoreBookmark, selectText } from '../selection/index.js';\nimport type { SelectionBookmark } from '../selection/index.js';\nimport {\n editListInput, handlesListInput, indentList, listState, selectedBlocks,\n listSelectionReplacement, prepareListSelectionPaste, replaceListSelection,\n replaceListSelectionWithFragment, handlesListForwardDelete, editListForwardDelete,\n handlesCollapsedListBlockPaste,\n inspectWrappedListInput, editWrappedListInput,\n} from '../lists/index.js';\nimport { editBlockInput, handlesBlockInput, handlesSelectionReplacement, replaceSelection, prepareSelectionPaste, replaceSelectionWithFragment } from '../input/index.js';\nimport { applyFormat, inlineFormats, readFormats } from '../formatting/index.js';\nimport { inlineStyles, normalizeInlineStyle } from '../formatting/inline-attributes.js';\nimport { createEventHub } from '../events/index.js';\nimport type { EditorEvents, EditorInputCommit } from '../events/types.js';\nimport type { Editor, EditorChange, EditorOptions, Snapshot } from './types.js';\nimport type { InputCommitOrigin } from './internal-types.js';\nimport { createHTMLSnapshots } from './html-snapshots.js';\nimport { createLocale, editorMessages, localize } from '../localization/index.js';\nconst paragraphOrigin = (event: Event, inputType: string): InputCommitOrigin | undefined => event.cancelable && inputType === 'insertParagraph' ? { inputType, sourceEvent: event } : undefined;\nconst isCompositionInput = (event: InputEvent): boolean => event.isComposing || event.inputType === 'insertCompositionText' || event.inputType === 'insertFromComposition' || event.inputType === 'deleteCompositionText';\nconst ensureDocument = (root: HTMLElement): boolean => {\n let normalized = false;\n if (!root.childNodes.length) {\n root.innerHTML = '<p><br></p>';\n normalized = true;\n }\n // Native input can create loose inline nodes; wrap them in paragraphs without replacing text nodes.\n let paragraph: HTMLParagraphElement | undefined;\n for (const node of [...root.childNodes]) {\n const inline = node.nodeType === 3 || (node.nodeType === 1 && /^(strong|em|u|s|a|span|code|img|br|sub|sup)$/.test((node as Element).localName));\n if (inline) {\n if (!paragraph) {\n paragraph = document.createElement('p');\n root.insertBefore(paragraph, node);\n }\n paragraph.append(node);\n normalized = true;\n }\n else\n paragraph = undefined;\n }\n if (['table', 'figure'].includes(root.lastElementChild?.localName ?? ''))\n root.append(Object.assign(document.createElement('p'), { innerHTML: '<br>' }));\n root.dataset.empty = String(!root.textContent && !root.querySelector('table,img,hr'));\n return normalized;\n};\nconst insertFragment = (root: HTMLElement, fragment: DocumentFragment): void => {\n const range = activeRange(root);\n if (!range)\n return;\n if (!fragment.childNodes.length)\n return;\n if (replaceSelectionWithFragment(root, fragment)) return;\n if (replaceListSelectionWithFragment(root, fragment)) return;\n range.deleteContents();\n const startElement = range.startContainer.nodeType === 1 ? range.startContainer as Element : range.startContainer.parentElement;\n const block = startElement?.closest('p,h1,h2,h3,h4,h5,h6,li,blockquote,pre');\n if (fragment.childNodes.length === 1 && fragment.firstChild instanceof HTMLParagraphElement && block) {\n const paragraph = fragment.firstChild;\n fragment.replaceChildren(...paragraph.childNodes);\n }\n const hasBlocks = [...fragment.childNodes].some((node) => node instanceof HTMLElement && /^(p|h[1-6]|ul|ol|table|figure|blockquote|pre)$/.test(node.localName));\n const last = fragment.lastChild!;\n if (hasBlocks && block && root.contains(block)) {\n const tailRange = document.createRange();\n tailRange.selectNodeContents(block);\n tailRange.setStart(range.startContainer, range.startOffset);\n const tail = block.cloneNode(false) as HTMLElement;\n tail.append(tailRange.extractContents());\n block.after(fragment);\n if (tail.textContent || tail.querySelector('img,br'))\n last.after(tail);\n if (!block.textContent && !block.querySelector('img'))\n block.remove();\n }\n else\n range.insertNode(fragment);\n const next = document.createRange();\n next.setStartAfter(last);\n next.collapse(true);\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(next);\n // Capture a stable text boundary before history serializes adjacent/empty Text nodes.\n if (!hasBlocks && block && root.contains(block)) block.normalize();\n};\nexport const createEditor = (host: HTMLElement, options: EditorOptions = {}): Editor => {\n if (host.childNodes.length)\n throw new Error('Editor host must be empty. Pass initial HTML through value.');\n const plugins = options.plugins ?? [];\n if (new Set(plugins.map((plugin) => plugin.name)).size !== plugins.length)\n throw new Error('Duplicate editor plugin.');\n const limit = options.historyLimit ?? 100;\n if (!Number.isInteger(limit) || limit < 1 || limit > 10000)\n throw new RangeError('historyLimit must be an integer from 1 to 10000.');\n const schema = createDocumentSchema([...(options.schema ?? []), ...plugins.flatMap((plugin) => plugin.schema ?? [])]);\n const prepareListSplit = (item: HTMLLIElement): void => {\n const attributes = Object.fromEntries([...item.attributes].map(({ name, value }) => [name, value]));\n for (const [name, value] of Object.entries(schema.attributesForSplit('li', attributes))) item.setAttribute(name, value);\n };\n const initialDocument = schema.parseHTML(options.value ?? '');\n let locale = createLocale(options.locale ?? 'ru', options.translations);\n const container = document.createElement('div');\n container.className = 'mw-editor';\n const surface = document.createElement('div');\n surface.className = 'mw-content';\n surface.setAttribute('role', 'textbox');\n surface.setAttribute('aria-multiline', 'true');\n const updateLocale = () => {\n surface.setAttribute('aria-label', options.label ?? localize(locale, 'editor.label', editorMessages));\n surface.dataset.placeholder = options.placeholder ?? localize(locale, 'editor.placeholder', editorMessages);\n };\n updateLocale();\n container.append(surface);\n host.append(container);\n surface.append(schema.renderDocument(initialDocument));\n ensureDocument(surface);\n let destroyed = false;\n let readOnly = options.readOnly ?? false;\n let composing = false;\n let compositionStart: Snapshot | undefined;\n let canceledComposition = false;\n let compositionTail: Snapshot | undefined;\n let compositionUndoRecorded = false;\n let pendingInput: Snapshot | undefined;\n let lastInputTime = 0;\n let lastInputType = '';\n let typingOverrides: Record<string, string | boolean> = {};\n let typingOffset: number | undefined;\n const clearTyping = () => { typingOverrides = {}; typingOffset = undefined; };\n const typingAtCaret = () => {\n if (typingOffset === undefined) return false;\n const selection = readTextSelection(surface);\n return selection?.length === 0 && selection.index === typingOffset;\n };\n const undoStack: Snapshot[] = [];\n const redoStack: Snapshot[] = [];\n const eventHub = createEventHub();\n let transactionDepth = 0;\n let transactionFailed = false;\n let transactionError: unknown;\n let pendingSelectionNotification = false;\n const pluginAPIs = new Map<string, unknown>();\n const disposers: (() => void)[] = [];\n if (options.onChange)\n eventHub.events.on('change', options.onChange);\n const assertActive = () => {\n if (destroyed)\n throw new Error('Editor has been destroyed.');\n };\n const rejectDuringTransaction = (operation: string) => {\n if (!transactionDepth)\n return;\n const error = new Error(`${operation} is unavailable inside a transaction.`);\n transactionFailed = true;\n transactionError = error;\n throw error;\n };\n const events: EditorEvents = {\n on: eventHub.events.on,\n emit: (event, payload) => {\n assertActive();\n rejectDuringTransaction('events.emit');\n eventHub.events.emit(event, payload);\n },\n };\n const htmlSnapshots = createHTMLSnapshots(surface, schema.sanitizeHTML);\n const capture = (): Snapshot => ({ html: htmlSnapshots.read(), selection: bookmark(surface), ...(typingOffset !== undefined && Object.keys(typingOverrides).length && typingAtCaret() ? { typing: { offset: typingOffset, formats: { ...typingOverrides } } } : {}) });\n const restoreTyping = (snapshot: Snapshot) => {\n clearTyping();\n const selection = readTextSelection(surface);\n if (snapshot.typing && selection?.length === 0 && selection.index === snapshot.typing.offset) {\n typingOffset = snapshot.typing.offset;\n typingOverrides = { ...snapshot.typing.formats };\n }\n };\n let current = capture();\n let lastSelection = current.selection;\n const clearCompositionTail = () => {\n compositionTail = undefined;\n compositionUndoRecorded = false;\n };\n const cancelComposition = (rollback: boolean) => {\n const before = compositionStart;\n canceledComposition = canceledComposition || composing || compositionTail !== undefined;\n composing = false;\n compositionStart = undefined;\n pendingInput = undefined;\n clearCompositionTail();\n if (rollback && before) {\n surface.innerHTML = before.html;\n ensureDocument(surface);\n restoreBookmark(surface, before.selection);\n restoreTyping(before);\n current = capture();\n lastSelection = current.selection;\n }\n };\n const restoreCurrentDOM = () => {\n surface.innerHTML = current.html;\n ensureDocument(surface);\n restoreBookmark(surface, current.selection);\n };\n const notifySelection = () => {\n if (destroyed)\n return;\n if (transactionDepth) {\n pendingSelectionNotification = true;\n return;\n }\n if (readTextSelection(surface) && !typingAtCaret())\n clearTyping();\n const saved = bookmark(surface);\n if (saved) {\n lastSelection = saved;\n current.selection = saved;\n }\n eventHub.notify('selectionchange', readTextSelection(surface));\n };\n const emit = (source: EditorChange['source']) => {\n const change: EditorChange = { html: editor.getHTML(), text: editor.getText(), source };\n const failures: unknown[] = [];\n try {\n eventHub.notify('change', change);\n }\n catch (error) {\n failures.push(error);\n }\n try {\n notifySelection();\n }\n catch (error) {\n failures.push(error);\n }\n if (failures.length)\n throw new AggregateError(failures, 'Editor change notification failed.');\n };\n const commitMutation = (before: Snapshot, inputType = ''): boolean => {\n const selection = readTextSelection(surface);\n if (ensureDocument(surface) && selection)\n selectText(surface, selection.index, selection.length);\n const after = capture();\n if (after.html === before.html) {\n current = after;\n return false;\n }\n const now = Date.now();\n const grouped = inputType === lastInputType && ['insertText', 'deleteContentBackward', 'deleteContentForward'].includes(inputType) && now - lastInputTime < 600 && before.selection && current.selection && JSON.stringify(before.selection) === JSON.stringify(current.selection);\n if (!grouped) {\n undoStack.push(before);\n if (undoStack.length > limit)\n undoStack.shift();\n }\n redoStack.length = 0;\n current = after;\n lastInputTime = inputType ? now : 0;\n lastInputType = inputType;\n return true;\n };\n const commit = (before: Snapshot, inputType = '') => {\n if (commitMutation(before, inputType))\n emit('user');\n };\n const restore = (snapshot: Snapshot) => {\n clearTyping();\n surface.innerHTML = snapshot.html;\n ensureDocument(surface);\n surface.focus({ preventScroll: true });\n restoreBookmark(surface, snapshot.selection);\n restoreTyping(snapshot);\n current = capture();\n lastSelection = current.selection;\n lastInputTime = 0;\n emit('user');\n };\n const notifyCommittedInput = (origin: InputCommitOrigin): void => {\n const committed = current;\n const selection = bookmark(surface);\n const selectionKey = JSON.stringify(selection);\n const typingKey = JSON.stringify(typingAtCaret() ? [typingOffset, typingOverrides] : []);\n const receipt: EditorInputCommit = {\n ...origin,\n selection,\n isCurrent: () => !destroyed && !readOnly && !composing && current === committed\n && JSON.stringify(bookmark(surface)) === selectionKey\n && JSON.stringify(typingAtCaret() ? [typingOffset, typingOverrides] : []) === typingKey,\n };\n const failures: unknown[] = [];\n try {\n emit('user');\n }\n catch (error) {\n failures.push(error);\n }\n try {\n eventHub.notify('inputcommit', receipt);\n }\n catch (error) {\n failures.push(error);\n }\n if (failures.length) throw new AggregateError(failures, 'Input commit notification failed.');\n };\n const runTransaction = (mutate: (surface: HTMLElement) => void, inputType = '', origin?: InputCommitOrigin) => {\n assertActive();\n if (readOnly || composing)\n return;\n clearCompositionTail();\n const invoke = () => {\n if (typeof mutate !== 'function' || mutate.constructor.name === 'AsyncFunction')\n throw new TypeError('Transactions require a synchronous callback.');\n const result: unknown = mutate(surface);\n if (result && (typeof result === 'object' || typeof result === 'function') && typeof (result as {\n then?: unknown;\n }).then === 'function') {\n if (result instanceof Promise)\n void result.catch(() => { });\n throw new TypeError('Transaction callbacks must not return a thenable.');\n }\n };\n if (transactionDepth) {\n transactionDepth++;\n try {\n invoke();\n }\n catch (error) {\n transactionFailed = true;\n transactionError = error;\n throw error;\n }\n finally {\n transactionDepth--;\n }\n return;\n }\n editor.focus();\n const before = capture();\n const previousUndo = [...undoStack];\n const previousRedo = [...redoStack];\n const previousInputTime = lastInputTime;\n const previousInputType = lastInputType;\n const previousPendingInput = pendingInput;\n const previousSelection = lastSelection;\n transactionDepth = 1;\n transactionFailed = false;\n transactionError = undefined;\n pendingSelectionNotification = false;\n let changed = false;\n try {\n // A replacement can return to the old text offset without a selectionchange flush.\n const initialRange = activeRange(surface);\n if (initialRange && !initialRange.collapsed) clearTyping();\n invoke();\n if (transactionFailed)\n throw transactionError;\n changed = commitMutation(before, inputType);\n }\n catch (error) {\n surface.innerHTML = before.html;\n ensureDocument(surface);\n restoreBookmark(surface, before.selection);\n restoreTyping(before);\n current = capture();\n lastSelection = previousSelection;\n pendingInput = previousPendingInput;\n undoStack.splice(0, undoStack.length, ...previousUndo);\n redoStack.splice(0, redoStack.length, ...previousRedo);\n lastInputTime = previousInputTime;\n lastInputType = previousInputType;\n transactionDepth = 0;\n pendingSelectionNotification = false;\n throw error;\n }\n finally {\n transactionDepth = 0;\n }\n const selectionChanged = pendingSelectionNotification;\n pendingSelectionNotification = false;\n // Notifications are outside the rollback boundary: observers cannot undo a committed edit by throwing.\n if (changed) {\n if (origin) notifyCommittedInput(origin);\n else emit('user');\n }\n else if (selectionChanged)\n notifySelection();\n };\n const registry = createCommandRegistry({ editor: () => editor, isComposing: () => composing, assertActive });\n const prepareHTML = (html: string): DocumentFragment => {\n try {\n const fragment = schema.renderDocument(schema.parseHTML(html));\n const range = activeRange(surface) ?? rangeFromBookmark(surface, lastSelection);\n prepareSelectionPaste(surface, fragment, range);\n prepareListSelectionPaste(surface, fragment, range);\n return fragment;\n }\n catch (error) {\n // Invalid nested imports poison the outer edit even when its caller catches them.\n if (transactionDepth) {\n transactionFailed = true;\n transactionError = error;\n }\n throw error;\n }\n };\n const insertPrepared = (fragment: DocumentFragment, origin?: InputCommitOrigin): void => {\n if (!fragment.childNodes.length) return;\n if (!activeRange(surface) && lastSelection) restoreBookmark(surface, lastSelection);\n runTransaction(() => {\n // Replacement or a new list body changes the caret's formatting context,\n // even at the same text offset. Capture the original snapshot first.\n const range = activeRange(surface);\n if (range && (!range.collapsed || handlesCollapsedListBlockPaste(surface, fragment, range))) clearTyping();\n insertFragment(surface, fragment);\n }, '', origin);\n };\n const editor: Editor = {\n element: container, surface, events, schema, commands: registry.commands,\n getLocale: () => {\n assertActive();\n return { locale: locale.locale, translations: { ...locale.translations } };\n },\n setLocale: (language, translations) => {\n assertActive();\n rejectDuringTransaction('setLocale');\n const next = createLocale(language, translations);\n const keys = Object.keys(next.translations);\n if (locale.locale === next.locale && keys.length === Object.keys(locale.translations).length && keys.every((key) => Object.hasOwn(locale.translations, key) && locale.translations[key] === next.translations[key]))\n return;\n locale = next;\n updateLocale();\n eventHub.notify('localechange', editor.getLocale());\n },\n getHTML: () => { assertActive(); return htmlSnapshots.read(); },\n getText: () => { assertActive(); return surface.innerText; },\n getJSON: () => { assertActive(); return schema.parseHTML(surface.innerHTML); },\n setHTML: (html) => {\n assertActive();\n rejectDuringTransaction('setHTML');\n const content = schema.documentHTML(schema.parseHTML(html));\n if (content === editor.getHTML())\n return;\n cancelComposition(false);\n clearTyping();\n surface.innerHTML = content;\n ensureDocument(surface);\n undoStack.length = 0;\n redoStack.length = 0;\n lastInputTime = 0;\n lastSelection = undefined;\n current = capture();\n emit('api');\n },\n setJSON: (value) => {\n assertActive();\n rejectDuringTransaction('setJSON');\n const validated = schema.validateDocument(value);\n editor.setHTML(schema.documentHTML(validated));\n },\n getSelection: () => { assertActive(); return readTextSelection(surface); },\n setSelection: (index, length = 0) => { assertActive(); selectText(surface, index, length); notifySelection(); },\n getFormats: (range) => {\n assertActive();\n return range === undefined ? { ...readFormats(surface), ...(typingAtCaret() ? typingOverrides : {}) } : readFormats(surface, range);\n },\n setReadOnly: (value) => {\n assertActive();\n rejectDuringTransaction('setReadOnly');\n const changed = readOnly !== value;\n if (changed && value)\n cancelComposition(true);\n readOnly = value;\n surface.contentEditable = String(!value);\n surface.setAttribute('aria-readonly', String(value));\n container.dataset.readonly = String(value);\n const failures: unknown[] = [];\n if (changed) {\n try {\n eventHub.notify('readonlychange', value);\n }\n catch (error) {\n failures.push(error);\n }\n }\n try {\n notifySelection();\n }\n catch (error) {\n failures.push(error);\n }\n if (failures.length)\n throw new AggregateError(failures, 'Editor state notification failed.');\n },\n isReadOnly: () => { assertActive(); return readOnly; },\n format: (name, value) => {\n assertActive();\n if (readOnly || composing)\n return;\n clearCompositionTail();\n editor.focus();\n const selection = readTextSelection(surface);\n if (selection?.length === 0 && (Object.hasOwn(inlineFormats, name) || Object.hasOwn(inlineStyles, name))) {\n if (!typingAtCaret())\n clearTyping();\n typingOffset = selection.index;\n typingOverrides[name] = Object.hasOwn(inlineStyles, name) ? normalizeInlineStyle(name, value) : Boolean(value);\n notifySelection();\n return;\n }\n clearTyping();\n editor.transact(() => applyFormat(surface, name, value, schema));\n },\n insertHTML: (html) => {\n assertActive();\n if (readOnly || composing) return;\n insertPrepared(prepareHTML(html));\n },\n focus: () => {\n assertActive();\n surface.focus({ preventScroll: true });\n if (!activeRange(surface)) {\n if (lastSelection)\n restoreBookmark(surface, lastSelection);\n else\n placeCaret(surface.firstElementChild as HTMLElement ?? surface, true);\n }\n },\n undo: () => {\n assertActive();\n rejectDuringTransaction('undo');\n if (readOnly || composing)\n return;\n clearCompositionTail();\n const previous = undoStack.pop();\n if (previous) {\n redoStack.push(capture());\n restore(previous);\n }\n },\n redo: () => {\n assertActive();\n rejectDuringTransaction('redo');\n if (readOnly || composing)\n return;\n clearCompositionTail();\n const next = redoStack.pop();\n if (next) {\n undoStack.push(capture());\n restore(next);\n }\n },\n canUndo: () => { assertActive(); return undoStack.length > 0; },\n canRedo: () => { assertActive(); return redoStack.length > 0; },\n transact: (mutate) => runTransaction(mutate),\n providePlugin: (name, api) => {\n assertActive();\n if (pluginAPIs.has(name))\n throw new Error(`Plugin API already registered: ${name}`);\n pluginAPIs.set(name, api);\n return () => { pluginAPIs.delete(name); };\n },\n getPlugin: <T>(name: string) => { assertActive(); return pluginAPIs.get(name) as T | undefined; },\n subscribe: (listener) => { assertActive(); return eventHub.events.on('change', listener); },\n onSelectionChange: (listener) => { assertActive(); return eventHub.events.on('selectionchange', listener); },\n destroy: () => {\n if (destroyed)\n return;\n rejectDuringTransaction('destroy');\n cancelComposition(false);\n destroyed = true;\n const failures: unknown[] = [];\n try {\n eventHub.destroy();\n }\n catch (error) {\n failures.push(error);\n }\n for (const dispose of disposers.reverse()) {\n try {\n dispose();\n }\n catch (error) {\n failures.push(error);\n }\n }\n registry.destroy();\n pluginAPIs.clear();\n undoStack.length = 0;\n redoStack.length = 0;\n htmlSnapshots.clear();\n container.remove();\n if (failures.length)\n throw new AggregateError(failures, 'Editor cleanup failed.');\n },\n };\n const listen = <K extends keyof HTMLElementEventMap>(type: K, handler: (event: HTMLElementEventMap[K]) => void) => {\n surface.addEventListener(type, handler);\n disposers.push(() => surface.removeEventListener(type, handler));\n };\n listen('beforeinput', (event) => {\n if (event.defaultPrevented)\n return;\n if (readOnly) {\n event.preventDefault();\n return;\n }\n const compositionInput = isCompositionInput(event);\n if (canceledComposition && compositionInput) {\n event.preventDefault();\n return;\n }\n if (composing || event.isComposing)\n return;\n if (!compositionInput) {\n canceledComposition = false;\n clearCompositionTail();\n }\n if (event.inputType === 'historyUndo' || event.inputType === 'historyRedo') {\n event.preventDefault();\n if (event.inputType === 'historyUndo')\n editor.undo();\n else\n editor.redo();\n return;\n }\n if (event.cancelable && handlesSelectionReplacement(surface, event.inputType, event.data)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n const text = event.inputType === 'insertText' ? event.data! : '';\n // A replacement is isolated from native typing/deletion bursts on both sides.\n runTransaction(() => replaceSelection(surface, text));\n return;\n }\n const listReplacementInput = (event.inputType === 'insertText' && typeof event.data === 'string')\n || event.inputType === 'deleteContentBackward' || event.inputType === 'deleteContentForward';\n if (event.cancelable && listReplacementInput) {\n const selection = listSelectionReplacement(surface);\n if (selection.status !== 'unowned') {\n event.preventDefault();\n pendingInput = undefined;\n if (selection.status === 'blocked') return;\n clearTyping();\n runTransaction(() => replaceListSelection(surface, event.inputType === 'insertText' ? event.data! : ''));\n return;\n }\n }\n if (event.cancelable && handlesListForwardDelete(surface, event.inputType)) {\n event.preventDefault();\n pendingInput = undefined;\n runTransaction(() => {\n // A boundary barrier is a real no-op, including pending caret formats.\n if (editListForwardDelete(surface)) clearTyping();\n });\n return;\n }\n const wrappedInput = inspectWrappedListInput(surface, event.inputType);\n if (wrappedInput === 'eligible' || wrappedInput === 'blocked') {\n if (!event.cancelable) {\n // Native default cannot be suppressed; do not also run legacy list edits.\n pendingInput = capture();\n return;\n }\n event.preventDefault();\n pendingInput = undefined;\n if (wrappedInput === 'blocked') return;\n runTransaction(() => {\n if (editWrappedListInput(surface, event.inputType, prepareListSplit)) clearTyping();\n }, '', paragraphOrigin(event, event.inputType));\n return;\n }\n if (!composing && !event.isComposing && handlesListInput(surface, event.inputType)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n runTransaction(() => editListInput(surface, event.inputType, prepareListSplit), '', paragraphOrigin(event, event.inputType));\n return;\n }\n if (handlesBlockInput(surface, event.inputType)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n runTransaction(() => editBlockInput(surface, event.inputType), '', paragraphOrigin(event, event.inputType));\n return;\n }\n if (event.inputType === 'insertText' && event.data && !composing && !event.isComposing && typingAtCaret() && Object.keys(typingOverrides).length) {\n event.preventDefault();\n const start = readTextSelection(surface)!.index;\n const text = event.data;\n const overrides = { ...typingOverrides };\n runTransaction(() => {\n const range = activeRange(surface)!;\n const parent = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement;\n const block = parent?.closest('p,h1,h2,h3,h4,h5,h6,li,blockquote,pre');\n if (block && !block.textContent && block.childNodes.length === 1 && block.firstChild instanceof HTMLBRElement) {\n block.replaceChildren();\n range.selectNodeContents(block);\n range.collapse(true);\n }\n range.insertNode(document.createTextNode(text));\n selectText(surface, start, text.length);\n for (const [name, enabled] of Object.entries(overrides))\n if ((Object.hasOwn(inlineStyles, name) ? readFormats(surface)[name] ?? false : Boolean(readFormats(surface)[name])) !== enabled)\n applyFormat(surface, name, enabled, schema);\n selectText(surface, start + text.length);\n typingOffset = start + text.length;\n }, 'insertText');\n pendingInput = undefined;\n return;\n }\n pendingInput = capture();\n });\n listen('input', (nativeEvent) => {\n const event = nativeEvent as InputEvent;\n const compositionInput = isCompositionInput(event);\n if (readOnly || (canceledComposition && compositionInput)) {\n restoreCurrentDOM();\n return;\n }\n if (composing || event.isComposing)\n return;\n if (compositionTail && compositionInput) {\n const before = compositionTail;\n const changed = htmlSnapshots.read() !== current.html;\n pendingInput = undefined;\n if (!changed)\n return;\n // Replace only our own last undo entry, never an intervening application edit.\n if (compositionUndoRecorded && undoStack.at(-1) === before)\n undoStack.pop();\n compositionUndoRecorded = commitMutation(before);\n emit('user');\n return;\n }\n canceledComposition = false;\n clearCompositionTail();\n const before = pendingInput ?? current;\n pendingInput = undefined;\n commit(before, event.inputType);\n });\n listen('compositionstart', () => {\n if (readOnly) {\n canceledComposition = true;\n return;\n }\n if (composing)\n return;\n clearTyping();\n clearCompositionTail();\n pendingInput = undefined;\n canceledComposition = false;\n compositionStart = capture();\n composing = true;\n });\n listen('compositionend', () => {\n if (canceledComposition) {\n pendingInput = undefined;\n restoreCurrentDOM();\n return;\n }\n composing = false;\n const before = compositionStart;\n compositionStart = undefined;\n pendingInput = undefined;\n if (before) {\n compositionTail = before;\n compositionUndoRecorded = commitMutation(before);\n if (compositionUndoRecorded)\n emit('user');\n }\n });\n listen('paste', (event) => {\n if (event.defaultPrevented) return;\n event.preventDefault();\n if (readOnly || composing || !event.clipboardData)\n return;\n let html = event.clipboardData.getData('text/html');\n if (!html) {\n const text = event.clipboardData.getData('text/plain');\n const holder = document.createElement('div');\n holder.textContent = text;\n html = holder.innerHTML.replace(/\\r\\n?|\\n/g, '<br>');\n }\n let fragment: DocumentFragment;\n try { fragment = prepareHTML(html); }\n catch { return; }\n // Commit/observer failures deliberately stay outside the import-only catch.\n insertPrepared(fragment, event.cancelable ? { inputType: 'insertFromPaste', sourceEvent: event } : undefined);\n });\n listen('drop', (event) => { event.preventDefault(); });\n listen('keydown', (event) => {\n if (event.defaultPrevented || event.keyCode === 229)\n return;\n if (!composing && !event.isComposing && !readOnly && !event.ctrlKey && !event.metaKey && !event.altKey && (event.key === 'Enter' || event.key === 'Backspace' || event.key === 'Delete')) {\n const type = event.key === 'Backspace' ? 'deleteContentBackward' : event.key === 'Delete' ? 'deleteContentForward' : event.shiftKey ? 'insertLineBreak' : 'insertParagraph';\n const wrappedInput = inspectWrappedListInput(surface, type);\n const listReplacement = type === 'deleteContentBackward' || type === 'deleteContentForward'\n ? listSelectionReplacement(surface).status !== 'unowned' : false;\n const listOwned = listReplacement || wrappedInput === 'eligible' || wrappedInput === 'blocked'\n || handlesListForwardDelete(surface, type);\n if (listOwned && event.cancelable) {\n // Some native protocols omit boundary beforeinput or mislabel Shift+Enter.\n // Keep one normalized, cancelable input path for core and plugin capture hooks.\n event.preventDefault();\n surface.dispatchEvent(new InputEvent('beforeinput', { inputType: type, bubbles: true, cancelable: true }));\n return;\n }\n if (!listOwned && handlesListInput(surface, type)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n runTransaction(() => editListInput(surface, type, prepareListSplit), '', paragraphOrigin(event, type));\n return;\n }\n // Enter must reach beforeinput so optional typing rules can consume it first.\n if (!listOwned && (event.key !== 'Enter' || event.shiftKey) && handlesBlockInput(surface, type)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n runTransaction(() => editBlockInput(surface, type));\n return;\n }\n }\n if (!composing && !event.isComposing && !readOnly && event.key === 'Tab' && !event.ctrlKey && !event.metaKey && !event.altKey) {\n const blocks = selectedBlocks(surface);\n if (blocks.length && blocks.every((block) => block.localName === 'li' && !block.closest('td,th')) && listState(surface).canOutdent) {\n event.preventDefault();\n clearTyping();\n runTransaction(() => indentList(surface, event.shiftKey ? -1 : 1));\n return;\n }\n }\n if (composing || event.isComposing || readOnly || !(event.ctrlKey || event.metaKey) || event.altKey)\n return;\n const key = event.key.toLowerCase();\n if (key === 'z' || key === 'y') {\n event.preventDefault();\n if (key === 'y' || event.shiftKey)\n editor.redo();\n else\n editor.undo();\n }\n const name = ({ b: 'bold', i: 'italic', u: 'underline' } as Record<string, string>)[key];\n if (name) {\n event.preventDefault();\n editor.format(name, (editor.getFormats().mixed as string[] | undefined)?.includes(name) || !editor.getFormats()[name]);\n }\n });\n document.addEventListener('selectionchange', notifySelection);\n disposers.push(() => document.removeEventListener('selectionchange', notifySelection));\n try {\n editor.setReadOnly(readOnly);\n for (const plugin of plugins) {\n const dispose = plugin.setup(editor);\n if (dispose)\n disposers.push(dispose);\n }\n return editor;\n }\n catch (error) {\n editor.destroy();\n throw error;\n }\n};\n", "import type { LocalizedToolbarAction, ToolbarAction, ToolbarOptions } from './types.js';\nexport type { ToolbarAction, ToolbarOptions } from './types.js';\nimport type { Editor } from '../../index.js';\nimport { inlineStyles, normalizeInlineStyle } from '../../formatting/inline-attributes.js';\nimport { bookmark, restoreBookmark } from '../../selection/index.js';\nimport type { SelectionBookmark } from '../../selection/index.js';\nimport { localize } from '../../localization/index.js';\nimport type { EditorLocale } from '../../localization/types.js';\nimport { toolbarMessages } from './messages.js';\nconst createDefaultActions = (): LocalizedToolbarAction[] => [\n { translationKey: 'toolbar.undo', label: toolbarMessages.ru['toolbar.undo'], text: '\u21B6', run: (editor) => editor.undo(), enabled: (editor) => editor.canUndo() },\n { translationKey: 'toolbar.redo', label: toolbarMessages.ru['toolbar.redo'], text: '\u21B7', run: (editor) => editor.redo(), enabled: (editor) => editor.canRedo() },\n { translationKey: 'toolbar.bold', label: toolbarMessages.ru['toolbar.bold'], text: 'B', format: 'bold' },\n { translationKey: 'toolbar.italic', label: toolbarMessages.ru['toolbar.italic'], text: 'I', format: 'italic' },\n { translationKey: 'toolbar.underline', label: toolbarMessages.ru['toolbar.underline'], text: 'U', format: 'underline' },\n { translationKey: 'toolbar.header', label: toolbarMessages.ru['toolbar.header'], text: 'H\u2082', format: 'header', value: 2 },\n { translationKey: 'toolbar.bulletList', label: toolbarMessages.ru['toolbar.bulletList'], text: '\u2637', format: 'list', value: 'bullet' },\n { translationKey: 'toolbar.orderedList', label: toolbarMessages.ru['toolbar.orderedList'], text: '1.', format: 'list', value: 'ordered' },\n { translationKey: 'toolbar.indent', label: toolbarMessages.ru['toolbar.indent'], text: '\u21E5', format: 'indent', value: 1, enabled: (editor) => Boolean(editor.getFormats().canIndent) },\n { translationKey: 'toolbar.outdent', label: toolbarMessages.ru['toolbar.outdent'], text: '\u21E4', format: 'indent', value: -1, enabled: (editor) => Boolean(editor.getFormats().canOutdent) },\n { translationKey: 'toolbar.blockquote', label: toolbarMessages.ru['toolbar.blockquote'], text: '\u275D', format: 'blockquote' },\n { translationKey: 'toolbar.clear', label: toolbarMessages.ru['toolbar.clear'], text: 'Tx', format: 'clear', enabled: (editor) => Boolean(editor.getSelection()?.length) },\n];\nexport const createToolbar = (host: HTMLElement, editor: Editor, requestedActions?: ToolbarAction[], options: ToolbarOptions = {}): () => void => {\n const defaultActions = requestedActions === undefined ? createDefaultActions() : [];\n const defaultKeys = defaultActions.map((action) => action.translationKey);\n const actions = (requestedActions ?? defaultActions).map((action) => action.format && Object.hasOwn(inlineStyles, action.format) ? { ...action, value: normalizeInlineStyle(action.format, action.value) } : action);\n const toolbar = document.createElement('div');\n toolbar.className = 'mw-toolbar';\n toolbar.setAttribute('role', 'toolbar');\n let saved: SelectionBookmark | undefined;\n let disposed = false;\n let tabIndex = 0;\n const cleanups: (() => void)[] = [];\n const buttons = actions.map((action) => {\n const button = document.createElement('button');\n button.type = 'button';\n button.textContent = action.text;\n button.title = action.label;\n button.setAttribute('aria-label', action.label);\n const down = (event: MouseEvent) => event.preventDefault();\n const click = () => {\n if (disposed || button.disabled || editor.isReadOnly())\n return;\n editor.focus();\n if (saved)\n restoreBookmark(editor.surface, saved);\n if (action.enabled && !action.enabled(editor))\n return;\n if (action.run)\n action.run(editor);\n else if (action.format) {\n const formats = editor.getFormats();\n const mixed = (formats.mixed as string[] | undefined)?.includes(action.format);\n editor.format(action.format, !mixed && formats[action.format] === (action.value ?? true) ? false : action.value ?? true);\n }\n update();\n };\n button.addEventListener('mousedown', down);\n button.addEventListener('click', click);\n cleanups.push(() => { button.removeEventListener('mousedown', down); button.removeEventListener('click', click); });\n toolbar.append(button);\n return button;\n });\n const updateLocale = (state: EditorLocale = editor.getLocale()) => {\n if (disposed)\n return;\n toolbar.setAttribute('aria-label', options.label ?? localize(state, 'toolbar.label', toolbarMessages));\n buttons.forEach((button, index) => {\n const key = defaultKeys[index];\n const label = key ? localize(state, key, toolbarMessages) : actions[index].label;\n button.title = label;\n button.setAttribute('aria-label', label);\n });\n };\n const update = () => {\n if (disposed)\n return;\n saved = bookmark(editor.surface) ?? saved;\n const formats = editor.getFormats();\n buttons.forEach((button, index) => {\n const action = actions[index];\n button.disabled = editor.isReadOnly() || (action.enabled ? !action.enabled(editor) : false);\n if (action.format && !['indent', 'clear'].includes(action.format))\n button.setAttribute('aria-pressed', (formats.mixed as string[] | undefined)?.includes(action.format) ? 'mixed' : String(formats[action.format] === (action.value ?? true)));\n });\n if (buttons[tabIndex]?.disabled || !buttons[tabIndex])\n tabIndex = buttons.findIndex((button) => !button.disabled);\n buttons.forEach((button, index) => { button.tabIndex = index === tabIndex ? 0 : -1; });\n };\n const keyboard = (event: KeyboardEvent) => {\n const enabled = buttons.filter((button) => !button.disabled);\n if (!enabled.length)\n return;\n const index = enabled.indexOf(document.activeElement as HTMLButtonElement);\n if (index < 0 || event.ctrlKey || event.metaKey || event.altKey)\n return;\n if (event.key === 'Escape') {\n event.preventDefault();\n editor.focus();\n if (saved)\n restoreBookmark(editor.surface, saved);\n return;\n }\n const direction = getComputedStyle(toolbar).direction === 'rtl' ? -1 : 1;\n const next = event.key === 'Home' ? 0 : event.key === 'End' ? enabled.length - 1 : event.key === 'ArrowRight' ? (index + direction + enabled.length) % enabled.length : event.key === 'ArrowLeft' ? (index - direction + enabled.length) % enabled.length : -1;\n if (next >= 0) {\n event.preventDefault();\n tabIndex = buttons.indexOf(enabled[next]);\n update();\n enabled[next].focus();\n }\n };\n toolbar.addEventListener('keydown', keyboard);\n const unsubscribe = editor.subscribe((change) => {\n if (change.source === 'api')\n saved = undefined; update();\n });\n const unselect = editor.onSelectionChange(update);\n const unlocale = editor.events.on('localechange', updateLocale);\n host.append(toolbar);\n updateLocale();\n update();\n return () => {\n if (disposed)\n return;\n disposed = true;\n unsubscribe();\n unselect();\n unlocale();\n toolbar.removeEventListener('keydown', keyboard);\n for (const dispose of cleanups)\n dispose();\n toolbar.remove();\n };\n};\n"],
|
|
5
|
-
"mappings": "iFAAO,IAAMA,GAAU,CAACC,EAAeC,IAAuC,CAC5E,IAAMC,EAAUF,EAAM,KAAK,EAC3B,GAAI,CAACE,GAAW,wBAAwB,KAAKA,CAAO,EAClD,OAEF,IAAMC,EAAW,wBAAwB,KAAKD,CAAO,IAAI,CAAC,EAAE,YAAY,EACxE,GAAI,EAAAC,GAAY,EAAEF,EAAQ,CAAC,OAAQ,OAAO,EAAI,CAAC,OAAQ,QAAS,SAAU,KAAK,GAAG,SAASE,CAAQ,IAE/F,EAAAD,EAAQ,WAAW,IAAI,GAAKA,EAAQ,WAAW,IAAI,GAEvD,OAAOA,CACT,ECXA,IAAME,GAAkB,IAAI,IAAI,CAAC,QAAS,aAAc,YAAa,UAA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,EAEJ,CAAAA,EAAW,GACXuB,EAAY,EACZE,EAAS,EACTC,EAAS,EACT5B,EAAQ,oBAAoB,UAAWqB,CAAQ,EAC/C,QAAWQ,KAAWzB,EACpByB,EAAQ,EACV7B,EAAQ,OAAO,EACjB,CACF",
|
|
6
|
-
"names": ["safeURL", "value", "image", "trimmed", "protocol", "genericFamilies", "wideKeywords", "identifier", "normalizeFontFamily", "input", "parts", "result", "part", "value", "quoted", "name", "generic", "word", "normalized", "markers", "normalizeListMarker", "tag", "value", "marker", "tags", "normalizeDirection", "tag", "value", "canonical", "direction", "copyDirection", "source", "target", "voidTags", "consume", "budget", "length", "escaped", "value", "attribute", "remaining", "index", "code", "countText", "countElement", "tag", "attributes", "name", "documentTags", "tags", "omitted", "aliases", "safeStyle", "tag", "value", "result", "declaration", "separator", "property", "marker", "normalizeListMarker", "family", "normalizeFontFamily", "content", "color", "length", "orderedListStart", "number", "attributesFor", "input", "source", "resolve", "originalTag", "output", "key", "direction", "normalizeDirection", "clean", "safeURL", "tokens", "token", "dimensions", "styles", "part", "readDOM", "node", "depth", "budget", "text", "countText", "element", "original", "children", "child", "attr", "attributes", "countElement", "parseHTML", "html", "template", "validateDocument", "visit", "attrs", "values", "index", "renderDocument", "owner", "fragment", "append", "parent", "documentHTML", "container", "sanitizeHTML", "inlineTags", "blockTags", "supportedTag", "kind", "tag", "record", "value", "keysWithin", "allowed", "key", "compileAttribute", "input", "required", "read", "limit", "values", "min", "max", "number", "clean", "safeURL", "createDocumentSchema", "nodes", "registry", "names", "tagAttributes", "splitPolicies", "node", "nonOwning", "documentTags", "rules", "attributes", "name", "rule", "compiled", "existing", "policies", "reset", "resolve", "source", "originalTag", "output", "marker", "validate", "validateDocument", "parse", "html", "parseHTML", "renderDocument", "documentHTML", "tokens", "createEditorCommand", "name", "command", "assertToken", "synchronous", "callback", "rejectThenable", "value", "createCommandRegistry", "options", "entries", "disposed", "assertActive", "resolve", "entry", "stateValue", "fallback", "enabled", "definition", "key", "validate", "execute", "isEnabled", "isActive", "isMixed", "editor", "payload", "validated", "activeRange", "root", "selection", "range", "nodePath", "target", "result", "node", "stableBoundary", "offset", "bookmark", "start", "startOffset", "end", "endOffset", "rangeFromBookmark", "saved", "resolve", "path", "index", "limit", "restoreBookmark", "readTextSelection", "prefix", "selectText", "length", "value", "walker", "nodes", "current", "locate", "last", "placeCaret", "element", "preserveRange", "mutate", "native", "backward", "tail", "head", "next", "blockTags", "inlineTags", "inlineTree", "element", "node", "parentOf", "editableBlock", "root", "block", "parent", "hasContent", "fragment", "selectedBlock", "range", "activeRange", "atEdge", "end", "remainder", "siblingBlock", "forward", "sibling", "handlesBlockInput", "inputType", "editBlockInput", "document", "tailRange", "tail", "emptyHeading", "headingEnd", "paragraph", "attribute", "copyDirection", "placeCaret", "next", "terminal", "lineBreak", "caret", "selection", "left", "right", "join", "leafTags", "inlineTags", "inlineTree", "element", "node", "ordinaryLeaf", "root", "leaf", "selectedLeaves", "range", "left", "right", "leaves", "next", "handlesSelectionReplacement", "inputType", "data", "selectionReplacement", "activeRange", "cutSelectionReplacement", "contentRoots", "document", "emptyLeft", "emptyRight", "caret", "tailRange", "tail", "placeholder", "cut", "ensureReplacementPlaceholder", "finishSelectionReplacement", "selection", "replaceSelection", "text", "selected", "inserted", "insertInlineFragment", "left", "caret", "fragment", "anchor", "last", "inlineTags", "leafTags", "blockTags", "inlineNode", "node", "ordinaryPayloadLeaf", "stripPlaceholder", "element", "placeholder", "prepareSelectionPaste", "root", "fragment", "range", "selected", "selectionReplacement", "placeholderAtStart", "leaf", "caret", "ensureReplacementPlaceholder", "meaningfulTail", "tail", "replaceSelectionWithFragment", "nodes", "singleParagraph", "inline", "leaves", "left", "right", "cutSelectionReplacement", "insertInlineFragment", "finishSelectionReplacement", "first", "last", "prefix", "middle", "end", "paragraph", "inserted", "suffix", "inlineTags", "inlinePayloadNode", "node", "formattingWhitespace", "ordinaryPayloadBody", "quoteBodyBlocks", "quote", "nodes", "isOrdinaryQuote", "inlineTags", "sourceInlineNode", "node", "sourceBody", "quoteSourceBodies", "quote", "isOrdinaryQuote", "children", "blocks", "formattingWhitespace", "directQuoteAt", "item", "quoteBodyPoint", "bodies", "range", "end", "point", "contained", "body", "offset", "next", "child", "previous", "quoteEndpointPoint", "quotePasteContext", "start", "normalized", "from", "to", "gaps", "gap", "quoteCrossingContext", "boundaries", "range", "startRoot", "endRoot", "start", "end", "gaps", "first", "last", "from", "to", "affected", "boundary", "index", "quotes", "body", "quote", "quoteSourceBodies", "startQuoted", "endQuoted", "directQuoteAt", "startPoint", "quoteEndpointPoint", "endPoint", "normalized", "left", "right", "ordered", "branch", "intervalBranches", "children", "begin", "finish", "node", "following", "siblings", "ensureBody", "point", "ensureReplacementPlaceholder", "promoteInlineBody", "item", "replaceQuoteCrossing", "context", "roots", "covered", "startQuoteBody", "endQuoteBody", "document", "suffixCut", "prefixCut", "root", "quoteBodies", "quoteBodyBlocks", "caretBody", "suffix", "gap", "caret", "finishSelectionReplacement", "inlineTags", "inlineNode", "node", "isList", "itemAt", "root", "item", "inspectItem", "preserveQuotes", "list", "ownNodes", "bodies", "nestedLists", "interleaved", "paragraph", "quote", "isOrdinaryQuote", "body", "ownStart", "ownEnd", "breaks", "count", "inspectListItem", "blocked", "reason", "listBodyAt", "range", "boundary", "end", "offset", "children", "child", "index", "normalizeListBodyRange", "point", "atStart", "selectionPlan", "options", "includeSameBody", "includeCollapsed", "firstItem", "lastItem", "first", "last", "directQuoteAt", "endQuote", "branch", "context", "quotePasteContext", "start", "startBody", "endBody", "from", "to", "crossing", "quoteCrossingContext", "workingRange", "leaves", "boundaries", "hasQuote", "gaps", "listSelectionReplacement", "activeRange", "listPasteSelection", "blockCandidate", "ordinaryParagraph", "fragment", "node", "inlinePayloadNode", "multiBlockCandidate", "nodes", "formattingWhitespace", "headingRoot", "ordinaryHeading", "quoteRoot", "ordinaryQuote", "isOrdinaryQuote", "blockPasteCandidate", "ordinaryBlocks", "ordinaryPayloadBody", "stripPlaceholder", "body", "placeholder", "ensureBodyPlaceholder", "caret", "ensureReplacementPlaceholder", "requireSupported", "selected", "handlesCollapsedListBlockPaste", "root", "range", "activeRange", "innerPayload", "listPasteSelection", "prepareListSelectionPaste", "blocks", "heading", "quote", "candidate", "quoteBodyBlocks", "cutListSelection", "forceParagraph", "context", "container", "sameItem", "firstBodies", "lastBodies", "startIndex", "endIndex", "following", "branches", "branch", "leaves", "cut", "cutSelectionReplacement", "caretContainer", "offset", "paragraph", "gap", "replaceListSelection", "text", "listSelectionReplacement", "left", "tail", "inserted", "finishSelectionReplacement", "replaceListSelectionWithFragment", "standalone", "roots", "replaceQuoteCrossing", "suffix", "quoteBlocks", "end", "first", "last", "prefix", "insertInlineFragment", "middle", "isList", "node", "selectedItem", "root", "range", "item", "atOwnEnd", "body", "children", "branchIndex", "firstBranch", "ownNodes", "end", "hasText", "blockers", "count", "suffix", "nextItem", "sibling", "removeOwnPlaceholder", "nodes", "placeholder", "atBodyEnd", "point", "content", "removeBodyPlaceholder", "handlesListForwardDelete", "inputType", "activeRange", "boundary", "inspectListItem", "previousEdge", "listBodyAt", "normalizeListBodyRange", "wrapped", "editListForwardDelete", "left", "current", "following", "join", "finishSelectionReplacement", "rightItem", "right", "branch", "target", "rightBody", "laterBodies", "rightNodes", "isList", "node", "whitespace", "supportedList", "root", "list", "inspectListItem", "firstBodyBackspacePlan", "boundary", "previous", "inspected", "parent", "outer", "laterBranches", "branch", "following", "next", "canEditFirstBodyBackspace", "selectRange", "range", "selection", "editFirstBodyBackspace", "start", "plan", "original", "activeRange", "editListForwardDelete", "container", "offset", "body", "copyDirection", "trailing", "caret", "itemAt", "root", "node", "item", "atBodyStart", "body", "range", "prefix", "content", "inspectWrappedListInput", "inputType", "activeRange", "last", "wrappedShape", "candidate", "boundary", "inspectListItem", "listBodyAt", "endBody", "start", "normalizeListBodyRange", "end", "listSelectionReplacement", "canEditFirstBodyBackspace", "ensurePlaceholder", "editWrappedListInput", "prepareSplit", "replaceListSelection", "editFirstBodyBackspace", "previous", "empty", "placeholder", "join", "finishSelectionReplacement", "cut", "caret", "breaks", "suffix", "trailing", "lineBreak", "selection", "tail", "nextItem", "nextBody", "laterBodies", "walker", "text", "placeCaret", "blocks", "isList", "element", "elementAt", "node", "blockAt", "root", "preferItem", "item", "block", "touches", "range", "content", "start", "end", "first", "last", "selectedBlocks", "activeRange", "preferItems", "found", "walker", "topItems", "items", "parent", "itemRange", "siblings", "depth", "result", "numberedBoundary", "list", "compatible", "a", "b", "joinLists", "previous", "splitAround", "replacement", "tail", "ownContent", "unwrapRoot", "paragraphOnly", "paragraphNode", "copyDirection", "paragraph", "nested", "output", "lift", "owner", "trailing", "listState", "canIndent", "child", "indentList", "direction", "preserveRange", "applyList", "value", "selected", "tag", "marker", "normalizeListMarker", "empty", "placeholder", "atStart", "prefix", "handlesListInput", "inputType", "editListInput", "prepareSplit", "next", "caret", "selection", "placeCaret", "br", "target", "inlineStyles", "blocks", "checkedAttributes", "tag", "attributes", "validateDocument", "normalizeInlineStyle", "name", "value", "family", "normalizeFontFamily", "property", "attrs", "probe", "normalized", "normalizeLink", "input", "link", "clean", "mergeLinkAttributes", "previous", "patch", "equalAttributes", "a", "b", "withoutProperty", "style", "part", "groupPieces", "pieces", "result", "piece", "last", "compact", "nodes", "node", "next", "transformInlineAttributes", "document", "from", "to", "operation", "position", "wrap", "group", "children", "visit", "inheritedLink", "start", "left", "right", "begin", "end", "selected", "text", "child", "content", "applyLink", "root", "value", "schema", "link", "normalizeLink", "range", "activeRange", "selection", "readTextSelection", "element", "anchor", "existing", "documentHTML", "transformInlineAttributes", "parseHTML", "selectText", "attrs", "mergeLinkAttributes", "attr", "preserveRange", "key", "val", "created", "parent", "tail", "native", "blockTags", "textLength", "node", "length", "child", "inlineDocument", "value", "from", "to", "tag", "enabled", "position", "visit", "start", "left", "right", "begin", "end", "selected", "text", "leaf", "children", "piece", "groups", "last", "group", "leaves", "inlineTags", "structuralAncestors", "elementAt", "node", "isInlineTree", "parent", "element", "applyLocalInline", "root", "range", "tag", "enabled", "schema", "block", "prefix", "from", "length", "native", "backward", "content", "inlineDocument", "parseHTML", "fragment", "renderDocument", "replacement", "selectText", "selected", "inlineFormats", "closestElement", "node", "formatsAt", "root", "element", "formats", "name", "tag", "property", "inlineStyles", "value", "normalizeFontFamily", "readFormats", "projection", "range", "activeRange", "mixed", "prefix", "index", "length", "walker", "position", "samples", "end", "keys", "normalized", "sample", "key", "listState", "applyFormat", "schema", "applyLocalInline", "selection", "readTextSelection", "applyList", "indentList", "content", "parseHTML", "inlineDocument", "documentHTML", "selectText", "applyLink", "style", "normalizeInlineStyle", "transformInlineAttributes", "blocks", "selectedBlocks", "paragraph", "preserveRange", "block", "nextTag", "replacement", "copyDirection", "tokens", "coreNames", "createPluginEvent", "name", "token", "assertToken", "event", "corePayload", "key", "payload", "locale", "receipt", "saved", "createEventHub", "listeners", "queue", "registration", "dispatching", "closing", "enqueue", "entry", "failures", "next", "bucket", "listener", "registered", "error", "createHTMLSnapshots", "surface", "sanitize", "sanitizeHTML", "previousInput", "previousHTML", "input", "html", "createLocale", "locale", "translations", "canonical", "prototype", "entries", "key", "value", "localize", "state", "dictionaries", "override", "exact", "base", "language", "message", "dictionary", "paragraphOrigin", "event", "inputType", "isCompositionInput", "ensureDocument", "root", "normalized", "paragraph", "node", "insertFragment", "fragment", "range", "activeRange", "replaceSelectionWithFragment", "replaceListSelectionWithFragment", "block", "hasBlocks", "last", "tailRange", "tail", "next", "selection", "createEditor", "host", "options", "plugins", "plugin", "limit", "schema", "createDocumentSchema", "prepareListSplit", "item", "attributes", "name", "value", "initialDocument", "locale", "createLocale", "container", "surface", "updateLocale", "localize", "editorMessages", "destroyed", "readOnly", "composing", "compositionStart", "canceledComposition", "compositionTail", "compositionUndoRecorded", "pendingInput", "lastInputTime", "lastInputType", "typingOverrides", "typingOffset", "clearTyping", "typingAtCaret", "readTextSelection", "undoStack", "redoStack", "eventHub", "createEventHub", "transactionDepth", "transactionFailed", "transactionError", "pendingSelectionNotification", "pluginAPIs", "disposers", "assertActive", "rejectDuringTransaction", "operation", "error", "events", "payload", "htmlSnapshots", "createHTMLSnapshots", "capture", "bookmark", "restoreTyping", "snapshot", "current", "lastSelection", "clearCompositionTail", "cancelComposition", "rollback", "before", "restoreBookmark", "restoreCurrentDOM", "notifySelection", "saved", "emit", "source", "change", "editor", "failures", "commitMutation", "selectText", "after", "now", "commit", "restore", "notifyCommittedInput", "origin", "committed", "selectionKey", "typingKey", "receipt", "runTransaction", "mutate", "invoke", "result", "previousUndo", "previousRedo", "previousInputTime", "previousInputType", "previousPendingInput", "previousSelection", "changed", "initialRange", "selectionChanged", "registry", "createCommandRegistry", "prepareHTML", "html", "rangeFromBookmark", "prepareSelectionPaste", "prepareListSelectionPaste", "insertPrepared", "handlesCollapsedListBlockPaste", "language", "translations", "keys", "key", "content", "validated", "index", "length", "readFormats", "inlineFormats", "inlineStyles", "normalizeInlineStyle", "applyFormat", "placeCaret", "previous", "api", "listener", "dispose", "listen", "type", "handler", "compositionInput", "handlesSelectionReplacement", "text", "replaceSelection", "listReplacementInput", "listSelectionReplacement", "replaceListSelection", "handlesListForwardDelete", "editListForwardDelete", "wrappedInput", "inspectWrappedListInput", "editWrappedListInput", "handlesListInput", "editListInput", "handlesBlockInput", "editBlockInput", "start", "overrides", "enabled", "nativeEvent", "holder", "listOwned", "blocks", "selectedBlocks", "listState", "indentList", "createDefaultActions", "toolbarMessages", "editor", "createToolbar", "host", "requestedActions", "options", "defaultActions", "defaultKeys", "action", "actions", "inlineStyles", "normalizeInlineStyle", "toolbar", "saved", "disposed", "tabIndex", "cleanups", "buttons", "button", "down", "event", "click", "restoreBookmark", "formats", "mixed", "update", "updateLocale", "state", "localize", "index", "key", "label", "bookmark", "keyboard", "enabled", "direction", "next", "unsubscribe", "change", "unselect", "unlocale", "dispose"]
|
|
3
|
+
"sources": ["../src/document/security.ts", "../src/document/font-family.ts", "../src/document/list-marker.ts", "../src/document/direction.ts", "../src/document/budget.ts", "../src/document/index.ts", "../src/schema/index.ts", "../src/commands/index.ts", "../src/selection/index.ts", "../src/input/inline-source.ts", "../src/input/block-boundaries.ts", "../src/input/replace-selection.ts", "../src/input/inline-fragment.ts", "../src/input/replacement-blocks.ts", "../src/input/paste-replacement.ts", "../src/lists/source-inline.ts", "../src/lists/paste-payload.ts", "../src/lists/quote-selection.ts", "../src/lists/quote-crossing.ts", "../src/lists/selection-boundaries.ts", "../src/lists/replace-selection.ts", "../src/lists/forward-delete.ts", "../src/lists/first-body-backspace.ts", "../src/lists/wrapped-input.ts", "../src/lists/index.ts", "../src/formatting/inline-attributes.ts", "../src/formatting/links.ts", "../src/formatting/inline-document.ts", "../src/formatting/local-inline.ts", "../src/formatting/index.ts", "../src/events/index.ts", "../src/editor/html-snapshots.ts", "../src/localization/index.ts", "../src/editor/create-editor.ts", "../src/ui/toolbar/index.ts"],
|
|
4
|
+
"sourcesContent": ["export const safeURL = (value: string, image: boolean): string | undefined => {\n const trimmed = value.trim();\n if (!trimmed || /[\\u0000-\\u0020\\u007f]/.test(trimmed))\n return;\n // Explicit protocols and relative references only. Never data:, blob:, or script URLs.\n const protocol = /^([a-z][a-z\\d+.-]*):/i.exec(trimmed)?.[1].toLowerCase();\n if (protocol && !(image ? ['http', 'https'] : ['http', 'https', 'mailto', 'tel']).includes(protocol))\n return;\n if (trimmed.startsWith('\\\\') || trimmed.startsWith('//'))\n return;\n return trimmed;\n};\n", "const genericFamilies = new Set(['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded', 'emoji', 'math', 'fangsong']);\nconst wideKeywords = new Set(['inherit', 'initial', 'unset', 'revert', 'revert-layer', 'default']);\nconst identifier = /^-?[a-z_][a-z\\d_-]*$/i;\n\n/** A deliberately small inert CSS subset, shared by HTML and JSON validation. */\nexport const normalizeFontFamily = (input: string): string | undefined => {\n if (!input || input.length > 256 || /[^\\x20-\\x7e]|[\\\\/()*;{}:]/.test(input)) return;\n const parts = input.split(',');\n if (parts.length > 8) return;\n const result: string[] = [];\n for (const part of parts) {\n const value = part.trim();\n const quoted = value.startsWith('\"') || value.startsWith(\"'\");\n if (quoted && (value.length < 3 || value.at(-1) !== value[0])) return;\n const name = (quoted ? value.slice(1, -1) : value).trim().replace(/ +/g, ' ');\n if (!name || !/^[a-z\\d_ -]+$/i.test(name) || wideKeywords.has(name.toLowerCase())) return;\n const generic = genericFamilies.has(name.toLowerCase());\n if (!quoted && name.split(' ').some((word) => !identifier.test(word))) return;\n if (!quoted && generic) result.push(name.toLowerCase());\n else if (!generic && identifier.test(name)) result.push(name);\n else result.push(`\"${name}\"`);\n }\n const normalized = result.join(', ');\n return normalized.length <= 256 ? normalized : undefined;\n};\n", "const markers: Readonly<Record<string, readonly string[]>> = {\n ul: ['disc', 'circle', 'square'],\n ol: ['decimal', 'lower-alpha', 'upper-alpha', 'lower-roman', 'upper-roman'],\n};\n\nexport const normalizeListMarker = (tag: string, value: string): string | undefined => {\n const marker = value.trim().toLowerCase();\n return Object.hasOwn(markers, tag) && markers[tag].includes(marker) ? marker : undefined;\n};\n", "const tags = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'blockquote', 'ul', 'ol', 'li', 'td', 'th']);\n\nexport const normalizeDirection = (tag: string, value: unknown, canonical = false): string | undefined => {\n if (!tags.has(tag) || typeof value !== 'string' || value.length > 20000) return;\n const direction = canonical ? value : value.trim().toLowerCase();\n return direction === 'ltr' || direction === 'rtl' ? direction : undefined;\n};\n\n/** Copy one validated attribute only, never application/schema metadata. */\nexport const copyDirection = (source: HTMLElement, target: HTMLElement): void => {\n const direction = normalizeDirection(source.localName, source.getAttribute('dir'), true);\n if (direction && normalizeDirection(target.localName, direction, true)) target.setAttribute('dir', direction);\n};\n", "import type { DocumentBudget } from './internal-types.js';\n\nexport const maximumHTMLLength = 5000000;\nexport const maximumNodes = 100000;\nexport const maximumDepth = 100;\nconst voidTags = new Set(['br', 'hr', 'img', 'col']);\n\nconst consume = (budget: DocumentBudget, length: number): void => {\n if (length > maximumHTMLLength - budget.htmlLength) throw new RangeError('Document serialized HTML exceeds size limit.');\n budget.htmlLength += length;\n};\nconst escaped = (budget: DocumentBudget, value: string, attribute = false): void => {\n const remaining = maximumHTMLLength - budget.htmlLength;\n let length = value.length;\n if (length > remaining) throw new RangeError('Document serialized HTML exceeds size limit.');\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n length += code === 38 ? 4 : code === 60 || code === 62 ? 3 : code === 160 || (attribute && code === 34) ? 5 : 0;\n if (length > remaining) throw new RangeError('Document serialized HTML exceeds size limit.');\n }\n budget.htmlLength += length;\n};\n\nexport const countText = (budget: DocumentBudget, value: string): void => escaped(budget, value);\nexport const countElement = (budget: DocumentBudget, tag: string, attributes: Record<string, string>): void => {\n consume(budget, voidTags.has(tag) ? tag.length + 2 : 2 * tag.length + 5);\n for (const [name, value] of Object.entries(attributes)) {\n consume(budget, name.length + 4);\n escaped(budget, value, true);\n }\n};\n", "import { safeURL } from './security.js';\nimport { normalizeFontFamily } from './font-family.js';\nimport { normalizeListMarker } from './list-marker.js';\nimport { normalizeDirection } from './direction.js';\nimport { countText, countElement, maximumHTMLLength, maximumNodes, maximumDepth } from './budget.js';\nimport type { DocumentAttributeResolver, DocumentBudget } from './internal-types.js';\nimport type { DocumentTag, TextNode, ElementNode, DocumentNode, EditorDocument } from './types.js';\nexport type { DocumentTag, TextNode, ElementNode, DocumentNode, EditorDocument } from './types.js';\n/** Versioned, framework-independent document tree. Only supported HTML semantics are stored. */\nexport const documentTags = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'code', 'strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'br', 'hr', 'ul', 'ol', 'li', 'img', 'figure', 'figcaption', 'table', 'caption', 'colgroup', 'col', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th'] as const;\nconst tags = new Set<string>(documentTags);\nconst omitted = new Set(['script', 'style', 'iframe', 'object', 'embed', 'svg', 'math', 'template', 'form', 'input', 'button', 'textarea', 'select', 'noscript', 'link', 'meta', 'base']);\nconst aliases: Record<string, string> = { b: 'strong', i: 'em', strike: 's', div: 'p' };\nconst safeStyle = (tag: DocumentTag, value: string): string => {\n const result: string[] = [];\n for (const declaration of value.split(';')) {\n const separator = declaration.indexOf(':');\n if (separator < 0)\n continue;\n const property = declaration.slice(0, separator).trim().toLowerCase();\n if (property === 'list-style-type') {\n const marker = normalizeListMarker(tag, declaration.slice(separator + 1));\n if (marker) result.push(`list-style-type: ${marker}`);\n continue;\n }\n if (property === 'font-family') {\n const family = normalizeFontFamily(declaration.slice(separator + 1).trim());\n if (family) result.push(`font-family: ${family}`);\n continue;\n }\n const content = declaration.slice(separator + 1).trim().toLowerCase();\n const color = /^(#[a-f\\d]{3,8}|[a-z]{1,24}|(?:rgb|rgba|hsl|hsla)\\([\\d\\s.,%+-]+\\))$/;\n const length = /^(?:\\d{1,4}(?:\\.\\d{1,3})?)(?:px|%|em|rem)$/;\n const valid = ['color', 'background-color', 'border-color'].includes(property) ? color.test(content)\n : ['width', 'height', 'font-size'].includes(property) ? length.test(content)\n : property === 'vertical-align' ? ['td', 'th'].includes(tag) && ['top', 'middle', 'bottom'].includes(content)\n : property === 'margin-left' || property === 'margin-right' ? tag === 'table' && ['0px', 'auto'].includes(content)\n : property === 'text-align' ? ['left', 'center', 'right', 'justify'].includes(content)\n : property === 'font-weight' ? /^(bold|normal|[1-9]00)$/.test(content)\n : property === 'font-style' ? ['italic', 'normal'].includes(content)\n : property === 'text-decoration' ? /^(underline|line-through|none)$/.test(content)\n : false;\n if (valid)\n result.push(`${property}: ${content}`);\n }\n return result.join('; ');\n};\n/** Keep ordered-list numbering within the signed DOM integer range. */\nconst orderedListStart = (value: unknown): string | undefined => {\n if (typeof value !== 'string' || value.length > 20000 || !/^[+-]?\\d+$/.test(value.trim())) return;\n const number = Number(value);\n if (Number.isSafeInteger(number) && number >= -2147483648 && number <= 2147483647) return String(number);\n};\nconst attributesFor = (tag: DocumentTag, input: Record<string, unknown>, source: 'html' | 'json', resolve?: DocumentAttributeResolver, originalTag?: string): Record<string, string> => {\n const output: Record<string, string> = {};\n for (const [key, value] of Object.entries(input)) {\n if (key === 'dir') {\n const direction = normalizeDirection(tag, value, source === 'json');\n if (direction) output.dir = direction;\n else if (source === 'json') throw new TypeError('Direction must be canonical ltr or rtl on a supported block.');\n continue;\n }\n if (key === 'start') {\n const clean = tag === 'ol' ? orderedListStart(value) : undefined;\n if (clean !== undefined) output.start = clean;\n else if (source === 'json') throw new TypeError('Ordered-list start must be a signed 32-bit decimal integer string on ol.');\n continue;\n }\n if (key === 'reversed') {\n if (tag === 'ol' && (source === 'html' || value === '')) output.reversed = '';\n else if (source === 'json') throw new TypeError('Reversed must be an empty string on ol.');\n continue;\n }\n if (typeof value !== 'string' || value.length > 20000)\n continue;\n if (key === 'style') {\n const clean = safeStyle(tag, value);\n if (clean)\n output.style = clean;\n }\n else if (key === 'title' || (tag === 'img' && key === 'alt'))\n output[key] = value;\n else if ((tag === 'a' && key === 'href') || (tag === 'img' && key === 'src')) {\n const clean = safeURL(value, tag === 'img');\n if (clean)\n output[key] = clean;\n }\n else if ((['td', 'th'].includes(tag) && ['rowspan', 'colspan'].includes(key)) || (['img', 'col', 'table'].includes(tag) && ['width', 'height', 'span'].includes(key))) {\n if (/^\\d{1,4}$/.test(value) && Number(value) > 0 && Number(value) <= 1000)\n output[key] = value;\n }\n else if (tag === 'a' && key === 'target' && ['_self', '_blank'].includes(value))\n output.target = value;\n else if (tag === 'a' && key === 'rel') {\n const tokens = [...new Set(value.toLowerCase().split(/\\s+/).filter((token) => ['noopener', 'noreferrer'].includes(token)))];\n if (tokens.length)\n output.rel = tokens.join(' ');\n }\n else if (tag === 'th' && key === 'scope' && ['row', 'col', 'rowgroup', 'colgroup'].includes(value))\n output[key] = value;\n }\n if (tag === 'img' && (output.width || output.height)) {\n const dimensions = ['width', 'height'].filter((key) => output[key]);\n const styles = (output.style ?? '').split(';').map((part) => part.trim()).filter((part) => part && !dimensions.includes(part.slice(0, part.indexOf(':')).trim()));\n output.style = [...styles, ...dimensions.map((key) => `${key}: ${output[key]}px`)].join('; ');\n }\n if (tag === 'a' && output.target === '_blank')\n output.rel = 'noopener noreferrer';\n if (resolve) Object.assign(output, resolve(tag, input, source, originalTag));\n else if (source === 'json' && Object.hasOwn(input, 'data-mw-node'))\n throw new TypeError('Unregistered schema node.');\n return output;\n};\nconst readDOM = (node: Node, depth: number, budget: DocumentBudget, resolve?: DocumentAttributeResolver): DocumentNode[] => {\n if (++budget.count > maximumNodes || depth > maximumDepth)\n throw new RangeError('Document exceeds structural limits.');\n if (node.nodeType === 3) {\n const text = node.textContent ?? '';\n countText(budget, text);\n return [{ type: 'text', text }];\n }\n if (node.nodeType !== 1)\n return [];\n const element = node as Element;\n const original = element.localName.toLowerCase();\n if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || omitted.has(original))\n return [];\n const children = [...element.childNodes].flatMap((child) => readDOM(child, depth + 1, budget, resolve));\n const tag = aliases[original] ?? original;\n if (!tags.has(tag)) {\n if (resolve && element.hasAttribute('data-mw-node'))\n resolve(tag, Object.fromEntries([...element.attributes].map((attr) => [attr.name, attr.value])), 'html', original);\n return children;\n }\n const attributes = attributesFor(tag as DocumentTag, Object.fromEntries([...element.attributes].map((attr) => [attr.name, attr.value])), 'html', resolve, original);\n if (tag === 'img' && !attributes.src)\n return [];\n countElement(budget, tag, attributes);\n return [{ type: 'element', tag: tag as DocumentTag, attributes, children }];\n};\nexport const parseHTML = (html: string, resolve?: DocumentAttributeResolver): EditorDocument => {\n if (html.length > maximumHTMLLength)\n throw new RangeError('HTML exceeds the document size limit.');\n // A template is inert: script execution and active resource loading are never used for import.\n const template = document.createElement('template');\n template.innerHTML = html;\n const budget: DocumentBudget = { count: 0, htmlLength: 0 };\n return { version: 1, children: [...template.content.childNodes].flatMap((node) => readDOM(node, 0, budget, resolve)) };\n};\nexport const validateDocument = (input: unknown, resolve?: DocumentAttributeResolver): EditorDocument => {\n if (!input || typeof input !== 'object' || !('version' in input) || input.version !== 1 || !('children' in input) || !Array.isArray(input.children))\n throw new TypeError('Expected a version 1 document.');\n const budget: DocumentBudget = { count: 0, htmlLength: 0 };\n const visit = (value: unknown, depth: number): DocumentNode => {\n if (++budget.count > maximumNodes || depth > maximumDepth)\n throw new RangeError('Document exceeds structural limits.');\n if (!value || typeof value !== 'object' || !('type' in value))\n throw new TypeError('Invalid document node.');\n if (value.type === 'text' && 'text' in value && typeof value.text === 'string') {\n countText(budget, value.text);\n return { type: 'text', text: value.text };\n }\n if (value.type !== 'element' || !('tag' in value) || typeof value.tag !== 'string' || !tags.has(value.tag) || !('children' in value) || !Array.isArray(value.children))\n throw new TypeError('Invalid document element.');\n const attrs = 'attributes' in value && value.attributes && typeof value.attributes === 'object' && !Array.isArray(value.attributes) ? value.attributes : {};\n const attributes = attributesFor(value.tag as DocumentTag, attrs as Record<string, unknown>, 'json', resolve);\n countElement(budget, value.tag, attributes);\n return { type: 'element', tag: value.tag as DocumentTag, attributes, children: children(value.children, depth + 1) };\n };\n const children = (values: unknown[], depth: number): DocumentNode[] => {\n if (values.length > maximumNodes) throw new RangeError('Document children exceed node limit.');\n const output: DocumentNode[] = [];\n for (let index = 0; index < values.length; index++) {\n if (!Object.hasOwn(values, index)) throw new TypeError('Document children must be dense arrays.');\n output.push(visit(values[index], depth));\n }\n return output;\n };\n return { version: 1, children: children(input.children, 0) };\n};\nexport const renderDocument = (value: EditorDocument, owner: Document = document): DocumentFragment => {\n const fragment = owner.createDocumentFragment();\n const append = (parent: Node, node: DocumentNode) => {\n if (node.type === 'text') {\n parent.appendChild(owner.createTextNode(node.text));\n return;\n }\n const element = owner.createElement(node.tag);\n for (const [key, value] of Object.entries(node.attributes))\n element.setAttribute(key, value);\n for (const child of node.children)\n append(element, child);\n parent.appendChild(element);\n };\n for (const node of value.children)\n append(fragment, node);\n return fragment;\n};\nexport const documentHTML = (value: EditorDocument): string => {\n const container = document.createElement('template');\n container.content.append(renderDocument(value, container.content.ownerDocument));\n return container.innerHTML;\n};\nexport const sanitizeHTML = (html: string): string => { return documentHTML(parseHTML(html)); };\n", "import { documentTags, parseHTML, validateDocument, renderDocument, documentHTML } from '../document/index.js';\nimport { safeURL } from '../document/security.js';\nimport type { DocumentAttributeResolver } from '../document/internal-types.js';\nimport type { CompiledAttribute, CompiledSchemaNode } from './internal-types.js';\nimport type { DocumentTag, EditorDocument } from '../document/types.js';\nimport type { DocumentSchema, SchemaContribution } from './types.js';\n\nexport type { DocumentSchema, SchemaAttributeSpec, SchemaNodeSpec, SchemaAttributesSpec, SchemaContribution } from './types.js';\n\nconst inlineTags = ['span', 'strong', 'em', 'u', 's', 'sub', 'sup', 'code'];\nconst blockTags = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'figure', 'figcaption'];\nconst supportedTag = (kind: unknown, tag: unknown): tag is DocumentTag => typeof tag === 'string' && (kind === 'block' ? blockTags : kind === 'inline' ? inlineTags : []).includes(tag);\nconst record = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object' && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);\nconst keysWithin = (value: Record<string, unknown>, allowed: readonly string[]) => {\n if (Object.keys(value).some((key) => !allowed.includes(key))) throw new TypeError('Unknown schema definition field.');\n};\nconst compileAttribute = (input: unknown): CompiledAttribute => {\n if (!record(input)) throw new TypeError('Schema attribute must be an object.');\n if (input.required !== undefined && typeof input.required !== 'boolean') throw new TypeError('Schema attribute required must be boolean.');\n const required = input.required === true;\n let read: (value: string) => string;\n if (input.type === 'text') {\n keysWithin(input, ['type', 'required', 'maxLength']);\n const limit = input.maxLength ?? 256;\n if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 0 || limit > 20000) throw new RangeError('Schema text maxLength must be from 0 to 20000.');\n read = (value) => {\n if (value.length > limit) throw new RangeError('Schema text exceeds its maximum length.');\n return value;\n };\n }\n else if (input.type === 'enum') {\n keysWithin(input, ['type', 'required', 'values']);\n if (!Array.isArray(input.values) || !input.values.length || input.values.length > 64 || input.values.some((value) => typeof value !== 'string' || value.length > 20000))\n throw new TypeError('Schema enum needs 1 to 64 bounded string values.');\n const values = new Set(input.values);\n read = (value) => {\n if (!values.has(value)) throw new TypeError('Invalid schema enum value.');\n return value;\n };\n }\n else if (input.type === 'integer') {\n keysWithin(input, ['type', 'required', 'min', 'max']);\n const min = input.min;\n const max = input.max;\n if (typeof min !== 'number' || typeof max !== 'number' || !Number.isSafeInteger(min) || !Number.isSafeInteger(max) || min > max) throw new RangeError('Schema integer bounds must be safe ordered integers.');\n read = (value) => {\n const number = Number(value);\n if (!/^-?\\d+$/.test(value) || !Number.isSafeInteger(number) || number < min || number > max) throw new RangeError('Schema integer is outside its bounds.');\n return String(number);\n };\n }\n else if (input.type === 'url') {\n keysWithin(input, ['type', 'required']);\n read = (value) => {\n const clean = safeURL(value, false);\n if (clean === undefined) throw new TypeError('Unsupported or unsafe schema URL.');\n return clean;\n };\n }\n else throw new TypeError('Unknown schema attribute type.');\n return Object.freeze({\n required,\n read: (value: unknown) => {\n if (typeof value !== 'string' || value.length > 20000) throw new TypeError('Schema attribute must be a bounded string.');\n return read(value);\n },\n });\n};\n\nexport const createDocumentSchema = (nodes: readonly SchemaContribution[] = []): DocumentSchema => {\n if (!Array.isArray(nodes) || nodes.length > 128) throw new TypeError('Schema contributions must be an array of at most 128 definitions.');\n const registry = new Map<string, CompiledSchemaNode>();\n const names = new Set<string>();\n // The document boundary also resolves unsupported source tags to reject semantic mismatches.\n const tagAttributes = new Map<string, Map<string, CompiledAttribute>>();\n const splitPolicies = new Map<DocumentTag, Map<string, string>>();\n for (const node of nodes) {\n if (!record(node)) throw new TypeError('Schema contribution must be an object.');\n keysWithin(node, node.kind === 'attributes' ? ['name', 'kind', 'tag', 'attributes', 'split'] : ['name', 'kind', 'tag', 'attributes']);\n if (typeof node.name !== 'string' || node.name.length > 128 || !/^[a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*)+$/.test(node.name))\n throw new TypeError('Schema names must be bounded namespaced identifiers.');\n if (names.has(node.name)) throw new Error(`Duplicate schema contribution: ${node.name}`);\n names.add(node.name);\n const nonOwning = node.kind === 'attributes';\n if (nonOwning ? !documentTags.includes(node.tag as DocumentTag) : !supportedTag(node.kind, node.tag))\n throw new TypeError('Schema tag must match its supported kind.');\n const tag = node.tag as DocumentTag;\n const rules = node.attributes ?? (nonOwning ? undefined : {});\n if (!record(rules) || Object.keys(rules).length > 64) throw new TypeError('Schema attributes must be a bounded record.');\n const attributes = new Map<string, CompiledAttribute>();\n for (const [name, rule] of Object.entries(rules)) {\n if (!/^data-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name) || name.startsWith('data-mw-'))\n throw new TypeError('Schema attributes must use non-reserved lowercase data-* names.');\n const compiled = compileAttribute(rule);\n if (nonOwning && compiled.required) throw new TypeError('Non-owning attributes must be optional.');\n attributes.set(name, compiled);\n }\n if (!nonOwning) {\n registry.set(node.name, Object.freeze({ tag, attributes }));\n continue;\n }\n const existing = tagAttributes.get(tag) ?? new Map<string, CompiledAttribute>();\n for (const [name, rule] of attributes) {\n if (existing.has(name)) throw new TypeError(`Duplicate schema tag attribute: ${name}`);\n existing.set(name, rule);\n }\n if (existing.size > 64) throw new RangeError('Schema tag attributes exceed their bound.');\n tagAttributes.set(tag, existing);\n if (node.split !== undefined) {\n if (tag !== 'li' || !record(node.split)) throw new TypeError('Schema split policy must be an LI attribute record.');\n const policies = splitPolicies.get(tag) ?? new Map<string, string>();\n for (const [name, reset] of Object.entries(node.split)) {\n const rule = attributes.get(name);\n if (!rule) throw new TypeError('Schema split policy must reference its declared attribute.');\n policies.set(name, rule.read(reset));\n }\n splitPolicies.set(tag, policies);\n }\n }\n for (const node of registry.values()) {\n if ([...node.attributes.keys()].some((name) => tagAttributes.get(node.tag)?.has(name)))\n throw new TypeError('Non-owning and semantic attribute definitions must not overlap.');\n }\n const resolve: DocumentAttributeResolver = (tag, input, source, originalTag) => {\n const output: Record<string, string> = {};\n for (const [name, rule] of tagAttributes.get(tag) ?? []) {\n if (Object.hasOwn(input, name)) {\n if (originalTag !== undefined && originalTag !== tag) throw new TypeError('Schema attribute does not match its original tag.');\n output[name] = rule.read(input[name]);\n }\n }\n if (!Object.hasOwn(input, 'data-mw-node')) return output;\n const marker = input['data-mw-node'];\n const node = typeof marker === 'string' ? registry.get(marker) : undefined;\n if (typeof marker !== 'string' || !node) {\n if (source === 'json') throw new TypeError('Unregistered schema node.');\n return output;\n }\n if (tag !== node.tag || (originalTag !== undefined && originalTag !== node.tag)) throw new TypeError('Schema node marker does not match its tag.');\n output['data-mw-node'] = marker;\n for (const [name, rule] of node.attributes) {\n if (Object.hasOwn(input, name)) output[name] = rule.read(input[name]);\n else if (rule.required) throw new TypeError(`Missing required schema attribute: ${name}`);\n }\n return output;\n };\n const validate: DocumentSchema['validateDocument'] = (input) => validateDocument(input, resolve);\n const parse: DocumentSchema['parseHTML'] = (html) => parseHTML(html, resolve);\n return Object.freeze({\n attributesForSplit: (tag: DocumentTag, input: Readonly<Record<string, string>>) => {\n if (!documentTags.includes(tag) || !record(input)) throw new TypeError('Expected a safe tag and attribute record.');\n const output: Record<string, string> = {};\n for (const [name, reset] of splitPolicies.get(tag) ?? []) {\n if (Object.hasOwn(input, name)) {\n tagAttributes.get(tag)!.get(name)!.read(input[name]);\n output[name] = reset;\n }\n }\n return output;\n },\n parseHTML: parse,\n validateDocument: validate,\n renderDocument: (value: EditorDocument) => renderDocument(validate(value)),\n documentHTML: (value: EditorDocument) => documentHTML(validate(value)),\n sanitizeHTML: (html: string) => documentHTML(parse(html)),\n });\n};\n", "import type { CommandRegistry, CommandRegistryOptions, RegisteredCommand } from './internal-types.js';\nimport type { EditorCommand, EditorCommandDefinition, EditorCommandState, EditorCommands } from './types.js';\n\nexport type { EditorCommand, EditorCommandDefinition, EditorCommandState, EditorCommands } from './types.js';\n\nconst tokens = /* @__PURE__ */ new WeakSet<object>();\n\nexport const createEditorCommand = <T>(name: string): EditorCommand<T> => {\n if (typeof name !== 'string' || !name.trim() || name.length > 200)\n throw new TypeError('Expected a command name with 1\u2013200 characters.');\n const command = Object.freeze({ name }) as EditorCommand<T>;\n tokens.add(command);\n return command;\n};\n\nconst assertToken = (command: unknown): object => {\n if (!command || typeof command !== 'object' || !tokens.has(command))\n throw new TypeError('Expected an editor command token.');\n return command;\n};\n\nconst synchronous = (callback: unknown): void => {\n if (typeof callback !== 'function' || callback.constructor.name === 'AsyncFunction')\n throw new TypeError('Command callbacks must be synchronous functions.');\n};\n\nconst rejectThenable = (value: unknown): void => {\n if (value && (typeof value === 'object' || typeof value === 'function') && typeof (value as { then?: unknown }).then === 'function') {\n if (value instanceof Promise)\n void value.catch(() => {});\n throw new TypeError('Command callbacks must not return a thenable.');\n }\n};\n\nexport const createCommandRegistry = (options: CommandRegistryOptions): CommandRegistry => {\n const entries = new Map<object, RegisteredCommand>();\n let disposed = false;\n const assertActive = () => {\n options.assertActive();\n if (disposed)\n throw new Error('Editor commands have been destroyed.');\n };\n const resolve = <T>(command: EditorCommand<T>): RegisteredCommand => {\n assertActive();\n const entry = entries.get(assertToken(command));\n if (!entry)\n throw new Error(`Command is not registered: ${command.name}`);\n return entry;\n };\n const stateValue = (callback: RegisteredCommand['isEnabled'], fallback: boolean): boolean => {\n if (!callback)\n return fallback;\n const value = callback(options.editor());\n rejectThenable(value);\n if (typeof value !== 'boolean')\n throw new TypeError('Command state callbacks must return a boolean.');\n return value;\n };\n const enabled = (entry: RegisteredCommand): boolean => !options.editor().isReadOnly() && !options.isComposing() && stateValue(entry.isEnabled, true);\n const commands: EditorCommands = {\n register: <T>(command: EditorCommand<T>, definition: EditorCommandDefinition<NoInfer<T>>): (() => void) => {\n assertActive();\n const key = assertToken(command);\n if (entries.has(key))\n throw new Error(`Command is already registered: ${command.name}`);\n if (!definition || typeof definition !== 'object')\n throw new TypeError('Expected a command definition.');\n const { validate, execute, isEnabled, isActive, isMixed } = definition;\n synchronous(validate);\n synchronous(execute);\n for (const callback of [isEnabled, isActive, isMixed]) {\n if (callback !== undefined)\n synchronous(callback);\n }\n const entry: RegisteredCommand = {\n validate,\n execute: (editor, payload) => execute(editor, payload as T),\n isEnabled,\n isActive,\n isMixed,\n };\n entries.set(key, entry);\n return () => {\n if (entries.get(key) === entry)\n entries.delete(key);\n };\n },\n execute: (command, payload): boolean => {\n const entry = resolve(command);\n if (!enabled(entry))\n return false;\n const editor = options.editor();\n editor.transact(() => {\n const validated = entry.validate(payload);\n rejectThenable(validated);\n // Keep the original return value so transact can reject thenables atomically.\n return entry.execute(editor, validated);\n });\n return true;\n },\n getState: (command): EditorCommandState => {\n const entry = resolve(command);\n return {\n enabled: enabled(entry),\n active: stateValue(entry.isActive, false),\n mixed: stateValue(entry.isMixed, false),\n };\n },\n };\n return {\n commands,\n destroy: () => {\n if (disposed)\n return;\n disposed = true;\n entries.clear();\n },\n };\n};\n", "import type { TextSelection, SelectionBookmark } from './types.js';\nexport type { TextSelection, SelectionBookmark } from './types.js';\nexport const activeRange = (root: HTMLElement): Range | undefined => {\n const selection = root.ownerDocument.getSelection();\n if (!selection?.rangeCount)\n return;\n const range = selection.getRangeAt(0);\n if (!root.contains(range.startContainer) || !root.contains(range.endContainer))\n return;\n return range.cloneRange();\n};\nconst nodePath = (root: Node, target: Node): number[] => {\n const result: number[] = [];\n let node = target;\n while (node !== root && node.parentNode) {\n result.unshift([...node.parentNode.childNodes].indexOf(node as ChildNode));\n node = node.parentNode;\n }\n return result;\n};\n// Empty text nodes disappear in HTML snapshots. Persist their parent boundary.\nconst stableBoundary = (node: Node, offset: number): [Node, number] => {\n if (node.nodeType === 3 && node.textContent === '' && node.parentNode)\n return [node.parentNode, [...node.parentNode.childNodes].indexOf(node as ChildNode)];\n return [node, offset];\n};\nexport const bookmark = (root: HTMLElement): SelectionBookmark | undefined => {\n const range = activeRange(root);\n if (!range)\n return;\n const selection = root.ownerDocument.getSelection()!;\n const [start, startOffset] = stableBoundary(range.startContainer, range.startOffset);\n const [end, endOffset] = stableBoundary(range.endContainer, range.endOffset);\n return { start: nodePath(root, start), startOffset, end: nodePath(root, end), endOffset, backward: !range.collapsed && selection.anchorNode === range.endContainer && selection.anchorOffset === range.endOffset };\n};\n/** Resolve a remembered selection without changing focus or the document selection. */\nexport const rangeFromBookmark = (root: HTMLElement, saved: SelectionBookmark | undefined): Range | undefined => {\n if (!saved)\n return;\n const resolve = (path: number[]) => path.reduce<Node>((node, index) => node.childNodes[index] ?? node, root);\n const start = resolve(saved.start);\n const end = resolve(saved.end);\n const limit = (node: Node, offset: number) => Math.min(offset, node.nodeType === 3 ? (node.textContent?.length ?? 0) : node.childNodes.length);\n const startOffset = limit(start, saved.startOffset);\n const endOffset = limit(end, saved.endOffset);\n const range = root.ownerDocument.createRange();\n range.setStart(start, startOffset);\n range.setEnd(end, endOffset);\n return range;\n};\nexport const restoreBookmark = (root: HTMLElement, saved: SelectionBookmark | undefined): void => {\n const range = rangeFromBookmark(root, saved);\n const selection = root.ownerDocument.getSelection();\n if (!range || !saved || !selection) return;\n if (saved.backward)\n selection.setBaseAndExtent(range.endContainer, range.endOffset, range.startContainer, range.startOffset);\n else\n selection.setBaseAndExtent(range.startContainer, range.startOffset, range.endContainer, range.endOffset);\n};\nexport const readTextSelection = (root: HTMLElement): TextSelection | undefined => {\n const range = activeRange(root);\n if (!range)\n return;\n const prefix = root.ownerDocument.createRange();\n prefix.selectNodeContents(root);\n prefix.setEnd(range.startContainer, range.startOffset);\n return { index: prefix.toString().length, length: range.toString().length };\n};\nexport const selectText = (root: HTMLElement, index: number, length = 0): void => {\n if (![index, length].every((value) => Number.isInteger(value) && value >= 0))\n throw new RangeError('Selection offsets must be non-negative integers.');\n const walker = root.ownerDocument.createTreeWalker(root, 4);\n const nodes: Text[] = [];\n let current: Node | null;\n while ((current = walker.nextNode()))\n nodes.push(current as Text);\n const locate = (offset: number): [\n Node,\n number\n ] => {\n for (const node of nodes) {\n if (offset <= node.length)\n return [node, offset];\n offset -= node.length;\n }\n const last = nodes.at(-1);\n return last ? [last, last.length] : [root.querySelector('p,h1,h2,h3,h4,h5,h6,li,blockquote,pre') ?? root, 0];\n };\n const [start, startOffset] = locate(index);\n const [end, endOffset] = locate(index + length);\n const range = root.ownerDocument.createRange();\n range.setStart(start, startOffset);\n range.setEnd(end, endOffset);\n root.focus({ preventScroll: true });\n const selection = root.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n};\nexport const placeCaret = (element: HTMLElement, end = false): void => {\n const range = element.ownerDocument.createRange();\n range.selectNodeContents(element);\n range.collapse(!end);\n const selection = element.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n};\n/** Keep actual DOM positions while moving blocks, including empty list items. */\nexport const preserveRange = (root: HTMLElement, mutate: () => void): void => {\n const range = activeRange(root);\n if (!range)\n return;\n const native = root.ownerDocument.getSelection()!;\n const backward = !range.collapsed && native.anchorNode === range.endContainer && native.anchorOffset === range.endOffset;\n const start = root.ownerDocument.createComment('mw-start');\n const end = range.collapsed ? undefined : root.ownerDocument.createComment('mw-end');\n if (end) {\n const tail = range.cloneRange();\n tail.collapse(false);\n tail.insertNode(end);\n }\n const head = range.cloneRange();\n head.collapse(true);\n head.insertNode(start);\n try {\n mutate();\n if (root.contains(start) && (!end || root.contains(end))) {\n const next = root.ownerDocument.createRange();\n next.setStartBefore(start);\n if (end)\n next.setEndBefore(end);\n else\n next.collapse(true);\n start.remove();\n end?.remove();\n root.normalize();\n if (backward)\n native.setBaseAndExtent(next.endContainer, next.endOffset, next.startContainer, next.startOffset);\n else {\n native.removeAllRanges();\n native.addRange(next);\n }\n }\n }\n finally {\n start.remove();\n end?.remove();\n }\n};\n", "const inlineTags = new Set(['strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'code', 'br']);\n\n/** Shared ordinary-block inline shape; callers retain their own ownership and semantic guards. */\nexport const inlineSourceChildren = (element: Element): boolean => [...element.childNodes].every((node) => node.nodeType === 3\n || (node instanceof HTMLElement && inlineTags.has(node.localName) && inlineSourceChildren(node)));\n", "import { inlineSourceChildren as inlineTree } from './inline-source.js';\nimport { activeRange, placeCaret } from '../selection/index.js';\nimport { copyDirection } from '../document/direction.js';\n\nconst blockTags = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\nconst parentOf = (node: Node): Element | null => node.nodeType === 1 ? node as Element : node.parentElement;\nconst editableBlock = (root: HTMLElement, node: Node): HTMLElement | undefined => {\n const block = parentOf(node)?.closest<HTMLElement>('p,h1,h2,h3,h4,h5,h6');\n if (!(block instanceof HTMLElement) || block.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !root.contains(block) || block.closest('li,figure,pre') || !inlineTree(block)) return;\n const parent = block.parentElement;\n if (parent !== root && !['blockquote', 'td', 'th'].includes(parent?.localName ?? '')) return;\n return block;\n};\nconst hasContent = (fragment: DocumentFragment): boolean => Boolean(fragment.textContent || fragment.querySelector('br'));\nconst selectedBlock = (root: HTMLElement): HTMLElement | undefined => {\n const range = activeRange(root);\n if (!range) return;\n const block = editableBlock(root, range.startContainer);\n return block && editableBlock(root, range.endContainer) === block ? block : undefined;\n};\nconst atEdge = (block: HTMLElement, range: Range, end: boolean): boolean => {\n if (!block.textContent && block.querySelectorAll('br').length <= 1) return true;\n const remainder = block.ownerDocument.createRange();\n remainder.selectNodeContents(block);\n if (end) remainder.setStart(range.endContainer, range.endOffset);\n else remainder.setEnd(range.startContainer, range.startOffset);\n // An actual line break is content even though Range.toString omits it.\n const fragment = remainder.cloneContents();\n return !hasContent(fragment);\n};\nconst siblingBlock = (root: HTMLElement, block: HTMLElement, forward: boolean): HTMLElement | undefined => {\n if (block.hasAttribute('data-mw-node')) return;\n const sibling = forward ? block.nextSibling : block.previousSibling;\n return sibling instanceof HTMLElement && !sibling.hasAttribute('data-mw-node') && blockTags.has(sibling.localName) && editableBlock(root, sibling) === sibling ? sibling : undefined;\n};\n\nexport const handlesBlockInput = (root: HTMLElement, inputType: string): boolean => {\n const block = selectedBlock(root);\n const range = activeRange(root);\n if (!block || !range) return false;\n if (inputType === 'insertParagraph' || inputType === 'insertLineBreak') return true;\n if (!range.collapsed) return false;\n if (inputType === 'deleteContentBackward') return atEdge(block, range, false);\n if (inputType === 'deleteContentForward') return atEdge(block, range, true);\n return false;\n};\n\n/** Called inside the editor's existing transaction after handlesBlockInput succeeds. */\nexport const editBlockInput = (root: HTMLElement, inputType: string): void => {\n const block = selectedBlock(root);\n const range = activeRange(root);\n if (!block || !range || !handlesBlockInput(root, inputType)) return;\n const document = root.ownerDocument;\n if (inputType === 'insertParagraph') {\n range.deleteContents();\n const tailRange = document.createRange();\n tailRange.selectNodeContents(block);\n tailRange.setStart(range.startContainer, range.startOffset);\n const tail = tailRange.extractContents();\n const emptyHeading = block.localName !== 'p' && !block.textContent && !tail.textContent && block.querySelectorAll('br').length + tail.querySelectorAll('br').length <= 1;\n const headingEnd = block.localName !== 'p' && (!hasContent(tail) || emptyHeading);\n if (emptyHeading && !block.hasAttribute('data-mw-node')) {\n const paragraph = document.createElement('p');\n for (const attribute of block.attributes)\n if (attribute.name !== 'dir') paragraph.setAttribute(attribute.name, attribute.value);\n copyDirection(block, paragraph);\n paragraph.append(document.createElement('br'));\n block.replaceWith(paragraph);\n placeCaret(paragraph);\n return;\n }\n const next = headingEnd ? document.createElement('p') : block.cloneNode(false) as HTMLElement;\n if (headingEnd) {\n // A semantic identity is valid only on its declared wrapper, never on an exit paragraph.\n for (const attribute of block.attributes) {\n if (!attribute.name.startsWith('data-') && attribute.name !== 'dir') next.setAttribute(attribute.name, attribute.value);\n }\n copyDirection(block, next);\n }\n next.append(tail);\n if (!next.textContent && !next.querySelector('br')) next.replaceChildren(document.createElement('br'));\n if (!block.textContent && !block.querySelector('br')) block.replaceChildren(document.createElement('br'));\n block.after(next);\n placeCaret(next);\n return;\n }\n if (inputType === 'insertLineBreak') {\n range.deleteContents();\n if (!block.textContent && block.querySelectorAll('br').length <= 1) {\n block.replaceChildren();\n range.selectNodeContents(block);\n range.collapse(true);\n }\n const terminal = atEdge(block, range, true);\n const lineBreak = document.createElement('br');\n range.insertNode(lineBreak);\n if (terminal) lineBreak.after(document.createElement('br'));\n const caret = document.createRange();\n caret.setStartAfter(lineBreak);\n caret.collapse(true);\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n return;\n }\n const forward = inputType === 'deleteContentForward';\n const sibling = siblingBlock(root, block, forward);\n if (!sibling) return;\n const left = forward ? block : sibling;\n const right = forward ? sibling : block;\n if (!left.textContent && left.childNodes.length === 1 && left.firstChild instanceof HTMLBRElement) left.replaceChildren();\n if (!right.textContent && right.childNodes.length === 1 && right.firstChild instanceof HTMLBRElement) right.replaceChildren();\n const join = document.createRange();\n join.selectNodeContents(left);\n join.collapse(false);\n left.append(...right.childNodes);\n right.remove();\n if (!left.childNodes.length) left.append(document.createElement('br'));\n left.normalize();\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(join);\n};\n", "import { inlineSourceChildren as inlineTree } from './inline-source.js';\nimport { activeRange } from '../selection/index.js';\nimport type { SelectionReplacement, CutSelectionReplacement } from './internal-types.js';\n\nconst leafTags = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\nconst ordinaryLeaf = (root: HTMLElement, node: Node): HTMLElement | undefined => {\n const parent = node.nodeType === 1 ? node as Element : node.parentElement;\n const leaf = parent?.closest<HTMLElement>('p,h1,h2,h3,h4,h5,h6');\n if (!(leaf instanceof HTMLElement) || !root.contains(leaf) || leaf.hasAttribute('data-mw-node') || leaf.closest('li,figure,pre') || !inlineTree(leaf)) return;\n if (leaf.parentElement !== root && !['blockquote', 'td', 'th'].includes(leaf.parentElement?.localName ?? '')) return;\n return leaf;\n};\n\nconst selectedLeaves = (root: HTMLElement, range: Range): HTMLElement[] | undefined => {\n const left = ordinaryLeaf(root, range.startContainer);\n const right = ordinaryLeaf(root, range.endContainer);\n if (!left || !right || left === right || left.parentElement !== right.parentElement) return;\n const leaves = [left];\n let next: ChildNode | null = left.nextSibling;\n while (next) {\n if (!(next instanceof HTMLElement) || !leafTags.has(next.localName) || ordinaryLeaf(root, next) !== next) return;\n leaves.push(next);\n if (next === right) return leaves;\n next = next.nextSibling;\n }\n return;\n};\n\nexport const handlesSelectionReplacement = (root: HTMLElement, inputType: string, data: string | null): boolean => {\n if (inputType !== 'deleteContentBackward' && inputType !== 'deleteContentForward' && !(inputType === 'insertText' && typeof data === 'string')) return false;\n return Boolean(selectionReplacement(root));\n};\n\nexport const selectionReplacement = (root: HTMLElement, range: Range | undefined = activeRange(root)): SelectionReplacement | undefined => {\n const leaves = range && !range.collapsed ? selectedLeaves(root, range) : undefined;\n return range && leaves ? { range, leaves } : undefined;\n};\n\n/** Shared live cut, called only after eligibility and detached import validation. */\nexport const cutSelectionReplacement = ({ range, leaves, contentRoots }: SelectionReplacement): CutSelectionReplacement => {\n const left = contentRoots?.left ?? leaves[0];\n const right = contentRoots?.right ?? leaves[leaves.length - 1];\n const document = left.ownerDocument;\n const emptyLeft = !left.textContent && left.querySelectorAll('br').length <= 1;\n const emptyRight = !right.textContent && right.querySelectorAll('br').length <= 1;\n // deleteContents may collapse its own range outside a partially selected mark.\n // A separate collapsed range retains the actual starting inline context.\n const caret = range.cloneRange();\n caret.collapse(true);\n\n const tailRange = document.createRange();\n tailRange.selectNodeContents(right);\n tailRange.setStart(range.endContainer, range.endOffset);\n const tail = tailRange.extractContents();\n if (emptyRight) {\n for (const placeholder of tail.querySelectorAll('br')) placeholder.remove();\n }\n\n const cut = document.createRange();\n cut.selectNodeContents(left);\n cut.setStart(range.startContainer, range.startOffset);\n cut.deleteContents();\n if (emptyLeft) {\n // Remove only the placeholder, keeping an empty starting mark/link as text affinity.\n for (const placeholder of left.querySelectorAll('br')) placeholder.remove();\n }\n for (const leaf of leaves.slice(1)) leaf.remove();\n return { left, right, tail, caret };\n};\n\nexport const ensureReplacementPlaceholder = (leaf: HTMLElement, caret: Range): void => {\n if (!leaf.textContent && !leaf.querySelector('br,img')) {\n // An empty semantic inline still owns metadata; keep it and its insertion context.\n const placeholder = leaf.ownerDocument.createElement('br');\n caret.insertNode(placeholder);\n caret.setStartBefore(placeholder);\n caret.collapse(true);\n }\n};\n\nexport const finishSelectionReplacement = (leaf: HTMLElement, caret: Range): void => {\n ensureReplacementPlaceholder(leaf, caret);\n leaf.normalize();\n const selection = leaf.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n};\n\n/** Replace only ordinary sibling leaves inside the editor's validated transaction. */\nexport const replaceSelection = (root: HTMLElement, text: string): void => {\n const selected = selectionReplacement(root);\n if (!selected) return;\n const { left, tail, caret } = cutSelectionReplacement(selected);\n if (text) {\n const inserted = root.ownerDocument.createTextNode(text);\n caret.insertNode(inserted);\n caret.setStart(inserted, inserted.length);\n caret.collapse(true);\n }\n left.append(tail);\n finishSelectionReplacement(left, caret);\n};\n", "/** Insert a prepared inline fragment without nesting its anchors in a starting link. */\nexport const insertInlineFragment = (left: HTMLElement, caret: Range, fragment: DocumentFragment): void => {\n const parent = caret.startContainer.nodeType === 1 ? caret.startContainer as Element : caret.startContainer.parentElement;\n const anchor = parent?.closest('a');\n if (fragment.querySelector('a') && anchor && left.contains(anchor)) {\n caret.setStartAfter(anchor);\n caret.collapse(true);\n }\n const last = fragment.lastChild;\n if (!last) return;\n caret.insertNode(fragment);\n if (last.nodeType === 3) caret.setStart(last, last.textContent!.length);\n else caret.setStartAfter(last);\n caret.collapse(true);\n};\n", "import { ensureReplacementPlaceholder, finishSelectionReplacement } from './replace-selection.js';\nimport { insertInlineFragment } from './inline-fragment.js';\nimport type { CutSelectionReplacement } from './internal-types.js';\n\nconst stripPlaceholder = (body: HTMLElement): void => {\n if (!body.textContent && !body.querySelector('img') && body.querySelectorAll('br').length <= 1) {\n for (const placeholder of body.querySelectorAll('br')) placeholder.remove();\n }\n};\n\nexport const ensureBodyPlaceholder = (body: HTMLElement): Range => {\n const caret = body.ownerDocument.createRange();\n caret.selectNodeContents(body);\n caret.collapse(true);\n ensureReplacementPlaceholder(body, caret);\n return caret;\n};\n\n/** Compose already validated body roots; source eligibility and branch placement stay caller-owned. */\nexport const insertReplacementBlocks = ({ left, tail, caret }: CutSelectionReplacement, blocks: HTMLElement[]): void => {\n const first = blocks[0];\n const last = blocks[blocks.length - 1];\n stripPlaceholder(first);\n const prefix = left.ownerDocument.createDocumentFragment();\n prefix.append(...first.childNodes);\n first.remove();\n insertInlineFragment(left, caret, prefix);\n left.after(...blocks.slice(1));\n ensureReplacementPlaceholder(left, caret);\n left.normalize();\n for (const middle of blocks.slice(1, -1)) ensureBodyPlaceholder(middle);\n stripPlaceholder(last);\n const end = left.ownerDocument.createRange();\n end.selectNodeContents(last);\n end.collapse(false);\n last.append(tail);\n finishSelectionReplacement(last, end);\n};\n", "import { selectionReplacement, cutSelectionReplacement, ensureReplacementPlaceholder, finishSelectionReplacement } from './replace-selection.js';\nimport { insertInlineFragment } from './inline-fragment.js';\nimport { ensureBodyPlaceholder, insertReplacementBlocks } from './replacement-blocks.js';\n\nconst inlineTags = new Set(['strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'code', 'br', 'img']);\nconst leafTags = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\nconst blockTags = new Set([...leafTags, 'blockquote', 'pre', 'hr', 'ul', 'ol', 'table', 'figure']);\nconst inlineNode = (node: Node): boolean => node.nodeType === 3 || (node instanceof HTMLElement && inlineTags.has(node.localName));\nconst ordinaryPayloadLeaf = (node: Node): node is HTMLElement => node instanceof HTMLElement && leafTags.has(node.localName) && !node.hasAttribute('data-mw-node') && [...node.childNodes].every(inlineNode);\n/** Validate/normalize a detached payload only when the new sibling-range path owns it. */\nexport const prepareSelectionPaste = (root: HTMLElement, fragment: DocumentFragment, range?: Range): void => {\n const selected = selectionReplacement(root, range);\n if (!selected) return;\n if (fragment.querySelector('table table') || (selected.leaves[0].closest('td,th') && fragment.querySelector('table')))\n throw new TypeError('Nested table insertion is unsupported for this selection.');\n for (const node of fragment.childNodes) {\n if (!inlineNode(node) && (!(node instanceof HTMLElement) || !blockTags.has(node.localName)))\n throw new TypeError('Unsupported root structure for sibling selection insertion.');\n }\n for (const element of fragment.querySelectorAll('*')) {\n if ((inlineTags.has(element.localName) || leafTags.has(element.localName)) && ![...element.childNodes].every(inlineNode))\n throw new TypeError('A phrasing wrapper cannot contain pasted blocks.');\n }\n const hasBlocks = [...fragment.childNodes].some((node) => !inlineNode(node));\n if (hasBlocks) {\n for (const node of [...fragment.childNodes]) {\n if (node.nodeType === 3 && /^[\\t\\n\\f\\r ]*$/.test(node.textContent ?? '')) node.remove();\n }\n }\n};\n\nconst meaningfulTail = (tail: DocumentFragment): boolean => Boolean(tail.textContent) || [...tail.querySelectorAll('*')].some((node) => node.attributes.length || ['br', 'img'].includes(node.localName));\n\n/** A validated fragment replaces only the accepted ordinary sibling range. */\nexport const replaceSelectionWithFragment = (root: HTMLElement, fragment: DocumentFragment): boolean => {\n const selected = selectionReplacement(root);\n if (!selected) return false;\n // Trusted focus listeners may have changed the context since detached preflight.\n prepareSelectionPaste(root, fragment, selected.range);\n const nodes = [...fragment.childNodes];\n const singleParagraph = nodes.length === 1 && ordinaryPayloadLeaf(nodes[0]) && nodes[0].localName === 'p';\n const inline = nodes.every(inlineNode) || singleParagraph;\n const leaves = nodes.length > 1 && nodes.every(ordinaryPayloadLeaf);\n const cut = cutSelectionReplacement(selected);\n const { left, right, tail, caret } = cut;\n if (inline) {\n if (singleParagraph) fragment.replaceChildren(...nodes[0].childNodes);\n insertInlineFragment(left, caret, fragment);\n left.append(tail);\n finishSelectionReplacement(left, caret);\n return true;\n }\n if (leaves) {\n insertReplacementBlocks(cut, nodes as HTMLElement[]);\n return true;\n }\n // Mixed root inline runs become proper sibling paragraphs, never children of a mark.\n let paragraph: HTMLParagraphElement | undefined;\n for (const node of [...fragment.childNodes]) {\n if (inlineNode(node)) {\n if (!paragraph) {\n paragraph = root.ownerDocument.createElement('p');\n fragment.insertBefore(paragraph, node);\n }\n paragraph.append(node);\n }\n else paragraph = undefined;\n }\n const last = fragment.lastChild!;\n const inserted = [...fragment.childNodes];\n left.after(fragment);\n ensureReplacementPlaceholder(left, caret);\n left.normalize();\n for (const node of inserted) {\n if (node instanceof HTMLElement && leafTags.has(node.localName)) ensureBodyPlaceholder(node);\n }\n const suffix = meaningfulTail(tail) ? right : root.ownerDocument.createElement('p');\n suffix.replaceChildren(tail);\n last.after(suffix);\n finishSelectionReplacement(suffix, ensureBodyPlaceholder(suffix));\n return true;\n};\n", "const inlineTags = new Set(['strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'code', 'br']);\n\n/** Editable list sources exclude images while requiring the HTML namespace at every level. */\nexport const sourceInlineNode = (node: Node): boolean => node.nodeType === 3 || (node instanceof HTMLElement\n && node.namespaceURI === 'http://www.w3.org/1999/xhtml' && inlineTags.has(node.localName)\n && [...node.childNodes].every(sourceInlineNode));\n", "const inlineTags = new Set(['strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'code', 'br', 'img']);\n\nexport const inlinePayloadNode = (node: Node): boolean => node.nodeType === 3 || (node instanceof HTMLElement && node.namespaceURI === 'http://www.w3.org/1999/xhtml' && inlineTags.has(node.localName) && [...node.childNodes].every(inlinePayloadNode));\n\nexport const formattingWhitespace = (node: Node): boolean => node.nodeType === 3 && /^[\\t\\n\\f\\r ]*$/.test(node.textContent ?? '');\n\nexport const ordinaryPayloadBody = (node: Node): node is HTMLElement => node instanceof HTMLElement\n && node.namespaceURI === 'http://www.w3.org/1999/xhtml'\n && /^(p|h[1-6])$/.test(node.localName) && !node.hasAttribute('data-mw-node')\n && [...node.childNodes].every(inlinePayloadNode);\n\nexport const quoteBodyBlocks = (quote: HTMLElement): HTMLElement[] | undefined => {\n const nodes = [...quote.childNodes].filter((node) => !formattingWhitespace(node));\n return nodes.length > 0 && nodes.every(ordinaryPayloadBody) ? nodes : undefined;\n};\n\n/** Read-only validation shared by detached payloads and opaque paste sources. */\nexport const isOrdinaryQuote = (node: Node): node is HTMLElement => node instanceof HTMLElement\n && node.namespaceURI === 'http://www.w3.org/1999/xhtml' && node.localName === 'blockquote'\n && !node.hasAttribute('data-mw-node')\n && ([...node.childNodes].every(inlinePayloadNode) || Boolean(quoteBodyBlocks(node)));\n", "import { sourceInlineNode } from './source-inline.js';\nimport { formattingWhitespace, isOrdinaryQuote } from './paste-payload.js';\nimport type { QuoteBodyPoint, QuotePasteContext } from './internal-types.js';\n\nconst sourceBody = (node: Node): node is HTMLElement => node instanceof HTMLElement\n && node.namespaceURI === 'http://www.w3.org/1999/xhtml' && /^(p|h[1-6])$/.test(node.localName)\n && !node.hasAttribute('data-mw-node') && [...node.childNodes].every(sourceInlineNode);\n\n/** A source quote being edited has stricter content than an opaque neighbor. */\nexport const quoteSourceBodies = (quote: HTMLElement): HTMLElement[] | undefined => {\n if (!isOrdinaryQuote(quote)) return;\n const children = [...quote.childNodes];\n if (children.every(sourceInlineNode)) return [quote];\n const blocks = children.filter((node) => !formattingWhitespace(node));\n return blocks.length && blocks.every(sourceBody) ? blocks : undefined;\n};\n\n/** Only a quote owned directly by this item can form the bounded inner scope. */\nexport const directQuoteAt = (item: HTMLElement, node: Node): HTMLElement | undefined => {\n const element = node instanceof Element ? node : node.parentElement;\n const quote = element?.closest('blockquote');\n return quote instanceof HTMLElement && quote.parentElement === item ? quote : undefined;\n};\n\nconst quoteBodyPoint = (quote: HTMLElement, bodies: HTMLElement[], range: Range, end: boolean): QuoteBodyPoint | undefined => {\n const point = range.cloneRange();\n point.collapse(!end);\n const node = point.startContainer;\n if (bodies[0] === quote) return { body: quote, range: point };\n const contained = bodies.find((body) => body === node || body.contains(node));\n if (contained) return { body: contained, range: point };\n const children = [...quote.childNodes];\n let offset: number;\n if (node === quote) offset = point.startOffset;\n else if (node.parentNode === quote && formattingWhitespace(node)) offset = children.indexOf(node as ChildNode);\n else return;\n const next = children.slice(offset).find((child): child is HTMLElement => bodies.includes(child as HTMLElement));\n const previous = children.slice(0, offset).reverse().find((child): child is HTMLElement => bodies.includes(child as HTMLElement));\n const body = end ? previous ?? bodies[0] : next ?? bodies[bodies.length - 1];\n point.selectNodeContents(body);\n point.collapse(end ? !previous : Boolean(next));\n return { body, range: point };\n};\n\n/** Resolve one actual quote endpoint using the same child/gap affinity as inner paste. */\nexport const quoteEndpointPoint = (quote: HTMLElement, range: Range, end: boolean): QuoteBodyPoint | undefined => {\n const node = end ? range.endContainer : range.startContainer;\n if (!quote.contains(node)) return;\n const bodies = quoteSourceBodies(quote);\n return bodies && quoteBodyPoint(quote, bodies, range, end);\n};\n\n/** Inspect without normalizing the actual quote or changing the active selection. */\nexport const quotePasteContext = (quote: HTMLElement, range: Range): QuotePasteContext | undefined => {\n if (!quote.contains(range.startContainer) || !quote.contains(range.endContainer)) return;\n const children = [...quote.childNodes];\n const bodies = quoteSourceBodies(quote);\n if (!bodies) return;\n const start = quoteBodyPoint(quote, bodies, range, false);\n const end = range.collapsed ? start : quoteBodyPoint(quote, bodies, range, true);\n if (!start || !end) return;\n const normalized = range.cloneRange();\n normalized.setStart(start.range.startContainer, start.range.startOffset);\n normalized.setEnd(end.range.startContainer, end.range.startOffset);\n const from = bodies.indexOf(start.body);\n const to = bodies.indexOf(end.body);\n // A noncollapsed formatting-gap selection may resolve to reversed body edges.\n if (from > to || start.range.compareBoundaryPoints(Range.START_TO_START, end.range) > 0) return;\n const gaps = children.filter((node) => {\n if (!formattingWhitespace(node)) return false;\n const gap = quote.ownerDocument.createRange();\n gap.selectNode(node);\n return normalized.compareBoundaryPoints(Range.START_TO_START, gap) <= 0\n && normalized.compareBoundaryPoints(Range.END_TO_END, gap) >= 0;\n });\n return { container: quote, bodies, range: normalized, startBody: start.body, endBody: end.body, gaps };\n};\n", "import { finishSelectionReplacement } from '../input/replace-selection.js';\nimport { ensureBodyPlaceholder as ensureBody } from '../input/replacement-blocks.js';\nimport { quoteBodyBlocks } from './paste-payload.js';\nimport { directQuoteAt, quoteEndpointPoint, quoteSourceBodies } from './quote-selection.js';\nimport type { ListItemBoundary, QuoteCrossingContext } from './internal-types.js';\n\n/** Read-only inspection of the selected body interval in consecutive inspected items. */\nexport const quoteCrossingContext = (boundaries: ListItemBoundary[], range: Range, startRoot: HTMLElement, endRoot: HTMLElement,\n start: Range, end: Range, gaps: ChildNode[] = []): QuoteCrossingContext | undefined => {\n if (range.collapsed) return;\n const first = boundaries[0];\n const last = boundaries[boundaries.length - 1];\n const from = first.bodies.indexOf(startRoot);\n const to = last.bodies.indexOf(endRoot);\n if (from < 0 || to < 0 || (first === last && to <= from)) return;\n const affected = boundaries.flatMap((boundary, index) => boundary.bodies.slice(index === 0 ? from : 0,\n index === boundaries.length - 1 ? to + 1 : undefined));\n const quotes = affected.filter((body) => body.localName === 'blockquote');\n if (!quotes.length || !quotes.every((quote) => quoteSourceBodies(quote))) return;\n const startQuoted = startRoot.localName === 'blockquote';\n const endQuoted = endRoot.localName === 'blockquote';\n if ((startQuoted && directQuoteAt(first.item, range.startContainer) !== startRoot)\n || (endQuoted && directQuoteAt(last.item, range.endContainer) !== endRoot)) return;\n const startPoint = startQuoted ? quoteEndpointPoint(startRoot, range, false) : undefined;\n const endPoint = endQuoted ? quoteEndpointPoint(endRoot, range, true) : undefined;\n if ((startQuoted && !startPoint) || (endQuoted && !endPoint)) return;\n const normalized = range.cloneRange();\n const left = startPoint?.range ?? start;\n const right = endPoint?.range ?? end;\n if (left.compareBoundaryPoints(Range.START_TO_START, right) > 0) return;\n normalized.setStart(left.startContainer, left.startOffset);\n normalized.setEnd(right.startContainer, right.startOffset);\n const ordered = boundaries.some((boundary) => boundary.interleaved);\n if (ordered && boundaries.some((boundary) => boundary.nestedLists.some((branch) =>\n branch.namespaceURI !== boundary.item.namespaceURI || branch.hasAttribute('data-mw-node')))) return;\n // Body indices describe editing ownership; actual children retain the source\n // body/list order for the separate ordered profile.\n const intervalBranches = ordered ? boundaries.flatMap((boundary, index) => {\n const children = [...boundary.item.children];\n const begin = index === 0 && startRoot !== boundary.item ? children.indexOf(startRoot) + 1 : 0;\n const finish = index === boundaries.length - 1 ? (endRoot === boundary.item ? 0 : children.indexOf(endRoot)) : children.length;\n return children.slice(begin, finish).filter((node): node is HTMLElement => boundary.nestedLists.includes(node as HTMLElement));\n }) : undefined;\n const following = ordered ? (endRoot === last.item ? last.nestedLists\n : [...last.item.children].slice([...last.item.children].indexOf(endRoot) + 1) as HTMLElement[]) : last.bodies.slice(to + 1);\n const siblings = boundaries.length > 1 || ordered ? {\n container: first.item,\n removedItems: boundaries.slice(1).map((boundary) => boundary.item),\n following,\n branches: intervalBranches ?? boundaries.flatMap((boundary) => boundary.nestedLists),\n gaps,\n directStart: startRoot === first.item,\n directEnd: endRoot === last.item,\n } : undefined;\n return { startRoot, endRoot, startQuoteBody: startPoint?.body, endQuoteBody: endPoint?.body,\n range: normalized, covered: affected.slice(1, -1), siblings, ordered };\n};\n\n/** Move actual retained inline descendants into a body, keeping the source item as owner. */\nconst promoteInlineBody = (item: HTMLElement): HTMLElement => {\n const body = item.ownerDocument.createElement('p');\n body.append(...item.childNodes);\n item.append(body);\n return body;\n};\n\n/** Payload/source were fully validated before this transaction-owned mutation. */\nexport const replaceQuoteCrossing = (context: QuoteCrossingContext, roots: HTMLElement[]): void => {\n const { range, covered, startQuoteBody, endQuoteBody, siblings } = context;\n let { startRoot, endRoot } = context;\n const document = startRoot.ownerDocument;\n // Detach protected branches before trimming direct-inline bodies or removing covered items.\n for (const branch of siblings?.branches ?? []) branch.remove();\n if (context.ordered && siblings?.directEnd) {\n for (const node of siblings.following) node.remove();\n }\n // Separate local ranges preserve both actual endpoint wrappers and all untouched\n // quote children/gaps; a cross-container delete would unwrap selected ancestry.\n const suffixCut = document.createRange();\n suffixCut.selectNodeContents(endRoot);\n suffixCut.setEnd(range.endContainer, range.endOffset);\n const prefixCut = document.createRange();\n prefixCut.selectNodeContents(startRoot);\n prefixCut.setStart(range.startContainer, range.startOffset);\n suffixCut.deleteContents();\n prefixCut.deleteContents();\n for (const body of covered) body.remove();\n if (siblings?.directStart) startRoot = promoteInlineBody(startRoot);\n if (siblings?.directEnd) endRoot = promoteInlineBody(endRoot);\n ensureBody(startQuoteBody ?? startRoot);\n if (endQuoteBody) ensureBody(endQuoteBody);\n for (const root of roots) {\n const quoteBodies = root.localName === 'blockquote' && quoteBodyBlocks(root);\n if (quoteBodies) for (const body of quoteBodies) ensureBody(body);\n else ensureBody(root);\n }\n const caretBody = endQuoteBody ? document.createElement('p') : endRoot;\n if (endQuoteBody) ensureBody(caretBody);\n if (context.ordered && siblings) {\n const suffix = endQuoteBody ? [caretBody, endRoot] : [endRoot];\n startRoot.after(...roots, ...siblings.branches, ...suffix, ...siblings.following);\n } else {\n if (endQuoteBody) startRoot.after(...roots, caretBody);\n else startRoot.after(...roots);\n if (siblings) {\n const destination = endQuoteBody ? caretBody : roots[roots.length - 1];\n destination.after(endRoot);\n siblings.container.append(...siblings.following, ...siblings.branches);\n }\n }\n if (siblings) {\n for (const item of siblings.removedItems) item.remove();\n for (const gap of siblings.gaps) gap.remove();\n }\n const caret = document.createRange();\n caret.selectNodeContents(caretBody);\n caret.collapse(true);\n finishSelectionReplacement(caretBody, caret);\n};\n", "import { sourceInlineNode as inlineNode } from './source-inline.js';\nimport { activeRange } from '../selection/index.js';\nimport { isOrdinaryQuote } from './paste-payload.js';\nimport { directQuoteAt, quotePasteContext } from './quote-selection.js';\nimport { quoteCrossingContext } from './quote-crossing.js';\nimport type { ListItemBoundary, ListSelectionOptions, ListSelectionResult } from './internal-types.js';\n\nconst isList = (node: Node): node is HTMLElement => node instanceof HTMLElement && /^(ul|ol)$/.test(node.localName);\nconst itemAt = (root: HTMLElement, node: Node): HTMLElement | undefined => {\n const element = node.nodeType === 1 ? node as Element : node.parentElement;\n const item = element?.closest<HTMLElement>('li');\n return item && root.contains(item) ? item : undefined;\n};\n\n/** Inspect direct bodies and optional paste-only interleaved branches without changing DOM. */\nconst inspectItem = (root: HTMLElement, item: HTMLElement, preserveQuotes: boolean): ListItemBoundary | undefined => {\n const list = item.parentElement;\n if (item.localName !== 'li' || item.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !root.contains(item) || !list || !isList(list) || item.hasAttribute('data-mw-node') || list.hasAttribute('data-mw-node')) return;\n const ownNodes: ChildNode[] = [];\n const bodies: HTMLElement[] = [];\n const nestedLists: HTMLElement[] = [];\n let interleaved = false;\n for (const node of item.childNodes) {\n if (isList(node)) nestedLists.push(node);\n else {\n if (nestedLists.length) {\n // Only wrapped paste bodies can form an ordered sequence after a branch.\n if (!preserveQuotes || !bodies.length) return;\n interleaved = true;\n }\n const paragraph = node instanceof HTMLElement && /^(p|h[1-6])$/.test(node.localName)\n && node.namespaceURI === item.namespaceURI && !node.hasAttribute('data-mw-node') && [...node.childNodes].every(inlineNode);\n const quote = preserveQuotes && isOrdinaryQuote(node);\n if (node instanceof HTMLElement && (paragraph || quote) && (!ownNodes.length || bodies.length)) {\n bodies.push(node);\n ownNodes.push(...node.childNodes);\n } else {\n if (bodies.length || !inlineNode(node)) return;\n ownNodes.push(node);\n }\n }\n }\n if (!bodies.length) bodies.push(item);\n const body = bodies[0];\n const ownStart = item.ownerDocument.createRange();\n ownStart.selectNodeContents(body);\n ownStart.collapse(true);\n const ownEnd = item.ownerDocument.createRange();\n ownEnd.selectNodeContents(bodies[bodies.length - 1]);\n if (body === item && nestedLists.length) ownEnd.setEndBefore(nestedLists[0]);\n ownEnd.collapse(false);\n return { item: item as HTMLLIElement, body, bodies, ownNodes, nestedLists, interleaved, ownStart, ownEnd };\n};\n\n/** Native/boundary callers deliberately keep the ordinary inline/p/h profile. */\nexport const inspectListItem = (root: HTMLElement, item: HTMLElement): ListItemBoundary | undefined => inspectItem(root, item, false);\n\nconst blocked = (reason: string): ListSelectionResult => ({ status: 'blocked', reason });\n/** Resolve an inline body or an unambiguous edge between direct body blocks. */\nexport const listBodyAt = (range: Range, boundary: ListItemBoundary, end: boolean): HTMLElement | undefined => {\n const node = end ? range.endContainer : range.startContainer;\n const offset = end ? range.endOffset : range.startOffset;\n if (boundary.body === boundary.item) return boundary.item;\n if (node === boundary.item) {\n if (boundary.interleaved) {\n const children = [...boundary.item.childNodes];\n if (offset > children.length) return;\n const child = children[end ? Math.max(0, offset - 1) : Math.min(offset, children.length - 1)];\n return boundary.bodies.find((body) => body === child);\n }\n if (offset > boundary.bodies.length) return;\n const index = end ? Math.max(0, offset - 1) : Math.min(offset, boundary.bodies.length - 1);\n return boundary.bodies[index];\n }\n return boundary.bodies.find((body) => body === node || body.contains(node));\n};\n/** Translate only unambiguous item-level edges; never mutate the active Range. */\nexport const normalizeListBodyRange = (range: Range, boundary: ListItemBoundary, end: boolean): Range | undefined => {\n const body = listBodyAt(range, boundary, end);\n if (!body) return;\n const point = range.cloneRange();\n point.collapse(!end);\n if (boundary.body !== boundary.item && point.startContainer === boundary.item) {\n const count = boundary.interleaved ? boundary.item.childNodes.length : boundary.bodies.length;\n const atStart = point.startOffset === 0 || (!end && point.startOffset < count);\n point.selectNodeContents(body);\n point.collapse(atStart);\n }\n if (point.compareBoundaryPoints(Range.START_TO_START, boundary.ownStart) < 0 || point.compareBoundaryPoints(Range.START_TO_START, boundary.ownEnd) > 0) return;\n return point;\n};\n\n/** A list-owned unsupported partial shape is blocked rather than natively cut. */\nconst selectionPlan = (root: HTMLElement, range: Range | undefined, options: ListSelectionOptions): ListSelectionResult => {\n const { includeSameBody, includeCollapsed, preserveQuotes } = options;\n if (!range || (range.collapsed && !includeCollapsed) || !root.contains(range.startContainer) || !root.contains(range.endContainer)) return { status: 'unowned' };\n const firstItem = itemAt(root, range.startContainer);\n const lastItem = itemAt(root, range.endContainer);\n if (!firstItem && !lastItem) return { status: 'unowned' };\n if (!firstItem || !lastItem) return blocked('A list selection cannot cross into a different block container.');\n if (firstItem.parentElement !== lastItem.parentElement) return blocked('Select sibling items in one list.');\n const first = inspectItem(root, firstItem, preserveQuotes);\n const last = inspectItem(root, lastItem, preserveQuotes);\n if (preserveQuotes && first && last && first.item === last.item) {\n const quote = directQuoteAt(first.item, range.startContainer);\n const endQuote = directQuoteAt(last.item, range.endContainer);\n if (quote && quote === endQuote) {\n if (first.interleaved && first.nestedLists.some((branch) =>\n branch.namespaceURI !== first.item.namespaceURI || branch.hasAttribute('data-mw-node')))\n return blocked('Insertion inside an interleaved item quote requires ordinary branch roots.');\n const context = quotePasteContext(quote, range);\n if (!context) return blocked('Block insertion inside a quote requires ordinary inline or paragraph/heading source content.');\n return { status: 'eligible', range: context.range, leaves: [first.item], gaps: [], first, last,\n startBody: context.startBody, endBody: context.endBody, quote: context };\n }\n }\n const start = first && normalizeListBodyRange(range, first, false);\n const startBody = first && listBodyAt(range, first, false);\n // A collapsed li-level point between blocks denotes the next body's start.\n // Resolving its end independently would instead pick the preceding body.\n const end = range.collapsed ? start : last && normalizeListBodyRange(range, last, true);\n const endBody = range.collapsed ? startBody : last && listBodyAt(range, last, true);\n if (!first || !last || !start || !end || !startBody || !endBody) {\n // Preserve legacy same-item paths except an explicitly block-shaped source.\n if (!includeSameBody && firstItem === lastItem && ![...firstItem.children].some((node) => /^(p|h[1-6])$/.test(node.localName))) return { status: 'unowned' };\n return blocked('List replacement requires inline content or ordinary paragraph/heading bodies.');\n }\n if (preserveQuotes && first.item === last.item) {\n const from = first.bodies.indexOf(startBody);\n const to = first.bodies.indexOf(endBody);\n if (first.bodies.slice(from, to + 1).some((body) => body.localName === 'blockquote')) {\n const crossing = quoteCrossingContext([first], range, startBody, endBody, start, end);\n if (!crossing) return blocked('A block insertion can cross only ordinary editable quotes within the same item.');\n return { status: 'eligible', range: crossing.range, leaves: [first.item], gaps: [], first, last,\n startBody, endBody, crossing };\n }\n }\n if (preserveQuotes && first.item === last.item && (startBody.localName === 'blockquote' || endBody.localName === 'blockquote'))\n return blocked('A block insertion endpoint cannot enter an existing quote.');\n if (first.item === last.item && first.interleaved) return blocked('An interleaved item requires an affected quote crossing.');\n if (!includeSameBody && firstItem === lastItem && startBody === endBody) return { status: 'unowned' };\n const workingRange = range.cloneRange();\n workingRange.setStart(start.startContainer, start.startOffset);\n workingRange.setEnd(end.startContainer, end.startOffset);\n const leaves: HTMLLIElement[] = [];\n const boundaries: ListItemBoundary[] = [];\n let hasQuote = false;\n const gaps: ChildNode[] = [];\n let node: ChildNode | null = first.item;\n while (node) {\n if (node.nodeType === 3 && /^[\\t\\n\\f\\r ]*$/.test(node.textContent ?? '')) gaps.push(node);\n else {\n if (!(node instanceof HTMLElement)) return blocked('Unsupported content between list items.');\n const item = inspectItem(root, node, preserveQuotes);\n if (!item) return blocked('A selected item contains an unsupported body.');\n if (preserveQuotes) {\n const from = item.item === first.item ? item.bodies.indexOf(startBody) : 0;\n const to = item.item === last.item ? item.bodies.indexOf(endBody) : item.bodies.length - 1;\n if (item.bodies.slice(from, to + 1).some((body) => body.localName === 'blockquote')) hasQuote = true;\n }\n leaves.push(item.item);\n boundaries.push(item);\n if (item.item === last.item) {\n if (hasQuote) {\n const unsupportedBranch = boundaries.slice(0, -1).some((boundary) => boundary.nestedLists.some((branch) =>\n branch.namespaceURI !== boundary.item.namespaceURI || branch.hasAttribute('data-mw-node')));\n if (unsupportedBranch) return blocked('Retained first and intermediate branches require ordinary trailing lists.');\n const crossing = quoteCrossingContext(boundaries, range, startBody, endBody, start, end, gaps);\n if (!crossing) return blocked('Block insertion across sibling items requires ordinary editable quotes and supported endpoints.');\n return { status: 'eligible', range: crossing.range, leaves, gaps, first, last, startBody, endBody, crossing };\n }\n if (boundaries.some((boundary) => boundary.interleaved))\n return blocked('Interleaved items require an affected quote crossing.');\n if (boundaries.slice(0, -1).some((boundary) => boundary.nestedLists.length))\n return blocked('A selected item contains a nested branch outside the quote-crossing profile.');\n return { status: 'eligible', range: workingRange, leaves, gaps, first, last, startBody, endBody };\n }\n }\n node = node.nextSibling;\n }\n return blocked('Select consecutive items in one list.');\n};\n\n/** Existing callers keep their earlier native and ordinary insertion ownership. */\nexport const listSelectionReplacement = (root: HTMLElement, range: Range | undefined = activeRange(root), includeSameBody = false, includeCollapsed = false): ListSelectionResult => selectionPlan(root, range, { includeSameBody, includeCollapsed, preserveQuotes: false });\n\n/** Only block payload candidates may preserve opaque quotes beside their range. */\nexport const listPasteSelection = (root: HTMLElement, range: Range | undefined = activeRange(root), blockCandidate = false): ListSelectionResult => selectionPlan(root, range, {\n includeSameBody: blockCandidate,\n includeCollapsed: blockCandidate,\n preserveQuotes: blockCandidate,\n});\n", "import { cutSelectionReplacement, ensureReplacementPlaceholder, finishSelectionReplacement, insertInlineFragment } from '../input/index.js';\nimport { activeRange } from '../selection/index.js';\nimport { ensureBodyPlaceholder, insertReplacementBlocks } from '../input/replacement-blocks.js';\nimport { listPasteSelection, listSelectionReplacement } from './selection-boundaries.js';\nimport { formattingWhitespace, inlinePayloadNode, isOrdinaryQuote, ordinaryPayloadBody, quoteBodyBlocks } from './paste-payload.js';\nimport { replaceQuoteCrossing } from './quote-crossing.js';\nimport type { ListSelectionPlan, ListSelectionResult } from './internal-types.js';\n\nconst ordinaryParagraph = (fragment: DocumentFragment): HTMLElement | undefined => {\n const node = fragment.firstChild;\n return fragment.childNodes.length === 1 && node instanceof HTMLElement && node.localName === 'p' && !node.hasAttribute('data-mw-node') && [...node.childNodes].every(inlinePayloadNode) ? node : undefined;\n};\nconst multiBlockCandidate = (fragment: DocumentFragment): boolean => {\n const nodes = [...fragment.childNodes].filter((node) => !formattingWhitespace(node));\n return nodes.length > 1 && nodes.some((node) => !inlinePayloadNode(node));\n};\nconst headingRoot = (fragment: DocumentFragment): Element | undefined => {\n const nodes = [...fragment.childNodes].filter((node) => !formattingWhitespace(node));\n const node = nodes[0];\n return nodes.length === 1 && node instanceof Element && /^h[1-6]$/.test(node.localName) ? node : undefined;\n};\nconst ordinaryHeading = (fragment: DocumentFragment): HTMLElement | undefined => {\n const node = headingRoot(fragment);\n return node instanceof HTMLElement && node.namespaceURI === 'http://www.w3.org/1999/xhtml'\n && !node.hasAttribute('data-mw-node') && [...node.childNodes].every(inlinePayloadNode) ? node : undefined;\n};\nconst quoteRoot = (fragment: DocumentFragment): Element | undefined => {\n const nodes = [...fragment.childNodes].filter((node) => !formattingWhitespace(node));\n const node = nodes[0];\n return nodes.length === 1 && node instanceof Element && node.localName === 'blockquote' ? node : undefined;\n};\nconst ordinaryQuote = (fragment: DocumentFragment): HTMLElement | undefined => {\n const node = quoteRoot(fragment);\n return node && isOrdinaryQuote(node) ? node : undefined;\n};\nconst blockPasteCandidate = (fragment: DocumentFragment): boolean => multiBlockCandidate(fragment)\n || Boolean(headingRoot(fragment) || quoteRoot(fragment));\nconst ordinaryBlocks = (fragment: DocumentFragment): HTMLElement[] | undefined => {\n const nodes = [...fragment.childNodes].filter((node) => !formattingWhitespace(node));\n return nodes.length > 1 && nodes.every(ordinaryPayloadBody) ? nodes : undefined;\n};\nconst requireSupported = (selected: ListSelectionResult): ListSelectionPlan | undefined => {\n if (selected.status === 'blocked') throw new RangeError(selected.reason);\n return selected.status === 'eligible' ? selected : undefined;\n};\n\n/** The transaction owner clears old caret formats only for this validated path. */\nexport const handlesCollapsedListBlockPaste = (root: HTMLElement, fragment: DocumentFragment, range: Range | undefined = activeRange(root)): boolean => {\n if (!range?.collapsed) return false;\n const innerPayload = Boolean(ordinaryBlocks(fragment) || ordinaryHeading(fragment));\n if (!innerPayload && !ordinaryQuote(fragment)) return false;\n const selected = listPasteSelection(root, range, true);\n return selected.status === 'eligible' && (!selected.quote || innerPayload);\n};\n\n/** Detached import preflight: an empty sanitized fragment stays a no-op for any source. */\nexport const prepareListSelectionPaste = (root: HTMLElement, fragment: DocumentFragment, range?: Range): void => {\n if (!fragment.childNodes.length) return;\n const blocks = ordinaryBlocks(fragment);\n const heading = ordinaryHeading(fragment);\n const quote = ordinaryQuote(fragment);\n const candidate = blockPasteCandidate(fragment);\n const selected = requireSupported(listPasteSelection(root, range, candidate));\n if (!selected) return;\n if (selected.quote && !blocks && !heading)\n throw new TypeError('Insertion inside a list quote supports multiple ordinary paragraphs/headings or one ordinary heading.');\n if (![...fragment.childNodes].every(inlinePayloadNode) && !ordinaryParagraph(fragment) && !blocks && !heading && !quote)\n throw new TypeError('List selection insertion supports inline HTML, an ordinary paragraph, heading or bounded quote, or multiple ordinary paragraphs/headings.');\n if (blocks || heading || quote) {\n for (const node of [...fragment.childNodes]) if (formattingWhitespace(node)) node.remove();\n }\n if (quote && quoteBodyBlocks(quote)) {\n for (const node of [...quote.childNodes]) if (formattingWhitespace(node)) node.remove();\n }\n};\n\nconst cutListSelection = (selected: ListSelectionPlan, forceParagraph = false) => {\n const context = selected.quote;\n const container = context?.container ?? selected.first.item;\n const sameItem = selected.first.item === selected.last.item;\n const firstBodies = context?.bodies ?? selected.first.bodies;\n const lastBodies = context?.bodies ?? selected.last.bodies;\n const startIndex = firstBodies.indexOf(selected.startBody);\n const endIndex = lastBodies.indexOf(selected.endBody);\n const following: ChildNode[] = context ? [] : lastBodies.slice(endIndex + 1);\n if (context && selected.endBody !== container) {\n let node = selected.endBody.nextSibling;\n while (node) {\n following.push(node);\n node = node.nextSibling;\n }\n }\n const branches = context ? [] : selected.last.nestedLists;\n // Keep unselected branches out of the generic cut: for a direct empty LI,\n // their placeholders must not be mistaken for the own-body placeholder.\n for (const branch of branches) branch.remove();\n for (const body of following) body.remove();\n const leaves = context || sameItem ? firstBodies.slice(startIndex, endIndex + 1) : selected.leaves;\n const cut = cutSelectionReplacement({ range: selected.range, leaves, contentRoots: { left: selected.startBody, right: selected.endBody } });\n if (!context && !sameItem) {\n for (const body of selected.first.bodies.slice(startIndex + 1)) body.remove();\n }\n // A direct-inline start needs a wrapper when surviving or incoming blocks\n // would otherwise create a mixed inline/block item. Keep actual descendants.\n if (cut.left === container && (following.length || forceParagraph)) {\n const caretContainer = cut.caret.startContainer;\n const offset = cut.caret.startOffset;\n const paragraph = cut.left.ownerDocument.createElement('p');\n paragraph.append(...cut.left.childNodes);\n cut.left.append(paragraph);\n cut.caret.setStart(caretContainer === cut.left ? paragraph : caretContainer, offset);\n cut.caret.collapse(true);\n cut.left = paragraph;\n }\n for (const gap of context?.gaps ?? selected.gaps) gap.remove();\n return { ...cut, following, branches, container };\n};\n\n/** Called only inside the editor transaction after native ownership was chosen. */\nexport const replaceListSelection = (root: HTMLElement, text: string): boolean => {\n const selected = requireSupported(listSelectionReplacement(root));\n if (!selected) return false;\n const { left, tail, caret, following, branches, container } = cutListSelection(selected);\n if (text) {\n const inserted = root.ownerDocument.createTextNode(text);\n caret.insertNode(inserted);\n caret.setStart(inserted, inserted.length);\n caret.collapse(true);\n }\n left.append(tail);\n finishSelectionReplacement(left, caret);\n container.append(...following, ...branches);\n return true;\n};\n\n/** Recheck the live range; trusted focus callbacks may have changed ownership. */\nexport const replaceListSelectionWithFragment = (root: HTMLElement, fragment: DocumentFragment): boolean => {\n if (!fragment.childNodes.length) return false;\n const blocks = ordinaryBlocks(fragment);\n const heading = ordinaryHeading(fragment);\n const quote = ordinaryQuote(fragment);\n const standalone = heading ?? quote;\n const candidate = blockPasteCandidate(fragment);\n const selected = requireSupported(listPasteSelection(root, undefined, candidate));\n if (!selected) return false;\n prepareListSelectionPaste(root, fragment, selected.range);\n if (selected.crossing) {\n // Crossing is a standalone structural profile: preserve every payload wrapper.\n const roots = blocks ?? (standalone ? [standalone] : undefined);\n if (!roots) throw new TypeError('Crossing a list quote requires an ordinary block payload.');\n replaceQuoteCrossing(selected.crossing, roots);\n return true;\n }\n const paragraph = ordinaryParagraph(fragment);\n // Keep the original end wrapper before a direct start is promoted by the cut.\n const suffix = standalone ? (selected.endBody === (selected.quote?.container ?? selected.last.item)\n ? root.ownerDocument.createElement('p') : selected.endBody.cloneNode(false) as HTMLElement) : undefined;\n const cut = cutListSelection(selected, Boolean(blocks || standalone));\n const { left, tail, caret, following, branches, container } = cut;\n if (standalone && suffix) {\n left.after(standalone, suffix);\n ensureReplacementPlaceholder(left, caret);\n left.normalize();\n const quoteBlocks = quote && quoteBodyBlocks(quote);\n if (quoteBlocks) {\n for (const body of quoteBlocks) ensureBodyPlaceholder(body);\n }\n else ensureBodyPlaceholder(standalone);\n suffix.append(tail);\n const end = root.ownerDocument.createRange();\n end.selectNodeContents(suffix);\n end.collapse(true);\n finishSelectionReplacement(suffix, end);\n container.append(...following, ...branches);\n return true;\n }\n if (blocks) {\n insertReplacementBlocks(cut, blocks);\n container.append(...following, ...branches);\n return true;\n }\n if (paragraph) fragment.replaceChildren(...paragraph.childNodes);\n insertInlineFragment(left, caret, fragment);\n left.append(tail);\n finishSelectionReplacement(left, caret);\n container.append(...following, ...branches);\n return true;\n};\n", "import { activeRange } from '../selection/index.js';\nimport { finishSelectionReplacement } from '../input/index.js';\nimport { inspectListItem, listBodyAt, normalizeListBodyRange } from './selection-boundaries.js';\n\nconst isList = (node: Node): node is HTMLElement => node instanceof HTMLElement && (node.localName === 'ul' || node.localName === 'ol');\n\nconst selectedItem = (root: HTMLElement, range: Range): HTMLLIElement | undefined => {\n const element = range.startContainer.nodeType === 1 ? range.startContainer as Element : range.startContainer.parentElement;\n const item = element?.closest('li');\n return item instanceof HTMLLIElement && root.contains(item) && item.parentElement && isList(item.parentElement) ? item : undefined;\n};\n\n/** Find an own-body edge even when the item's shape will be a mutation barrier. */\nconst atOwnEnd = (item: HTMLLIElement, range: Range): boolean => {\n const body = item.ownerDocument.createRange();\n body.selectNodeContents(item);\n const children = [...item.childNodes];\n const branchIndex = children.findIndex(isList);\n const firstBranch = children[branchIndex];\n const ownNodes = branchIndex === -1 ? children : children.slice(0, branchIndex);\n if (firstBranch) body.setEndBefore(firstBranch);\n const end = body.cloneRange();\n end.collapse(false);\n if (range.compareBoundaryPoints(Range.START_TO_START, end) > 0) return false;\n const hasText = ownNodes.some((node) => (node.nodeType === 1 || node.nodeType === 3 || node.nodeType === 4) && Boolean(node.textContent));\n const blockers = 'img,hr,table,figure,pre,blockquote,ul,ol';\n const empty = !hasText\n && ownNodes.every((node) => !(node instanceof Element) || (!node.matches(blockers) && !node.querySelector(blockers)))\n && ownNodes.reduce((count, node) => count + (node instanceof Element ? Number(node.localName === 'br') + node.querySelectorAll('br').length : 0), 0) <= 1;\n if (empty) return true;\n body.setStart(range.startContainer, range.startOffset);\n const suffix = body.cloneContents();\n return !suffix.textContent && !suffix.querySelector('br,img,hr,table,figure,ul,ol');\n};\n\nconst nextItem = (item: HTMLLIElement): HTMLLIElement | undefined => {\n let sibling = item.nextSibling;\n // Formatting whitespace between item elements is retained in the list.\n while (sibling?.nodeType === 3 && /^[\\t\\n\\f\\r ]*$/.test(sibling.textContent ?? '')) sibling = sibling.nextSibling;\n return sibling instanceof HTMLLIElement && sibling.parentElement === item.parentElement ? sibling : undefined;\n};\n\nconst removeOwnPlaceholder = (nodes: readonly ChildNode[]): void => {\n for (const node of nodes) {\n if (node instanceof HTMLBRElement) node.remove();\n else if (node instanceof HTMLElement) {\n for (const placeholder of node.querySelectorAll('br')) placeholder.remove();\n }\n }\n};\n\nconst atBodyEnd = (body: HTMLElement, point: Range): boolean => {\n const suffix = body.ownerDocument.createRange();\n suffix.selectNodeContents(body);\n suffix.setStart(point.startContainer, point.startOffset);\n const content = suffix.cloneContents();\n if (!body.textContent && body.querySelectorAll('br').length <= 1) return true;\n return !content.textContent && !content.querySelector('br,img');\n};\n\nconst removeBodyPlaceholder = (body: HTMLElement): void => {\n if (!body.textContent && body.querySelectorAll('br').length <= 1) removeOwnPlaceholder([...body.childNodes]);\n};\n\n/** Only the validated cancelable beforeinput path calls this handler. */\nexport const handlesListForwardDelete = (root: HTMLElement, inputType: string): boolean => {\n if (inputType !== 'deleteContentForward') return false;\n const range = activeRange(root);\n if (!range?.collapsed) return false;\n const item = selectedItem(root, range);\n if (!item) return false;\n const boundary = inspectListItem(root, item);\n const previousEdge = range.startContainer === item && range.startOffset > 0;\n const body = boundary && listBodyAt(range, boundary, previousEdge);\n const point = boundary && normalizeListBodyRange(range, boundary, previousEdge);\n if (body && point) {\n if (body === item) return atOwnEnd(item, range);\n return atBodyEnd(body, point);\n }\n const element = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement;\n const wrapped = element?.closest<HTMLElement>('p,h1,h2,h3,h4,h5,h6');\n if (wrapped?.parentElement === item && atBodyEnd(wrapped, range)) return true;\n return atOwnEnd(item, range);\n};\n\n/** Join one sibling pair inside the existing editor transaction; barriers are no-ops. */\nexport const editListForwardDelete = (root: HTMLElement): boolean => {\n const range = activeRange(root);\n if (!range?.collapsed) return false;\n const item = selectedItem(root, range);\n if (!item) return false;\n const left = inspectListItem(root, item);\n const previousEdge = range.startContainer === item && range.startOffset > 0;\n const current = left && listBodyAt(range, left, previousEdge);\n const point = left && normalizeListBodyRange(range, left, previousEdge);\n if (!left || !current || !point || !(current === item ? atOwnEnd(item, range) : atBodyEnd(current, point))) return false;\n const following = left.bodies[left.bodies.indexOf(current) + 1];\n if (following) {\n removeBodyPlaceholder(current);\n removeBodyPlaceholder(following);\n const join = root.ownerDocument.createRange();\n join.selectNodeContents(current);\n join.collapse(false);\n current.append(...following.childNodes);\n following.remove();\n finishSelectionReplacement(current, join);\n return true;\n }\n const rightItem = nextItem(item);\n const right = rightItem && inspectListItem(root, rightItem);\n if (!right) return false;\n\n // Branches stay independent: no list scan/coalescing, attribute rewrite or\n // descendant normalization is needed to join the items' own inline bodies.\n for (const branch of left.nestedLists) branch.remove();\n for (const branch of right.nestedLists) branch.remove();\n let target = current;\n const rightBody = right.bodies[0];\n const laterBodies = right.bodies.slice(1);\n if (target === item && laterBodies.length) {\n // A direct-inline item cannot also own block siblings. Promote only when\n // preserving later right bodies requires that representation.\n target = root.ownerDocument.createElement('p');\n target.append(...left.ownNodes);\n item.append(target);\n }\n removeBodyPlaceholder(target);\n removeBodyPlaceholder(rightBody);\n const join = root.ownerDocument.createRange();\n join.selectNodeContents(target);\n join.collapse(false);\n const rightNodes = rightBody === right.item ? right.ownNodes : [...rightBody.childNodes];\n target.append(...rightNodes.filter((node) => node.parentNode === rightBody));\n finishSelectionReplacement(target, join);\n item.append(...laterBodies, ...left.nestedLists, ...right.nestedLists);\n right.item.remove();\n return true;\n};\n", "import { activeRange } from '../selection/index.js';\nimport { copyDirection } from '../document/direction.js';\nimport { editListForwardDelete } from './forward-delete.js';\nimport { inspectListItem } from './selection-boundaries.js';\nimport type { ListItemBoundary } from './internal-types.js';\nimport type { FirstBodyBackspacePlan } from './first-body-backspace.types.js';\n\nconst isList = (node: Element | null): node is HTMLElement => node instanceof HTMLElement\n && node.namespaceURI === 'http://www.w3.org/1999/xhtml' && /^(ul|ol)$/.test(node.localName);\nconst whitespace = (node: Node): boolean => node.nodeType === 3 && /^[\\t\\n\\f\\r ]*$/.test(node.textContent ?? '');\n\nconst supportedList = (root: HTMLElement, list: HTMLElement): boolean => isList(list)\n && !list.hasAttribute('data-mw-node')\n && [...list.childNodes].every((node) => whitespace(node)\n || (node instanceof HTMLLIElement && Boolean(inspectListItem(root, node))));\n\n/** Resolve every changed container before opening the structural mutation. */\nconst firstBodyBackspacePlan = (root: HTMLElement, boundary: ListItemBoundary): FirstBodyBackspacePlan | undefined => {\n const list = boundary.item.parentElement;\n if (boundary.bodies.length < 2 || boundary.body === boundary.item || !list || !supportedList(root, list)) return;\n const previous = boundary.item.previousElementSibling;\n if (previous instanceof HTMLElement) {\n const inspected = inspectListItem(root, previous);\n return inspected ? { kind: 'join', previous: inspected } : undefined;\n }\n const parent = list.parentElement;\n if (!(parent instanceof HTMLElement) || parent.namespaceURI !== 'http://www.w3.org/1999/xhtml') return;\n if (parent === root || ['blockquote', 'td', 'th'].includes(parent.localName)) return { kind: 'unwrap', list };\n if (!(parent instanceof HTMLLIElement) || !inspectListItem(root, parent)) return;\n const outer = parent.parentElement;\n if (!outer || !supportedList(root, outer)) return;\n const laterBranches: HTMLElement[] = [];\n let branch = list.nextSibling;\n while (branch) {\n if (!(branch instanceof HTMLElement) || !supportedList(root, branch)) return;\n laterBranches.push(branch);\n branch = branch.nextSibling;\n }\n const following: ChildNode[] = [];\n let next = boundary.item.nextSibling;\n while (next) {\n following.push(next);\n next = next.nextSibling;\n }\n return { kind: 'lift', list, owner: parent, following, laterBranches };\n};\n\nexport const canEditFirstBodyBackspace = (root: HTMLElement, boundary: ListItemBoundary): boolean => Boolean(firstBodyBackspacePlan(root, boundary));\n\nconst selectRange = (root: HTMLElement, range: Range): void => {\n const selection = root.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n};\n\n/** Invoked only inside the cancelable-beforeinput transaction owner. */\nexport const editFirstBodyBackspace = (root: HTMLElement, boundary: ListItemBoundary, start: Range): boolean => {\n const plan = firstBodyBackspacePlan(root, boundary);\n if (!plan) return false;\n if (plan.kind === 'join') {\n // The outer transaction already captured the original first-body bookmark.\n // Reuse the validated forward join rather than duplicate body/branch rules.\n const original = activeRange(root)?.cloneRange();\n selectRange(root, plan.previous.ownEnd.cloneRange());\n if (editListForwardDelete(root)) return true;\n if (original) selectRange(root, original);\n return false;\n }\n\n // DOM Range coordinates can move to the old parent when an actual subtree is\n // transferred. Preserve the normalized inline node/offset explicitly.\n const container = start.startContainer;\n const offset = start.startOffset;\n if (plan.kind === 'unwrap') {\n for (const body of boundary.bodies)\n if (/^(p|h[1-6])$/.test(body.localName) && !body.hasAttribute('dir')) copyDirection(boundary.item, body);\n plan.list.before(...boundary.bodies, ...boundary.nestedLists);\n boundary.item.remove();\n } else {\n if (plan.following.some((node) => node instanceof HTMLLIElement)) {\n const trailing = plan.list.cloneNode(false) as HTMLElement;\n trailing.append(...plan.following);\n boundary.item.append(trailing);\n }\n // The remaining source siblings precede all later owner branches in the\n // original depth-first order. Keep whole branches separate in that order.\n boundary.item.append(...plan.laterBranches);\n plan.owner.after(boundary.item);\n }\n if (!plan.list.children.length) plan.list.remove();\n const caret = root.ownerDocument.createRange();\n caret.setStart(container, offset);\n caret.collapse(true);\n selectRange(root, caret);\n return true;\n};\n", "import { activeRange, placeCaret } from '../selection/index.js';\nimport { finishSelectionReplacement } from '../input/index.js';\nimport { inspectListItem, listBodyAt, listSelectionReplacement, normalizeListBodyRange } from './selection-boundaries.js';\nimport { replaceListSelection } from './replace-selection.js';\nimport { canEditFirstBodyBackspace, editFirstBodyBackspace } from './first-body-backspace.js';\nimport type { WrappedListInputStatus } from './wrapped-input.types.js';\n\nconst itemAt = (root: HTMLElement, node: Node): HTMLLIElement | undefined => {\n const element = node instanceof Element ? node : node.parentElement;\n const item = element?.closest('li');\n return item instanceof HTMLLIElement && root.contains(item) ? item : undefined;\n};\n\nconst atBodyStart = (body: HTMLElement, range: Range): boolean => {\n if (!body.textContent && body.querySelectorAll('br').length <= 1) return true;\n const prefix = body.ownerDocument.createRange();\n prefix.selectNodeContents(body);\n prefix.setEnd(range.startContainer, range.startOffset);\n const content = prefix.cloneContents();\n return !content.textContent && !content.querySelector('br,img');\n};\n\n/** Own only p/heading-shaped items; ordinary inline-list input stays unchanged. */\nexport const inspectWrappedListInput = (root: HTMLElement, inputType: string): WrappedListInputStatus => {\n if (inputType !== 'insertParagraph' && inputType !== 'insertLineBreak' && inputType !== 'deleteContentBackward') return 'unowned';\n const range = activeRange(root);\n if (!range) return 'unowned';\n const item = itemAt(root, range.startContainer);\n const last = itemAt(root, range.endContainer);\n const wrappedShape = (candidate: HTMLLIElement | undefined): boolean => Boolean(candidate && [...candidate.children].some((node) => /^(p|h[1-6])$/.test(node.localName)));\n if (!wrappedShape(item) && !wrappedShape(last)) return 'unowned';\n if (!item || item !== last) return inputType === 'deleteContentBackward' ? 'unowned' : 'blocked';\n const boundary = inspectListItem(root, item);\n if (!boundary || boundary.body === item) {\n if (inputType !== 'deleteContentBackward') return 'blocked';\n const element = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement;\n const body = element?.closest<HTMLElement>('p,h1,h2,h3,h4,h5,h6');\n if (range.collapsed && range.startContainer === item && range.startOffset === 0) return 'blocked';\n return range.collapsed && body?.parentElement === item && atBodyStart(body, range) ? 'blocked' : 'unowned';\n }\n const body = listBodyAt(range, boundary, false);\n const endBody = range.collapsed ? body : listBodyAt(range, boundary, true);\n const start = normalizeListBodyRange(range, boundary, false);\n const end = range.collapsed ? start : normalizeListBodyRange(range, boundary, true);\n if (!body || !start || !end) return inputType === 'deleteContentBackward' ? 'unowned' : 'blocked';\n if (body !== endBody) {\n if (inputType === 'deleteContentBackward') return 'unowned';\n return listSelectionReplacement(root, range).status === 'eligible' ? 'eligible' : 'blocked';\n }\n if (inputType === 'deleteContentBackward') {\n if (!range.collapsed || !atBodyStart(body, start)) return 'unowned';\n if (boundary.bodies.indexOf(body) > 0) return 'eligible';\n return boundary.bodies.length > 1 ? (canEditFirstBodyBackspace(root, boundary) ? 'eligible' : 'blocked') : 'unowned';\n }\n // Preserve the legacy empty-item exit/lift policy, including whitespace-only\n // bodies; branches make this an ordinary split rather than a list exit.\n if (inputType === 'insertParagraph' && boundary.bodies.length === 1 && !item.textContent?.trim() && !boundary.nestedLists.length) return 'legacy';\n return 'eligible';\n};\n\nconst ensurePlaceholder = (body: HTMLElement): void => {\n if (!body.textContent && !body.querySelector('br')) body.append(body.ownerDocument.createElement('br'));\n};\n\n/** Called only by the guarded cancelable-beforeinput transaction owner. */\nexport const editWrappedListInput = (root: HTMLElement, inputType: string, prepareSplit?: (item: HTMLLIElement) => void): boolean => {\n if (inspectWrappedListInput(root, inputType) !== 'eligible') return false;\n let range = activeRange(root)!;\n let boundary = inspectListItem(root, itemAt(root, range.startContainer)!)!;\n if (!range.collapsed && listBodyAt(range, boundary, false) !== listBodyAt(range, boundary, true)) {\n if (!replaceListSelection(root, '')) return false;\n range = activeRange(root)!;\n boundary = inspectListItem(root, itemAt(root, range.startContainer)!)!;\n }\n const body = listBodyAt(range, boundary, false)!;\n const start = normalizeListBodyRange(range, boundary, false)!;\n const end = range.collapsed ? start : normalizeListBodyRange(range, boundary, true)!;\n if (inputType === 'deleteContentBackward') {\n if (body === boundary.body) return editFirstBodyBackspace(root, boundary, start);\n const previous = boundary.bodies[boundary.bodies.indexOf(body) - 1];\n const empty = (node: HTMLElement) => !node.textContent && node.querySelectorAll('br').length <= 1;\n for (const node of [previous, body]) {\n if (empty(node)) for (const placeholder of node.querySelectorAll('br')) placeholder.remove();\n }\n const join = root.ownerDocument.createRange();\n join.selectNodeContents(previous);\n join.collapse(false);\n previous.append(...body.childNodes);\n body.remove();\n finishSelectionReplacement(previous, join);\n return true;\n }\n const cut = start.cloneRange();\n cut.setEnd(end.startContainer, end.startOffset);\n // Keep a separate live starting point: deleteContents may collapse a range\n // across inline wrappers to a common ancestor and lose starting affinity.\n const caret = start.cloneRange();\n cut.deleteContents();\n\n if (inputType === 'insertLineBreak') {\n // A lone empty-body br is a placeholder, not an existing real line.\n // Removing it keeps live caret affinity and semantic inline wrappers.\n const breaks = body.querySelectorAll('br');\n if (!body.textContent && breaks.length <= 1) {\n for (const placeholder of breaks) placeholder.remove();\n }\n const suffix = root.ownerDocument.createRange();\n suffix.selectNodeContents(body);\n suffix.setStart(caret.startContainer, caret.startOffset);\n const trailing = suffix.cloneContents();\n const lineBreak = root.ownerDocument.createElement('br');\n caret.insertNode(lineBreak);\n if (!trailing.textContent && !trailing.querySelector('br')) lineBreak.after(root.ownerDocument.createElement('br'));\n caret.setStartAfter(lineBreak);\n caret.collapse(true);\n const selection = root.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n return true;\n }\n\n const tail = root.ownerDocument.createRange();\n tail.selectNodeContents(body);\n tail.setStart(caret.startContainer, caret.startOffset);\n const nextItem = boundary.item.cloneNode(false) as HTMLLIElement;\n prepareSplit?.(nextItem);\n const nextBody = body.cloneNode(false) as HTMLElement;\n nextBody.append(tail.extractContents());\n const laterBodies = boundary.bodies.slice(boundary.bodies.indexOf(body) + 1);\n nextItem.append(nextBody, ...laterBodies, ...boundary.nestedLists);\n boundary.item.after(nextItem);\n ensurePlaceholder(body);\n ensurePlaceholder(nextBody);\n const walker = root.ownerDocument.createTreeWalker(nextBody, NodeFilter.SHOW_TEXT);\n let text = walker.nextNode();\n while (text && !text.textContent) text = walker.nextNode();\n if (!text) placeCaret(nextBody);\n else {\n caret.setStart(text, 0);\n caret.collapse(true);\n const selection = root.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n }\n return true;\n};\n", "export { inspectWrappedListInput, editWrappedListInput } from './wrapped-input.js';\nimport { activeRange, placeCaret, preserveRange } from '../selection/index.js';\nimport { normalizeListMarker } from '../document/list-marker.js';\nimport { copyDirection } from '../document/direction.js';\nexport { handlesListForwardDelete, editListForwardDelete } from './forward-delete.js';\nexport { inspectListItem, listSelectionReplacement } from './selection-boundaries.js';\nexport { prepareListSelectionPaste, replaceListSelection, replaceListSelectionWithFragment, handlesCollapsedListBlockPaste } from './replace-selection.js';\nconst blocks = 'p,h1,h2,h3,h4,h5,h6,blockquote,pre,li';\nconst isList = (element: Element | null): element is HTMLUListElement | HTMLOListElement => !!element && /^(ul|ol)$/.test(element.localName);\nconst elementAt = (node: Node): Element | null => node instanceof Element ? node : node.parentElement;\nconst blockAt = (root: HTMLElement, node: Node, preferItem = true): HTMLElement | undefined => {\n const element = elementAt(node);\n const item = element?.closest<HTMLElement>('li');\n const block = (preferItem && item && root.contains(item) ? item : undefined) ?? element?.closest<HTMLElement>(blocks);\n return block && root.contains(block) ? block : undefined;\n};\nconst touches = (range: Range, node: Node): boolean => {\n const content = node.ownerDocument!.createRange();\n if (node.nodeType === 3)\n content.selectNodeContents(node);\n else\n content.selectNode(node);\n const start = range.cloneRange();\n start.collapse(true);\n const end = range.cloneRange();\n end.collapse(false);\n const first = content.cloneRange();\n first.collapse(true);\n const last = content.cloneRange();\n last.collapse(false);\n return start.compareBoundaryPoints(Range.START_TO_START, last) < 0 && end.compareBoundaryPoints(Range.START_TO_START, first) > 0;\n};\nexport const selectedBlocks = (root: HTMLElement, range = activeRange(root), preferItems = true): HTMLElement[] => {\n if (!range)\n return [];\n if (range.collapsed) {\n const block = blockAt(root, range.startContainer, preferItems);\n return block ? [block] : [];\n }\n const found = new Set<HTMLElement>();\n const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);\n let node: Node | null;\n while ((node = walker.nextNode())) {\n if (!(node.nodeType === 3 && node.textContent) && !(node instanceof Element && /^(br|img|hr)$/.test(node.localName)))\n continue;\n if (touches(range, node)) {\n const block = blockAt(root, node, preferItems);\n if (block)\n found.add(block);\n }\n }\n return [...root.querySelectorAll<HTMLElement>(blocks)].filter((block) => found.has(block));\n};\nconst topItems = (items: HTMLElement[]) => items.filter((item) => !items.some((parent) => parent !== item && parent.contains(item)));\nconst itemRange = (root: HTMLElement, range?: Range): HTMLLIElement[] => {\n const items = topItems(selectedBlocks(root, range));\n if (!items.length || items.some((item) => item.localName !== 'li' || !isList(item.parentElement)))\n return [];\n const parent = items[0].parentElement;\n if (items.some((item) => item.parentElement !== parent))\n return [];\n const siblings = [...parent!.children];\n if (siblings.indexOf(items.at(-1)!) - siblings.indexOf(items[0]) + 1 !== items.length)\n return [];\n return items as HTMLLIElement[];\n};\nconst depth = (root: HTMLElement, item: HTMLElement): number => {\n let result = 0; let parent: Element | null = item.parentElement; while (parent && parent !== root) {\n if (isList(parent))\n result++;\n parent = parent.parentElement;\n } return result;\n};\nconst numberedBoundary = (list: Element): boolean => list.localName === 'ol' && (list.hasAttribute('start') || list.hasAttribute('reversed'));\nconst compatible = (a: Element | null, b: Element): a is HTMLElement => !!a && a.localName === b.localName && isList(a)\n && !numberedBoundary(a) && !numberedBoundary(b) && a.getAttribute('dir') === b.getAttribute('dir')\n && a.getAttribute('style') === b.getAttribute('style');\nconst joinLists = (root: HTMLElement): void => {\n for (const list of [...root.querySelectorAll<HTMLElement>('ul,ol')]) {\n if (!root.contains(list))\n continue;\n const previous = list.previousSibling;\n if (previous instanceof Element && compatible(previous, list)) {\n previous.append(...list.childNodes);\n list.remove();\n }\n }\n};\nconst splitAround = (item: HTMLLIElement, replacement: Node[]): void => {\n const list = item.parentElement!;\n const tail = list.cloneNode(false) as HTMLElement;\n while (item.nextSibling)\n tail.append(item.nextSibling);\n item.remove();\n list.after(...replacement, ...(tail.childNodes.length ? [tail] : []));\n if (!list.childNodes.length)\n list.remove();\n};\nconst ownContent = (item: HTMLElement) => [...item.childNodes].filter((node) => !(node instanceof Element && isList(node)));\nconst unwrapRoot = (item: HTMLLIElement, paragraphOnly = false): void => {\n const paragraphNode = () => {\n const node = document.createElement('p');\n if (item.hasAttribute('style')) node.setAttribute('style', item.getAttribute('style')!);\n copyDirection(item, node);\n return node;\n };\n let paragraph = paragraphNode();\n const nested = [...item.children].filter(isList);\n const content = ownContent(item);\n // Imported items may contain paragraphs; retain their block structure rather than nest p in p.\n const output: Node[] = [];\n for (const node of content) {\n if (paragraphOnly && node instanceof HTMLElement && /^(p|h[1-6]|blockquote|pre)$/.test(node.localName)) {\n copyDirection(node, paragraph);\n paragraph.append(...node.childNodes);\n }\n else if (node instanceof HTMLElement && /^(p|h[1-6]|blockquote|pre)$/.test(node.localName)) {\n if (paragraph.childNodes.length)\n output.push(paragraph);\n paragraph = paragraphNode();\n if (/^(p|h[1-6])$/.test(node.localName) && !node.hasAttribute('dir')) copyDirection(item, node);\n output.push(node);\n }\n else\n paragraph.append(node);\n }\n if (paragraph.childNodes.length || !output.length) {\n if (!paragraph.childNodes.length)\n paragraph.append(document.createElement('br'));\n output.push(paragraph);\n }\n splitAround(item, [...output, ...nested]);\n};\nconst lift = (items: HTMLLIElement[]): void => {\n const list = items[0].parentElement!;\n const owner = list.parentElement;\n if (owner?.localName !== 'li' || !isList(owner.parentElement)) {\n for (const item of items)\n unwrapRoot(item);\n return;\n }\n const trailing = list.cloneNode(false) as HTMLElement;\n while (items.at(-1)!.nextSibling)\n trailing.append(items.at(-1)!.nextSibling!);\n if (trailing.childNodes.length)\n items.at(-1)!.append(trailing);\n owner.after(...items);\n if (!list.childNodes.length)\n list.remove();\n};\nexport const listState = (root: HTMLElement, range?: Range) => {\n const items = itemRange(root, range);\n const canIndent = !!items.length && items[0].previousElementSibling?.localName === 'li' && items.every((item) => [item, ...item.querySelectorAll<HTMLElement>('li')].every((child) => depth(root, child) < 8));\n return { listDepth: items.length ? depth(root, items[0]) : 0, canIndent, canOutdent: !!items.length };\n};\nexport const indentList = (root: HTMLElement, direction: unknown): void => {\n if (direction !== 1 && direction !== -1)\n throw new TypeError('List indentation requires 1 or -1.');\n const items = itemRange(root);\n if (!items.length)\n throw new RangeError('Select consecutive items in the same list.');\n if (direction === 1 && !listState(root).canIndent)\n return;\n preserveRange(root, () => {\n if (direction === -1)\n lift(items);\n else {\n const list = items[0].parentElement!;\n const previous = items[0].previousElementSibling!;\n let nested = previous.lastElementChild;\n if (!compatible(nested, list)) {\n nested = list.cloneNode(false) as HTMLElement;\n previous.append(nested);\n }\n nested!.append(...items);\n }\n joinLists(root);\n });\n};\nexport const applyList = (root: HTMLElement, value: unknown): void => {\n if (value !== false && value !== 'bullet' && value !== 'ordered')\n throw new TypeError('Expected bullet, ordered or false.');\n const selected = topItems(selectedBlocks(root));\n if (selected.some((block) => block.localName === 'li' && !isList(block.parentElement)))\n throw new RangeError('A list item must belong to a list.');\n preserveRange(root, () => {\n for (const block of selected) {\n if (!value) {\n if (block.localName === 'li')\n lift([block as HTMLLIElement]);\n continue;\n }\n const tag = value === 'bullet' ? 'ul' : 'ol';\n if (block.localName === 'li') {\n if (block.parentElement!.localName === tag)\n continue;\n const list = document.createElement(tag);\n if (block.parentElement!.hasAttribute('style'))\n list.setAttribute('style', block.parentElement!.getAttribute('style')!);\n copyDirection(block.parentElement!, list);\n const marker = list.style.getPropertyValue('list-style-type');\n if (marker && !normalizeListMarker(tag, marker)) {\n list.style.removeProperty('list-style-type');\n if (!list.style.length) list.removeAttribute('style');\n }\n splitAround(block as HTMLLIElement, [list]);\n list.append(block);\n }\n else {\n const list = document.createElement(tag);\n const item = document.createElement('li');\n if (block.hasAttribute('style'))\n item.setAttribute('style', block.getAttribute('style')!);\n copyDirection(block, item);\n item.append(...block.childNodes);\n list.append(item);\n block.replaceWith(list);\n }\n }\n joinLists(root);\n });\n};\nconst empty = (item: HTMLElement) => !item.textContent?.trim() && !item.querySelector('img,hr,ul,ol');\nconst placeholder = (item: HTMLElement): void => {\n const own = ownContent(item);\n const meaningful = own.some((node) => node.textContent || (node instanceof Element && (node.matches('br,img,hr') || node.querySelector('br,img,hr'))));\n if (!meaningful) {\n if ([...item.children].some(isList))\n item.prepend(Object.assign(document.createElement('p'), { innerHTML: '<br>' }));\n else\n item.append(document.createElement('br'));\n }\n};\nconst atStart = (item: HTMLElement, range: Range) => {\n const prefix = range.cloneRange();\n prefix.selectNodeContents(item);\n prefix.setEnd(range.startContainer, range.startOffset);\n return !prefix.toString() && !prefix.cloneContents().querySelector('img,hr,br');\n};\nexport const handlesListInput = (root: HTMLElement, inputType: string): boolean => {\n const range = activeRange(root);\n if (!range)\n return false;\n const item = blockAt(root, range.startContainer);\n if (item?.localName !== 'li' || !isList(item.parentElement) || blockAt(root, range.endContainer) !== item)\n return false;\n return ['insertParagraph', 'insertLineBreak'].includes(inputType) || (inputType === 'deleteContentBackward' && range.collapsed && atStart(item, range));\n};\nexport const editListInput = (root: HTMLElement, inputType: string, prepareSplit?: (item: HTMLLIElement) => void): void => {\n const range = activeRange(root)!;\n const item = blockAt(root, range.startContainer) as HTMLLIElement;\n if (inputType === 'insertParagraph') {\n if (empty(item)) {\n preserveRange(root, () => {\n const owner = item.parentElement!.parentElement; if (owner?.localName === 'li' && isList(owner.parentElement))\n lift([item]);\n else\n unwrapRoot(item, true);\n });\n joinLists(root);\n return;\n }\n range.deleteContents();\n const tail = range.cloneRange();\n tail.selectNodeContents(item);\n tail.setStart(range.startContainer, range.startOffset);\n const next = item.cloneNode(false) as HTMLLIElement;\n prepareSplit?.(next);\n next.append(tail.extractContents());\n item.after(next);\n placeholder(item);\n placeholder(next);\n const walker = document.createTreeWalker(next, NodeFilter.SHOW_TEXT);\n let first: Node | null;\n do {\n first = walker.nextNode();\n } while (first && (!first.textContent || first.parentElement?.closest('li') !== next));\n if (first) {\n const caret = document.createRange();\n caret.setStart(first, 0);\n caret.collapse(true);\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n }\n else\n placeCaret(next.querySelector<HTMLElement>('p,h1,h2,h3,h4,h5,h6,pre') ?? next);\n }\n else if (inputType === 'insertLineBreak') {\n range.deleteContents();\n const br = document.createElement('br');\n range.insertNode(br);\n if (!br.nextSibling)\n br.after(document.createElement('br'));\n range.setStartAfter(br);\n range.collapse(true);\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n }\n else {\n const previous = item.previousElementSibling as HTMLLIElement | null;\n if (previous && previous.localName !== 'li')\n return;\n if (!previous) {\n preserveRange(root, () => lift([item]));\n joinLists(root);\n return;\n }\n if (!ownContent(previous).some((node) => node.textContent || (node instanceof Element && (node.localName === 'img' || node.querySelector('img'))))) {\n for (const br of [...previous.querySelectorAll('br')])\n if (br.closest('li') === previous)\n br.remove();\n }\n const marker = document.createComment('mw-join');\n const previousContent = ownContent(previous);\n const last = previousContent.at(-1);\n const target = last instanceof HTMLElement && /^(p|h[1-6]|blockquote|pre)$/.test(last.localName) ? last : previous;\n if (target === previous)\n previous.insertBefore(marker, [...previous.children].find(isList) ?? null);\n else\n target.append(marker);\n const content = ownContent(item);\n if (content[0] instanceof HTMLElement && /^(p|h[1-6])$/.test(content[0].localName))\n content.splice(0, 1, ...content[0].childNodes);\n marker.after(...content);\n for (const nested of [...item.children].filter(isList))\n previous.append(nested);\n item.remove();\n joinLists(root);\n const caret = document.createRange();\n caret.setStartBefore(marker);\n caret.collapse(true);\n marker.remove();\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n }\n};\n", "import type { LinkFormat, Attributes, Operation, Piece } from './inline-attributes.types.js';\nexport type { LinkFormat } from './inline-attributes.types.js';\nimport { validateDocument } from '../document/index.js';\nimport { normalizeFontFamily } from '../document/font-family.js';\nimport type { DocumentNode, EditorDocument, ElementNode } from '../document/index.js';\nexport const inlineStyles: Record<string, string> = { color: 'color', background: 'background-color', fontFamily: 'font-family', fontSize: 'font-size' };\nconst blocks = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'caption', 'colgroup', 'figure', 'figcaption']);\nconst checkedAttributes = (tag: 'span' | 'a', attributes: Attributes): Attributes => (validateDocument({ version: 1, children: [{ type: 'element', tag, attributes, children: [] }] }).children[0] as ElementNode).attributes;\nexport const normalizeInlineStyle = (name: string, value: unknown): string | false => {\n if (value === false)\n return false;\n if (name === 'fontFamily') {\n const family = typeof value === 'string' ? normalizeFontFamily(value) : undefined;\n if (!family) throw new TypeError('Expected a supported font family or false.');\n return family;\n }\n if (typeof value !== 'string' || !value.trim() || value.length > 128 || /[;{}]/.test(value))\n throw new TypeError('Expected a supported CSS inline style or false.');\n const property = inlineStyles[name];\n const attrs = checkedAttributes('span', { style: `${property}: ${value}` });\n const probe = document.createElement('span');\n probe.setAttribute('style', attrs.style ?? '');\n const normalized = probe.style.getPropertyValue(property);\n if (!normalized)\n throw new TypeError('Unsupported or invalid CSS inline style.');\n return normalized;\n};\nexport const normalizeLink = (value: unknown): {\n attributes: Attributes;\n text?: string;\n} | false => {\n if (value === false)\n return false;\n const input = typeof value === 'string' ? { href: value } : value;\n if (!input || typeof input !== 'object' || Array.isArray(input) || !('href' in input) || typeof input.href !== 'string')\n throw new TypeError('Expected a link URL, LinkFormat or false.');\n const link = input as Record<string, unknown>;\n const attributes: Attributes = { href: input.href };\n if (link.title !== undefined) {\n if (typeof link.title !== 'string' || link.title.length > 1024)\n throw new TypeError('Link title must be a string up to 1024 characters.');\n attributes.title = link.title;\n }\n if (link.target !== undefined) {\n if (link.target !== '_self' && link.target !== '_blank')\n throw new TypeError('Link target must be _self or _blank.');\n attributes.target = link.target;\n }\n if (link.text !== undefined && (typeof link.text !== 'string' || !link.text.length || link.text.length > 20000))\n throw new TypeError('New link text must contain 1\u201320000 characters.');\n const clean = checkedAttributes('a', attributes);\n if (!clean.href)\n throw new TypeError('Unsupported or unsafe link URL.');\n return { attributes: clean, ...(typeof link.text === 'string' ? { text: link.text } : {}) };\n};\nexport const mergeLinkAttributes = (previous: Attributes, patch: Attributes): Attributes => {\n const attrs = { ...previous, ...patch };\n if (!attrs.title)\n delete attrs.title;\n if (patch.target === '_self')\n delete attrs.rel;\n return checkedAttributes('a', attrs);\n};\nconst equalAttributes = (a?: Attributes, b?: Attributes) => JSON.stringify(Object.entries(a ?? {}).sort()) === JSON.stringify(Object.entries(b ?? {}).sort());\nconst withoutProperty = (attributes: Attributes, property: string): Attributes => {\n const attrs = { ...attributes };\n const style = (attrs.style ?? '').split(';').map((part) => part.trim()).filter((part) => part && part.slice(0, part.indexOf(':')).trim() !== property).join('; ');\n if (style)\n attrs.style = style;\n else\n delete attrs.style;\n return attrs;\n};\nconst groupPieces = (pieces: Piece[]): {\n pieces: Piece[];\n selected: boolean;\n link?: Attributes;\n}[] => {\n const result: {\n pieces: Piece[];\n selected: boolean;\n link?: Attributes;\n }[] = [];\n for (const piece of pieces) {\n const last = result.at(-1);\n if (last && last.selected === piece.selected && equalAttributes(last.link, piece.link))\n last.pieces.push(piece);\n else\n result.push({ pieces: [piece], selected: piece.selected, link: piece.link });\n }\n return result;\n};\nconst compact = (nodes: DocumentNode[]): DocumentNode[] => {\n const result: DocumentNode[] = [];\n for (const node of nodes) {\n const next = node.type === 'element' ? { ...node, children: compact(node.children) } : node;\n const previous = result.at(-1);\n if (next.type === 'text' && previous?.type === 'text')\n previous.text += next.text;\n else if (next.type === 'element' && previous?.type === 'element' && !blocks.has(next.tag) && !next.attributes['data-mw-node'] && !['img', 'br', 'hr'].includes(next.tag) && previous.tag === next.tag && equalAttributes(previous.attributes, next.attributes))\n previous.children = compact([...previous.children, ...next.children]);\n else\n result.push(next);\n }\n return result;\n};\nexport const transformInlineAttributes = (document: EditorDocument, from: number, to: number, operation: Operation): EditorDocument => {\n let position = 0;\n const wrap = (pieces: Piece[]): DocumentNode[] => groupPieces(pieces).flatMap((group) => {\n const children = group.pieces.map((piece) => piece.node);\n if (operation.kind === 'style')\n return group.selected && operation.value !== false ? [{ type: 'element', tag: 'span', attributes: { style: `${operation.property}: ${operation.value}` }, children } as ElementNode] : children;\n const attrs = group.selected ? operation.attributes === false ? undefined : mergeLinkAttributes(group.link ?? {}, operation.attributes) : group.link;\n return attrs ? [{ type: 'element', tag: 'a', attributes: attrs, children } as ElementNode] : children;\n });\n const visit = (node: DocumentNode, inheritedLink?: Attributes): Piece[] => {\n if (node.type === 'text') {\n const start = position;\n position += node.text.length;\n const left = Math.max(0, Math.min(node.text.length, from - start));\n const right = Math.max(left, Math.min(node.text.length, to - start));\n return [[0, left, false], [left, right, true], [right, node.text.length, false]].flatMap(([begin, end, selected]) => {\n const text = node.text.slice(begin as number, end as number);\n return text ? [{ node: { type: 'text', text } as DocumentNode, selected: Boolean(selected), link: inheritedLink }] : [];\n });\n }\n const link = operation.kind === 'link' && node.tag === 'a' ? node.attributes : inheritedLink;\n if (!node.children.length)\n return [{ node, selected: position >= from && position < to, link }];\n const children = node.children.flatMap((child) => visit(child, link));\n if (operation.kind === 'link' && node.tag === 'a')\n return children;\n if (blocks.has(node.tag) || node.attributes['data-mw-node'])\n return [{ node: { ...node, children: wrap(children) }, selected: false }];\n return groupPieces(children).flatMap<Piece>((group) => {\n const attrs = operation.kind === 'style' && group.selected ? withoutProperty(node.attributes, operation.property) : node.attributes;\n const content = group.pieces.map((piece) => piece.node);\n if (node.tag === 'span' && !Object.keys(attrs).length)\n return group.pieces;\n return [{ node: { ...node, attributes: attrs, children: content }, selected: group.selected, link: group.link }];\n });\n };\n return { version: 1, children: compact(wrap(document.children.flatMap((node) => visit(node)))) };\n};\n", "import type { DocumentSchema } from '../schema/types.js';\nimport { normalizeLink, mergeLinkAttributes, transformInlineAttributes } from './inline-attributes.js';\nimport { activeRange, readTextSelection, selectText, preserveRange } from '../selection/index.js';\nexport const applyLink = (root: HTMLElement, value: unknown, schema: DocumentSchema): void => {\n const link = normalizeLink(value);\n const range = activeRange(root);\n if (!range)\n return;\n const selection = readTextSelection(root)!;\n const element = range.startContainer.nodeType === 1 ? range.startContainer as Element : range.startContainer.parentElement;\n const anchor = element?.closest('a');\n const existing = anchor && root.contains(anchor) ? anchor : undefined;\n if (link && link.text !== undefined && (!range.collapsed || existing))\n throw new TypeError('Link text is only supported for insertion at a caret outside links.');\n if (!range.collapsed) {\n root.innerHTML = schema.documentHTML(transformInlineAttributes(schema.parseHTML(root.innerHTML), selection.index, selection.index + selection.length, { kind: 'link', attributes: link && link.attributes }));\n selectText(root, selection.index, selection.length);\n return;\n }\n if (existing) {\n const attrs = link && mergeLinkAttributes(Object.fromEntries([...existing.attributes].map((attr) => [attr.name, attr.value])), link.attributes);\n preserveRange(root, () => {\n if (!attrs)\n existing.replaceWith(...existing.childNodes);\n else {\n for (const attr of [...existing.attributes])\n existing.removeAttribute(attr.name);\n for (const [key, val] of Object.entries(attrs))\n existing.setAttribute(key, val);\n }\n });\n return;\n }\n if (!link || link.text === undefined)\n return;\n const created = root.ownerDocument.createElement('a');\n for (const [key, val] of Object.entries(link.attributes))\n created.setAttribute(key, val);\n created.textContent = link.text;\n const parent = element?.closest('p,li,h1,h2,h3,h4,h5,h6,blockquote,pre,td,th');\n if (parent?.childNodes.length === 1 && parent.firstChild instanceof HTMLBRElement) {\n parent.firstChild.remove();\n range.setStart(parent, 0);\n }\n range.insertNode(created);\n const tail = root.ownerDocument.createTextNode('');\n created.after(tail);\n range.setStart(tail, 0);\n range.collapse(true);\n const native = root.ownerDocument.getSelection();\n native?.removeAllRanges();\n native?.addRange(range);\n};\n", "import type { DocumentNode, DocumentTag, EditorDocument, ElementNode } from '../document/index.js';\nimport type { InlineGroup, Piece } from './types.js';\n\nconst blockTags = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'caption', 'colgroup', 'figure', 'figcaption']);\n\nconst textLength = (node: DocumentNode): number => node.type === 'text'\n ? node.text.length\n : node.children.reduce((length, child) => length + textLength(child), 0);\n\nexport const inlineDocument = (value: EditorDocument, from: number, to: number, tag: DocumentTag, enabled: boolean): EditorDocument => {\n let position = 0;\n const visit = (node: DocumentNode): Piece[] => {\n if (node.type === 'text') {\n const start = position;\n position += node.text.length;\n const left = Math.max(0, Math.min(node.text.length, from - start));\n const right = Math.max(left, Math.min(node.text.length, to - start));\n return [[0, left, false], [left, right, true], [right, node.text.length, false]].flatMap(([begin, end, selected]) => {\n const text = node.text.slice(begin as number, end as number);\n if (!text)\n return [];\n const leaf: DocumentNode = { type: 'text', text };\n return [{ node: selected && enabled ? { type: 'element', tag, attributes: {}, children: [leaf] } as ElementNode : leaf, selected: Boolean(selected) }];\n });\n }\n // Descendants already inherit this mark. Keep their validated wrapper shape unchanged.\n if (enabled && node.tag === tag) {\n position += textLength(node);\n return [{ node, selected: false }];\n }\n const children = node.children.flatMap(visit);\n if (blockTags.has(node.tag) || node.attributes['data-mw-node'])\n return [{ node: { ...node, children: children.map((piece) => piece.node) }, selected: false }];\n if (!children.length)\n return [{ node, selected: false }];\n const groups: InlineGroup[] = [];\n for (const piece of children) {\n const last = groups.at(-1);\n if (last?.selected === piece.selected)\n last.children.push(piece.node);\n else\n groups.push({ selected: piece.selected, children: [piece.node] });\n }\n return groups.flatMap<Piece>((group) => node.tag === tag && !enabled && group.selected\n ? group.children.map((child) => ({ node: child, selected: true }))\n : [{ node: { ...node, children: group.children }, selected: group.selected }]);\n };\n return { version: 1, children: value.children.flatMap(visit).map((piece) => piece.node) };\n};\n", "import type { DocumentSchema } from '../schema/types.js';\nimport type { DocumentTag } from '../document/index.js';\nimport { selectText } from '../selection/index.js';\nimport { inlineDocument } from './inline-document.js';\n\nconst leaves = 'p,h1,h2,h3,h4,h5,h6';\nconst inlineTags = new Set(['strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'code']);\nconst structuralAncestors = new Set(['blockquote', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th']);\nconst elementAt = (node: Node): Element | null => node.nodeType === 1 ? node as Element : node.parentElement;\nconst isInlineTree = (parent: Element): boolean => {\n for (const node of parent.childNodes) {\n if (node.nodeType === 3) continue;\n if (node.nodeType !== 1) return false;\n const element = node as Element;\n if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !inlineTags.has(element.localName) || !isInlineTree(element)) return false;\n }\n return true;\n};\n\n/** Transform one schema-validated leaf while keeping unrelated editor DOM connected. */\nexport const applyLocalInline = (root: HTMLElement, range: Range, tag: DocumentTag, enabled: boolean, schema: DocumentSchema): boolean => {\n const block = elementAt(range.startContainer)?.closest<HTMLElement>(leaves);\n if (!block || !root.contains(block) || block.namespaceURI !== 'http://www.w3.org/1999/xhtml') return false;\n if (elementAt(range.endContainer)?.closest(leaves) !== block || !isInlineTree(block)) return false;\n for (let parent = block.parentElement; parent && parent !== root; parent = parent.parentElement) {\n if (parent.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !structuralAncestors.has(parent.localName)) return false;\n }\n\n const prefix = root.ownerDocument.createRange();\n prefix.selectNodeContents(block);\n prefix.setEnd(range.startContainer, range.startOffset);\n const from = prefix.toString().length;\n const length = range.toString().length;\n if (!length || from + length > (block.textContent?.length ?? 0)) return false;\n const native = root.ownerDocument.getSelection();\n const backward = native?.anchorNode === range.endContainer && native.anchorOffset === range.endOffset;\n const content = inlineDocument(schema.parseHTML(block.outerHTML), from, from + length, tag, enabled);\n const fragment = schema.renderDocument(content);\n const replacement = fragment.firstElementChild;\n if (fragment.childNodes.length !== 1 || !(replacement instanceof HTMLElement) || replacement.localName !== block.localName) return false;\n\n // HTML history replay merges adjacent text nodes; capture the same local node shape.\n replacement.normalize();\n if (replacement.outerHTML === block.outerHTML) return true;\n\n block.replaceWith(fragment);\n selectText(replacement, from, length);\n root.focus({ preventScroll: true });\n if (backward && native?.rangeCount) {\n const selected = native.getRangeAt(0);\n native.setBaseAndExtent(selected.endContainer, selected.endOffset, selected.startContainer, selected.startOffset);\n }\n return true;\n};\n", "import type { DocumentSchema } from '../schema/types.js';\nimport type { DocumentTag } from '../document/index.js';\nimport { normalizeFontFamily } from '../document/font-family.js';\nimport { copyDirection } from '../document/direction.js';\nimport { activeRange, readTextSelection, selectText, preserveRange } from '../selection/index.js';\nimport { inlineStyles, normalizeInlineStyle, transformInlineAttributes } from './inline-attributes.js';\nimport { applyLink } from './links.js';\nimport { inlineDocument } from './inline-document.js';\nimport { applyLocalInline } from './local-inline.js';\nimport { applyList, indentList, listState, selectedBlocks } from '../lists/index.js';\nexport const inlineFormats: Record<string, DocumentTag> = { bold: 'strong', italic: 'em', underline: 'u', strike: 's', code: 'code', subscript: 'sub', superscript: 'sup' };\n\nconst closestElement = (node: Node): Element | null => { return node.nodeType === 1 ? node as Element : node.parentElement; };\nconst formatsAt = (root: HTMLElement, node: Node): Record<string, unknown> => {\n let element = closestElement(node);\n const formats: Record<string, unknown> = {};\n while (element && element !== root) {\n for (const [name, tag] of Object.entries(inlineFormats))\n if (element.localName === tag)\n formats[name] = true;\n if (/^h[1-6]$/.test(element.localName) && formats.header === undefined)\n formats.header = Number(element.localName[1]);\n if (element.localName === 'blockquote')\n formats.blockquote = true;\n if (element.localName === 'pre')\n formats['code-block'] = true;\n if ((element.localName === 'ul' || element.localName === 'ol') && formats.list === undefined)\n formats.list = element.localName === 'ul' ? 'bullet' : 'ordered';\n if (element.localName === 'a' && formats.link === undefined) {\n formats.link = element.getAttribute('href');\n formats.linkTitle = element.getAttribute('title') ?? '';\n formats.linkTarget = element.getAttribute('target') ?? '_self';\n }\n if (element instanceof HTMLElement)\n for (const [name, property] of Object.entries(inlineStyles)) {\n const value = element.style.getPropertyValue(property);\n if (formats[name] === undefined && value)\n formats[name] = name === 'fontFamily' ? normalizeFontFamily(value) ?? value : value;\n }\n if (element instanceof HTMLElement && element.style.textAlign && formats.align === undefined)\n formats.align = element.style.textAlign;\n element = element.parentElement;\n }\n return formats;\n};\nexport const readFormats = (root: HTMLElement, projection?: Range): Record<string, unknown> => {\n let range: Range | undefined;\n if (projection === undefined) range = activeRange(root);\n else {\n try { range = root.ownerDocument.defaultView!.Range.prototype.cloneRange.call(projection); }\n catch { throw new TypeError('Expected a native Range for format projection.'); }\n if (!root.contains(range.startContainer) || !root.contains(range.endContainer)) return {};\n }\n if (!range)\n return {};\n let formats = formatsAt(root, range.startContainer);\n const mixed = new Set<string>();\n if (!range.collapsed) {\n const prefix = root.ownerDocument.createRange();\n prefix.selectNodeContents(root);\n prefix.setEnd(range.startContainer, range.startOffset);\n const index = prefix.toString().length;\n const length = range.toString().length;\n const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT);\n let position = 0;\n let node: Node | null;\n const samples: Record<string, unknown>[] = [];\n while ((node = walker.nextNode())) {\n const end = position + node.textContent!.length;\n if (end > index && position < index + length)\n samples.push(formatsAt(root, node));\n position = end;\n }\n if (samples.length)\n formats = samples[0];\n const keys = [...Object.keys(inlineFormats), ...Object.keys(inlineStyles), 'header', 'list', 'blockquote', 'code-block', 'link', 'linkTitle', 'linkTarget', 'align'];\n const normalized = (sample: Record<string, unknown>, key: string) => sample[key] ?? (key === 'align' ? 'left' : key === 'header' ? 0 : false);\n for (const key of keys)\n if (samples.some((sample) => normalized(sample, key) !== normalized(samples[0], key)))\n mixed.add(key);\n }\n return { ...formats, align: formats.align ?? 'left', mixed: [...mixed], ...listState(root, range) };\n};\nexport const applyFormat = (root: HTMLElement, name: string, value: unknown, schema: DocumentSchema): void => {\n const range = activeRange(root);\n if (!range)\n return;\n const tag = inlineFormats[name];\n if (tag && !range.collapsed && applyLocalInline(root, range, tag, Boolean(value), schema))\n return;\n const selection = readTextSelection(root)!;\n if (name === 'list') {\n applyList(root, value);\n return;\n }\n if (name === 'indent') {\n indentList(root, value);\n return;\n }\n if (name === 'clear') {\n if (value !== true || !selection.length)\n return;\n let content = schema.parseHTML(root.innerHTML);\n for (const tag of [...Object.values(inlineFormats), 'a', 'span'] as DocumentTag[])\n content = inlineDocument(content, selection.index, selection.index + selection.length, tag, false);\n root.innerHTML = schema.documentHTML(content);\n selectText(root, selection.index, selection.length);\n return;\n }\n if (tag) {\n if (range.collapsed)\n return;\n root.innerHTML = schema.documentHTML(inlineDocument(schema.parseHTML(root.innerHTML), selection.index, selection.index + selection.length, tag, Boolean(value)));\n selectText(root, selection.index, selection.length);\n return;\n }\n if (name === 'link') {\n applyLink(root, value, schema);\n return;\n }\n if (Object.hasOwn(inlineStyles, name)) {\n const style = normalizeInlineStyle(name, value);\n if (!selection.length)\n return;\n root.innerHTML = schema.documentHTML(transformInlineAttributes(schema.parseHTML(root.innerHTML), selection.index, selection.index + selection.length, { kind: 'style', property: inlineStyles[name], value: style }));\n selectText(root, selection.index, selection.length);\n return;\n }\n let blocks = selectedBlocks(root, range, false);\n if (!blocks.length) {\n const paragraph = document.createElement('p');\n paragraph.append(range.extractContents());\n if (!paragraph.childNodes.length)\n paragraph.append(document.createElement('br'));\n range.insertNode(paragraph);\n blocks = [paragraph];\n }\n preserveRange(root, () => {\n for (const block of blocks) {\n if (name === 'align' && ['left', 'center', 'right', 'justify', false].includes(value as string | false)) {\n block.style.textAlign = value ? String(value) : '';\n continue;\n }\n const nextTag = name === 'header' ? (Number.isInteger(value) && Number(value) >= 1 && Number(value) <= 6 ? `h${value}` : 'p')\n : name === 'blockquote' ? (value ? 'blockquote' : 'p')\n : name === 'code-block' ? (value ? 'pre' : 'p') : undefined;\n if (nextTag) {\n if (block.hasAttribute('data-mw-node') && block.localName !== nextTag)\n throw new RangeError('Cannot change the tag of a registered semantic node.');\n const replacement = document.createElement(nextTag);\n if (block.localName === 'li') {\n const content = [...block.childNodes].filter((node) => !(node instanceof Element && /^(ul|ol|p|h[1-6]|pre|blockquote)$/.test(node.localName)));\n replacement.append(...content);\n block.prepend(replacement);\n }\n else {\n replacement.append(...block.childNodes);\n replacement.setAttribute('style', block.getAttribute('style') ?? '');\n copyDirection(block, replacement);\n block.replaceWith(replacement);\n }\n }\n }\n });\n};\n", "import type { EditorEventMap, EditorEvents, EventHub, PluginEvent, QueuedEvent, EditorInputCommit } from './types.js';\nexport type { EditorEventMap, EditorEvents, PluginEvent, EditorInputCommit } from './types.js';\nconst tokens = new WeakSet<object>();\nconst coreNames = new Set(['change', 'selectionchange', 'readonlychange', 'localechange', 'inputcommit', 'destroy']);\nexport const createPluginEvent = <T>(name: string): PluginEvent<T> => {\n if (typeof name !== 'string' || !name.trim() || name.length > 200) {\n throw new TypeError('Expected an event name with 1\u2013200 characters.');\n }\n const token = Object.freeze({ name }) as PluginEvent<T>;\n tokens.add(token);\n return token;\n};\nconst assertToken = (event: unknown): object => {\n if (!event || typeof event !== 'object' || !tokens.has(event)) {\n throw new TypeError('Expected a plugin event token. Core events cannot be emitted publicly.');\n }\n return event;\n};\nconst corePayload = (key: string | object, payload: unknown): unknown => {\n if (!payload || typeof payload !== 'object') return payload;\n if (key === 'localechange') {\n const locale = payload as EditorEventMap['localechange'];\n return { ...locale, translations: { ...locale.translations } };\n }\n if (key === 'inputcommit') {\n const receipt = payload as EditorInputCommit;\n const saved = receipt.selection;\n return { ...receipt, selection: saved ? { ...saved, start: [...saved.start], end: [...saved.end] } : undefined };\n }\n return { ...payload };\n};\nexport const createEventHub = (): EventHub => {\n const listeners = new Map<string | object, Map<(payload: unknown) => void, number>>();\n const queue: QueuedEvent[] = [];\n let registration = 0;\n let dispatching = false;\n let closing = false;\n const enqueue = (entry: QueuedEvent) => {\n if (closing && entry.key !== 'destroy')\n return;\n queue.push(entry);\n if (dispatching)\n return;\n dispatching = true;\n const failures: unknown[] = [];\n try {\n while (queue.length) {\n const next = queue.shift()!;\n if (closing && next.key !== 'destroy')\n continue;\n const bucket = listeners.get(next.key);\n for (const [listener, registered] of [...(bucket ?? [])]) {\n if ((closing && next.key !== 'destroy') || bucket?.get(listener) !== registered)\n continue;\n try {\n const payload = next.core ? corePayload(next.key, next.payload) : next.payload;\n listener(payload);\n }\n catch (error) {\n failures.push(error);\n }\n }\n if (next.key === 'destroy') {\n listeners.clear();\n queue.length = 0;\n }\n }\n }\n finally {\n dispatching = false;\n }\n if (failures.length)\n throw new AggregateError(failures, 'Editor event listeners failed.');\n };\n const on = (event: keyof EditorEventMap | PluginEvent<unknown>, listener: (payload: unknown) => void): (() => void) => {\n if (closing)\n throw new Error('Editor events have been destroyed.');\n if (typeof listener !== 'function')\n throw new TypeError('Expected an event listener.');\n const key = typeof event === 'string' && coreNames.has(event) ? event : assertToken(event);\n let bucket = listeners.get(key);\n if (!bucket) {\n bucket = new Map();\n listeners.set(key, bucket);\n }\n if (!bucket.has(listener))\n bucket.set(listener, ++registration);\n const registered = bucket.get(listener);\n return () => {\n if (bucket!.get(listener) !== registered)\n return;\n bucket!.delete(listener);\n if (!bucket!.size && listeners.get(key) === bucket)\n listeners.delete(key);\n };\n };\n const events: EditorEvents = {\n on: on as EditorEvents['on'],\n emit: (event, payload) => {\n if (closing)\n throw new Error('Editor events have been destroyed.');\n enqueue({ key: assertToken(event), payload, core: false });\n },\n };\n return {\n events,\n notify: (event, payload) => enqueue({ key: event, payload, core: true }),\n destroy: () => {\n if (closing)\n return;\n closing = true;\n queue.length = 0;\n enqueue({ key: 'destroy', payload: undefined, core: true });\n },\n };\n};\n", "import type { DocumentSchema } from '../schema/types.js';\n\n/** Reuse only a successfully validated string for the exact current serialized DOM. */\nexport const createHTMLSnapshots = (surface: HTMLElement, sanitize: DocumentSchema['sanitizeHTML']) => {\n let previousInput: string | undefined;\n let previousHTML = '';\n\n const read = (): string => {\n const input = surface.innerHTML;\n if (input === previousInput)\n return previousHTML;\n\n // Keep the last successful pair intact when validation rejects a new input.\n const html = sanitize(input);\n previousInput = input;\n previousHTML = html;\n return html;\n };\n\n const clear = (): void => {\n previousInput = undefined;\n previousHTML = '';\n };\n\n return { read, clear };\n};\n", "import type { EditorLocale, EditorTranslations, LocaleDictionaries } from './types.js';\n\nexport type { EditorLocale, EditorTranslations, LocaleDictionaries, EditorTranslationKey } from './types.js';\nexport { editorMessages } from './messages.js';\n\n/** Copy and validate before changing UI state or mounting DOM. */\nexport const createLocale = (locale: string, translations: EditorTranslations = {}): EditorLocale => {\n if (typeof locale !== 'string' || !locale || locale.length > 100)\n throw new TypeError('Expected a language tag with 1\u2013100 characters.');\n const canonical = Intl.getCanonicalLocales(locale)[0];\n if (!canonical)\n throw new RangeError('Expected a valid language tag.');\n if (!translations || typeof translations !== 'object' || Array.isArray(translations))\n throw new TypeError('Translations must be a record of strings.');\n const prototype = Object.getPrototypeOf(translations);\n if (prototype !== Object.prototype && prototype !== null)\n throw new TypeError('Translations must be a plain record of strings.');\n const entries = Object.entries(translations);\n if (entries.some(([key, value]) => !key || typeof value !== 'string'))\n throw new TypeError('Translation keys must be nonempty and values must be strings.');\n return { locale: canonical, translations: Object.fromEntries(entries) };\n};\n\n/** Resolve feature-owned copy without pulling optional feature dictionaries into core. */\nexport const localize = (state: EditorLocale, key: string, dictionaries: LocaleDictionaries): string => {\n const override = Object.hasOwn(state.translations, key) ? state.translations[key] : undefined;\n const exact = Object.hasOwn(dictionaries, state.locale) ? dictionaries[state.locale] : undefined;\n const base = state.locale.split('-')[0];\n const language = Object.hasOwn(dictionaries, base) ? dictionaries[base] : undefined;\n const message = (dictionary: EditorTranslations | undefined) => dictionary && Object.hasOwn(dictionary, key) ? dictionary[key] : undefined;\n const value = override ?? message(exact) ?? message(language) ?? message(dictionaries.en);\n if (typeof value !== 'string')\n throw new Error(`Missing English fallback for translation: ${key}`);\n return value;\n};\n", "import { createDocumentSchema } from '../schema/index.js';\nimport { createCommandRegistry } from '../commands/index.js';\nimport { activeRange, bookmark, placeCaret, rangeFromBookmark, readTextSelection, restoreBookmark, selectText } from '../selection/index.js';\nimport type { SelectionBookmark } from '../selection/index.js';\nimport {\n editListInput, handlesListInput, indentList, listState, selectedBlocks,\n listSelectionReplacement, prepareListSelectionPaste, replaceListSelection,\n replaceListSelectionWithFragment, handlesListForwardDelete, editListForwardDelete,\n handlesCollapsedListBlockPaste,\n inspectWrappedListInput, editWrappedListInput,\n} from '../lists/index.js';\nimport { editBlockInput, handlesBlockInput, handlesSelectionReplacement, replaceSelection, prepareSelectionPaste, replaceSelectionWithFragment } from '../input/index.js';\nimport { applyFormat, inlineFormats, readFormats } from '../formatting/index.js';\nimport { inlineStyles, normalizeInlineStyle } from '../formatting/inline-attributes.js';\nimport { createEventHub } from '../events/index.js';\nimport type { EditorEvents, EditorInputCommit } from '../events/types.js';\nimport type { Editor, EditorChange, EditorOptions, Snapshot } from './types.js';\nimport type { InputCommitOrigin } from './internal-types.js';\nimport { createHTMLSnapshots } from './html-snapshots.js';\nimport { createLocale, editorMessages, localize } from '../localization/index.js';\nconst paragraphOrigin = (event: Event, inputType: string): InputCommitOrigin | undefined => event.cancelable && inputType === 'insertParagraph' ? { inputType, sourceEvent: event } : undefined;\nconst isCompositionInput = (event: InputEvent): boolean => event.isComposing || event.inputType === 'insertCompositionText' || event.inputType === 'insertFromComposition' || event.inputType === 'deleteCompositionText';\nconst ensureDocument = (root: HTMLElement): boolean => {\n let normalized = false;\n if (!root.childNodes.length) {\n root.innerHTML = '<p><br></p>';\n normalized = true;\n }\n // Native input can create loose inline nodes; wrap them in paragraphs without replacing text nodes.\n let paragraph: HTMLParagraphElement | undefined;\n for (const node of [...root.childNodes]) {\n const inline = node.nodeType === 3 || (node.nodeType === 1 && /^(strong|em|u|s|a|span|code|img|br|sub|sup)$/.test((node as Element).localName));\n if (inline) {\n if (!paragraph) {\n paragraph = document.createElement('p');\n root.insertBefore(paragraph, node);\n }\n paragraph.append(node);\n normalized = true;\n }\n else\n paragraph = undefined;\n }\n if (['table', 'figure'].includes(root.lastElementChild?.localName ?? ''))\n root.append(Object.assign(document.createElement('p'), { innerHTML: '<br>' }));\n root.dataset.empty = String(!root.textContent && !root.querySelector('table,img,hr'));\n return normalized;\n};\nconst insertFragment = (root: HTMLElement, fragment: DocumentFragment): void => {\n const range = activeRange(root);\n if (!range)\n return;\n if (!fragment.childNodes.length)\n return;\n if (replaceSelectionWithFragment(root, fragment)) return;\n if (replaceListSelectionWithFragment(root, fragment)) return;\n range.deleteContents();\n const startElement = range.startContainer.nodeType === 1 ? range.startContainer as Element : range.startContainer.parentElement;\n const block = startElement?.closest('p,h1,h2,h3,h4,h5,h6,li,blockquote,pre');\n if (fragment.childNodes.length === 1 && fragment.firstChild instanceof HTMLParagraphElement && block) {\n const paragraph = fragment.firstChild;\n fragment.replaceChildren(...paragraph.childNodes);\n }\n const hasBlocks = [...fragment.childNodes].some((node) => node instanceof HTMLElement && /^(p|h[1-6]|ul|ol|table|figure|blockquote|pre)$/.test(node.localName));\n const last = fragment.lastChild!;\n if (hasBlocks && block && root.contains(block)) {\n const tailRange = document.createRange();\n tailRange.selectNodeContents(block);\n tailRange.setStart(range.startContainer, range.startOffset);\n const tail = block.cloneNode(false) as HTMLElement;\n tail.append(tailRange.extractContents());\n block.after(fragment);\n if (tail.textContent || tail.querySelector('img,br'))\n last.after(tail);\n if (!block.textContent && !block.querySelector('img'))\n block.remove();\n }\n else\n range.insertNode(fragment);\n const next = document.createRange();\n next.setStartAfter(last);\n next.collapse(true);\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(next);\n // Capture a stable text boundary before history serializes adjacent/empty Text nodes.\n if (!hasBlocks && block && root.contains(block)) block.normalize();\n};\nexport const createEditor = (host: HTMLElement, options: EditorOptions = {}): Editor => {\n if (host.childNodes.length)\n throw new Error('Editor host must be empty. Pass initial HTML through value.');\n const plugins = options.plugins ?? [];\n if (new Set(plugins.map((plugin) => plugin.name)).size !== plugins.length)\n throw new Error('Duplicate editor plugin.');\n const limit = options.historyLimit ?? 100;\n if (!Number.isInteger(limit) || limit < 1 || limit > 10000)\n throw new RangeError('historyLimit must be an integer from 1 to 10000.');\n const schema = createDocumentSchema([...(options.schema ?? []), ...plugins.flatMap((plugin) => plugin.schema ?? [])]);\n const prepareListSplit = (item: HTMLLIElement): void => {\n const attributes = Object.fromEntries([...item.attributes].map(({ name, value }) => [name, value]));\n for (const [name, value] of Object.entries(schema.attributesForSplit('li', attributes))) item.setAttribute(name, value);\n };\n const initialDocument = schema.parseHTML(options.value ?? '');\n let locale = createLocale(options.locale ?? 'ru', options.translations);\n const container = document.createElement('div');\n container.className = 'mw-editor';\n const surface = document.createElement('div');\n surface.className = 'mw-content';\n surface.setAttribute('role', 'textbox');\n surface.setAttribute('aria-multiline', 'true');\n const updateLocale = () => {\n surface.setAttribute('aria-label', options.label ?? localize(locale, 'editor.label', editorMessages));\n surface.dataset.placeholder = options.placeholder ?? localize(locale, 'editor.placeholder', editorMessages);\n };\n updateLocale();\n container.append(surface);\n host.append(container);\n surface.append(schema.renderDocument(initialDocument));\n ensureDocument(surface);\n let destroyed = false;\n let readOnly = options.readOnly ?? false;\n let composing = false;\n let compositionStart: Snapshot | undefined;\n let canceledComposition = false;\n let compositionTail: Snapshot | undefined;\n let compositionUndoRecorded = false;\n let pendingInput: Snapshot | undefined;\n let lastInputTime = 0;\n let lastInputType = '';\n let typingOverrides: Record<string, string | boolean> = {};\n let typingOffset: number | undefined;\n const clearTyping = () => { typingOverrides = {}; typingOffset = undefined; };\n const typingAtCaret = () => {\n if (typingOffset === undefined) return false;\n const selection = readTextSelection(surface);\n return selection?.length === 0 && selection.index === typingOffset;\n };\n const undoStack: Snapshot[] = [];\n const redoStack: Snapshot[] = [];\n const eventHub = createEventHub();\n let transactionDepth = 0;\n let transactionFailed = false;\n let transactionError: unknown;\n let pendingSelectionNotification = false;\n const pluginAPIs = new Map<string, unknown>();\n const disposers: (() => void)[] = [];\n if (options.onChange)\n eventHub.events.on('change', options.onChange);\n const assertActive = () => {\n if (destroyed)\n throw new Error('Editor has been destroyed.');\n };\n const rejectDuringTransaction = (operation: string) => {\n if (!transactionDepth)\n return;\n const error = new Error(`${operation} is unavailable inside a transaction.`);\n transactionFailed = true;\n transactionError = error;\n throw error;\n };\n const events: EditorEvents = {\n on: eventHub.events.on,\n emit: (event, payload) => {\n assertActive();\n rejectDuringTransaction('events.emit');\n eventHub.events.emit(event, payload);\n },\n };\n const htmlSnapshots = createHTMLSnapshots(surface, schema.sanitizeHTML);\n const capture = (): Snapshot => ({ html: htmlSnapshots.read(), selection: bookmark(surface), ...(typingOffset !== undefined && Object.keys(typingOverrides).length && typingAtCaret() ? { typing: { offset: typingOffset, formats: { ...typingOverrides } } } : {}) });\n const restoreTyping = (snapshot: Snapshot) => {\n clearTyping();\n const selection = readTextSelection(surface);\n if (snapshot.typing && selection?.length === 0 && selection.index === snapshot.typing.offset) {\n typingOffset = snapshot.typing.offset;\n typingOverrides = { ...snapshot.typing.formats };\n }\n };\n let current = capture();\n let lastSelection = current.selection;\n const clearCompositionTail = () => {\n compositionTail = undefined;\n compositionUndoRecorded = false;\n };\n const cancelComposition = (rollback: boolean) => {\n const before = compositionStart;\n canceledComposition = canceledComposition || composing || compositionTail !== undefined;\n composing = false;\n compositionStart = undefined;\n pendingInput = undefined;\n clearCompositionTail();\n if (rollback && before) {\n surface.innerHTML = before.html;\n ensureDocument(surface);\n restoreBookmark(surface, before.selection);\n restoreTyping(before);\n current = capture();\n lastSelection = current.selection;\n }\n };\n const restoreCurrentDOM = () => {\n surface.innerHTML = current.html;\n ensureDocument(surface);\n restoreBookmark(surface, current.selection);\n };\n const notifySelection = () => {\n if (destroyed)\n return;\n if (transactionDepth) {\n pendingSelectionNotification = true;\n return;\n }\n if (readTextSelection(surface) && !typingAtCaret())\n clearTyping();\n const saved = bookmark(surface);\n if (saved) {\n lastSelection = saved;\n current.selection = saved;\n }\n eventHub.notify('selectionchange', readTextSelection(surface));\n };\n const emit = (source: EditorChange['source']) => {\n const change: EditorChange = { html: editor.getHTML(), text: editor.getText(), source };\n const failures: unknown[] = [];\n try {\n eventHub.notify('change', change);\n }\n catch (error) {\n failures.push(error);\n }\n try {\n notifySelection();\n }\n catch (error) {\n failures.push(error);\n }\n if (failures.length)\n throw new AggregateError(failures, 'Editor change notification failed.');\n };\n const commitMutation = (before: Snapshot, inputType = ''): boolean => {\n const selection = readTextSelection(surface);\n if (ensureDocument(surface) && selection)\n selectText(surface, selection.index, selection.length);\n const after = capture();\n if (after.html === before.html) {\n current = after;\n return false;\n }\n const now = Date.now();\n const grouped = inputType === lastInputType && ['insertText', 'deleteContentBackward', 'deleteContentForward'].includes(inputType) && now - lastInputTime < 600 && before.selection && current.selection && JSON.stringify(before.selection) === JSON.stringify(current.selection);\n if (!grouped) {\n undoStack.push(before);\n if (undoStack.length > limit)\n undoStack.shift();\n }\n redoStack.length = 0;\n current = after;\n lastInputTime = inputType ? now : 0;\n lastInputType = inputType;\n return true;\n };\n const commit = (before: Snapshot, inputType = '') => {\n if (commitMutation(before, inputType))\n emit('user');\n };\n const restore = (snapshot: Snapshot) => {\n clearTyping();\n surface.innerHTML = snapshot.html;\n ensureDocument(surface);\n surface.focus({ preventScroll: true });\n restoreBookmark(surface, snapshot.selection);\n restoreTyping(snapshot);\n current = capture();\n lastSelection = current.selection;\n lastInputTime = 0;\n emit('user');\n };\n const notifyCommittedInput = (origin: InputCommitOrigin): void => {\n const committed = current;\n const selection = bookmark(surface);\n const selectionKey = JSON.stringify(selection);\n const typingKey = JSON.stringify(typingAtCaret() ? [typingOffset, typingOverrides] : []);\n const receipt: EditorInputCommit = {\n ...origin,\n selection,\n isCurrent: () => !destroyed && !readOnly && !composing && current === committed\n && JSON.stringify(bookmark(surface)) === selectionKey\n && JSON.stringify(typingAtCaret() ? [typingOffset, typingOverrides] : []) === typingKey,\n };\n const failures: unknown[] = [];\n try {\n emit('user');\n }\n catch (error) {\n failures.push(error);\n }\n try {\n eventHub.notify('inputcommit', receipt);\n }\n catch (error) {\n failures.push(error);\n }\n if (failures.length) throw new AggregateError(failures, 'Input commit notification failed.');\n };\n const runTransaction = (mutate: (surface: HTMLElement) => void, inputType = '', origin?: InputCommitOrigin) => {\n assertActive();\n if (readOnly || composing)\n return;\n clearCompositionTail();\n const invoke = () => {\n if (typeof mutate !== 'function' || mutate.constructor.name === 'AsyncFunction')\n throw new TypeError('Transactions require a synchronous callback.');\n const result: unknown = mutate(surface);\n if (result && (typeof result === 'object' || typeof result === 'function') && typeof (result as {\n then?: unknown;\n }).then === 'function') {\n if (result instanceof Promise)\n void result.catch(() => { });\n throw new TypeError('Transaction callbacks must not return a thenable.');\n }\n };\n if (transactionDepth) {\n transactionDepth++;\n try {\n invoke();\n }\n catch (error) {\n transactionFailed = true;\n transactionError = error;\n throw error;\n }\n finally {\n transactionDepth--;\n }\n return;\n }\n editor.focus();\n const before = capture();\n const previousUndo = [...undoStack];\n const previousRedo = [...redoStack];\n const previousInputTime = lastInputTime;\n const previousInputType = lastInputType;\n const previousPendingInput = pendingInput;\n const previousSelection = lastSelection;\n transactionDepth = 1;\n transactionFailed = false;\n transactionError = undefined;\n pendingSelectionNotification = false;\n let changed = false;\n try {\n // A replacement can return to the old text offset without a selectionchange flush.\n const initialRange = activeRange(surface);\n if (initialRange && !initialRange.collapsed) clearTyping();\n invoke();\n if (transactionFailed)\n throw transactionError;\n changed = commitMutation(before, inputType);\n }\n catch (error) {\n surface.innerHTML = before.html;\n ensureDocument(surface);\n restoreBookmark(surface, before.selection);\n restoreTyping(before);\n current = capture();\n lastSelection = previousSelection;\n pendingInput = previousPendingInput;\n undoStack.splice(0, undoStack.length, ...previousUndo);\n redoStack.splice(0, redoStack.length, ...previousRedo);\n lastInputTime = previousInputTime;\n lastInputType = previousInputType;\n transactionDepth = 0;\n pendingSelectionNotification = false;\n throw error;\n }\n finally {\n transactionDepth = 0;\n }\n const selectionChanged = pendingSelectionNotification;\n pendingSelectionNotification = false;\n // Notifications are outside the rollback boundary: observers cannot undo a committed edit by throwing.\n if (changed) {\n if (origin) notifyCommittedInput(origin);\n else emit('user');\n }\n else if (selectionChanged)\n notifySelection();\n };\n const registry = createCommandRegistry({ editor: () => editor, isComposing: () => composing, assertActive });\n const prepareHTML = (html: string): DocumentFragment => {\n try {\n const fragment = schema.renderDocument(schema.parseHTML(html));\n const range = activeRange(surface) ?? rangeFromBookmark(surface, lastSelection);\n prepareSelectionPaste(surface, fragment, range);\n prepareListSelectionPaste(surface, fragment, range);\n return fragment;\n }\n catch (error) {\n // Invalid nested imports poison the outer edit even when its caller catches them.\n if (transactionDepth) {\n transactionFailed = true;\n transactionError = error;\n }\n throw error;\n }\n };\n const insertPrepared = (fragment: DocumentFragment, origin?: InputCommitOrigin): void => {\n if (!fragment.childNodes.length) return;\n if (!activeRange(surface) && lastSelection) restoreBookmark(surface, lastSelection);\n runTransaction(() => {\n // Replacement or a new list body changes the caret's formatting context,\n // even at the same text offset. Capture the original snapshot first.\n const range = activeRange(surface);\n if (range && (!range.collapsed || handlesCollapsedListBlockPaste(surface, fragment, range))) clearTyping();\n insertFragment(surface, fragment);\n }, '', origin);\n };\n const editor: Editor = {\n element: container, surface, events, schema, commands: registry.commands,\n getLocale: () => {\n assertActive();\n return { locale: locale.locale, translations: { ...locale.translations } };\n },\n setLocale: (language, translations) => {\n assertActive();\n rejectDuringTransaction('setLocale');\n const next = createLocale(language, translations);\n const keys = Object.keys(next.translations);\n if (locale.locale === next.locale && keys.length === Object.keys(locale.translations).length && keys.every((key) => Object.hasOwn(locale.translations, key) && locale.translations[key] === next.translations[key]))\n return;\n locale = next;\n updateLocale();\n eventHub.notify('localechange', editor.getLocale());\n },\n getHTML: () => { assertActive(); return htmlSnapshots.read(); },\n getText: () => { assertActive(); return surface.innerText; },\n getJSON: () => { assertActive(); return schema.parseHTML(surface.innerHTML); },\n setHTML: (html) => {\n assertActive();\n rejectDuringTransaction('setHTML');\n const content = schema.documentHTML(schema.parseHTML(html));\n if (content === editor.getHTML())\n return;\n cancelComposition(false);\n clearTyping();\n surface.innerHTML = content;\n ensureDocument(surface);\n undoStack.length = 0;\n redoStack.length = 0;\n lastInputTime = 0;\n lastSelection = undefined;\n current = capture();\n emit('api');\n },\n setJSON: (value) => {\n assertActive();\n rejectDuringTransaction('setJSON');\n const validated = schema.validateDocument(value);\n editor.setHTML(schema.documentHTML(validated));\n },\n getSelection: () => { assertActive(); return readTextSelection(surface); },\n setSelection: (index, length = 0) => { assertActive(); selectText(surface, index, length); notifySelection(); },\n getFormats: (range) => {\n assertActive();\n return range === undefined ? { ...readFormats(surface), ...(typingAtCaret() ? typingOverrides : {}) } : readFormats(surface, range);\n },\n setReadOnly: (value) => {\n assertActive();\n rejectDuringTransaction('setReadOnly');\n const changed = readOnly !== value;\n if (changed && value)\n cancelComposition(true);\n readOnly = value;\n surface.contentEditable = String(!value);\n surface.setAttribute('aria-readonly', String(value));\n container.dataset.readonly = String(value);\n const failures: unknown[] = [];\n if (changed) {\n try {\n eventHub.notify('readonlychange', value);\n }\n catch (error) {\n failures.push(error);\n }\n }\n try {\n notifySelection();\n }\n catch (error) {\n failures.push(error);\n }\n if (failures.length)\n throw new AggregateError(failures, 'Editor state notification failed.');\n },\n isReadOnly: () => { assertActive(); return readOnly; },\n format: (name, value) => {\n assertActive();\n if (readOnly || composing)\n return;\n clearCompositionTail();\n editor.focus();\n const selection = readTextSelection(surface);\n if (selection?.length === 0 && (Object.hasOwn(inlineFormats, name) || Object.hasOwn(inlineStyles, name))) {\n if (!typingAtCaret())\n clearTyping();\n typingOffset = selection.index;\n typingOverrides[name] = Object.hasOwn(inlineStyles, name) ? normalizeInlineStyle(name, value) : Boolean(value);\n notifySelection();\n return;\n }\n clearTyping();\n editor.transact(() => applyFormat(surface, name, value, schema));\n },\n insertHTML: (html) => {\n assertActive();\n if (readOnly || composing) return;\n insertPrepared(prepareHTML(html));\n },\n focus: () => {\n assertActive();\n surface.focus({ preventScroll: true });\n if (!activeRange(surface)) {\n if (lastSelection)\n restoreBookmark(surface, lastSelection);\n else\n placeCaret(surface.firstElementChild as HTMLElement ?? surface, true);\n }\n },\n undo: () => {\n assertActive();\n rejectDuringTransaction('undo');\n if (readOnly || composing)\n return;\n clearCompositionTail();\n const previous = undoStack.pop();\n if (previous) {\n redoStack.push(capture());\n restore(previous);\n }\n },\n redo: () => {\n assertActive();\n rejectDuringTransaction('redo');\n if (readOnly || composing)\n return;\n clearCompositionTail();\n const next = redoStack.pop();\n if (next) {\n undoStack.push(capture());\n restore(next);\n }\n },\n canUndo: () => { assertActive(); return undoStack.length > 0; },\n canRedo: () => { assertActive(); return redoStack.length > 0; },\n transact: (mutate) => runTransaction(mutate),\n providePlugin: (name, api) => {\n assertActive();\n if (pluginAPIs.has(name))\n throw new Error(`Plugin API already registered: ${name}`);\n pluginAPIs.set(name, api);\n return () => { pluginAPIs.delete(name); };\n },\n getPlugin: <T>(name: string) => { assertActive(); return pluginAPIs.get(name) as T | undefined; },\n subscribe: (listener) => { assertActive(); return eventHub.events.on('change', listener); },\n onSelectionChange: (listener) => { assertActive(); return eventHub.events.on('selectionchange', listener); },\n destroy: () => {\n if (destroyed)\n return;\n rejectDuringTransaction('destroy');\n cancelComposition(false);\n destroyed = true;\n const failures: unknown[] = [];\n try {\n eventHub.destroy();\n }\n catch (error) {\n failures.push(error);\n }\n for (const dispose of disposers.reverse()) {\n try {\n dispose();\n }\n catch (error) {\n failures.push(error);\n }\n }\n registry.destroy();\n pluginAPIs.clear();\n undoStack.length = 0;\n redoStack.length = 0;\n htmlSnapshots.clear();\n container.remove();\n if (failures.length)\n throw new AggregateError(failures, 'Editor cleanup failed.');\n },\n };\n const listen = <K extends keyof HTMLElementEventMap>(type: K, handler: (event: HTMLElementEventMap[K]) => void) => {\n surface.addEventListener(type, handler);\n disposers.push(() => surface.removeEventListener(type, handler));\n };\n listen('beforeinput', (event) => {\n if (event.defaultPrevented)\n return;\n if (readOnly) {\n event.preventDefault();\n return;\n }\n const compositionInput = isCompositionInput(event);\n if (canceledComposition && compositionInput) {\n event.preventDefault();\n return;\n }\n if (composing || event.isComposing)\n return;\n if (!compositionInput) {\n canceledComposition = false;\n clearCompositionTail();\n }\n if (event.inputType === 'historyUndo' || event.inputType === 'historyRedo') {\n event.preventDefault();\n if (event.inputType === 'historyUndo')\n editor.undo();\n else\n editor.redo();\n return;\n }\n if (event.cancelable && handlesSelectionReplacement(surface, event.inputType, event.data)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n const text = event.inputType === 'insertText' ? event.data! : '';\n // A replacement is isolated from native typing/deletion bursts on both sides.\n runTransaction(() => replaceSelection(surface, text));\n return;\n }\n const listReplacementInput = (event.inputType === 'insertText' && typeof event.data === 'string')\n || event.inputType === 'deleteContentBackward' || event.inputType === 'deleteContentForward';\n if (event.cancelable && listReplacementInput) {\n const selection = listSelectionReplacement(surface);\n if (selection.status !== 'unowned') {\n event.preventDefault();\n pendingInput = undefined;\n if (selection.status === 'blocked') return;\n clearTyping();\n runTransaction(() => replaceListSelection(surface, event.inputType === 'insertText' ? event.data! : ''));\n return;\n }\n }\n if (event.cancelable && handlesListForwardDelete(surface, event.inputType)) {\n event.preventDefault();\n pendingInput = undefined;\n runTransaction(() => {\n // A boundary barrier is a real no-op, including pending caret formats.\n if (editListForwardDelete(surface)) clearTyping();\n });\n return;\n }\n const wrappedInput = inspectWrappedListInput(surface, event.inputType);\n if (wrappedInput === 'eligible' || wrappedInput === 'blocked') {\n if (!event.cancelable) {\n // Native default cannot be suppressed; do not also run legacy list edits.\n pendingInput = capture();\n return;\n }\n event.preventDefault();\n pendingInput = undefined;\n if (wrappedInput === 'blocked') return;\n runTransaction(() => {\n if (editWrappedListInput(surface, event.inputType, prepareListSplit)) clearTyping();\n }, '', paragraphOrigin(event, event.inputType));\n return;\n }\n if (!composing && !event.isComposing && handlesListInput(surface, event.inputType)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n runTransaction(() => editListInput(surface, event.inputType, prepareListSplit), '', paragraphOrigin(event, event.inputType));\n return;\n }\n if (handlesBlockInput(surface, event.inputType)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n runTransaction(() => editBlockInput(surface, event.inputType), '', paragraphOrigin(event, event.inputType));\n return;\n }\n if (event.inputType === 'insertText' && event.data && !composing && !event.isComposing && typingAtCaret() && Object.keys(typingOverrides).length) {\n event.preventDefault();\n const start = readTextSelection(surface)!.index;\n const text = event.data;\n const overrides = { ...typingOverrides };\n runTransaction(() => {\n const range = activeRange(surface)!;\n const parent = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement;\n const block = parent?.closest('p,h1,h2,h3,h4,h5,h6,li,blockquote,pre');\n if (block && !block.textContent && block.childNodes.length === 1 && block.firstChild instanceof HTMLBRElement) {\n block.replaceChildren();\n range.selectNodeContents(block);\n range.collapse(true);\n }\n range.insertNode(document.createTextNode(text));\n selectText(surface, start, text.length);\n for (const [name, enabled] of Object.entries(overrides))\n if ((Object.hasOwn(inlineStyles, name) ? readFormats(surface)[name] ?? false : Boolean(readFormats(surface)[name])) !== enabled)\n applyFormat(surface, name, enabled, schema);\n selectText(surface, start + text.length);\n typingOffset = start + text.length;\n }, 'insertText');\n pendingInput = undefined;\n return;\n }\n pendingInput = capture();\n });\n listen('input', (nativeEvent) => {\n const event = nativeEvent as InputEvent;\n const compositionInput = isCompositionInput(event);\n if (readOnly || (canceledComposition && compositionInput)) {\n restoreCurrentDOM();\n return;\n }\n if (composing || event.isComposing)\n return;\n if (compositionTail && compositionInput) {\n const before = compositionTail;\n const changed = htmlSnapshots.read() !== current.html;\n pendingInput = undefined;\n if (!changed)\n return;\n // Replace only our own last undo entry, never an intervening application edit.\n if (compositionUndoRecorded && undoStack.at(-1) === before)\n undoStack.pop();\n compositionUndoRecorded = commitMutation(before);\n emit('user');\n return;\n }\n canceledComposition = false;\n clearCompositionTail();\n const before = pendingInput ?? current;\n pendingInput = undefined;\n commit(before, event.inputType);\n });\n listen('compositionstart', () => {\n if (readOnly) {\n canceledComposition = true;\n return;\n }\n if (composing)\n return;\n clearTyping();\n clearCompositionTail();\n pendingInput = undefined;\n canceledComposition = false;\n compositionStart = capture();\n composing = true;\n });\n listen('compositionend', () => {\n if (canceledComposition) {\n pendingInput = undefined;\n restoreCurrentDOM();\n return;\n }\n composing = false;\n const before = compositionStart;\n compositionStart = undefined;\n pendingInput = undefined;\n if (before) {\n compositionTail = before;\n compositionUndoRecorded = commitMutation(before);\n if (compositionUndoRecorded)\n emit('user');\n }\n });\n listen('paste', (event) => {\n if (event.defaultPrevented) return;\n event.preventDefault();\n if (readOnly || composing || !event.clipboardData)\n return;\n let html = event.clipboardData.getData('text/html');\n if (!html) {\n const text = event.clipboardData.getData('text/plain');\n const holder = document.createElement('div');\n holder.textContent = text;\n html = holder.innerHTML.replace(/\\r\\n?|\\n/g, '<br>');\n }\n let fragment: DocumentFragment;\n try { fragment = prepareHTML(html); }\n catch { return; }\n // Commit/observer failures deliberately stay outside the import-only catch.\n insertPrepared(fragment, event.cancelable ? { inputType: 'insertFromPaste', sourceEvent: event } : undefined);\n });\n listen('drop', (event) => { event.preventDefault(); });\n listen('keydown', (event) => {\n if (event.defaultPrevented || event.keyCode === 229)\n return;\n if (!composing && !event.isComposing && !readOnly && !event.ctrlKey && !event.metaKey && !event.altKey && (event.key === 'Enter' || event.key === 'Backspace' || event.key === 'Delete')) {\n const type = event.key === 'Backspace' ? 'deleteContentBackward' : event.key === 'Delete' ? 'deleteContentForward' : event.shiftKey ? 'insertLineBreak' : 'insertParagraph';\n const wrappedInput = inspectWrappedListInput(surface, type);\n const listReplacement = type === 'deleteContentBackward' || type === 'deleteContentForward'\n ? listSelectionReplacement(surface).status !== 'unowned' : false;\n const listOwned = listReplacement || wrappedInput === 'eligible' || wrappedInput === 'blocked'\n || handlesListForwardDelete(surface, type);\n if (listOwned && event.cancelable) {\n // Some native protocols omit boundary beforeinput or mislabel Shift+Enter.\n // Keep one normalized, cancelable input path for core and plugin capture hooks.\n event.preventDefault();\n surface.dispatchEvent(new InputEvent('beforeinput', { inputType: type, bubbles: true, cancelable: true }));\n return;\n }\n if (!listOwned && handlesListInput(surface, type)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n runTransaction(() => editListInput(surface, type, prepareListSplit), '', paragraphOrigin(event, type));\n return;\n }\n // Enter must reach beforeinput so optional typing rules can consume it first.\n if (!listOwned && (event.key !== 'Enter' || event.shiftKey) && handlesBlockInput(surface, type)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n runTransaction(() => editBlockInput(surface, type));\n return;\n }\n }\n if (!composing && !event.isComposing && !readOnly && event.key === 'Tab' && !event.ctrlKey && !event.metaKey && !event.altKey) {\n const blocks = selectedBlocks(surface);\n if (blocks.length && blocks.every((block) => block.localName === 'li' && !block.closest('td,th')) && listState(surface).canOutdent) {\n event.preventDefault();\n clearTyping();\n runTransaction(() => indentList(surface, event.shiftKey ? -1 : 1));\n return;\n }\n }\n if (composing || event.isComposing || readOnly || !(event.ctrlKey || event.metaKey) || event.altKey)\n return;\n const key = event.key.toLowerCase();\n if (key === 'z' || key === 'y') {\n event.preventDefault();\n if (key === 'y' || event.shiftKey)\n editor.redo();\n else\n editor.undo();\n }\n const name = ({ b: 'bold', i: 'italic', u: 'underline' } as Record<string, string>)[key];\n if (name) {\n event.preventDefault();\n editor.format(name, (editor.getFormats().mixed as string[] | undefined)?.includes(name) || !editor.getFormats()[name]);\n }\n });\n document.addEventListener('selectionchange', notifySelection);\n disposers.push(() => document.removeEventListener('selectionchange', notifySelection));\n try {\n editor.setReadOnly(readOnly);\n for (const plugin of plugins) {\n const dispose = plugin.setup(editor);\n if (dispose)\n disposers.push(dispose);\n }\n return editor;\n }\n catch (error) {\n editor.destroy();\n throw error;\n }\n};\n", "import type { LocalizedToolbarAction, ToolbarAction, ToolbarOptions } from './types.js';\nexport type { ToolbarAction, ToolbarOptions } from './types.js';\nimport type { Editor } from '../../index.js';\nimport { inlineStyles, normalizeInlineStyle } from '../../formatting/inline-attributes.js';\nimport { bookmark, restoreBookmark } from '../../selection/index.js';\nimport type { SelectionBookmark } from '../../selection/index.js';\nimport { localize } from '../../localization/index.js';\nimport type { EditorLocale } from '../../localization/types.js';\nimport { toolbarMessages } from './messages.js';\nconst createDefaultActions = (): LocalizedToolbarAction[] => [\n { translationKey: 'toolbar.undo', label: toolbarMessages.ru['toolbar.undo'], text: '\u21B6', run: (editor) => editor.undo(), enabled: (editor) => editor.canUndo() },\n { translationKey: 'toolbar.redo', label: toolbarMessages.ru['toolbar.redo'], text: '\u21B7', run: (editor) => editor.redo(), enabled: (editor) => editor.canRedo() },\n { translationKey: 'toolbar.bold', label: toolbarMessages.ru['toolbar.bold'], text: 'B', format: 'bold' },\n { translationKey: 'toolbar.italic', label: toolbarMessages.ru['toolbar.italic'], text: 'I', format: 'italic' },\n { translationKey: 'toolbar.underline', label: toolbarMessages.ru['toolbar.underline'], text: 'U', format: 'underline' },\n { translationKey: 'toolbar.header', label: toolbarMessages.ru['toolbar.header'], text: 'H\u2082', format: 'header', value: 2 },\n { translationKey: 'toolbar.bulletList', label: toolbarMessages.ru['toolbar.bulletList'], text: '\u2637', format: 'list', value: 'bullet' },\n { translationKey: 'toolbar.orderedList', label: toolbarMessages.ru['toolbar.orderedList'], text: '1.', format: 'list', value: 'ordered' },\n { translationKey: 'toolbar.indent', label: toolbarMessages.ru['toolbar.indent'], text: '\u21E5', format: 'indent', value: 1, enabled: (editor) => Boolean(editor.getFormats().canIndent) },\n { translationKey: 'toolbar.outdent', label: toolbarMessages.ru['toolbar.outdent'], text: '\u21E4', format: 'indent', value: -1, enabled: (editor) => Boolean(editor.getFormats().canOutdent) },\n { translationKey: 'toolbar.blockquote', label: toolbarMessages.ru['toolbar.blockquote'], text: '\u275D', format: 'blockquote' },\n { translationKey: 'toolbar.clear', label: toolbarMessages.ru['toolbar.clear'], text: 'Tx', format: 'clear', enabled: (editor) => Boolean(editor.getSelection()?.length) },\n];\nexport const createToolbar = (host: HTMLElement, editor: Editor, requestedActions?: ToolbarAction[], options: ToolbarOptions = {}): () => void => {\n const defaultActions = requestedActions === undefined ? createDefaultActions() : [];\n const defaultKeys = defaultActions.map((action) => action.translationKey);\n const actions = (requestedActions ?? defaultActions).map((action) => action.format && Object.hasOwn(inlineStyles, action.format) ? { ...action, value: normalizeInlineStyle(action.format, action.value) } : action);\n const toolbar = document.createElement('div');\n toolbar.className = 'mw-toolbar';\n toolbar.setAttribute('role', 'toolbar');\n let saved: SelectionBookmark | undefined;\n let disposed = false;\n let tabIndex = 0;\n const cleanups: (() => void)[] = [];\n const buttons = actions.map((action) => {\n const button = document.createElement('button');\n button.type = 'button';\n button.textContent = action.text;\n button.title = action.label;\n button.setAttribute('aria-label', action.label);\n const down = (event: MouseEvent) => event.preventDefault();\n const click = () => {\n if (disposed || button.disabled || editor.isReadOnly())\n return;\n editor.focus();\n if (saved)\n restoreBookmark(editor.surface, saved);\n if (action.enabled && !action.enabled(editor))\n return;\n if (action.run)\n action.run(editor);\n else if (action.format) {\n const formats = editor.getFormats();\n const mixed = (formats.mixed as string[] | undefined)?.includes(action.format);\n editor.format(action.format, !mixed && formats[action.format] === (action.value ?? true) ? false : action.value ?? true);\n }\n update();\n };\n button.addEventListener('mousedown', down);\n button.addEventListener('click', click);\n cleanups.push(() => { button.removeEventListener('mousedown', down); button.removeEventListener('click', click); });\n toolbar.append(button);\n return button;\n });\n const updateLocale = (state: EditorLocale = editor.getLocale()) => {\n if (disposed)\n return;\n toolbar.setAttribute('aria-label', options.label ?? localize(state, 'toolbar.label', toolbarMessages));\n buttons.forEach((button, index) => {\n const key = defaultKeys[index];\n const label = key ? localize(state, key, toolbarMessages) : actions[index].label;\n button.title = label;\n button.setAttribute('aria-label', label);\n });\n };\n const update = () => {\n if (disposed)\n return;\n saved = bookmark(editor.surface) ?? saved;\n const formats = editor.getFormats();\n buttons.forEach((button, index) => {\n const action = actions[index];\n button.disabled = editor.isReadOnly() || (action.enabled ? !action.enabled(editor) : false);\n if (action.format && !['indent', 'clear'].includes(action.format))\n button.setAttribute('aria-pressed', (formats.mixed as string[] | undefined)?.includes(action.format) ? 'mixed' : String(formats[action.format] === (action.value ?? true)));\n });\n if (buttons[tabIndex]?.disabled || !buttons[tabIndex])\n tabIndex = buttons.findIndex((button) => !button.disabled);\n buttons.forEach((button, index) => { button.tabIndex = index === tabIndex ? 0 : -1; });\n };\n const keyboard = (event: KeyboardEvent) => {\n const enabled = buttons.filter((button) => !button.disabled);\n if (!enabled.length)\n return;\n const index = enabled.indexOf(document.activeElement as HTMLButtonElement);\n if (index < 0 || event.ctrlKey || event.metaKey || event.altKey)\n return;\n if (event.key === 'Escape') {\n event.preventDefault();\n editor.focus();\n if (saved)\n restoreBookmark(editor.surface, saved);\n return;\n }\n const direction = getComputedStyle(toolbar).direction === 'rtl' ? -1 : 1;\n const next = event.key === 'Home' ? 0 : event.key === 'End' ? enabled.length - 1 : event.key === 'ArrowRight' ? (index + direction + enabled.length) % enabled.length : event.key === 'ArrowLeft' ? (index - direction + enabled.length) % enabled.length : -1;\n if (next >= 0) {\n event.preventDefault();\n tabIndex = buttons.indexOf(enabled[next]);\n update();\n enabled[next].focus();\n }\n };\n toolbar.addEventListener('keydown', keyboard);\n const unsubscribe = editor.subscribe((change) => {\n if (change.source === 'api')\n saved = undefined; update();\n });\n const unselect = editor.onSelectionChange(update);\n const unlocale = editor.events.on('localechange', updateLocale);\n host.append(toolbar);\n updateLocale();\n update();\n return () => {\n if (disposed)\n return;\n disposed = true;\n unsubscribe();\n unselect();\n unlocale();\n toolbar.removeEventListener('keydown', keyboard);\n for (const dispose of cleanups)\n dispose();\n toolbar.remove();\n };\n};\n"],
|
|
5
|
+
"mappings": "iFAAO,IAAMA,GAAU,CAACC,EAAeC,IAAuC,CAC5E,IAAMC,EAAUF,EAAM,KAAK,EAC3B,GAAI,CAACE,GAAW,wBAAwB,KAAKA,CAAO,EAClD,OAEF,IAAMC,EAAW,wBAAwB,KAAKD,CAAO,IAAI,CAAC,EAAE,YAAY,EACxE,GAAI,EAAAC,GAAY,EAAEF,EAAQ,CAAC,OAAQ,OAAO,EAAI,CAAC,OAAQ,QAAS,SAAU,KAAK,GAAG,SAASE,CAAQ,IAE/F,EAAAD,EAAQ,WAAW,I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Families", "wideKeywords", "identifier", "normalizeFontFamily", "input", "parts", "result", "part", "value", "quoted", "name", "generic", "word", "normalized", "markers", "normalizeListMarker", "tag", "value", "marker", "tags", "normalizeDirection", "tag", "value", "canonical", "direction", "copyDirection", "source", "target", "voidTags", "consume", "budget", "length", "escaped", "value", "attribute", "remaining", "index", "code", "countText", "countElement", "tag", "attributes", "name", "documentTags", "tags", "omitted", "aliases", "safeStyle", "tag", "value", "result", "declaration", "separator", "property", "marker", "normalizeListMarker", "family", "normalizeFontFamily", "content", "color", "length", "orderedListStart", "number", "attributesFor", "input", "source", "resolve", "originalTag", "output", "key", "direction", "normalizeDirection", "clean", "safeURL", "tokens", "token", "dimensions", "styles", "part", "readDOM", "node", "depth", "budget", "text", "countText", "element", "original", "children", "child", "attr", "attributes", "countElement", "parseHTML", "html", "template", "validateDocument", "visit", "attrs", "values", "index", "renderDocument", "owner", "fragment", "append", "parent", "documentHTML", "container", "sanitizeHTML", "inlineTags", "blockTags", "supportedTag", "kind", "tag", "record", "value", "keysWithin", "allowed", "key", "compileAttribute", "input", "required", "read", "limit", "values", "min", "max", "number", "clean", "safeURL", "createDocumentSchema", "nodes", "registry", "names", "tagAttributes", "splitPolicies", "node", "nonOwning", "documentTags", "rules", "attributes", "name", "rule", "compiled", "existing", "policies", "reset", "resolve", "source", "originalTag", "output", "marker", "validate", "validateDocument", "parse", "html", "parseHTML", "renderDocument", "documentHTML", "tokens", "createEditorCommand", "name", "command", "assertToken", "synchronous", "callback", "rejectThenable", "value", "createCommandRegistry", "options", "entries", "disposed", "assertActive", "resolve", "entry", "stateValue", "fallback", "enabled", "definition", "key", "validate", "execute", "isEnabled", "isActive", "isMixed", "editor", "payload", "validated", "activeRange", "root", "selection", "range", "nodePath", "target", "result", "node", "stableBoundary", "offset", "bookmark", "start", "startOffset", "end", "endOffset", "rangeFromBookmark", "saved", "resolve", "path", "index", "limit", "restoreBookmark", "readTextSelection", "prefix", "selectText", "length", "value", "walker", "nodes", "current", "locate", "last", "placeCaret", "element", "preserveRange", "mutate", "native", "backward", "tail", "head", "next", "inlineTags", "inlineSourceChildren", "element", "node", "blockTags", "parentOf", "node", "editableBlock", "root", "block", "inlineSourceChildren", "parent", "hasContent", "fragment", "selectedBlock", "range", "activeRange", "atEdge", "end", "remainder", "siblingBlock", "forward", "sibling", "handlesBlockInput", "inputType", "editBlockInput", "document", "tailRange", "tail", "emptyHeading", "headingEnd", "paragraph", "attribute", "copyDirection", "placeCaret", "next", "terminal", "lineBreak", "caret", "selection", "left", "right", "join", "leafTags", "ordinaryLeaf", "root", "node", "leaf", "inlineSourceChildren", "selectedLeaves", "range", "left", "right", "leaves", "next", "handlesSelectionReplacement", "inputType", "data", "selectionReplacement", "activeRange", "cutSelectionReplacement", "contentRoots", "document", "emptyLeft", "emptyRight", "caret", "tailRange", "tail", "placeholder", "cut", "ensureReplacementPlaceholder", "finishSelectionReplacement", "selection", "replaceSelection", "text", "selected", "inserted", "insertInlineFragment", "left", "caret", "fragment", "anchor", "last", "stripPlaceholder", "body", "placeholder", "ensureBodyPlaceholder", "caret", "ensureReplacementPlaceholder", "insertReplacementBlocks", "left", "tail", "blocks", "first", "last", "prefix", "insertInlineFragment", "middle", "end", "finishSelectionReplacement", "inlineTags", "leafTags", "blockTags", "inlineNode", "node", "ordinaryPayloadLeaf", "prepareSelectionPaste", "root", "fragment", "range", "selected", "selectionReplacement", "element", "meaningfulTail", "tail", "replaceSelectionWithFragment", "nodes", "singleParagraph", "inline", "leaves", "cut", "cutSelectionReplacement", "left", "right", "caret", "insertInlineFragment", "finishSelectionReplacement", "insertReplacementBlocks", "paragraph", "last", "inserted", "ensureReplacementPlaceholder", "ensureBodyPlaceholder", "suffix", "inlineTags", "sourceInlineNode", "node", "inlineTags", "inlinePayloadNode", "node", "formattingWhitespace", "ordinaryPayloadBody", "quoteBodyBlocks", "quote", "nodes", "isOrdinaryQuote", "sourceBody", "node", "sourceInlineNode", "quoteSourceBodies", "quote", "isOrdinaryQuote", "children", "blocks", "formattingWhitespace", "directQuoteAt", "item", "quoteBodyPoint", "bodies", "range", "end", "point", "contained", "body", "offset", "next", "child", "previous", "quoteEndpointPoint", "quotePasteContext", "start", "normalized", "from", "to", "gaps", "gap", "quoteCrossingContext", "boundaries", "range", "startRoot", "endRoot", "start", "end", "gaps", "first", "last", "from", "to", "affected", "boundary", "index", "quotes", "body", "quote", "quoteSourceBodies", "startQuoted", "endQuoted", "directQuoteAt", "startPoint", "quoteEndpointPoint", "endPoint", "normalized", "left", "right", "ordered", "branch", "intervalBranches", "children", "begin", "finish", "node", "following", "siblings", "promoteInlineBody", "item", "replaceQuoteCrossing", "context", "roots", "covered", "startQuoteBody", "endQuoteBody", "document", "suffixCut", "prefixCut", "ensureBodyPlaceholder", "root", "quoteBodies", "quoteBodyBlocks", "caretBody", "suffix", "gap", "caret", "finishSelectionReplacement", "isList", "node", "itemAt", "root", "item", "inspectItem", "preserveQuotes", "list", "ownNodes", "bodies", "nestedLists", "interleaved", "paragraph", "sourceInlineNode", "quote", "isOrdinaryQuote", "body", "ownStart", "ownEnd", "inspectListItem", "blocked", "reason", "listBodyAt", "range", "boundary", "end", "offset", "children", "child", "index", "normalizeListBodyRange", "point", "count", "atStart", "selectionPlan", "options", "includeSameBody", "includeCollapsed", "firstItem", "lastItem", "first", "last", "directQuoteAt", "endQuote", "branch", "context", "quotePasteContext", "start", "startBody", "endBody", "from", "to", "crossing", "quoteCrossingContext", "workingRange", "leaves", "boundaries", "hasQuote", "gaps", "listSelectionReplacement", "activeRange", "listPasteSelection", "blockCandidate", "ordinaryParagraph", "fragment", "node", "inlinePayloadNode", "multiBlockCandidate", "nodes", "formattingWhitespace", "headingRoot", "ordinaryHeading", "quoteRoot", "ordinaryQuote", "isOrdinaryQuote", "blockPasteCandidate", "ordinaryBlocks", "ordinaryPayloadBody", "requireSupported", "selected", "handlesCollapsedListBlockPaste", "root", "range", "activeRange", "innerPayload", "listPasteSelection", "prepareListSelectionPaste", "blocks", "heading", "quote", "candidate", "quoteBodyBlocks", "cutListSelection", "forceParagraph", "context", "container", "sameItem", "firstBodies", "lastBodies", "startIndex", "endIndex", "following", "branches", "branch", "body", "leaves", "cut", "cutSelectionReplacement", "caretContainer", "offset", "paragraph", "gap", "replaceListSelection", "text", "listSelectionReplacement", "left", "tail", "caret", "inserted", "finishSelectionReplacement", "replaceListSelectionWithFragment", "standalone", "roots", "replaceQuoteCrossing", "suffix", "ensureReplacementPlaceholder", "quoteBlocks", "ensureBodyPlaceholder", "end", "insertReplacementBlocks", "insertInlineFragment", "isList", "node", "selectedItem", "root", "range", "item", "atOwnEnd", "body", "children", "branchIndex", "firstBranch", "ownNodes", "end", "hasText", "blockers", "count", "suffix", "nextItem", "sibling", "removeOwnPlaceholder", "nodes", "placeholder", "atBodyEnd", "point", "content", "removeBodyPlaceholder", "handlesListForwardDelete", "inputType", "activeRange", "boundary", "inspectListItem", "previousEdge", "listBodyAt", "normalizeListBodyRange", "wrapped", "editListForwardDelete", "left", "current", "following", "join", "finishSelectionReplacement", "rightItem", "right", "branch", "target", "rightBody", "laterBodies", "rightNodes", "isList", "node", "whitespace", "supportedList", "root", "list", "inspectListItem", "firstBodyBackspacePlan", "boundary", "previous", "inspected", "parent", "outer", "laterBranches", "branch", "following", "next", "canEditFirstBodyBackspace", "selectRange", "range", "selection", "editFirstBodyBackspace", "start", "plan", "original", "activeRange", "editListForwardDelete", "container", "offset", "body", "copyDirection", "trailing", "caret", "itemAt", "root", "node", "item", "atBodyStart", "body", "range", "prefix", "content", "inspectWrappedListInput", "inputType", "activeRange", "last", "wrappedShape", "candidate", "boundary", "inspectListItem", "listBodyAt", "endBody", "start", "normalizeListBodyRange", "end", "listSelectionReplacement", "canEditFirstBodyBackspace", "ensurePlaceholder", "editWrappedListInput", "prepareSplit", "replaceListSelection", "editFirstBodyBackspace", "previous", "empty", "placeholder", "join", "finishSelectionReplacement", "cut", "caret", "breaks", "suffix", "trailing", "lineBreak", "selection", "tail", "nextItem", "nextBody", "laterBodies", "walker", "text", "placeCaret", "blocks", "isList", "element", "elementAt", "node", "blockAt", "root", "preferItem", "item", "block", "touches", "range", "content", "start", "end", "first", "last", "selectedBlocks", "activeRange", "preferItems", "found", "walker", "topItems", "items", "parent", "itemRange", "siblings", "depth", "result", "numberedBoundary", "list", "compatible", "a", "b", "joinLists", "previous", "splitAround", "replacement", "tail", "ownContent", "unwrapRoot", "paragraphOnly", "paragraphNode", "copyDirection", "paragraph", "nested", "output", "lift", "owner", "trailing", "listState", "canIndent", "child", "indentList", "direction", "preserveRange", "applyList", "value", "selected", "tag", "marker", "normalizeListMarker", "empty", "placeholder", "atStart", "prefix", "handlesListInput", "inputType", "editListInput", "prepareSplit", "next", "caret", "selection", "placeCaret", "br", "target", "inlineStyles", "blocks", "checkedAttributes", "tag", "attributes", "validateDocument", "normalizeInlineStyle", "name", "value", "family", "normalizeFontFamily", "property", "attrs", "probe", "normalized", "normalizeLink", "input", "link", "clean", "mergeLinkAttributes", "previous", "patch", "equalAttributes", "a", "b", "withoutProperty", "style", "part", "groupPieces", "pieces", "result", "piece", "last", "compact", "nodes", "node", "next", "transformInlineAttributes", "document", "from", "to", "operation", "position", "wrap", "group", "children", "visit", "inheritedLink", "start", "left", "right", "begin", "end", "selected", "text", "child", "content", "applyLink", "root", "value", "schema", "link", "normalizeLink", "range", "activeRange", "selection", "readTextSelection", "element", "anchor", "existing", "transformInlineAttributes", "selectText", "attrs", "mergeLinkAttributes", "attr", "preserveRange", "key", "val", "created", "parent", "tail", "native", "blockTags", "textLength", "node", "length", "child", "inlineDocument", "value", "from", "to", "tag", "enabled", "position", "visit", "start", "left", "right", "begin", "end", "selected", "text", "leaf", "children", "piece", "groups", "last", "group", "leaves", "inlineTags", "structuralAncestors", "elementAt", "node", "isInlineTree", "parent", "element", "applyLocalInline", "root", "range", "tag", "enabled", "schema", "block", "prefix", "from", "length", "native", "backward", "content", "inlineDocument", "fragment", "replacement", "selectText", "selected", "inlineFormats", "closestElement", "node", "formatsAt", "root", "element", "formats", "name", "tag", "property", "inlineStyles", "value", "normalizeFontFamily", "readFormats", "projection", "range", "activeRange", "mixed", "prefix", "index", "length", "walker", "position", "samples", "end", "keys", "normalized", "sample", "key", "listState", "applyFormat", "schema", "applyLocalInline", "selection", "readTextSelection", "applyList", "indentList", "content", "inlineDocument", "selectText", "applyLink", "style", "normalizeInlineStyle", "transformInlineAttributes", "blocks", "selectedBlocks", "paragraph", "preserveRange", "block", "nextTag", "replacement", "copyDirection", "tokens", "coreNames", "createPluginEvent", "name", "token", "assertToken", "event", "corePayload", "key", "payload", "locale", "receipt", "saved", "createEventHub", "listeners", "queue", "registration", "dispatching", "closing", "enqueue", "entry", "failures", "next", "bucket", "listener", "registered", "error", "createHTMLSnapshots", "surface", "sanitize", "previousInput", "previousHTML", "input", "html", "createLocale", "locale", "translations", "canonical", "prototype", "entries", "key", "value", "localize", "state", "dictionaries", "override", "exact", "base", "language", "message", "dictionary", "paragraphOrigin", "event", "inputType", "isCompositionInput", "ensureDocument", "root", "normalized", "paragraph", "node", "insertFragment", "fragment", "range", "activeRange", "replaceSelectionWithFragment", "replaceListSelectionWithFragment", "block", "hasBlocks", "last", "tailRange", "tail", "next", "selection", "createEditor", "host", "options", "plugins", "plugin", "limit", "schema", "createDocumentSchema", "prepareListSplit", "item", "attributes", "name", "value", "initialDocument", "locale", "createLocale", "container", "surface", "updateLocale", "localize", "editorMessages", "destroyed", "readOnly", "composing", "compositionStart", "canceledComposition", "compositionTail", "compositionUndoRecorded", "pendingInput", "lastInputTime", "lastInputType", "typingOverrides", "typingOffset", "clearTyping", "typingAtCaret", "readTextSelection", "undoStack", "redoStack", "eventHub", "createEventHub", "transactionDepth", "transactionFailed", "transactionError", "pendingSelectionNotification", "pluginAPIs", "disposers", "assertActive", "rejectDuringTransaction", "operation", "error", "events", "payload", "htmlSnapshots", "createHTMLSnapshots", "capture", "bookmark", "restoreTyping", "snapshot", "current", "lastSelection", "clearCompositionTail", "cancelComposition", "rollback", "before", "restoreBookmark", "restoreCurrentDOM", "notifySelection", "saved", "emit", "source", "change", "editor", "failures", "commitMutation", "selectText", "after", "now", "commit", "restore", "notifyCommittedInput", "origin", "committed", "selectionKey", "typingKey", "receipt", "runTransaction", "mutate", "invoke", "result", "previousUndo", "previousRedo", "previousInputTime", "previousInputType", "previousPendingInput", "previousSelection", "changed", "initialRange", "selectionChanged", "registry", "createCommandRegistry", "prepareHTML", "html", "rangeFromBookmark", "prepareSelectionPaste", "prepareListSelectionPaste", "insertPrepared", "handlesCollapsedListBlockPaste", "language", "translations", "keys", "key", "content", "validated", "index", "length", "readFormats", "inlineFormats", "inlineStyles", "normalizeInlineStyle", "applyFormat", "placeCaret", "previous", "api", "listener", "dispose", "listen", "type", "handler", "compositionInput", "handlesSelectionReplacement", "text", "replaceSelection", "listReplacementInput", "listSelectionReplacement", "replaceListSelection", "handlesListForwardDelete", "editListForwardDelete", "wrappedInput", "inspectWrappedListInput", "editWrappedListInput", "handlesListInput", "editListInput", "handlesBlockInput", "editBlockInput", "start", "overrides", "enabled", "nativeEvent", "holder", "listOwned", "blocks", "selectedBlocks", "listState", "indentList", "createDefaultActions", "toolbarMessages", "editor", "createToolbar", "host", "requestedActions", "options", "defaultActions", "defaultKeys", "action", "actions", "inlineStyles", "normalizeInlineStyle", "toolbar", "saved", "disposed", "tabIndex", "cleanups", "buttons", "button", "down", "event", "click", "restoreBookmark", "formats", "mixed", "update", "updateLocale", "state", "localize", "index", "key", "label", "bookmark", "keyboard", "enabled", "direction", "next", "unsubscribe", "change", "unselect", "unlocale", "dispose"]
|
|
7
7
|
}
|