@morfira-dev/wysiwyg-core 1.4.0 → 1.5.1

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.
@@ -1,21 +1,7 @@
1
+ import type { EditorDocument } from './types.js';
2
+ export type { DocumentTag, TextNode, ElementNode, DocumentNode, EditorDocument } from './types.js';
1
3
  /** Versioned, framework-independent document tree. Only supported HTML semantics are stored. */
2
4
  export declare const documentTags: readonly ["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"];
3
- export type DocumentTag = typeof documentTags[number];
4
- export interface TextNode {
5
- type: 'text';
6
- text: string;
7
- }
8
- export interface ElementNode {
9
- type: 'element';
10
- tag: DocumentTag;
11
- attributes: Record<string, string>;
12
- children: DocumentNode[];
13
- }
14
- export type DocumentNode = TextNode | ElementNode;
15
- export interface EditorDocument {
16
- version: 1;
17
- children: DocumentNode[];
18
- }
19
5
  export declare const parseHTML: (html: string) => EditorDocument;
20
6
  export declare const validateDocument: (input: unknown) => EditorDocument;
21
7
  export declare const renderDocument: (value: EditorDocument) => DocumentFragment;
@@ -0,0 +1,17 @@
1
+ import type { documentTags } from './index.js';
2
+ export type DocumentTag = typeof documentTags[number];
3
+ export interface TextNode {
4
+ type: 'text';
5
+ text: string;
6
+ }
7
+ export interface ElementNode {
8
+ type: 'element';
9
+ tag: DocumentTag;
10
+ attributes: Record<string, string>;
11
+ children: DocumentNode[];
12
+ }
13
+ export type DocumentNode = TextNode | ElementNode;
14
+ export interface EditorDocument {
15
+ version: 1;
16
+ children: DocumentNode[];
17
+ }
@@ -0,0 +1,2 @@
1
+ import type { Editor, EditorOptions } from './types.js';
2
+ export declare const createEditor: (host: HTMLElement, options?: EditorOptions) => Editor;
@@ -0,0 +1,5 @@
1
+ /** Reuse only a successfully validated string for the exact current serialized DOM. */
2
+ export declare const createHTMLSnapshots: (surface: HTMLElement) => {
3
+ read: () => string;
4
+ clear: () => void;
5
+ };
@@ -0,0 +1,58 @@
1
+ import type { EditorDocument } from '../document/index.js';
2
+ import type { SelectionBookmark, TextSelection } from '../selection/index.js';
3
+ import type { EditorEvents } from '../events/types.js';
4
+ export interface EditorChange {
5
+ html: string;
6
+ text: string;
7
+ source: 'user' | 'api';
8
+ }
9
+ export interface EditorPlugin {
10
+ name: string;
11
+ setup(editor: Editor): void | (() => void);
12
+ }
13
+ export interface EditorOptions {
14
+ value?: string;
15
+ placeholder?: string;
16
+ readOnly?: boolean;
17
+ label?: string;
18
+ plugins?: EditorPlugin[];
19
+ onChange?: (change: EditorChange) => void;
20
+ historyLimit?: number;
21
+ }
22
+ export interface Editor {
23
+ readonly element: HTMLElement;
24
+ readonly surface: HTMLElement;
25
+ readonly events: EditorEvents;
26
+ getHTML(): string;
27
+ getText(): string;
28
+ getJSON(): EditorDocument;
29
+ setHTML(html: string): void;
30
+ setJSON(value: EditorDocument): void;
31
+ getSelection(): TextSelection | undefined;
32
+ setSelection(index: number, length?: number): void;
33
+ getFormats(): Record<string, unknown>;
34
+ setReadOnly(value: boolean): void;
35
+ isReadOnly(): boolean;
36
+ format(name: string, value: unknown): void;
37
+ insertHTML(html: string): void;
38
+ focus(): void;
39
+ undo(): void;
40
+ redo(): void;
41
+ canUndo(): boolean;
42
+ canRedo(): boolean;
43
+ /** Execute a plugin edit as one undoable operation. Read-only mode blocks it. */
44
+ transact(mutate: (surface: HTMLElement) => void): void;
45
+ providePlugin<T>(name: string, api: T): () => void;
46
+ getPlugin<T>(name: string): T | undefined;
47
+ subscribe(listener: (change: EditorChange) => void): () => void;
48
+ onSelectionChange(listener: () => void): () => void;
49
+ destroy(): void;
50
+ }
51
+ export interface Snapshot {
52
+ html: string;
53
+ selection: SelectionBookmark | undefined;
54
+ typing?: {
55
+ offset: number;
56
+ formats: Record<string, string | boolean>;
57
+ };
58
+ }
@@ -0,0 +1,4 @@
1
+ import type { EventHub, PluginEvent } from './types.js';
2
+ export type { EditorEventMap, EditorEvents, PluginEvent } from './types.js';
3
+ export declare const createPluginEvent: <T>(name: string) => PluginEvent<T>;
4
+ export declare const createEventHub: () => EventHub;
@@ -0,0 +1,29 @@
1
+ import type { EditorChange } from '../editor/types.js';
2
+ import type { TextSelection } from '../selection/index.js';
3
+ declare const eventType: unique symbol;
4
+ export interface PluginEvent<T> {
5
+ readonly name: string;
6
+ readonly [eventType]: (payload: T) => T;
7
+ }
8
+ export interface EditorEventMap {
9
+ change: EditorChange;
10
+ selectionchange: TextSelection | undefined;
11
+ readonlychange: boolean;
12
+ destroy: void;
13
+ }
14
+ export interface EditorEvents {
15
+ on<K extends keyof EditorEventMap>(event: K, listener: (payload: EditorEventMap[K]) => void): () => void;
16
+ on<T>(event: PluginEvent<T>, listener: (payload: T) => void): () => void;
17
+ emit<T>(event: PluginEvent<T>, payload: T): void;
18
+ }
19
+ export interface EventHub {
20
+ events: EditorEvents;
21
+ notify<K extends keyof EditorEventMap>(event: K, payload: EditorEventMap[K]): void;
22
+ destroy(): void;
23
+ }
24
+ export interface QueuedEvent {
25
+ key: string | object;
26
+ payload: unknown;
27
+ core: boolean;
28
+ }
29
+ export {};
@@ -1,4 +1,4 @@
1
- import type { DocumentTag } from './model.js';
1
+ import type { DocumentTag } from '../document/index.js';
2
2
  export declare const inlineFormats: Record<string, DocumentTag>;
3
3
  export declare const readFormats: (root: HTMLElement) => Record<string, unknown>;
4
4
  export declare const applyFormat: (root: HTMLElement, name: string, value: unknown) => void;
@@ -1,25 +1,11 @@
1
- import type { EditorDocument } from './model.js';
2
- export interface LinkFormat {
3
- href: string;
4
- title?: string;
5
- target?: '_self' | '_blank';
6
- text?: string;
7
- }
1
+ import type { Attributes, Operation } from './inline-attributes.types.js';
2
+ export type { LinkFormat } from './inline-attributes.types.js';
3
+ import type { EditorDocument } from '../document/index.js';
8
4
  export declare const inlineStyles: Record<string, string>;
9
- type Attributes = Record<string, string>;
10
5
  export declare const normalizeInlineStyle: (name: string, value: unknown) => string | false;
11
6
  export declare const normalizeLink: (value: unknown) => {
12
7
  attributes: Attributes;
13
8
  text?: string;
14
9
  } | false;
15
10
  export declare const mergeLinkAttributes: (previous: Attributes, patch: Attributes) => Attributes;
16
- type Operation = {
17
- kind: 'style';
18
- property: string;
19
- value: string | false;
20
- } | {
21
- kind: 'link';
22
- attributes: Attributes | false;
23
- };
24
11
  export declare const transformInlineAttributes: (document: EditorDocument, from: number, to: number, operation: Operation) => EditorDocument;
25
- export {};
@@ -0,0 +1,21 @@
1
+ import type { DocumentNode } from '../document/index.js';
2
+ export interface LinkFormat {
3
+ href: string;
4
+ title?: string;
5
+ target?: '_self' | '_blank';
6
+ text?: string;
7
+ }
8
+ export type Attributes = Record<string, string>;
9
+ export type Operation = {
10
+ kind: 'style';
11
+ property: string;
12
+ value: string | false;
13
+ } | {
14
+ kind: 'link';
15
+ attributes: Attributes | false;
16
+ };
17
+ export interface Piece {
18
+ node: DocumentNode;
19
+ selected: boolean;
20
+ link?: Attributes;
21
+ }
@@ -0,0 +1,2 @@
1
+ import type { DocumentTag, EditorDocument } from '../document/index.js';
2
+ export declare const inlineDocument: (value: EditorDocument, from: number, to: number, tag: DocumentTag, enabled: boolean) => EditorDocument;
@@ -0,0 +1,3 @@
1
+ import type { DocumentTag } from '../document/index.js';
2
+ /** Transform one schema-validated leaf while keeping unrelated editor DOM connected. */
3
+ export declare const applyLocalInline: (root: HTMLElement, range: Range, tag: DocumentTag, enabled: boolean) => boolean;
@@ -0,0 +1,9 @@
1
+ import type { DocumentNode } from '../document/index.js';
2
+ export interface Piece {
3
+ node: DocumentNode;
4
+ selected: boolean;
5
+ }
6
+ export interface InlineGroup {
7
+ selected: boolean;
8
+ children: DocumentNode[];
9
+ }
package/dist/index.d.ts CHANGED
@@ -1,55 +1,10 @@
1
- import type { EditorDocument } from './model.js';
2
- import type { TextSelection } from './selection.js';
3
- export type { LinkFormat } from './inline-attributes.js';
4
- export { sanitizeHTML } from './model.js';
5
- export type { EditorDocument, DocumentNode, ElementNode, TextNode, DocumentTag } from './model.js';
6
- export type { TextSelection, SelectionBookmark } from './selection.js';
7
- export interface EditorChange {
8
- html: string;
9
- text: string;
10
- source: 'user' | 'api';
11
- }
12
- export interface EditorPlugin {
13
- name: string;
14
- setup(editor: Editor): void | (() => void);
15
- }
16
- export interface EditorOptions {
17
- value?: string;
18
- placeholder?: string;
19
- readOnly?: boolean;
20
- label?: string;
21
- plugins?: EditorPlugin[];
22
- onChange?: (change: EditorChange) => void;
23
- historyLimit?: number;
24
- }
25
- export interface Editor {
26
- readonly element: HTMLElement;
27
- readonly surface: HTMLElement;
28
- getHTML(): string;
29
- getText(): string;
30
- getJSON(): EditorDocument;
31
- setHTML(html: string): void;
32
- setJSON(value: EditorDocument): void;
33
- getSelection(): TextSelection | undefined;
34
- setSelection(index: number, length?: number): void;
35
- getFormats(): Record<string, unknown>;
36
- setReadOnly(value: boolean): void;
37
- isReadOnly(): boolean;
38
- format(name: string, value: unknown): void;
39
- insertHTML(html: string): void;
40
- focus(): void;
41
- undo(): void;
42
- redo(): void;
43
- canUndo(): boolean;
44
- canRedo(): boolean;
45
- /** Execute a plugin edit as one undoable operation. Read-only mode blocks it. */
46
- transact(mutate: (surface: HTMLElement) => void): void;
47
- providePlugin<T>(name: string, api: T): () => void;
48
- getPlugin<T>(name: string): T | undefined;
49
- subscribe(listener: (change: EditorChange) => void): () => void;
50
- onSelectionChange(listener: () => void): () => void;
51
- destroy(): void;
52
- }
53
- export declare const createEditor: (host: HTMLElement, options?: EditorOptions) => Editor;
54
- export { createToolbar } from './toolbar.js';
55
- export type { ToolbarAction, ToolbarOptions } from './toolbar.js';
1
+ export { createEditor } from './editor/create-editor.js';
2
+ export type { Editor, EditorChange, EditorOptions, EditorPlugin } from './editor/types.js';
3
+ export { sanitizeHTML } from './document/index.js';
4
+ export type { EditorDocument, DocumentNode, ElementNode, TextNode, DocumentTag } from './document/types.js';
5
+ export type { TextSelection, SelectionBookmark } from './selection/types.js';
6
+ export type { LinkFormat } from './formatting/inline-attributes.types.js';
7
+ export { createToolbar } from './ui/toolbar/index.js';
8
+ export type { ToolbarAction, ToolbarOptions } from './ui/toolbar/types.js';
9
+ export { createPluginEvent } from './events/index.js';
10
+ export type { EditorEvents, EditorEventMap, PluginEvent } from './events/types.js';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Ue=["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"],Le=new Set(Ue),We=new Set(["script","style","iframe","object","embed","svg","math","template","form","input","button","textarea","select","noscript","link","meta","base"]),Je={b:"strong",i:"em",strike:"s",div:"p"},we=1e5,Ne=100,Xe=(e,r)=>{let t=e.trim();if(!t||/[\u0000-\u0020\u007f]/.test(t))return;let n=/^([a-z][a-z\d+.-]*):/i.exec(t)?.[1].toLowerCase();if(!(n&&!(r?["http","https"]:["http","https","mailto","tel"]).includes(n))&&!(t.startsWith("\\")||t.startsWith("//")))return t},Ve=e=>{let r=[];for(let t of e.split(";")){let n=t.indexOf(":");if(n<0)continue;let o=t.slice(0,n).trim().toLowerCase(),s=t.slice(n+1).trim().toLowerCase(),i=/^(#[a-f\d]{3,8}|[a-z]{1,24}|(?:rgb|rgba|hsl|hsla)\([\d\s.,%+-]+\))$/,a=/^(?:\d{1,4}(?:\.\d{1,3})?)(?:px|%|em|rem)$/;(["color","background-color","border-color"].includes(o)?i.test(s):["width","height","font-size"].includes(o)?a.test(s):o==="text-align"?["left","center","right","justify"].includes(s):o==="font-weight"?/^(bold|normal|[1-9]00)$/.test(s):o==="font-style"?["italic","normal"].includes(s):o==="text-decoration"?/^(underline|line-through|none)$/.test(s):!1)&&r.push(`${o}: ${s}`)}return r.join("; ")},Me=(e,r)=>{let t={};for(let[n,o]of Object.entries(r))if(!(typeof o!="string"||o.length>2e4))if(n==="style"){let s=Ve(o);s&&(t.style=s)}else if(n==="title"||e==="img"&&n==="alt")t[n]=o;else if(e==="a"&&n==="href"||e==="img"&&n==="src"){let s=Xe(o,e==="img");s&&(t[n]=s)}else if(["td","th"].includes(e)&&["rowspan","colspan"].includes(n)||["img","col","table"].includes(e)&&["width","height","span"].includes(n))/^\d{1,4}$/.test(o)&&Number(o)>0&&Number(o)<=1e3&&(t[n]=o);else if(e==="a"&&n==="target"&&["_self","_blank"].includes(o))t.target=o;else if(e==="a"&&n==="rel"){let s=[...new Set(o.toLowerCase().split(/\s+/).filter(i=>["noopener","noreferrer"].includes(i)))];s.length&&(t.rel=s.join(" "))}else e==="th"&&n==="scope"&&["row","col","rowgroup","colgroup"].includes(o)&&(t[n]=o);if(e==="img"&&(t.width||t.height)){let n=["width","height"].filter(s=>t[s]),o=(t.style??"").split(";").map(s=>s.trim()).filter(s=>s&&!n.includes(s.slice(0,s.indexOf(":")).trim()));t.style=[...o,...n.map(s=>`${s}: ${t[s]}px`)].join("; ")}return e==="a"&&t.target==="_blank"&&(t.rel="noopener noreferrer"),t},Se=(e,r,t)=>{if(++t.count>we||r>Ne)throw new RangeError("Document exceeds structural limits.");if(e.nodeType===3)return[{type:"text",text:e.textContent??""}];if(e.nodeType!==1)return[];let n=e,o=n.localName.toLowerCase();if(n.namespaceURI!=="http://www.w3.org/1999/xhtml"||We.has(o))return[];let s=[...n.childNodes].flatMap(c=>Se(c,r+1,t)),i=Je[o]??o;if(!Le.has(i))return s;let a=Me(i,Object.fromEntries([...n.attributes].map(c=>[c.name,c.value])));return i==="img"&&!a.src?[]:[{type:"element",tag:i,attributes:a,children:s}]},A=e=>{if(e.length>5e6)throw new RangeError("HTML exceeds the document size limit.");let r=document.createElement("template");r.innerHTML=e;let t={count:0};return{version:1,children:[...r.content.childNodes].flatMap(n=>Se(n,0,t))}},ne=e=>{if(!e||typeof e!="object"||!("version"in e)||e.version!==1||!("children"in e)||!Array.isArray(e.children))throw new TypeError("Expected a version 1 document.");let r=0,t=0,n=(o,s)=>{if(++r>we||s>Ne)throw new RangeError("Document exceeds structural limits.");if(!o||typeof o!="object"||!("type"in o))throw new TypeError("Invalid document node.");if(o.type==="text"&&"text"in o&&typeof o.text=="string"){if(t+=o.text.length,t>5e6)throw new RangeError("Document text exceeds size limit.");return{type:"text",text:o.text}}if(o.type!=="element"||!("tag"in o)||typeof o.tag!="string"||!Le.has(o.tag)||!("children"in o)||!Array.isArray(o.children))throw new TypeError("Invalid document element.");let i="attributes"in o&&o.attributes&&typeof o.attributes=="object"&&!Array.isArray(o.attributes)?o.attributes:{};return{type:"element",tag:o.tag,attributes:Me(o.tag,i),children:o.children.map(a=>n(a,s+1))}};return{version:1,children:e.children.map(o=>n(o,0))}},re=e=>{let r=document.createDocumentFragment(),t=(n,o)=>{if(o.type==="text"){n.appendChild(document.createTextNode(o.text));return}let s=document.createElement(o.tag);for(let[i,a]of Object.entries(o.attributes))s.setAttribute(i,a);for(let i of o.children)t(s,i);n.appendChild(s)};for(let n of e.children)t(r,n);return r},j=e=>{let r=document.createElement("div");return r.append(re(e)),r.innerHTML},oe=e=>j(A(e));var N=e=>{let r=e.ownerDocument.getSelection();if(!r?.rangeCount)return;let t=r.getRangeAt(0);if(!(!e.contains(t.startContainer)||!e.contains(t.endContainer)))return t.cloneRange()},He=(e,r)=>{let t=[],n=r;for(;n!==e&&n.parentNode;)t.unshift([...n.parentNode.childNodes].indexOf(n)),n=n.parentNode;return t},X=e=>{let r=N(e);if(!r)return;let t=e.ownerDocument.getSelection();return{start:He(e,r.startContainer),startOffset:r.startOffset,end:He(e,r.endContainer),endOffset:r.endOffset,backward:!r.collapsed&&t.anchorNode===r.endContainer&&t.anchorOffset===r.endOffset}},q=(e,r)=>{if(!r)return;let t=d=>d.reduce((g,u)=>g.childNodes[u]??g,e),n=t(r.start),o=t(r.end),s=(d,g)=>Math.min(g,d.nodeType===3?d.textContent?.length??0:d.childNodes.length),i=e.ownerDocument.getSelection();if(!i)return;let a=s(n,r.startOffset),c=s(o,r.endOffset);r.backward?i.setBaseAndExtent(o,c,n,a):i.setBaseAndExtent(n,a,o,c)},H=e=>{let r=N(e);if(!r)return;let t=e.ownerDocument.createRange();return t.selectNodeContents(e),t.setEnd(r.startContainer,r.startOffset),{index:t.toString().length,length:r.toString().length}},R=(e,r,t=0)=>{if(![r,t].every(b=>Number.isInteger(b)&&b>=0))throw new RangeError("Selection offsets must be non-negative integers.");let n=e.ownerDocument.createTreeWalker(e,4),o=[],s;for(;s=n.nextNode();)o.push(s);let i=b=>{for(let h of o){if(b<=h.length)return[h,b];b-=h.length}let f=o.at(-1);return f?[f,f.length]:[e.querySelector("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre")??e,0]},[a,c]=i(r),[d,g]=i(r+t),u=e.ownerDocument.createRange();u.setStart(a,c),u.setEnd(d,g),e.focus({preventScroll:!0});let m=e.ownerDocument.getSelection();m?.removeAllRanges(),m?.addRange(u)},se=(e,r=!1)=>{let t=e.ownerDocument.createRange();t.selectNodeContents(e),t.collapse(!r);let n=e.ownerDocument.getSelection();n?.removeAllRanges(),n?.addRange(t)},B=(e,r)=>{let t=N(e);if(!t)return;let n=e.ownerDocument.getSelection(),o=!t.collapsed&&n.anchorNode===t.endContainer&&n.anchorOffset===t.endOffset,s=e.ownerDocument.createComment("mw-start"),i=t.collapsed?void 0:e.ownerDocument.createComment("mw-end");if(i){let c=t.cloneRange();c.collapse(!1),c.insertNode(i)}let a=t.cloneRange();a.collapse(!0),a.insertNode(s);try{if(r(),e.contains(s)&&(!i||e.contains(i))){let c=e.ownerDocument.createRange();c.setStartBefore(s),i?c.setEndBefore(i):c.collapse(!0),s.remove(),i?.remove(),e.normalize(),o?n.setBaseAndExtent(c.endContainer,c.endOffset,c.startContainer,c.startOffset):(n.removeAllRanges(),n.addRange(c))}}finally{s.remove(),i?.remove()}};var De="p,h1,h2,h3,h4,h5,h6,blockquote,pre,li",D=e=>!!e&&/^(ul|ol)$/.test(e.localName),Ge=e=>e instanceof Element?e:e.parentElement,Q=(e,r,t=!0)=>{let n=Ge(r),o=n?.closest("li"),s=(t&&o&&e.contains(o)?o:void 0)??n?.closest(De);return s&&e.contains(s)?s:void 0},Qe=(e,r)=>{let t=r.ownerDocument.createRange();r.nodeType===3?t.selectNodeContents(r):t.selectNode(r);let n=e.cloneRange();n.collapse(!0);let o=e.cloneRange();o.collapse(!1);let s=t.cloneRange();s.collapse(!0);let i=t.cloneRange();return i.collapse(!1),n.compareBoundaryPoints(Range.START_TO_START,i)<0&&o.compareBoundaryPoints(Range.START_TO_START,s)>0},$=(e,r=N(e),t=!0)=>{if(!r)return[];if(r.collapsed){let i=Q(e,r.startContainer,t);return i?[i]:[]}let n=new Set,o=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT),s;for(;s=o.nextNode();)if(!(!(s.nodeType===3&&s.textContent)&&!(s instanceof Element&&/^(br|img|hr)$/.test(s.localName)))&&Qe(r,s)){let i=Q(e,s,t);i&&n.add(i)}return[...e.querySelectorAll(De)].filter(i=>n.has(i))},Re=e=>e.filter(r=>!e.some(t=>t!==r&&t.contains(r))),Oe=e=>{let r=Re($(e));if(!r.length||r.some(o=>o.localName!=="li"||!D(o.parentElement)))return[];let t=r[0].parentElement;if(r.some(o=>o.parentElement!==t))return[];let n=[...t.children];return n.indexOf(r.at(-1))-n.indexOf(r[0])+1!==r.length?[]:r},Ce=(e,r)=>{let t=0,n=r.parentElement;for(;n&&n!==e;)D(n)&&t++,n=n.parentElement;return t},ve=(e,r)=>!!e&&e.localName===r.localName&&D(e)&&e.getAttribute("style")===r.getAttribute("style"),V=e=>{for(let r of[...e.querySelectorAll("ul,ol")]){if(!e.contains(r))continue;let t=r.previousSibling;t instanceof Element&&ve(t,r)&&(t.append(...r.childNodes),r.remove())}},je=(e,r)=>{let t=e.parentElement,n=t.cloneNode(!1);for(;e.nextSibling;)n.append(e.nextSibling);e.remove(),t.after(...r,...n.childNodes.length?[n]:[]),t.childNodes.length||t.remove()},G=e=>[...e.childNodes].filter(r=>!(r instanceof Element&&D(r))),Be=(e,r=!1)=>{let t=()=>{let a=document.createElement("p");return e.hasAttribute("style")&&a.setAttribute("style",e.getAttribute("style")),a},n=t(),o=[...e.children].filter(D),s=G(e),i=[];for(let a of s)r&&a instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(a.localName)?n.append(...a.childNodes):a instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(a.localName)?(n.childNodes.length&&i.push(n),n=t(),i.push(a)):n.append(a);(n.childNodes.length||!i.length)&&(n.childNodes.length||n.append(document.createElement("br")),i.push(n)),je(e,[...i,...o])},ie=e=>{let r=e[0].parentElement,t=r.parentElement;if(t?.localName!=="li"||!D(t.parentElement)){for(let o of e)Be(o);return}let n=r.cloneNode(!1);for(;e.at(-1).nextSibling;)n.append(e.at(-1).nextSibling);n.childNodes.length&&e.at(-1).append(n),t.after(...e),r.childNodes.length||r.remove()},Y=e=>{let r=Oe(e),t=!!r.length&&r[0].previousElementSibling?.localName==="li"&&r.every(n=>[n,...n.querySelectorAll("li")].every(o=>Ce(e,o)<8));return{listDepth:r.length?Ce(e,r[0]):0,canIndent:t,canOutdent:!!r.length}},le=(e,r)=>{if(r!==1&&r!==-1)throw new TypeError("List indentation requires 1 or -1.");let t=Oe(e);if(!t.length)throw new RangeError("Select consecutive items in the same list.");r===1&&!Y(e).canIndent||B(e,()=>{if(r===-1)ie(t);else{let n=t[0].parentElement,o=t[0].previousElementSibling,s=o.lastElementChild;ve(s,n)||(s=n.cloneNode(!1),o.append(s)),s.append(...t)}V(e)})},Ie=(e,r)=>{if(r!==!1&&r!=="bullet"&&r!=="ordered")throw new TypeError("Expected bullet, ordered or false.");let t=Re($(e));if(t.some(n=>n.localName==="li"&&!D(n.parentElement)))throw new RangeError("A list item must belong to a list.");B(e,()=>{for(let n of t){if(!r){n.localName==="li"&&ie([n]);continue}let o=r==="bullet"?"ul":"ol";if(n.localName==="li"){if(n.parentElement.localName===o)continue;let s=document.createElement(o);n.parentElement.hasAttribute("style")&&s.setAttribute("style",n.parentElement.getAttribute("style")),je(n,[s]),s.append(n)}else{let s=document.createElement(o),i=document.createElement("li");n.hasAttribute("style")&&i.setAttribute("style",n.getAttribute("style")),i.append(...n.childNodes),s.append(i),n.replaceWith(s)}}V(e)})},Ye=e=>!e.textContent?.trim()&&!e.querySelector("img,hr,ul,ol"),Ae=e=>{G(e).some(n=>n.textContent||n instanceof Element&&(n.matches("br,img,hr")||n.querySelector("br,img,hr")))||([...e.children].some(D)?e.prepend(Object.assign(document.createElement("p"),{innerHTML:"<br>"})):e.append(document.createElement("br")))},Ze=(e,r)=>{let t=r.cloneRange();return t.selectNodeContents(e),t.setEnd(r.startContainer,r.startOffset),!t.toString()&&!t.cloneContents().querySelector("img,hr,br")},pe=(e,r)=>{let t=N(e);if(!t)return!1;let n=Q(e,t.startContainer);return n?.localName!=="li"||!D(n.parentElement)||Q(e,t.endContainer)!==n?!1:["insertParagraph","insertLineBreak"].includes(r)||r==="deleteContentBackward"&&t.collapsed&&Ze(n,t)},ge=(e,r)=>{let t=N(e),n=Q(e,t.startContainer);if(r==="insertParagraph"){if(Ye(n)){B(e,()=>{let c=n.parentElement.parentElement;c?.localName==="li"&&D(c.parentElement)?ie([n]):Be(n,!0)}),V(e);return}t.deleteContents();let o=t.cloneRange();o.selectNodeContents(n),o.setStart(t.startContainer,t.startOffset);let s=n.cloneNode(!1);s.append(o.extractContents()),n.after(s),Ae(n),Ae(s);let i=document.createTreeWalker(s,NodeFilter.SHOW_TEXT),a;do a=i.nextNode();while(a&&(!a.textContent||a.parentElement?.closest("li")!==s));if(a){let c=document.createRange();c.setStart(a,0),c.collapse(!0);let d=document.getSelection();d?.removeAllRanges(),d?.addRange(c)}else se(s.querySelector("p,h1,h2,h3,h4,h5,h6,pre")??s)}else if(r==="insertLineBreak"){t.deleteContents();let o=document.createElement("br");t.insertNode(o),o.nextSibling||o.after(document.createElement("br")),t.setStartAfter(o),t.collapse(!0);let s=document.getSelection();s?.removeAllRanges(),s?.addRange(t)}else{let o=n.previousElementSibling;if(o&&o.localName!=="li")return;if(!o){B(e,()=>ie([n])),V(e);return}if(!G(o).some(m=>m.textContent||m instanceof Element&&(m.localName==="img"||m.querySelector("img"))))for(let m of[...o.querySelectorAll("br")])m.closest("li")===o&&m.remove();let s=document.createComment("mw-join"),a=G(o).at(-1),c=a instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(a.localName)?a:o;c===o?o.insertBefore(s,[...o.children].find(D)??null):c.append(s);let d=G(n);d[0]instanceof HTMLElement&&/^(p|h[1-6])$/.test(d[0].localName)&&d.splice(0,1,...d[0].childNodes),s.after(...d);for(let m of[...n.children].filter(D))o.append(m);n.remove(),V(e);let g=document.createRange();g.setStartBefore(s),g.collapse(!0),s.remove();let u=document.getSelection();u?.removeAllRanges(),u?.addRange(g)}};var O={color:"color",background:"background-color"},Pe=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"]),be=(e,r)=>ne({version:1,children:[{type:"element",tag:e,attributes:r,children:[]}]}).children[0].attributes,_=(e,r)=>{if(r===!1)return!1;if(typeof r!="string"||!r.trim()||r.length>128||/[;{}]/.test(r))throw new TypeError("Expected a CSS color or false.");let t=O[e],n=be("span",{style:`${t}: ${r}`}),o=document.createElement("span");o.setAttribute("style",n.style??"");let s=o.style.getPropertyValue(t);if(!s)throw new TypeError("Unsupported or invalid CSS color.");return s},Fe=e=>{if(e===!1)return!1;let r=typeof e=="string"?{href:e}:e;if(!r||typeof r!="object"||Array.isArray(r)||!("href"in r)||typeof r.href!="string")throw new TypeError("Expected a link URL, LinkFormat or false.");let t=r,n={href:r.href};if(t.title!==void 0){if(typeof t.title!="string"||t.title.length>1024)throw new TypeError("Link title must be a string up to 1024 characters.");n.title=t.title}if(t.target!==void 0){if(t.target!=="_self"&&t.target!=="_blank")throw new TypeError("Link target must be _self or _blank.");n.target=t.target}if(t.text!==void 0&&(typeof t.text!="string"||!t.text.length||t.text.length>2e4))throw new TypeError("New link text must contain 1\u201320000 characters.");let o=be("a",n);if(!o.href)throw new TypeError("Unsupported or unsafe link URL.");return{attributes:o,...typeof t.text=="string"?{text:t.text}:{}}},Ee=(e,r)=>{let t={...e,...r};return t.title||delete t.title,r.target==="_self"&&delete t.rel,be("a",t)},$e=(e,r)=>JSON.stringify(Object.entries(e??{}).sort())===JSON.stringify(Object.entries(r??{}).sort()),et=(e,r)=>{let t={...e},n=(t.style??"").split(";").map(o=>o.trim()).filter(o=>o&&o.slice(0,o.indexOf(":")).trim()!==r).join("; ");return n?t.style=n:delete t.style,t},qe=e=>{let r=[];for(let t of e){let n=r.at(-1);n&&n.selected===t.selected&&$e(n.link,t.link)?n.pieces.push(t):r.push({pieces:[t],selected:t.selected,link:t.link})}return r},he=e=>{let r=[];for(let t of e){let n=t.type==="element"?{...t,children:he(t.children)}:t,o=r.at(-1);n.type==="text"&&o?.type==="text"?o.text+=n.text:n.type==="element"&&o?.type==="element"&&!Pe.has(n.tag)&&!["img","br","hr"].includes(n.tag)&&o.tag===n.tag&&$e(o.attributes,n.attributes)?o.children=he([...o.children,...n.children]):r.push(n)}return r},ae=(e,r,t,n)=>{let o=0,s=a=>qe(a).flatMap(c=>{let d=c.pieces.map(u=>u.node);if(n.kind==="style")return c.selected&&n.value!==!1?[{type:"element",tag:"span",attributes:{style:`${n.property}: ${n.value}`},children:d}]:d;let g=c.selected?n.attributes===!1?void 0:Ee(c.link??{},n.attributes):c.link;return g?[{type:"element",tag:"a",attributes:g,children:d}]:d}),i=(a,c)=>{if(a.type==="text"){let u=o;o+=a.text.length;let m=Math.max(0,Math.min(a.text.length,r-u)),b=Math.max(m,Math.min(a.text.length,t-u));return[[0,m,!1],[m,b,!0],[b,a.text.length,!1]].flatMap(([f,h,y])=>{let x=a.text.slice(f,h);return x?[{node:{type:"text",text:x},selected:!!y,link:c}]:[]})}let d=n.kind==="link"&&a.tag==="a"?a.attributes:c;if(!a.children.length)return[{node:a,selected:o>=r&&o<t,link:d}];let g=a.children.flatMap(u=>i(u,d));return n.kind==="link"&&a.tag==="a"?g:Pe.has(a.tag)?[{node:{...a,children:s(g)},selected:!1}]:qe(g).flatMap(u=>{let m=n.kind==="style"&&u.selected?et(a.attributes,n.property):a.attributes,b=u.pieces.map(f=>f.node);return a.tag==="span"&&!Object.keys(m).length?u.pieces:[{node:{...a,attributes:m,children:b},selected:u.selected,link:u.link}]})};return{version:1,children:he(s(e.children.flatMap(a=>i(a))))}};var _e=(e,r)=>{let t=Fe(r),n=N(e);if(!n)return;let o=H(e),s=n.startContainer.nodeType===1?n.startContainer:n.startContainer.parentElement,i=s?.closest("a"),a=i&&e.contains(i)?i:void 0;if(t&&t.text!==void 0&&(!n.collapsed||a))throw new TypeError("Link text is only supported for insertion at a caret outside links.");if(!n.collapsed){e.innerHTML=j(ae(A(e.innerHTML),o.index,o.index+o.length,{kind:"link",attributes:t&&t.attributes})),R(e,o.index,o.length);return}if(a){let m=t&&Ee(Object.fromEntries([...a.attributes].map(b=>[b.name,b.value])),t.attributes);B(e,()=>{if(!m)a.replaceWith(...a.childNodes);else{for(let b of[...a.attributes])a.removeAttribute(b.name);for(let[b,f]of Object.entries(m))a.setAttribute(b,f)}});return}if(!t||t.text===void 0)return;let c=e.ownerDocument.createElement("a");for(let[m,b]of Object.entries(t.attributes))c.setAttribute(m,b);c.textContent=t.text;let d=s?.closest("p,li,h1,h2,h3,h4,h5,h6,blockquote,pre,td,th");d?.childNodes.length===1&&d.firstChild instanceof HTMLBRElement&&(d.firstChild.remove(),n.setStart(d,0)),n.insertNode(c);let g=e.ownerDocument.createTextNode("");c.after(g),n.setStart(g,0),n.collapse(!0);let u=e.ownerDocument.getSelection();u?.removeAllRanges(),u?.addRange(n)};var z={bold:"strong",italic:"em",underline:"u",strike:"s",code:"code",subscript:"sub",superscript:"sup"},tt=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"]),ze=(e,r,t,n,o)=>{let s=0,i=(a,c)=>{if(a.type==="text"){let u=s;s+=a.text.length;let m=Math.max(0,Math.min(a.text.length,r-u)),b=Math.max(m,Math.min(a.text.length,t-u));return[[0,m,!1],[m,b,!0],[b,a.text.length,!1]].flatMap(([f,h,y])=>{let x=a.text.slice(f,h);if(!x)return[];let T={type:"text",text:x};return[{node:y&&o&&!c?{type:"element",tag:n,attributes:{},children:[T]}:T,selected:!!y}]})}let d=a.children.flatMap(u=>i(u,c||o&&a.tag===n));if(tt.has(a.tag))return[{node:{...a,children:d.map(u=>u.node)},selected:!1}];if(!d.length)return[{node:a,selected:!1}];let g=[];for(let u of d){let m=g.at(-1);m?.selected===u.selected?m.children.push(u.node):g.push({selected:u.selected,children:[u.node]})}return g.flatMap(u=>a.tag===n&&!o&&u.selected?u.children.map(m=>({node:m,selected:!0})):[{node:{...a,children:u.children},selected:u.selected}])};return{version:1,children:e.children.flatMap(a=>i(a,!1)).map(a=>a.node)}},nt=e=>e.nodeType===1?e:e.parentElement,Ke=(e,r)=>{let t=nt(r),n={};for(;t&&t!==e;){for(let[o,s]of Object.entries(z))t.localName===s&&(n[o]=!0);if(/^h[1-6]$/.test(t.localName)&&n.header===void 0&&(n.header=Number(t.localName[1])),t.localName==="blockquote"&&(n.blockquote=!0),t.localName==="pre"&&(n["code-block"]=!0),(t.localName==="ul"||t.localName==="ol")&&n.list===void 0&&(n.list=t.localName==="ul"?"bullet":"ordered"),t.localName==="a"&&n.link===void 0&&(n.link=t.getAttribute("href"),n.linkTitle=t.getAttribute("title")??"",n.linkTarget=t.getAttribute("target")??"_self"),t instanceof HTMLElement)for(let[o,s]of Object.entries(O))n[o]===void 0&&t.style.getPropertyValue(s)&&(n[o]=t.style.getPropertyValue(s));t instanceof HTMLElement&&t.style.textAlign&&n.align===void 0&&(n.align=t.style.textAlign),t=t.parentElement}return n},ce=e=>{let r=N(e);if(!r)return{};let t=Ke(e,r.startContainer),n=new Set;if(!r.collapsed){let{index:o,length:s}=H(e),i=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT),a=0,c,d=[];for(;c=i.nextNode();){let m=a+c.textContent.length;m>o&&a<o+s&&d.push(Ke(e,c)),a=m}d.length&&(t=d[0]);let g=[...Object.keys(z),"header","list","blockquote","code-block","link","linkTitle","linkTarget","color","background","align"],u=(m,b)=>m[b]??(b==="align"?"left":b==="header"?0:!1);for(let m of g)d.some(b=>u(b,m)!==u(d[0],m))&&n.add(m)}return{...t,align:t.align??"left",mixed:[...n],...Y(e)}},ye=(e,r,t)=>{let n=N(e);if(!n)return;let o=H(e);if(r==="list"){Ie(e,t);return}if(r==="indent"){le(e,t);return}if(r==="clear"){if(t!==!0||!o.length)return;let a=A(e.innerHTML);for(let c of[...Object.values(z),"a","span"])a=ze(a,o.index,o.index+o.length,c,!1);e.innerHTML=j(a),R(e,o.index,o.length);return}let s=z[r];if(s){if(n.collapsed)return;e.innerHTML=j(ze(A(e.innerHTML),o.index,o.index+o.length,s,!!t)),R(e,o.index,o.length);return}if(r==="link"){_e(e,t);return}if(Object.hasOwn(O,r)){let a=_(r,t);if(!o.length)return;e.innerHTML=j(ae(A(e.innerHTML),o.index,o.index+o.length,{kind:"style",property:O[r],value:a})),R(e,o.index,o.length);return}let i=$(e,n,!1);if(!i.length){let a=document.createElement("p");a.append(n.extractContents()),a.childNodes.length||a.append(document.createElement("br")),n.insertNode(a),i=[a]}B(e,()=>{for(let a of i){if(r==="align"&&["left","center","right","justify",!1].includes(t)){a.style.textAlign=t?String(t):"";continue}let c=r==="header"?Number.isInteger(t)&&Number(t)>=1&&Number(t)<=6?`h${t}`:"p":r==="blockquote"?t?"blockquote":"p":r==="code-block"?t?"pre":"p":void 0;if(c){let d=document.createElement(c);if(a.localName==="li"){let g=[...a.childNodes].filter(u=>!(u instanceof Element&&/^(ul|ol|p|h[1-6]|pre|blockquote)$/.test(u.localName)));d.append(...g),a.prepend(d)}else d.append(...a.childNodes),d.setAttribute("style",a.getAttribute("style")??""),a.replaceWith(d)}}})};var rt=[{label:"\u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C",text:"\u21B6",run:e=>e.undo(),enabled:e=>e.canUndo()},{label:"\u041F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u044C",text:"\u21B7",run:e=>e.redo(),enabled:e=>e.canRedo()},{label:"\u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439",text:"B",format:"bold"},{label:"\u041A\u0443\u0440\u0441\u0438\u0432",text:"I",format:"italic"},{label:"\u041F\u043E\u0434\u0447\u0451\u0440\u043A\u043D\u0443\u0442\u044B\u0439",text:"U",format:"underline"},{label:"\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A",text:"H\u2082",format:"header",value:2},{label:"\u041C\u0430\u0440\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A",text:"\u2637",format:"list",value:"bullet"},{label:"\u041D\u0443\u043C\u0435\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A",text:"1.",format:"list",value:"ordered"},{label:"\u0423\u0432\u0435\u043B\u0438\u0447\u0438\u0442\u044C \u043E\u0442\u0441\u0442\u0443\u043F",text:"\u21E5",format:"indent",value:1,enabled:e=>!!e.getFormats().canIndent},{label:"\u0423\u043C\u0435\u043D\u044C\u0448\u0438\u0442\u044C \u043E\u0442\u0441\u0442\u0443\u043F",text:"\u21E4",format:"indent",value:-1,enabled:e=>!!e.getFormats().canOutdent},{label:"\u0426\u0438\u0442\u0430\u0442\u0430",text:"\u275D",format:"blockquote"},{label:"\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435",text:"Tx",format:"clear",enabled:e=>!!e.getSelection()?.length}],ot=(e,r,t=rt,n={})=>{t=t.map(f=>f.format&&Object.hasOwn(O,f.format)?{...f,value:_(f.format,f.value)}:f);let o=document.createElement("div");o.className="mw-toolbar",o.setAttribute("role","toolbar"),o.setAttribute("aria-label",n.label??"\u0424\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435");let s,i=!1,a=0,c=[],d=t.map(f=>{let h=document.createElement("button");h.type="button",h.textContent=f.text,h.title=f.label,h.setAttribute("aria-label",f.label);let y=T=>T.preventDefault(),x=()=>{if(!(i||h.disabled||r.isReadOnly())&&(r.focus(),s&&q(r.surface,s),!(f.enabled&&!f.enabled(r)))){if(f.run)f.run(r);else if(f.format){let T=r.getFormats(),S=T.mixed?.includes(f.format);r.format(f.format,!S&&T[f.format]===(f.value??!0)?!1:f.value??!0)}g()}};return h.addEventListener("mousedown",y),h.addEventListener("click",x),c.push(()=>{h.removeEventListener("mousedown",y),h.removeEventListener("click",x)}),o.append(h),h}),g=()=>{if(i)return;s=X(r.surface)??s;let f=r.getFormats();d.forEach((h,y)=>{let x=t[y];h.disabled=r.isReadOnly()||(x.enabled?!x.enabled(r):!1),x.format&&!["indent","clear"].includes(x.format)&&h.setAttribute("aria-pressed",f.mixed?.includes(x.format)?"mixed":String(f[x.format]===(x.value??!0)))}),(d[a]?.disabled||!d[a])&&(a=d.findIndex(h=>!h.disabled)),d.forEach((h,y)=>{h.tabIndex=y===a?0:-1})},u=f=>{let h=d.filter(S=>!S.disabled);if(!h.length)return;let y=h.indexOf(document.activeElement);if(y<0||f.ctrlKey||f.metaKey||f.altKey)return;if(f.key==="Escape"){f.preventDefault(),r.focus(),s&&q(r.surface,s);return}let x=getComputedStyle(o).direction==="rtl"?-1:1,T=f.key==="Home"?0:f.key==="End"?h.length-1:f.key==="ArrowRight"?(y+x+h.length)%h.length:f.key==="ArrowLeft"?(y-x+h.length)%h.length:-1;T>=0&&(f.preventDefault(),a=d.indexOf(h[T]),g(),h[T].focus())};o.addEventListener("keydown",u);let m=r.subscribe(f=>{f.source==="api"&&(s=void 0),g()}),b=r.onSelectionChange(g);return e.append(o),g(),()=>{if(!i){i=!0,m(),b(),o.removeEventListener("keydown",u);for(let f of c)f();o.remove()}}};var de=e=>{let r=!1;e.childNodes.length||(e.innerHTML="<p><br></p>",r=!0);let t;for(let n of[...e.childNodes])n.nodeType===3||n.nodeType===1&&/^(strong|em|u|s|a|span|code|img|br|sub|sup)$/.test(n.localName)?(t||(t=document.createElement("p"),e.insertBefore(t,n)),t.append(n),r=!0):t=void 0;return["table","figure"].includes(e.lastElementChild?.localName??"")&&e.append(Object.assign(document.createElement("p"),{innerHTML:"<br>"})),e.dataset.empty=String(!e.textContent&&!e.querySelector("table,img,hr")),r},st=(e,r)=>{let t=N(e);if(!t)return;let n=re(A(r));if(!n.childNodes.length)return;t.deleteContents();let s=(t.startContainer.nodeType===1?t.startContainer:t.startContainer.parentElement)?.closest("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre");if(n.childNodes.length===1&&n.firstChild instanceof HTMLParagraphElement&&s){let g=n.firstChild;n.replaceChildren(...g.childNodes)}let i=[...n.childNodes].some(g=>g instanceof HTMLElement&&/^(p|h[1-6]|ul|ol|table|figure|blockquote|pre)$/.test(g.localName)),a=n.lastChild;if(i&&s&&e.contains(s)){let g=document.createRange();g.selectNodeContents(s),g.setStart(t.startContainer,t.startOffset);let u=s.cloneNode(!1);u.append(g.extractContents()),s.after(n),(u.textContent||u.querySelector("img,br"))&&a.after(u),!s.textContent&&!s.querySelector("img")&&s.remove()}else t.insertNode(n);let c=document.createRange();c.setStartAfter(a),c.collapse(!0);let d=document.getSelection();d?.removeAllRanges(),d?.addRange(c)},At=(e,r={})=>{if(e.childNodes.length)throw new Error("Editor host must be empty. Pass initial HTML through value.");let t=r.plugins??[];if(new Set(t.map(l=>l.name)).size!==t.length)throw new Error("Duplicate editor plugin.");let n=r.historyLimit??100;if(!Number.isInteger(n)||n<1||n>1e4)throw new RangeError("historyLimit must be an integer from 1 to 10000.");let o=A(r.value??""),s=document.createElement("div");s.className="mw-editor";let i=document.createElement("div");i.className="mw-content",i.setAttribute("role","textbox"),i.setAttribute("aria-multiline","true"),i.setAttribute("aria-label",r.label??"\u0422\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440"),i.dataset.placeholder=r.placeholder??"\u041D\u0430\u0447\u043D\u0438\u0442\u0435 \u043F\u0438\u0441\u0430\u0442\u044C\u2026",s.append(i),e.append(s),i.append(re(o)),de(i);let a=!1,c=r.readOnly??!1,d=!1,g,u,m=0,b="",f={},h,y=()=>{f={},h=void 0},x=()=>{let l=H(i);return l?.length===0&&l.index===h},T=[],S=[],K=new Set,Z=new Set,U=new Map,ee=[];r.onChange&&K.add(r.onChange);let L=()=>{if(a)throw new Error("Editor has been destroyed.")},v=()=>({html:oe(i.innerHTML),selection:X(i),...h!==void 0&&Object.keys(f).length&&x()?{typing:{offset:h,formats:{...f}}}:{}}),xe=l=>{y();let p=H(i);l.typing&&p?.length===0&&p.index===l.typing.offset&&(h=l.typing.offset,f={...l.typing.formats})},C=v(),W=C.selection,P=()=>{if(a)return;H(i)&&!x()&&y();let l=X(i);l&&(W=l,C.selection=l);for(let p of Z)p()},ue=l=>{let p={html:k.getHTML(),text:k.getText(),source:l};for(let E of[...K])E(p);P()},fe=(l,p="")=>{let E=H(i);de(i)&&E&&R(i,E.index,E.length);let w=v();if(w.html===l.html){C=w;return}let M=Date.now();p===b&&["insertText","deleteContentBackward","deleteContentForward"].includes(p)&&M-m<600&&l.selection&&C.selection&&JSON.stringify(l.selection)===JSON.stringify(C.selection)||(T.push(l),T.length>n&&T.shift()),S.length=0,C=w,m=p?M:0,b=p,ue("user")},Te=l=>{y(),i.innerHTML=l.html,de(i),i.focus({preventScroll:!0}),q(i,l.selection),xe(l),C=v(),W=C.selection,m=0,ue("user")},J=(l,p="")=>{if(L(),c)return;k.focus();let E=v(),w=[...T],M=[...S];try{l(i),fe(E,p)}catch(me){throw i.innerHTML=E.html,q(i,E.selection),xe(E),C=v(),T.splice(0,T.length,...w),S.splice(0,S.length,...M),me}},k={element:s,surface:i,getHTML:()=>(L(),oe(i.innerHTML)),getText:()=>(L(),i.innerText),getJSON:()=>(L(),A(i.innerHTML)),setHTML:l=>{L();let p=j(A(l));p!==k.getHTML()&&(y(),i.innerHTML=p,de(i),T.length=0,S.length=0,m=0,W=void 0,C=v(),ue("api"))},setJSON:l=>{L();let p=ne(l);k.setHTML(j(p))},getSelection:()=>(L(),H(i)),setSelection:(l,p=0)=>{L(),R(i,l,p),P()},getFormats:()=>(L(),{...ce(i),...x()?f:{}}),setReadOnly:l=>{L(),c=l,i.contentEditable=String(!l),i.setAttribute("aria-readonly",String(l)),s.dataset.readonly=String(l),P()},isReadOnly:()=>(L(),c),format:(l,p)=>{if(L(),c)return;k.focus();let E=H(i);if(E?.length===0&&(Object.hasOwn(z,l)||Object.hasOwn(O,l))){x()||y(),h=E.index,f[l]=Object.hasOwn(O,l)?_(l,p):!!p,P();return}y(),k.transact(()=>ye(i,l,p))},insertHTML:l=>k.transact(()=>st(i,l)),focus:()=>{L(),i.focus({preventScroll:!0}),N(i)||(W?q(i,W):se(i.firstElementChild??i,!0))},undo:()=>{if(L(),c)return;let l=T.pop();l&&(S.push(v()),Te(l))},redo:()=>{if(L(),c)return;let l=S.pop();l&&(T.push(v()),Te(l))},canUndo:()=>(L(),T.length>0),canRedo:()=>(L(),S.length>0),transact:l=>J(l),providePlugin:(l,p)=>{if(L(),U.has(l))throw new Error(`Plugin API already registered: ${l}`);return U.set(l,p),()=>{U.delete(l)}},getPlugin:l=>(L(),U.get(l)),subscribe:l=>(L(),K.add(l),()=>{K.delete(l)}),onSelectionChange:l=>(L(),Z.add(l),()=>{Z.delete(l)}),destroy:()=>{if(a)return;a=!0;let l=[];for(let p of ee.reverse())try{p()}catch(E){l.push(E)}if(K.clear(),Z.clear(),U.clear(),T.length=0,S.length=0,s.remove(),l.length)throw new AggregateError(l,"Editor cleanup failed.")}},I=(l,p)=>{i.addEventListener(l,p),ee.push(()=>i.removeEventListener(l,p))};I("beforeinput",l=>{if(c){l.preventDefault();return}if(l.inputType==="historyUndo"||l.inputType==="historyRedo"){l.preventDefault(),l.inputType==="historyUndo"?k.undo():k.redo();return}if(!d&&!l.isComposing&&pe(i,l.inputType)){l.preventDefault(),y(),u=void 0,J(()=>ge(i,l.inputType));return}if(l.inputType==="insertText"&&l.data&&!d&&!l.isComposing&&x()&&Object.keys(f).length){l.preventDefault();let p=H(i).index,E=l.data,w={...f};J(()=>{let M=N(i),F=(M.startContainer instanceof Element?M.startContainer:M.startContainer.parentElement)?.closest("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre");F&&!F.textContent&&F.childNodes.length===1&&F.firstChild instanceof HTMLBRElement&&(F.replaceChildren(),M.selectNodeContents(F),M.collapse(!0)),M.insertNode(document.createTextNode(E)),R(i,p,E.length);for(let[te,ke]of Object.entries(w))(Object.hasOwn(O,te)?ce(i)[te]??!1:!!ce(i)[te])!==ke&&ye(i,te,ke);R(i,p+E.length),h=p+E.length},"insertText"),u=void 0;return}u=v()}),I("input",l=>{let p=l;if(c){i.innerHTML=C.html;return}d||p.isComposing||(fe(u??C,p.inputType),u=void 0)}),I("compositionstart",()=>{y(),d=!0,g=v()}),I("compositionend",()=>{d=!1,g&&fe(g),g=void 0,u=void 0}),I("paste",l=>{if(l.preventDefault(),c||!l.clipboardData)return;k.focus();let p=l.clipboardData.getData("text/html");if(p)k.insertHTML(p);else{let E=l.clipboardData.getData("text/plain"),w=document.createElement("div");w.textContent=E,k.insertHTML(w.innerHTML.replace(/\r?\n/g,"<br>"))}}),I("drop",l=>{l.preventDefault()}),I("keydown",l=>{if(!d&&!l.isComposing&&!c&&!l.ctrlKey&&!l.metaKey&&!l.altKey&&(l.key==="Enter"||l.key==="Backspace")){let w=l.key==="Backspace"?"deleteContentBackward":l.shiftKey?"insertLineBreak":"insertParagraph";if(pe(i,w)){l.preventDefault(),y(),u=void 0,J(()=>ge(i,w));return}}if(!d&&!l.isComposing&&!c&&l.key==="Tab"&&!l.ctrlKey&&!l.metaKey&&!l.altKey){let w=$(i);if(w.length&&w.every(M=>M.localName==="li"&&!M.closest("td,th"))&&Y(i).canOutdent){l.preventDefault(),y(),J(()=>le(i,l.shiftKey?-1:1));return}}if(d||l.isComposing||c||!(l.ctrlKey||l.metaKey)||l.altKey)return;let p=l.key.toLowerCase();(p==="z"||p==="y")&&(l.preventDefault(),p==="y"||l.shiftKey?k.redo():k.undo());let E={b:"bold",i:"italic",u:"underline"}[p];E&&(l.preventDefault(),k.format(E,k.getFormats().mixed?.includes(E)||!k.getFormats()[E]))}),document.addEventListener("selectionchange",P),ee.push(()=>document.removeEventListener("selectionchange",P));try{k.setReadOnly(c);for(let l of t){let p=l.setup(k);p&&ee.push(p)}return k}catch(l){throw k.destroy(),l}};export{At as createEditor,ot as createToolbar,oe as sanitizeHTML};
1
+ var ut=["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"],De=new Set(ut),ft=new Set(["script","style","iframe","object","embed","svg","math","template","form","input","button","textarea","select","noscript","link","meta","base"]),mt={b:"strong",i:"em",strike:"s",div:"p"},Oe=1e5,Re=100,pt=(e,r)=>{let t=e.trim();if(!t||/[\u0000-\u0020\u007f]/.test(t))return;let n=/^([a-z][a-z\d+.-]*):/i.exec(t)?.[1].toLowerCase();if(!(n&&!(r?["http","https"]:["http","https","mailto","tel"]).includes(n))&&!(t.startsWith("\\")||t.startsWith("//")))return t},ht=e=>{let r=[];for(let t of e.split(";")){let n=t.indexOf(":");if(n<0)continue;let o=t.slice(0,n).trim().toLowerCase(),s=t.slice(n+1).trim().toLowerCase(),i=/^(#[a-f\d]{3,8}|[a-z]{1,24}|(?:rgb|rgba|hsl|hsla)\([\d\s.,%+-]+\))$/,c=/^(?:\d{1,4}(?:\.\d{1,3})?)(?:px|%|em|rem)$/;(["color","background-color","border-color"].includes(o)?i.test(s):["width","height","font-size"].includes(o)?c.test(s):o==="text-align"?["left","center","right","justify"].includes(s):o==="font-weight"?/^(bold|normal|[1-9]00)$/.test(s):o==="font-style"?["italic","normal"].includes(s):o==="text-decoration"?/^(underline|line-through|none)$/.test(s):!1)&&r.push(`${o}: ${s}`)}return r.join("; ")},je=(e,r)=>{let t={};for(let[n,o]of Object.entries(r))if(!(typeof o!="string"||o.length>2e4))if(n==="style"){let s=ht(o);s&&(t.style=s)}else if(n==="title"||e==="img"&&n==="alt")t[n]=o;else if(e==="a"&&n==="href"||e==="img"&&n==="src"){let s=pt(o,e==="img");s&&(t[n]=s)}else if(["td","th"].includes(e)&&["rowspan","colspan"].includes(n)||["img","col","table"].includes(e)&&["width","height","span"].includes(n))/^\d{1,4}$/.test(o)&&Number(o)>0&&Number(o)<=1e3&&(t[n]=o);else if(e==="a"&&n==="target"&&["_self","_blank"].includes(o))t.target=o;else if(e==="a"&&n==="rel"){let s=[...new Set(o.toLowerCase().split(/\s+/).filter(i=>["noopener","noreferrer"].includes(i)))];s.length&&(t.rel=s.join(" "))}else e==="th"&&n==="scope"&&["row","col","rowgroup","colgroup"].includes(o)&&(t[n]=o);if(e==="img"&&(t.width||t.height)){let n=["width","height"].filter(s=>t[s]),o=(t.style??"").split(";").map(s=>s.trim()).filter(s=>s&&!n.includes(s.slice(0,s.indexOf(":")).trim()));t.style=[...o,...n.map(s=>`${s}: ${t[s]}px`)].join("; ")}return e==="a"&&t.target==="_blank"&&(t.rel="noopener noreferrer"),t},Ie=(e,r,t)=>{if(++t.count>Oe||r>Re)throw new RangeError("Document exceeds structural limits.");if(e.nodeType===3)return[{type:"text",text:e.textContent??""}];if(e.nodeType!==1)return[];let n=e,o=n.localName.toLowerCase();if(n.namespaceURI!=="http://www.w3.org/1999/xhtml"||ft.has(o))return[];let s=[...n.childNodes].flatMap(a=>Ie(a,r+1,t)),i=mt[o]??o;if(!De.has(i))return s;let c=je(i,Object.fromEntries([...n.attributes].map(a=>[a.name,a.value])));return i==="img"&&!c.src?[]:[{type:"element",tag:i,attributes:c,children:s}]},S=e=>{if(e.length>5e6)throw new RangeError("HTML exceeds the document size limit.");let r=document.createElement("template");r.innerHTML=e;let t={count:0};return{version:1,children:[...r.content.childNodes].flatMap(n=>Ie(n,0,t))}},fe=e=>{if(!e||typeof e!="object"||!("version"in e)||e.version!==1||!("children"in e)||!Array.isArray(e.children))throw new TypeError("Expected a version 1 document.");let r=0,t=0,n=(o,s)=>{if(++r>Oe||s>Re)throw new RangeError("Document exceeds structural limits.");if(!o||typeof o!="object"||!("type"in o))throw new TypeError("Invalid document node.");if(o.type==="text"&&"text"in o&&typeof o.text=="string"){if(t+=o.text.length,t>5e6)throw new RangeError("Document text exceeds size limit.");return{type:"text",text:o.text}}if(o.type!=="element"||!("tag"in o)||typeof o.tag!="string"||!De.has(o.tag)||!("children"in o)||!Array.isArray(o.children))throw new TypeError("Invalid document element.");let i="attributes"in o&&o.attributes&&typeof o.attributes=="object"&&!Array.isArray(o.attributes)?o.attributes:{};return{type:"element",tag:o.tag,attributes:je(o.tag,i),children:o.children.map(c=>n(c,s+1))}};return{version:1,children:e.children.map(o=>n(o,0))}},J=e=>{let r=document.createDocumentFragment(),t=(n,o)=>{if(o.type==="text"){n.appendChild(document.createTextNode(o.text));return}let s=document.createElement(o.tag);for(let[i,c]of Object.entries(o.attributes))s.setAttribute(i,c);for(let i of o.children)t(s,i);n.appendChild(s)};for(let n of e.children)t(r,n);return r},I=e=>{let r=document.createElement("div");return r.append(J(e)),r.innerHTML},xe=e=>I(S(e));var N=e=>{let r=e.ownerDocument.getSelection();if(!r?.rangeCount)return;let t=r.getRangeAt(0);if(!(!e.contains(t.startContainer)||!e.contains(t.endContainer)))return t.cloneRange()},Be=(e,r)=>{let t=[],n=r;for(;n!==e&&n.parentNode;)t.unshift([...n.parentNode.childNodes].indexOf(n)),n=n.parentNode;return t},ee=e=>{let r=N(e);if(!r)return;let t=e.ownerDocument.getSelection();return{start:Be(e,r.startContainer),startOffset:r.startOffset,end:Be(e,r.endContainer),endOffset:r.endOffset,backward:!r.collapsed&&t.anchorNode===r.endContainer&&t.anchorOffset===r.endOffset}},U=(e,r)=>{if(!r)return;let t=d=>d.reduce((u,f)=>u.childNodes[f]??u,e),n=t(r.start),o=t(r.end),s=(d,u)=>Math.min(u,d.nodeType===3?d.textContent?.length??0:d.childNodes.length),i=e.ownerDocument.getSelection();if(!i)return;let c=s(n,r.startOffset),a=s(o,r.endOffset);r.backward?i.setBaseAndExtent(o,a,n,c):i.setBaseAndExtent(n,c,o,a)},H=e=>{let r=N(e);if(!r)return;let t=e.ownerDocument.createRange();return t.selectNodeContents(e),t.setEnd(r.startContainer,r.startOffset),{index:t.toString().length,length:r.toString().length}},C=(e,r,t=0)=>{if(![r,t].every(g=>Number.isInteger(g)&&g>=0))throw new RangeError("Selection offsets must be non-negative integers.");let n=e.ownerDocument.createTreeWalker(e,4),o=[],s;for(;s=n.nextNode();)o.push(s);let i=g=>{for(let b of o){if(g<=b.length)return[b,g];g-=b.length}let m=o.at(-1);return m?[m,m.length]:[e.querySelector("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre")??e,0]},[c,a]=i(r),[d,u]=i(r+t),f=e.ownerDocument.createRange();f.setStart(c,a),f.setEnd(d,u),e.focus({preventScroll:!0});let h=e.ownerDocument.getSelection();h?.removeAllRanges(),h?.addRange(f)},me=(e,r=!1)=>{let t=e.ownerDocument.createRange();t.selectNodeContents(e),t.collapse(!r);let n=e.ownerDocument.getSelection();n?.removeAllRanges(),n?.addRange(t)},P=(e,r)=>{let t=N(e);if(!t)return;let n=e.ownerDocument.getSelection(),o=!t.collapsed&&n.anchorNode===t.endContainer&&n.anchorOffset===t.endOffset,s=e.ownerDocument.createComment("mw-start"),i=t.collapsed?void 0:e.ownerDocument.createComment("mw-end");if(i){let a=t.cloneRange();a.collapse(!1),a.insertNode(i)}let c=t.cloneRange();c.collapse(!0),c.insertNode(s);try{if(r(),e.contains(s)&&(!i||e.contains(i))){let a=e.ownerDocument.createRange();a.setStartBefore(s),i?a.setEndBefore(i):a.collapse(!0),s.remove(),i?.remove(),e.normalize(),o?n.setBaseAndExtent(a.endContainer,a.endOffset,a.startContainer,a.startOffset):(n.removeAllRanges(),n.addRange(a))}}finally{s.remove(),i?.remove()}};var Fe="p,h1,h2,h3,h4,h5,h6,blockquote,pre,li",D=e=>!!e&&/^(ul|ol)$/.test(e.localName),gt=e=>e instanceof Element?e:e.parentElement,re=(e,r,t=!0)=>{let n=gt(r),o=n?.closest("li"),s=(t&&o&&e.contains(o)?o:void 0)??n?.closest(Fe);return s&&e.contains(s)?s:void 0},bt=(e,r)=>{let t=r.ownerDocument.createRange();r.nodeType===3?t.selectNodeContents(r):t.selectNode(r);let n=e.cloneRange();n.collapse(!0);let o=e.cloneRange();o.collapse(!1);let s=t.cloneRange();s.collapse(!0);let i=t.cloneRange();return i.collapse(!1),n.compareBoundaryPoints(Range.START_TO_START,i)<0&&o.compareBoundaryPoints(Range.START_TO_START,s)>0},X=(e,r=N(e),t=!0)=>{if(!r)return[];if(r.collapsed){let i=re(e,r.startContainer,t);return i?[i]:[]}let n=new Set,o=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT),s;for(;s=o.nextNode();)if(!(!(s.nodeType===3&&s.textContent)&&!(s instanceof Element&&/^(br|img|hr)$/.test(s.localName)))&&bt(r,s)){let i=re(e,s,t);i&&n.add(i)}return[...e.querySelectorAll(Fe)].filter(i=>n.has(i))},$e=e=>e.filter(r=>!e.some(t=>t!==r&&t.contains(r))),ze=e=>{let r=$e(X(e));if(!r.length||r.some(o=>o.localName!=="li"||!D(o.parentElement)))return[];let t=r[0].parentElement;if(r.some(o=>o.parentElement!==t))return[];let n=[...t.children];return n.indexOf(r.at(-1))-n.indexOf(r[0])+1!==r.length?[]:r},Pe=(e,r)=>{let t=0,n=r.parentElement;for(;n&&n!==e;)D(n)&&t++,n=n.parentElement;return t},Ke=(e,r)=>!!e&&e.localName===r.localName&&D(e)&&e.getAttribute("style")===r.getAttribute("style"),te=e=>{for(let r of[...e.querySelectorAll("ul,ol")]){if(!e.contains(r))continue;let t=r.previousSibling;t instanceof Element&&Ke(t,r)&&(t.append(...r.childNodes),r.remove())}},_e=(e,r)=>{let t=e.parentElement,n=t.cloneNode(!1);for(;e.nextSibling;)n.append(e.nextSibling);e.remove(),t.after(...r,...n.childNodes.length?[n]:[]),t.childNodes.length||t.remove()},ne=e=>[...e.childNodes].filter(r=>!(r instanceof Element&&D(r))),Ue=(e,r=!1)=>{let t=()=>{let c=document.createElement("p");return e.hasAttribute("style")&&c.setAttribute("style",e.getAttribute("style")),c},n=t(),o=[...e.children].filter(D),s=ne(e),i=[];for(let c of s)r&&c instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(c.localName)?n.append(...c.childNodes):c instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(c.localName)?(n.childNodes.length&&i.push(n),n=t(),i.push(c)):n.append(c);(n.childNodes.length||!i.length)&&(n.childNodes.length||n.append(document.createElement("br")),i.push(n)),_e(e,[...i,...o])},pe=e=>{let r=e[0].parentElement,t=r.parentElement;if(t?.localName!=="li"||!D(t.parentElement)){for(let o of e)Ue(o);return}let n=r.cloneNode(!1);for(;e.at(-1).nextSibling;)n.append(e.at(-1).nextSibling);n.childNodes.length&&e.at(-1).append(n),t.after(...e),r.childNodes.length||r.remove()},oe=e=>{let r=ze(e),t=!!r.length&&r[0].previousElementSibling?.localName==="li"&&r.every(n=>[n,...n.querySelectorAll("li")].every(o=>Pe(e,o)<8));return{listDepth:r.length?Pe(e,r[0]):0,canIndent:t,canOutdent:!!r.length}},he=(e,r)=>{if(r!==1&&r!==-1)throw new TypeError("List indentation requires 1 or -1.");let t=ze(e);if(!t.length)throw new RangeError("Select consecutive items in the same list.");r===1&&!oe(e).canIndent||P(e,()=>{if(r===-1)pe(t);else{let n=t[0].parentElement,o=t[0].previousElementSibling,s=o.lastElementChild;Ke(s,n)||(s=n.cloneNode(!1),o.append(s)),s.append(...t)}te(e)})},We=(e,r)=>{if(r!==!1&&r!=="bullet"&&r!=="ordered")throw new TypeError("Expected bullet, ordered or false.");let t=$e(X(e));if(t.some(n=>n.localName==="li"&&!D(n.parentElement)))throw new RangeError("A list item must belong to a list.");P(e,()=>{for(let n of t){if(!r){n.localName==="li"&&pe([n]);continue}let o=r==="bullet"?"ul":"ol";if(n.localName==="li"){if(n.parentElement.localName===o)continue;let s=document.createElement(o);n.parentElement.hasAttribute("style")&&s.setAttribute("style",n.parentElement.getAttribute("style")),_e(n,[s]),s.append(n)}else{let s=document.createElement(o),i=document.createElement("li");n.hasAttribute("style")&&i.setAttribute("style",n.getAttribute("style")),i.append(...n.childNodes),s.append(i),n.replaceWith(s)}}te(e)})},yt=e=>!e.textContent?.trim()&&!e.querySelector("img,hr,ul,ol"),qe=e=>{ne(e).some(n=>n.textContent||n instanceof Element&&(n.matches("br,img,hr")||n.querySelector("br,img,hr")))||([...e.children].some(D)?e.prepend(Object.assign(document.createElement("p"),{innerHTML:"<br>"})):e.append(document.createElement("br")))},Et=(e,r)=>{let t=r.cloneRange();return t.selectNodeContents(e),t.setEnd(r.startContainer,r.startOffset),!t.toString()&&!t.cloneContents().querySelector("img,hr,br")},Te=(e,r)=>{let t=N(e);if(!t)return!1;let n=re(e,t.startContainer);return n?.localName!=="li"||!D(n.parentElement)||re(e,t.endContainer)!==n?!1:["insertParagraph","insertLineBreak"].includes(r)||r==="deleteContentBackward"&&t.collapsed&&Et(n,t)},we=(e,r)=>{let t=N(e),n=re(e,t.startContainer);if(r==="insertParagraph"){if(yt(n)){P(e,()=>{let a=n.parentElement.parentElement;a?.localName==="li"&&D(a.parentElement)?pe([n]):Ue(n,!0)}),te(e);return}t.deleteContents();let o=t.cloneRange();o.selectNodeContents(n),o.setStart(t.startContainer,t.startOffset);let s=n.cloneNode(!1);s.append(o.extractContents()),n.after(s),qe(n),qe(s);let i=document.createTreeWalker(s,NodeFilter.SHOW_TEXT),c;do c=i.nextNode();while(c&&(!c.textContent||c.parentElement?.closest("li")!==s));if(c){let a=document.createRange();a.setStart(c,0),a.collapse(!0);let d=document.getSelection();d?.removeAllRanges(),d?.addRange(a)}else me(s.querySelector("p,h1,h2,h3,h4,h5,h6,pre")??s)}else if(r==="insertLineBreak"){t.deleteContents();let o=document.createElement("br");t.insertNode(o),o.nextSibling||o.after(document.createElement("br")),t.setStartAfter(o),t.collapse(!0);let s=document.getSelection();s?.removeAllRanges(),s?.addRange(t)}else{let o=n.previousElementSibling;if(o&&o.localName!=="li")return;if(!o){P(e,()=>pe([n])),te(e);return}if(!ne(o).some(h=>h.textContent||h instanceof Element&&(h.localName==="img"||h.querySelector("img"))))for(let h of[...o.querySelectorAll("br")])h.closest("li")===o&&h.remove();let s=document.createComment("mw-join"),c=ne(o).at(-1),a=c instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(c.localName)?c:o;a===o?o.insertBefore(s,[...o.children].find(D)??null):a.append(s);let d=ne(n);d[0]instanceof HTMLElement&&/^(p|h[1-6])$/.test(d[0].localName)&&d.splice(0,1,...d[0].childNodes),s.after(...d);for(let h of[...n.children].filter(D))o.append(h);n.remove(),te(e);let u=document.createRange();u.setStartBefore(s),u.collapse(!0),s.remove();let f=document.getSelection();f?.removeAllRanges(),f?.addRange(u)}};var R={color:"color",background:"background-color"},Xe=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"]),Le=(e,r)=>fe({version:1,children:[{type:"element",tag:e,attributes:r,children:[]}]}).children[0].attributes,Q=(e,r)=>{if(r===!1)return!1;if(typeof r!="string"||!r.trim()||r.length>128||/[;{}]/.test(r))throw new TypeError("Expected a CSS color or false.");let t=R[e],n=Le("span",{style:`${t}: ${r}`}),o=document.createElement("span");o.setAttribute("style",n.style??"");let s=o.style.getPropertyValue(t);if(!s)throw new TypeError("Unsupported or invalid CSS color.");return s},Qe=e=>{if(e===!1)return!1;let r=typeof e=="string"?{href:e}:e;if(!r||typeof r!="object"||Array.isArray(r)||!("href"in r)||typeof r.href!="string")throw new TypeError("Expected a link URL, LinkFormat or false.");let t=r,n={href:r.href};if(t.title!==void 0){if(typeof t.title!="string"||t.title.length>1024)throw new TypeError("Link title must be a string up to 1024 characters.");n.title=t.title}if(t.target!==void 0){if(t.target!=="_self"&&t.target!=="_blank")throw new TypeError("Link target must be _self or _blank.");n.target=t.target}if(t.text!==void 0&&(typeof t.text!="string"||!t.text.length||t.text.length>2e4))throw new TypeError("New link text must contain 1\u201320000 characters.");let o=Le("a",n);if(!o.href)throw new TypeError("Unsupported or unsafe link URL.");return{attributes:o,...typeof t.text=="string"?{text:t.text}:{}}},Ne=(e,r)=>{let t={...e,...r};return t.title||delete t.title,r.target==="_self"&&delete t.rel,Le("a",t)},Ve=(e,r)=>JSON.stringify(Object.entries(e??{}).sort())===JSON.stringify(Object.entries(r??{}).sort()),xt=(e,r)=>{let t={...e},n=(t.style??"").split(";").map(o=>o.trim()).filter(o=>o&&o.slice(0,o.indexOf(":")).trim()!==r).join("; ");return n?t.style=n:delete t.style,t},Je=e=>{let r=[];for(let t of e){let n=r.at(-1);n&&n.selected===t.selected&&Ve(n.link,t.link)?n.pieces.push(t):r.push({pieces:[t],selected:t.selected,link:t.link})}return r},ke=e=>{let r=[];for(let t of e){let n=t.type==="element"?{...t,children:ke(t.children)}:t,o=r.at(-1);n.type==="text"&&o?.type==="text"?o.text+=n.text:n.type==="element"&&o?.type==="element"&&!Xe.has(n.tag)&&!["img","br","hr"].includes(n.tag)&&o.tag===n.tag&&Ve(o.attributes,n.attributes)?o.children=ke([...o.children,...n.children]):r.push(n)}return r},ge=(e,r,t,n)=>{let o=0,s=c=>Je(c).flatMap(a=>{let d=a.pieces.map(f=>f.node);if(n.kind==="style")return a.selected&&n.value!==!1?[{type:"element",tag:"span",attributes:{style:`${n.property}: ${n.value}`},children:d}]:d;let u=a.selected?n.attributes===!1?void 0:Ne(a.link??{},n.attributes):a.link;return u?[{type:"element",tag:"a",attributes:u,children:d}]:d}),i=(c,a)=>{if(c.type==="text"){let f=o;o+=c.text.length;let h=Math.max(0,Math.min(c.text.length,r-f)),g=Math.max(h,Math.min(c.text.length,t-f));return[[0,h,!1],[h,g,!0],[g,c.text.length,!1]].flatMap(([m,b,x])=>{let T=c.text.slice(m,b);return T?[{node:{type:"text",text:T},selected:!!x,link:a}]:[]})}let d=n.kind==="link"&&c.tag==="a"?c.attributes:a;if(!c.children.length)return[{node:c,selected:o>=r&&o<t,link:d}];let u=c.children.flatMap(f=>i(f,d));return n.kind==="link"&&c.tag==="a"?u:Xe.has(c.tag)?[{node:{...c,children:s(u)},selected:!1}]:Je(u).flatMap(f=>{let h=n.kind==="style"&&f.selected?xt(c.attributes,n.property):c.attributes,g=f.pieces.map(m=>m.node);return c.tag==="span"&&!Object.keys(h).length?f.pieces:[{node:{...c,attributes:h,children:g},selected:f.selected,link:f.link}]})};return{version:1,children:ke(s(e.children.flatMap(c=>i(c))))}};var Ge=(e,r)=>{let t=Qe(r),n=N(e);if(!n)return;let o=H(e),s=n.startContainer.nodeType===1?n.startContainer:n.startContainer.parentElement,i=s?.closest("a"),c=i&&e.contains(i)?i:void 0;if(t&&t.text!==void 0&&(!n.collapsed||c))throw new TypeError("Link text is only supported for insertion at a caret outside links.");if(!n.collapsed){e.innerHTML=I(ge(S(e.innerHTML),o.index,o.index+o.length,{kind:"link",attributes:t&&t.attributes})),C(e,o.index,o.length);return}if(c){let h=t&&Ne(Object.fromEntries([...c.attributes].map(g=>[g.name,g.value])),t.attributes);P(e,()=>{if(!h)c.replaceWith(...c.childNodes);else{for(let g of[...c.attributes])c.removeAttribute(g.name);for(let[g,m]of Object.entries(h))c.setAttribute(g,m)}});return}if(!t||t.text===void 0)return;let a=e.ownerDocument.createElement("a");for(let[h,g]of Object.entries(t.attributes))a.setAttribute(h,g);a.textContent=t.text;let d=s?.closest("p,li,h1,h2,h3,h4,h5,h6,blockquote,pre,td,th");d?.childNodes.length===1&&d.firstChild instanceof HTMLBRElement&&(d.firstChild.remove(),n.setStart(d,0)),n.insertNode(a);let u=e.ownerDocument.createTextNode("");a.after(u),n.setStart(u,0),n.collapse(!0);let f=e.ownerDocument.getSelection();f?.removeAllRanges(),f?.addRange(n)};var Tt=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"]),Ye=e=>e.type==="text"?e.text.length:e.children.reduce((r,t)=>r+Ye(t),0),se=(e,r,t,n,o)=>{let s=0,i=c=>{if(c.type==="text"){let u=s;s+=c.text.length;let f=Math.max(0,Math.min(c.text.length,r-u)),h=Math.max(f,Math.min(c.text.length,t-u));return[[0,f,!1],[f,h,!0],[h,c.text.length,!1]].flatMap(([g,m,b])=>{let x=c.text.slice(g,m);if(!x)return[];let T={type:"text",text:x};return[{node:b&&o?{type:"element",tag:n,attributes:{},children:[T]}:T,selected:!!b}]})}if(o&&c.tag===n)return s+=Ye(c),[{node:c,selected:!1}];let a=c.children.flatMap(i);if(Tt.has(c.tag))return[{node:{...c,children:a.map(u=>u.node)},selected:!1}];if(!a.length)return[{node:c,selected:!1}];let d=[];for(let u of a){let f=d.at(-1);f?.selected===u.selected?f.children.push(u.node):d.push({selected:u.selected,children:[u.node]})}return d.flatMap(u=>c.tag===n&&!o&&u.selected?u.children.map(f=>({node:f,selected:!0})):[{node:{...c,children:u.children},selected:u.selected}])};return{version:1,children:e.children.flatMap(i).map(c=>c.node)}};var Ze="p,h1,h2,h3,h4,h5,h6",wt=new Set(["strong","em","u","s","sub","sup","a","span","code"]),kt=new Set(["blockquote","ul","ol","li","table","thead","tbody","tfoot","tr","td","th"]),et=e=>e.nodeType===1?e:e.parentElement,tt=e=>{for(let r of e.childNodes){if(r.nodeType===3)continue;if(r.nodeType!==1)return!1;let t=r;if(t.namespaceURI!=="http://www.w3.org/1999/xhtml"||!wt.has(t.localName)||!tt(t))return!1}return!0},nt=(e,r,t,n)=>{let o=et(r.startContainer)?.closest(Ze);if(!o||!e.contains(o)||o.namespaceURI!=="http://www.w3.org/1999/xhtml"||et(r.endContainer)?.closest(Ze)!==o||!tt(o))return!1;for(let g=o.parentElement;g&&g!==e;g=g.parentElement)if(g.namespaceURI!=="http://www.w3.org/1999/xhtml"||!kt.has(g.localName))return!1;let s=e.ownerDocument.createRange();s.selectNodeContents(o),s.setEnd(r.startContainer,r.startOffset);let i=s.toString().length,c=r.toString().length;if(!c||i+c>(o.textContent?.length??0))return!1;let a=e.ownerDocument.getSelection(),d=a?.anchorNode===r.endContainer&&a.anchorOffset===r.endOffset,u=se(S(o.outerHTML),i,i+c,t,n),f=J(u),h=f.firstElementChild;if(f.childNodes.length!==1||!(h instanceof HTMLElement)||h.localName!==o.localName)return!1;if(h.normalize(),h.outerHTML===o.outerHTML)return!0;if(o.replaceWith(f),C(h,i,c),e.focus({preventScroll:!0}),d&&a?.rangeCount){let g=a.getRangeAt(0);a.setBaseAndExtent(g.endContainer,g.endOffset,g.startContainer,g.startOffset)}return!0};var V={bold:"strong",italic:"em",underline:"u",strike:"s",code:"code",subscript:"sub",superscript:"sup"},Lt=e=>e.nodeType===1?e:e.parentElement,rt=(e,r)=>{let t=Lt(r),n={};for(;t&&t!==e;){for(let[o,s]of Object.entries(V))t.localName===s&&(n[o]=!0);if(/^h[1-6]$/.test(t.localName)&&n.header===void 0&&(n.header=Number(t.localName[1])),t.localName==="blockquote"&&(n.blockquote=!0),t.localName==="pre"&&(n["code-block"]=!0),(t.localName==="ul"||t.localName==="ol")&&n.list===void 0&&(n.list=t.localName==="ul"?"bullet":"ordered"),t.localName==="a"&&n.link===void 0&&(n.link=t.getAttribute("href"),n.linkTitle=t.getAttribute("title")??"",n.linkTarget=t.getAttribute("target")??"_self"),t instanceof HTMLElement)for(let[o,s]of Object.entries(R))n[o]===void 0&&t.style.getPropertyValue(s)&&(n[o]=t.style.getPropertyValue(s));t instanceof HTMLElement&&t.style.textAlign&&n.align===void 0&&(n.align=t.style.textAlign),t=t.parentElement}return n},be=e=>{let r=N(e);if(!r)return{};let t=rt(e,r.startContainer),n=new Set;if(!r.collapsed){let{index:o,length:s}=H(e),i=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT),c=0,a,d=[];for(;a=i.nextNode();){let h=c+a.textContent.length;h>o&&c<o+s&&d.push(rt(e,a)),c=h}d.length&&(t=d[0]);let u=[...Object.keys(V),"header","list","blockquote","code-block","link","linkTitle","linkTarget","color","background","align"],f=(h,g)=>h[g]??(g==="align"?"left":g==="header"?0:!1);for(let h of u)d.some(g=>f(g,h)!==f(d[0],h))&&n.add(h)}return{...t,align:t.align??"left",mixed:[...n],...oe(e)}},Me=(e,r,t)=>{let n=N(e);if(!n)return;let o=V[r];if(o&&!n.collapsed&&nt(e,n,o,!!t))return;let s=H(e);if(r==="list"){We(e,t);return}if(r==="indent"){he(e,t);return}if(r==="clear"){if(t!==!0||!s.length)return;let c=S(e.innerHTML);for(let a of[...Object.values(V),"a","span"])c=se(c,s.index,s.index+s.length,a,!1);e.innerHTML=I(c),C(e,s.index,s.length);return}if(o){if(n.collapsed)return;e.innerHTML=I(se(S(e.innerHTML),s.index,s.index+s.length,o,!!t)),C(e,s.index,s.length);return}if(r==="link"){Ge(e,t);return}if(Object.hasOwn(R,r)){let c=Q(r,t);if(!s.length)return;e.innerHTML=I(ge(S(e.innerHTML),s.index,s.index+s.length,{kind:"style",property:R[r],value:c})),C(e,s.index,s.length);return}let i=X(e,n,!1);if(!i.length){let c=document.createElement("p");c.append(n.extractContents()),c.childNodes.length||c.append(document.createElement("br")),n.insertNode(c),i=[c]}P(e,()=>{for(let c of i){if(r==="align"&&["left","center","right","justify",!1].includes(t)){c.style.textAlign=t?String(t):"";continue}let a=r==="header"?Number.isInteger(t)&&Number(t)>=1&&Number(t)<=6?`h${t}`:"p":r==="blockquote"?t?"blockquote":"p":r==="code-block"?t?"pre":"p":void 0;if(a){let d=document.createElement(a);if(c.localName==="li"){let u=[...c.childNodes].filter(f=>!(f instanceof Element&&/^(ul|ol|p|h[1-6]|pre|blockquote)$/.test(f.localName)));d.append(...u),c.prepend(d)}else d.append(...c.childNodes),d.setAttribute("style",c.getAttribute("style")??""),c.replaceWith(d)}}})};var st=new WeakSet,Nt=new Set(["change","selectionchange","readonlychange","destroy"]),Mt=e=>{if(typeof e!="string"||!e.trim()||e.length>200)throw new TypeError("Expected an event name with 1\u2013200 characters.");let r=Object.freeze({name:e});return st.add(r),r},ot=e=>{if(!e||typeof e!="object"||!st.has(e))throw new TypeError("Expected a plugin event token. Core events cannot be emitted publicly.");return e},it=()=>{let e=new Map,r=[],t=0,n=!1,o=!1,s=a=>{if(o&&a.key!=="destroy"||(r.push(a),n))return;n=!0;let d=[];try{for(;r.length;){let u=r.shift();if(o&&u.key!=="destroy")continue;let f=e.get(u.key);for(let[h,g]of[...f??[]])if(!(o&&u.key!=="destroy"||f?.get(h)!==g))try{let m=u.core&&u.payload&&typeof u.payload=="object"?{...u.payload}:u.payload;h(m)}catch(m){d.push(m)}u.key==="destroy"&&(e.clear(),r.length=0)}}finally{n=!1}if(d.length)throw new AggregateError(d,"Editor event listeners failed.")};return{events:{on:(a,d)=>{if(o)throw new Error("Editor events have been destroyed.");if(typeof d!="function")throw new TypeError("Expected an event listener.");let u=typeof a=="string"&&Nt.has(a)?a:ot(a),f=e.get(u);f||(f=new Map,e.set(u,f)),f.has(d)||f.set(d,++t);let h=f.get(d);return()=>{f.get(d)===h&&(f.delete(d),!f.size&&e.get(u)===f&&e.delete(u))}},emit:(a,d)=>{if(o)throw new Error("Editor events have been destroyed.");s({key:ot(a),payload:d,core:!1})}},notify:(a,d)=>s({key:a,payload:d,core:!0}),destroy:()=>{o||(o=!0,r.length=0,s({key:"destroy",payload:void 0,core:!0}))}}};var lt=e=>{let r,t="";return{read:()=>{let s=e.innerHTML;if(s===r)return t;let i=xe(s);return r=s,t=i,i},clear:()=>{r=void 0,t=""}}};var ie=e=>{let r=!1;e.childNodes.length||(e.innerHTML="<p><br></p>",r=!0);let t;for(let n of[...e.childNodes])n.nodeType===3||n.nodeType===1&&/^(strong|em|u|s|a|span|code|img|br|sub|sup)$/.test(n.localName)?(t||(t=document.createElement("p"),e.insertBefore(t,n)),t.append(n),r=!0):t=void 0;return["table","figure"].includes(e.lastElementChild?.localName??"")&&e.append(Object.assign(document.createElement("p"),{innerHTML:"<br>"})),e.dataset.empty=String(!e.textContent&&!e.querySelector("table,img,hr")),r},St=(e,r)=>{let t=N(e);if(!t)return;let n=J(S(r));if(!n.childNodes.length)return;t.deleteContents();let s=(t.startContainer.nodeType===1?t.startContainer:t.startContainer.parentElement)?.closest("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre");if(n.childNodes.length===1&&n.firstChild instanceof HTMLParagraphElement&&s){let u=n.firstChild;n.replaceChildren(...u.childNodes)}let i=[...n.childNodes].some(u=>u instanceof HTMLElement&&/^(p|h[1-6]|ul|ol|table|figure|blockquote|pre)$/.test(u.localName)),c=n.lastChild;if(i&&s&&e.contains(s)){let u=document.createRange();u.selectNodeContents(s),u.setStart(t.startContainer,t.startOffset);let f=s.cloneNode(!1);f.append(u.extractContents()),s.after(n),(f.textContent||f.querySelector("img,br"))&&c.after(f),!s.textContent&&!s.querySelector("img")&&s.remove()}else t.insertNode(n);let a=document.createRange();a.setStartAfter(c),a.collapse(!0);let d=document.getSelection();d?.removeAllRanges(),d?.addRange(a)},Ht=(e,r={})=>{if(e.childNodes.length)throw new Error("Editor host must be empty. Pass initial HTML through value.");let t=r.plugins??[];if(new Set(t.map(l=>l.name)).size!==t.length)throw new Error("Duplicate editor plugin.");let n=r.historyLimit??100;if(!Number.isInteger(n)||n<1||n>1e4)throw new RangeError("historyLimit must be an integer from 1 to 10000.");let o=S(r.value??""),s=document.createElement("div");s.className="mw-editor";let i=document.createElement("div");i.className="mw-content",i.setAttribute("role","textbox"),i.setAttribute("aria-multiline","true"),i.setAttribute("aria-label",r.label??"\u0422\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440"),i.dataset.placeholder=r.placeholder??"\u041D\u0430\u0447\u043D\u0438\u0442\u0435 \u043F\u0438\u0441\u0430\u0442\u044C\u2026",s.append(i),e.append(s),i.append(J(o)),ie(i);let c=!1,a=r.readOnly??!1,d=!1,u,f,h=0,g="",m={},b,x=()=>{m={},b=void 0},T=()=>{let l=H(i);return l?.length===0&&l.index===b},L=[],v=[],B=it(),q=0,le=!1,ce,G=!1,Y=new Map,ae=[];r.onChange&&B.events.on("change",r.onChange);let w=()=>{if(c)throw new Error("Editor has been destroyed.")},$=l=>{if(!q)return;let p=new Error(`${l} is unavailable inside a transaction.`);throw le=!0,ce=p,p},ct={on:B.events.on,emit:(l,p)=>{w(),$("events.emit"),B.events.emit(l,p)}},ye=lt(i),j=()=>({html:ye.read(),selection:ee(i),...b!==void 0&&Object.keys(m).length&&T()?{typing:{offset:b,formats:{...m}}}:{}}),Se=l=>{x();let p=H(i);l.typing&&p?.length===0&&p.index===l.typing.offset&&(b=l.typing.offset,m={...l.typing.formats})},A=j(),z=A.selection,K=()=>{if(c)return;if(q){G=!0;return}H(i)&&!T()&&x();let l=ee(i);l&&(z=l,A.selection=l),B.notify("selectionchange",H(i))},de=l=>{let p={html:k.getHTML(),text:k.getText(),source:l},y=[];try{B.notify("change",p)}catch(E){y.push(E)}try{K()}catch(E){y.push(E)}if(y.length)throw new AggregateError(y,"Editor change notification failed.")},He=(l,p="")=>{let y=H(i);ie(i)&&y&&C(i,y.index,y.length);let E=j();if(E.html===l.html)return A=E,!1;let M=Date.now();return p===g&&["insertText","deleteContentBackward","deleteContentForward"].includes(p)&&M-h<600&&l.selection&&A.selection&&JSON.stringify(l.selection)===JSON.stringify(A.selection)||(L.push(l),L.length>n&&L.shift()),v.length=0,A=E,h=p?M:0,g=p,!0},ve=(l,p="")=>{He(l,p)&&de("user")},Ce=l=>{x(),i.innerHTML=l.html,ie(i),i.focus({preventScroll:!0}),U(i,l.selection),Se(l),A=j(),z=A.selection,h=0,de("user")},Z=(l,p="")=>{if(w(),a)return;let y=()=>{if(typeof l!="function"||l.constructor.name==="AsyncFunction")throw new TypeError("Transactions require a synchronous callback.");let O=l(i);if(O&&(typeof O=="object"||typeof O=="function")&&typeof O.then=="function")throw O instanceof Promise&&O.catch(()=>{}),new TypeError("Transaction callbacks must not return a thenable.")};if(q){q++;try{y()}catch(O){throw le=!0,ce=O,O}finally{q--}return}k.focus();let E=j(),M=[...L],Ee=[...v],F=h,W=g,ue=f,at=z;q=1,le=!1,ce=void 0,G=!1;let Ae=!1;try{if(y(),le)throw ce;Ae=He(E,p)}catch(O){throw i.innerHTML=E.html,ie(i),U(i,E.selection),Se(E),A=j(),z=at,f=ue,L.splice(0,L.length,...M),v.splice(0,v.length,...Ee),h=F,g=W,q=0,G=!1,O}finally{q=0}let dt=G;G=!1,Ae?de("user"):dt&&K()},k={element:s,surface:i,events:ct,getHTML:()=>(w(),ye.read()),getText:()=>(w(),i.innerText),getJSON:()=>(w(),S(i.innerHTML)),setHTML:l=>{w(),$("setHTML");let p=I(S(l));p!==k.getHTML()&&(x(),i.innerHTML=p,ie(i),L.length=0,v.length=0,h=0,z=void 0,A=j(),de("api"))},setJSON:l=>{w(),$("setJSON");let p=fe(l);k.setHTML(I(p))},getSelection:()=>(w(),H(i)),setSelection:(l,p=0)=>{w(),C(i,l,p),K()},getFormats:()=>(w(),{...be(i),...T()?m:{}}),setReadOnly:l=>{w(),$("setReadOnly");let p=a!==l;a=l,i.contentEditable=String(!l),i.setAttribute("aria-readonly",String(l)),s.dataset.readonly=String(l);let y=[];if(p)try{B.notify("readonlychange",l)}catch(E){y.push(E)}try{K()}catch(E){y.push(E)}if(y.length)throw new AggregateError(y,"Editor state notification failed.")},isReadOnly:()=>(w(),a),format:(l,p)=>{if(w(),a)return;k.focus();let y=H(i);if(y?.length===0&&(Object.hasOwn(V,l)||Object.hasOwn(R,l))){T()||x(),b=y.index,m[l]=Object.hasOwn(R,l)?Q(l,p):!!p,K();return}x(),k.transact(()=>Me(i,l,p))},insertHTML:l=>k.transact(()=>St(i,l)),focus:()=>{w(),i.focus({preventScroll:!0}),N(i)||(z?U(i,z):me(i.firstElementChild??i,!0))},undo:()=>{if(w(),$("undo"),a)return;let l=L.pop();l&&(v.push(j()),Ce(l))},redo:()=>{if(w(),$("redo"),a)return;let l=v.pop();l&&(L.push(j()),Ce(l))},canUndo:()=>(w(),L.length>0),canRedo:()=>(w(),v.length>0),transact:l=>Z(l),providePlugin:(l,p)=>{if(w(),Y.has(l))throw new Error(`Plugin API already registered: ${l}`);return Y.set(l,p),()=>{Y.delete(l)}},getPlugin:l=>(w(),Y.get(l)),subscribe:l=>(w(),B.events.on("change",l)),onSelectionChange:l=>(w(),B.events.on("selectionchange",l)),destroy:()=>{if(c)return;$("destroy"),c=!0;let l=[];try{B.destroy()}catch(p){l.push(p)}for(let p of ae.reverse())try{p()}catch(y){l.push(y)}if(Y.clear(),L.length=0,v.length=0,ye.clear(),s.remove(),l.length)throw new AggregateError(l,"Editor cleanup failed.")}},_=(l,p)=>{i.addEventListener(l,p),ae.push(()=>i.removeEventListener(l,p))};_("beforeinput",l=>{if(a){l.preventDefault();return}if(l.inputType==="historyUndo"||l.inputType==="historyRedo"){l.preventDefault(),l.inputType==="historyUndo"?k.undo():k.redo();return}if(!d&&!l.isComposing&&Te(i,l.inputType)){l.preventDefault(),x(),f=void 0,Z(()=>we(i,l.inputType));return}if(l.inputType==="insertText"&&l.data&&!d&&!l.isComposing&&T()&&Object.keys(m).length){l.preventDefault();let p=H(i).index,y=l.data,E={...m};Z(()=>{let M=N(i),F=(M.startContainer instanceof Element?M.startContainer:M.startContainer.parentElement)?.closest("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre");F&&!F.textContent&&F.childNodes.length===1&&F.firstChild instanceof HTMLBRElement&&(F.replaceChildren(),M.selectNodeContents(F),M.collapse(!0)),M.insertNode(document.createTextNode(y)),C(i,p,y.length);for(let[W,ue]of Object.entries(E))(Object.hasOwn(R,W)?be(i)[W]??!1:!!be(i)[W])!==ue&&Me(i,W,ue);C(i,p+y.length),b=p+y.length},"insertText"),f=void 0;return}f=j()}),_("input",l=>{let p=l;if(a){i.innerHTML=A.html;return}if(d||p.isComposing)return;let y=f??A;f=void 0,ve(y,p.inputType)}),_("compositionstart",()=>{x(),d=!0,u=j()}),_("compositionend",()=>{d=!1;let l=u;u=void 0,f=void 0,l&&ve(l)}),_("paste",l=>{if(l.preventDefault(),a||!l.clipboardData)return;k.focus();let p=l.clipboardData.getData("text/html");if(p)k.insertHTML(p);else{let y=l.clipboardData.getData("text/plain"),E=document.createElement("div");E.textContent=y,k.insertHTML(E.innerHTML.replace(/\r?\n/g,"<br>"))}}),_("drop",l=>{l.preventDefault()}),_("keydown",l=>{if(!d&&!l.isComposing&&!a&&!l.ctrlKey&&!l.metaKey&&!l.altKey&&(l.key==="Enter"||l.key==="Backspace")){let E=l.key==="Backspace"?"deleteContentBackward":l.shiftKey?"insertLineBreak":"insertParagraph";if(Te(i,E)){l.preventDefault(),x(),f=void 0,Z(()=>we(i,E));return}}if(!d&&!l.isComposing&&!a&&l.key==="Tab"&&!l.ctrlKey&&!l.metaKey&&!l.altKey){let E=X(i);if(E.length&&E.every(M=>M.localName==="li"&&!M.closest("td,th"))&&oe(i).canOutdent){l.preventDefault(),x(),Z(()=>he(i,l.shiftKey?-1:1));return}}if(d||l.isComposing||a||!(l.ctrlKey||l.metaKey)||l.altKey)return;let p=l.key.toLowerCase();(p==="z"||p==="y")&&(l.preventDefault(),p==="y"||l.shiftKey?k.redo():k.undo());let y={b:"bold",i:"italic",u:"underline"}[p];y&&(l.preventDefault(),k.format(y,k.getFormats().mixed?.includes(y)||!k.getFormats()[y]))}),document.addEventListener("selectionchange",K),ae.push(()=>document.removeEventListener("selectionchange",K));try{k.setReadOnly(a);for(let l of t){let p=l.setup(k);p&&ae.push(p)}return k}catch(l){throw k.destroy(),l}};var vt=[{label:"\u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C",text:"\u21B6",run:e=>e.undo(),enabled:e=>e.canUndo()},{label:"\u041F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u044C",text:"\u21B7",run:e=>e.redo(),enabled:e=>e.canRedo()},{label:"\u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439",text:"B",format:"bold"},{label:"\u041A\u0443\u0440\u0441\u0438\u0432",text:"I",format:"italic"},{label:"\u041F\u043E\u0434\u0447\u0451\u0440\u043A\u043D\u0443\u0442\u044B\u0439",text:"U",format:"underline"},{label:"\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A",text:"H\u2082",format:"header",value:2},{label:"\u041C\u0430\u0440\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A",text:"\u2637",format:"list",value:"bullet"},{label:"\u041D\u0443\u043C\u0435\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A",text:"1.",format:"list",value:"ordered"},{label:"\u0423\u0432\u0435\u043B\u0438\u0447\u0438\u0442\u044C \u043E\u0442\u0441\u0442\u0443\u043F",text:"\u21E5",format:"indent",value:1,enabled:e=>!!e.getFormats().canIndent},{label:"\u0423\u043C\u0435\u043D\u044C\u0448\u0438\u0442\u044C \u043E\u0442\u0441\u0442\u0443\u043F",text:"\u21E4",format:"indent",value:-1,enabled:e=>!!e.getFormats().canOutdent},{label:"\u0426\u0438\u0442\u0430\u0442\u0430",text:"\u275D",format:"blockquote"},{label:"\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435",text:"Tx",format:"clear",enabled:e=>!!e.getSelection()?.length}],Ct=(e,r,t=vt,n={})=>{t=t.map(m=>m.format&&Object.hasOwn(R,m.format)?{...m,value:Q(m.format,m.value)}:m);let o=document.createElement("div");o.className="mw-toolbar",o.setAttribute("role","toolbar"),o.setAttribute("aria-label",n.label??"\u0424\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435");let s,i=!1,c=0,a=[],d=t.map(m=>{let b=document.createElement("button");b.type="button",b.textContent=m.text,b.title=m.label,b.setAttribute("aria-label",m.label);let x=L=>L.preventDefault(),T=()=>{if(!(i||b.disabled||r.isReadOnly())&&(r.focus(),s&&U(r.surface,s),!(m.enabled&&!m.enabled(r)))){if(m.run)m.run(r);else if(m.format){let L=r.getFormats(),v=L.mixed?.includes(m.format);r.format(m.format,!v&&L[m.format]===(m.value??!0)?!1:m.value??!0)}u()}};return b.addEventListener("mousedown",x),b.addEventListener("click",T),a.push(()=>{b.removeEventListener("mousedown",x),b.removeEventListener("click",T)}),o.append(b),b}),u=()=>{if(i)return;s=ee(r.surface)??s;let m=r.getFormats();d.forEach((b,x)=>{let T=t[x];b.disabled=r.isReadOnly()||(T.enabled?!T.enabled(r):!1),T.format&&!["indent","clear"].includes(T.format)&&b.setAttribute("aria-pressed",m.mixed?.includes(T.format)?"mixed":String(m[T.format]===(T.value??!0)))}),(d[c]?.disabled||!d[c])&&(c=d.findIndex(b=>!b.disabled)),d.forEach((b,x)=>{b.tabIndex=x===c?0:-1})},f=m=>{let b=d.filter(v=>!v.disabled);if(!b.length)return;let x=b.indexOf(document.activeElement);if(x<0||m.ctrlKey||m.metaKey||m.altKey)return;if(m.key==="Escape"){m.preventDefault(),r.focus(),s&&U(r.surface,s);return}let T=getComputedStyle(o).direction==="rtl"?-1:1,L=m.key==="Home"?0:m.key==="End"?b.length-1:m.key==="ArrowRight"?(x+T+b.length)%b.length:m.key==="ArrowLeft"?(x-T+b.length)%b.length:-1;L>=0&&(m.preventDefault(),c=d.indexOf(b[L]),u(),b[L].focus())};o.addEventListener("keydown",f);let h=r.subscribe(m=>{m.source==="api"&&(s=void 0),u()}),g=r.onSelectionChange(u);return e.append(o),u(),()=>{if(!i){i=!0,h(),g(),o.removeEventListener("keydown",f);for(let m of a)m();o.remove()}}};export{Ht as createEditor,Mt as createPluginEvent,Ct as createToolbar,xe as sanitizeHTML};
2
2
  //# sourceMappingURL=index.js.map