diff --git a/resources/js/vendor/ckeditor/build/ckeditor.js b/resources/js/vendor/ckeditor/build/ckeditor.js index 58d2359..c9923c9 100644 --- a/resources/js/vendor/ckeditor/build/ckeditor.js +++ b/resources/js/vendor/ckeditor/build/ckeditor.js @@ -1,7 +1,86516 @@ -!function(t){const e=t.fr=t.fr||{};e.dictionary=Object.assign(e.dictionary||{},{"%0 of %1":"%0 sur %1","Align center":"Centrer","Align left":"Aligner à gauche","Align right":"Aligner à droite",Aquamarine:"Bleu vert",Big:"Grand",Black:"Noir","Block quote":"Citation",Blue:"Bleu",Bold:"Gras","Bulleted List":"Liste à puces","Bulleted list styles toolbar":"Barre d'outils des styles de liste à puce",Cancel:"Annuler","Characters: %0":"Caractères : %0","Choose heading":"Choisir l'en-tête",Circle:"Cercle",Decimal:"Chiffres","Decimal with leading zero":"Chiffres avec des zéros supplémentaire","Decrease indent":"Diminuer le retrait",Default:"Par défaut","Dim grey":"Gris pâle",Disc:"Disque","Document colors":"Couleurs du document",Downloadable:"Fichier téléchargeable","Dropdown toolbar":"Barre d'outils dans un menu déroulant","Edit block":"Modifier le bloc","Edit link":"Modifier le lien","Editor block content toolbar":"Barre d'outils du contenu du bloc éditeur","Editor contextual toolbar":"Barre d'outils contextuelle de l'éditeur","Editor editing area: %0":"Zone d'édition de l'éditeur : %0","Editor toolbar":"Barre d'outils de l'éditeur","Font Color":"Couleur de police","Font Family":"Police","Font Size":"Taille de police",Green:"Vert",Grey:"Gris",Heading:"En-tête","Heading 1":"Titre 1","Heading 2":"Titre 2","Heading 3":"Titre 3","Heading 4":"Titre 4","Heading 5":"Titre 5","Heading 6":"Titre 6","Horizontal line":"Ligne horizontale",Huge:"Enorme","Increase indent":"Augmenter le retrait","Insert paragraph after block":"Insérer du texte après ce bloc","Insert paragraph before block":"Insérer du texte avant ce bloc",Italic:"Italique",Justify:"Justifier","Light blue":"Bleu clair","Light green":"Vert clair","Light grey":"Gris clair",Link:"Lien","Link URL":"URL du lien","List properties":"Liste des propriétés","Lower-latin":"Lettres minuscules","Lower–roman":"Chiffres romains en minuscules",Next:"Suivant","Numbered List":"Liste numérotée","Numbered list styles toolbar":"Barre d'outils des styles de liste numérotée","Open in a new tab":"Ouvrir dans un nouvel onglet","Open link in new tab":"Ouvrir le lien dans un nouvel onglet",Orange:"Orange",Paragraph:"Paragraphe","Press Enter to type after or press Shift + Enter to type before the widget":"Appuyez sur la touche Entrée pour taper après ou sur Maj + Entrée pour taper avant le widget.",Previous:"Précedent",Purple:"Violet",Red:"Rouge",Redo:"Restaurer","Remove color":"Enlever la couleur","Remove Format":"Enlever le format","Reversed order":"Ordre inversé","Rich Text Editor":"Éditeur de texte enrichi",Save:"Enregistrer","Select all":"Sélectionner tout","Show more items":"Montrer plus d'éléments",Small:"Petit",Source:"Source",Square:"Carré","Start at":"Commencer à","Start index must be greater than 0.":"L'indice de départ doit être supérieur à 0.","Text alignment":"Alignement du texte","Text alignment toolbar":"Barre d'outils d'alignement du texte","This link has no URL":"Ce lien n'a pas d'URL",Tiny:"Minuscule","Toggle the circle list style":'Activer / désactiver le style de liste "cercle"',"Toggle the decimal list style":'Activer / désactiver le style de liste "chiffres"',"Toggle the decimal with leading zero list style":'Activer / désactiver le style de liste "chiffres de mêmes longueurs"',"Toggle the disc list style":'Activer / désactiver le style de liste "disque"',"Toggle the lower–latin list style":'Activer / désactiver le style de liste "lettres minuscules"',"Toggle the lower–roman list style":'Activer / désactiver le style de liste "chiffres romains en minuscules"',"Toggle the square list style":'Activer / désactiver le style de liste "carré"',"Toggle the upper–latin list style":'Activer / désactiver le style de liste "lettres majuscules"',"Toggle the upper–roman list style":'Activer / désactiver le style de liste "chiffres romains en majuscules"',Turquoise:"Turquoise",Underline:"Souligné",Undo:"Annuler",Unlink:"Supprimer le lien","Upper-latin":"Lettres majuscules","Upper-roman":"Chiffres romains en majuscules",White:"Blanc","Widget toolbar":"Barre d'outils du widget","Words: %0":"Mots : %0",Yellow:"Jaune"}),e.getPluralForm=function(t){return 0==t||1==t?0:0!=t&&t%1e6==0?1:2}}(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={})), +(function(d){ const l = d['fr'] = d['fr'] || {}; l.dictionary=Object.assign( l.dictionary||{}, {"%0 of %1":"%0 sur %1",Accept:"","Align center":"Centrer","Align left":"Aligner à gauche","Align right":"Aligner à droite",Aquamarine:"Bleu vert",Big:"Grand",Black:"Noir","Block quote":"Citation",Blue:"Bleu",Bold:"Gras","Bulleted List":"Liste à puces","Bulleted list styles toolbar":"Barre d'outils des styles de liste à puce",Cancel:"Annuler","Characters: %0":"Caractères : %0","Choose heading":"Choisir l'en-tête",Circle:"Cercle",Decimal:"Chiffres","Decimal with leading zero":"Chiffres avec des zéros supplémentaire","Decrease indent":"Diminuer le retrait",Default:"Par défaut","Dim grey":"Gris pâle",Disc:"Disque","Document colors":"Couleurs du document",Downloadable:"Fichier téléchargeable","Dropdown toolbar":"Barre d'outils dans un menu déroulant","Edit block":"Modifier le bloc","Edit link":"Modifier le lien","Editor block content toolbar":"Barre d'outils du contenu du bloc éditeur","Editor contextual toolbar":"Barre d'outils contextuelle de l'éditeur","Editor editing area: %0":"Zone d'édition de l'éditeur : %0","Editor toolbar":"Barre d'outils de l'éditeur","Font Color":"Couleur de police","Font Family":"Police","Font Size":"Taille de police",Green:"Vert",Grey:"Gris",Heading:"En-tête","Heading 1":"Titre 1","Heading 2":"Titre 2","Heading 3":"Titre 3","Heading 4":"Titre 4","Heading 5":"Titre 5","Heading 6":"Titre 6",HEX:"","Horizontal line":"Ligne horizontale",Huge:"Enorme","Increase indent":"Augmenter le retrait","Insert paragraph after block":"Insérer du texte après ce bloc","Insert paragraph before block":"Insérer du texte avant ce bloc",Italic:"Italique",Justify:"Justifier","Light blue":"Bleu clair","Light green":"Vert clair","Light grey":"Gris clair",Link:"Lien","Link URL":"URL du lien","List properties":"Liste des propriétés","Lower-latin":"Lettres minuscules","Lower–roman":"Chiffres romains en minuscules",Next:"Suivant","Numbered List":"Liste numérotée","Numbered list styles toolbar":"Barre d'outils des styles de liste numérotée","Open in a new tab":"Ouvrir dans un nouvel onglet","Open link in new tab":"Ouvrir le lien dans un nouvel onglet",Orange:"Orange",Paragraph:"Paragraphe","Press Enter to type after or press Shift + Enter to type before the widget":"Appuyez sur la touche Entrée pour taper après ou sur Maj + Entrée pour taper avant le widget.",Previous:"Précedent",Purple:"Violet",Red:"Rouge",Redo:"Restaurer","Remove color":"Enlever la couleur","Remove Format":"Enlever le format","Reversed order":"Ordre inversé","Rich Text Editor":"Éditeur de texte enrichi",Save:"Enregistrer","Select all":"Sélectionner tout","Show more items":"Montrer plus d'éléments",Small:"Petit",Source:"Source",Square:"Carré","Start at":"Commencer à","Start index must be greater than 0.":"L'indice de départ doit être supérieur à 0.","Text alignment":"Alignement du texte","Text alignment toolbar":"Barre d'outils d'alignement du texte","This link has no URL":"Ce lien n'a pas d'URL",Tiny:"Minuscule","Toggle the circle list style":"Activer / désactiver le style de liste \"cercle\"","Toggle the decimal list style":"Activer / désactiver le style de liste \"chiffres\"","Toggle the decimal with leading zero list style":"Activer / désactiver le style de liste \"chiffres de mêmes longueurs\"","Toggle the disc list style":"Activer / désactiver le style de liste \"disque\"","Toggle the lower–latin list style":"Activer / désactiver le style de liste \"lettres minuscules\"","Toggle the lower–roman list style":"Activer / désactiver le style de liste \"chiffres romains en minuscules\"","Toggle the square list style":"Activer / désactiver le style de liste \"carré\"","Toggle the upper–latin list style":"Activer / désactiver le style de liste \"lettres majuscules\"","Toggle the upper–roman list style":"Activer / désactiver le style de liste \"chiffres romains en majuscules\"",Turquoise:"Turquoise",Underline:"Souligné",Undo:"Annuler",Unlink:"Supprimer le lien","Upper-latin":"Lettres majuscules","Upper-roman":"Chiffres romains en majuscules",White:"Blanc","Widget toolbar":"Barre d'outils du widget","Words: %0":"Mots : %0",Yellow:"Jaune"} );l.getPluralForm=function(n){return (n == 0 || n == 1) ? 0 : n != 0 && n % 1000000 == 0 ? 1 : 2;;};})(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={})); /*! * @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved. * For licensing, see LICENSE.md. */ -function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.ClassicEditor=e():t.ClassicEditor=e()}(self,(()=>(()=>{"use strict";var t={d:(e,i)=>{for(var n in i)t.o(i,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:i[n]})}};t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),t.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var e={};function i({emitter:t,activator:e,callback:i,contextElements:n}){t.listenTo(document,"mousedown",((t,s)=>{if(!e())return;const o="function"==typeof s.composedPath?s.composedPath():[],r="function"==typeof n?n():n;for(const t of r)if(t.contains(s.target)||o.includes(t))return;i()}))}function n({keystrokeHandler:t,focusTracker:e,gridItems:i,numberOfColumns:n,uiLanguageDirection:s}){const o="number"==typeof n?()=>n:n;function r(t){return n=>{const s=i.find((t=>t.element===e.focusedElement)),o=i.getIndex(s),r=t(o,i);i.get(r).focus(),n.stopPropagation(),n.preventDefault()}}function a(t,e){return t===e-1?0:t+1}function l(t,e){return 0===t?e-1:t-1}t.set("arrowright",r(((t,e)=>"rtl"===s?l(t,e.length):a(t,e.length)))),t.set("arrowleft",r(((t,e)=>"rtl"===s?a(t,e.length):l(t,e.length)))),t.set("arrowup",r(((t,e)=>{let i=t-o();return i<0&&(i=t+o()*Math.floor(e.length/o()),i>e.length-1&&(i-=o())),i}))),t.set("arrowdown",r(((t,e)=>{let i=t+o();return i>e.length-1&&(i=t%o()),i})))}t.d(e,{default:()=>K_});const s=function(){try{return navigator.userAgent.toLowerCase()}catch(t){return""}}(),o={isMac:a(s),isWindows:function(t){return t.indexOf("windows")>-1}(s),isGecko:function(t){return!!t.match(/gecko\/\d+/)}(s),isSafari:function(t){return t.indexOf(" applewebkit/")>-1&&-1===t.indexOf("chrome")}(s),isiOS:function(t){return!!t.match(/iphone|ipad/i)||a(t)&&navigator.maxTouchPoints>0}(s),isAndroid:function(t){return t.indexOf("android")>-1}(s),isBlink:function(t){return t.indexOf("chrome/")>-1&&t.indexOf("edge/")<0}(s),features:{isRegExpUnicodePropertySupported:function(){let t=!1;try{t=0==="ć".search(new RegExp("[\\p{L}]","u"))}catch(t){}return t}()}},r=o;function a(t){return t.indexOf("macintosh")>-1}function l(t,e,i,n){i=i||function(t,e){return t===e};const s=Array.isArray(t)?t:Array.prototype.slice.call(t),o=Array.isArray(e)?e:Array.prototype.slice.call(e),r=function(t,e,i){const n=c(t,e,i);if(-1===n)return{firstIndex:-1,lastIndexOld:-1,lastIndexNew:-1};const s=h(t,n),o=h(e,n),r=c(s,o,i),a=t.length-r,l=e.length-r;return{firstIndex:n,lastIndexOld:a,lastIndexNew:l}}(s,o,i),a=n?function(t,e){const{firstIndex:i,lastIndexOld:n,lastIndexNew:s}=t;if(-1===i)return Array(e).fill("equal");let o=[];i>0&&(o=o.concat(Array(i).fill("equal")));s-i>0&&(o=o.concat(Array(s-i).fill("insert")));n-i>0&&(o=o.concat(Array(n-i).fill("delete")));s0&&i.push({index:n,type:"insert",values:t.slice(n,o)});s-n>0&&i.push({index:n+(o-n),type:"delete",howMany:s-n});return i}(o,r);return a}function c(t,e,i){for(let n=0;n200||s>200||n+s>300)return d.fastDiff(t,e,i,!0);let o,r;if(sc?-1:1;h[n+d]&&(h[n]=h[n+d].slice(0)),h[n]||(h[n]=[]),h[n].push(s>c?o:r);let f=Math.max(s,c),m=f-n;for(;mc;m--)u[m]=f(m);u[c]=f(c),g++}while(u[c]!==l);return h[c].slice(1)}function u(t,...e){e.forEach((e=>{const i=Object.getOwnPropertyNames(e),n=Object.getOwnPropertySymbols(e);i.concat(n).forEach((i=>{if(i in t.prototype)return;if("function"==typeof e&&("length"==i||"name"==i||"prototype"==i))return;const n=Object.getOwnPropertyDescriptor(e,i);n.enumerable=!1,Object.defineProperty(t.prototype,i,n)}))}))}d.fastDiff=l;const f=function(){return function t(){t.called=!0}};class m{constructor(t,e){this.source=t,this.name=e,this.path=[],this.stop=f(),this.off=f()}}const g=new Array(256).fill("").map(((t,e)=>("0"+e.toString(16)).slice(-2)));function p(){const t=4294967296*Math.random()>>>0,e=4294967296*Math.random()>>>0,i=4294967296*Math.random()>>>0,n=4294967296*Math.random()>>>0;return"e"+g[t>>0&255]+g[t>>8&255]+g[t>>16&255]+g[t>>24&255]+g[e>>0&255]+g[e>>8&255]+g[e>>16&255]+g[e>>24&255]+g[i>>0&255]+g[i>>8&255]+g[i>>16&255]+g[i>>24&255]+g[n>>0&255]+g[n>>8&255]+g[n>>16&255]+g[n>>24&255]}const w={get(t="normal"){return"number"!=typeof t?this[t]||this.normal:t},highest:1e5,high:1e3,normal:0,low:-1e3,lowest:-1e5};function b(t,e){const i=w.get(e.priority);for(let n=0;n{if("object"==typeof e&&null!==e){if(i.has(e))return`[object ${e.constructor.name}]`;i.add(e)}return e},s=e?` ${JSON.stringify(e,n)}`:"",o=k(t);return t+s+o}(t,i)),this.name="CKEditorError",this.context=e,this.data=i}is(t){return"CKEditorError"===t}static rethrowUnexpectedError(t,e){if(t.is&&t.is("CKEditorError"))throw t;const i=new v(t.message,e);throw i.stack=t.stack,i}}function y(t,e){console.warn(...A(t,e))}function k(t){return`\nRead more: ${_}#error-${t}`}function A(t,e){const i=k(t);return e?[t,e,i]:[t,i]}const x="36.0.0",C="object"==typeof window?window:t.g;if(C.CKEDITOR_VERSION)throw new v("ckeditor-duplicated-modules",null);C.CKEDITOR_VERSION=x;const P=Symbol("listeningTo"),T=Symbol("emitterId"),E=Symbol("delegations"),S=R(Object);function R(t){if(!t)return S;return class extends t{on(t,e,i){this.listenTo(this,t,e,i)}once(t,e,i){let n=!1;this.listenTo(this,t,((t,...i)=>{n||(n=!0,t.off(),e.call(this,t,...i))}),i)}off(t,e){this.stopListening(this,t,e)}listenTo(t,e,i,n={}){let s,o;this[P]||(this[P]={});const r=this[P];I(t)||O(t);const a=I(t);(s=r[a])||(s=r[a]={emitter:t,callbacks:{}}),(o=s.callbacks[e])||(o=s.callbacks[e]=[]),o.push(i),function(t,e,i,n,s){e._addEventListener?e._addEventListener(i,n,s):t._addEventListener.call(e,i,n,s)}(this,t,e,i,n)}stopListening(t,e,i){const n=this[P];let s=t&&I(t);const o=n&&s?n[s]:void 0,r=o&&e?o.callbacks[e]:void 0;if(!(!n||t&&!o||e&&!r))if(i){D(this,t,e,i);-1!==r.indexOf(i)&&(1===r.length?delete o.callbacks[e]:D(this,t,e,i))}else if(r){for(;i=r.pop();)D(this,t,e,i);delete o.callbacks[e]}else if(o){for(e in o.callbacks)this.stopListening(t,e);delete n[s]}else{for(s in n)this.stopListening(n[s].emitter);delete this[P]}}fire(t,...e){try{const i=t instanceof m?t:new m(this,t),n=i.name;let s=N(this,n);if(i.path.push(this),s){const t=[i,...e];s=Array.from(s);for(let e=0;e{this[E]||(this[E]=new Map),t.forEach((t=>{const n=this[E].get(t);n?n.set(e,i):this[E].set(t,new Map([[e,i]]))}))}}}stopDelegating(t,e){if(this[E])if(t)if(e){const i=this[E].get(t);i&&i.delete(e)}else this[E].delete(t);else this[E].clear()}_addEventListener(t,e,i){!function(t,e){const i=V(t);if(i[e])return;let n=e,s=null;const o=[];for(;""!==n&&!i[n];)i[n]={callbacks:[],childEvents:[]},o.push(i[n]),s&&i[n].childEvents.push(s),s=n,n=n.substr(0,n.lastIndexOf(":"));if(""!==n){for(const t of o)t.callbacks=i[n].callbacks.slice();i[n].childEvents.push(s)}}(this,t);const n=M(this,t),s={callback:e,priority:w.get(i.priority)};for(const t of n)b(t,s)}_removeEventListener(t,e){const i=M(this,t);for(const t of i)for(let i=0;i-1?N(t,e.substr(0,e.lastIndexOf(":"))):null}function B(t,e,i){for(let[n,s]of t){s?"function"==typeof s&&(s=s(e.name)):s=e.name;const t=new m(e.source,s);t.path=[...e.path],n.fire(t,...i)}}function D(t,e,i,n){e._removeEventListener?e._removeEventListener(i,n):t._removeEventListener.call(e,i,n)}["on","once","off","listenTo","stopListening","fire","delegate","stopDelegating","_addEventListener","_removeEventListener"].forEach((t=>{R[t]=S.prototype[t]}));const F=function(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)},L=Symbol("observableProperties"),z=Symbol("boundObservables"),H=Symbol("boundProperties"),j=Symbol("decoratedMethods"),$=Symbol("decoratedOriginal"),W=q(R());function q(t){if(!t)return W;return class extends t{set(t,e){if(F(t))return void Object.keys(t).forEach((e=>{this.set(e,t[e])}),this);U(this);const i=this[L];if(t in this&&!i.has(t))throw new v("observable-set-cannot-override",this);Object.defineProperty(this,t,{enumerable:!0,configurable:!0,get:()=>i.get(t),set(e){const n=i.get(t);let s=this.fire(`set:${t}`,t,e,n);void 0===s&&(s=e),n===s&&i.has(t)||(i.set(t,s),this.fire(`change:${t}`,t,s,n))}}),this[t]=e}bind(...t){if(!t.length||!J(t))throw new v("observable-bind-wrong-properties",this);if(new Set(t).size!==t.length)throw new v("observable-bind-duplicate-properties",this);U(this);const e=this[H];t.forEach((t=>{if(e.has(t))throw new v("observable-bind-rebind",this)}));const i=new Map;return t.forEach((t=>{const n={property:t,to:[]};e.set(t,n),i.set(t,n)})),{to:K,toMany:G,_observable:this,_bindProperties:t,_to:[],_bindings:i}}unbind(...t){if(!this[L])return;const e=this[H],i=this[z];if(t.length){if(!J(t))throw new v("observable-unbind-wrong-properties",this);t.forEach((t=>{const n=e.get(t);n&&(n.to.forEach((([t,e])=>{const s=i.get(t),o=s[e];o.delete(n),o.size||delete s[e],Object.keys(s).length||(i.delete(t),this.stopListening(t,"change"))})),e.delete(t))}))}else i.forEach(((t,e)=>{this.stopListening(e,"change")})),i.clear(),e.clear()}decorate(t){U(this);const e=this[t];if(!e)throw new v("observablemixin-cannot-decorate-undefined",this,{object:this,methodName:t});this.on(t,((t,i)=>{t.return=e.apply(this,i)})),this[t]=function(...e){return this.fire(t,e)},this[t][$]=e,this[j]||(this[j]=[]),this[j].push(t)}stopListening(t,e,i){if(!t&&this[j]){for(const t of this[j])this[t]=this[t][$];delete this[j]}super.stopListening(t,e,i)}}}function U(t){t[L]||(Object.defineProperty(t,L,{value:new Map}),Object.defineProperty(t,z,{value:new Map}),Object.defineProperty(t,H,{value:new Map}))}function K(...t){const e=function(...t){if(!t.length)throw new v("observable-bind-to-parse-error",null);const e={to:[]};let i;"function"==typeof t[t.length-1]&&(e.callback=t.pop());return t.forEach((t=>{if("string"==typeof t)i.properties.push(t);else{if("object"!=typeof t)throw new v("observable-bind-to-parse-error",null);i={observable:t,properties:[]},e.to.push(i)}})),e}(...t),i=Array.from(this._bindings.keys()),n=i.length;if(!e.callback&&e.to.length>1)throw new v("observable-bind-to-no-callback",this);if(n>1&&e.callback)throw new v("observable-bind-to-extra-callback",this);var s;e.to.forEach((t=>{if(t.properties.length&&t.properties.length!==n)throw new v("observable-bind-to-properties-length",this);t.properties.length||(t.properties=this._bindProperties)})),this._to=e.to,e.callback&&(this._bindings.get(i[0]).callback=e.callback),s=this._observable,this._to.forEach((t=>{const e=s[z];let i;e.get(t.observable)||s.listenTo(t.observable,"change",((n,o)=>{i=e.get(t.observable)[o],i&&i.forEach((t=>{Q(s,t.property)}))}))})),function(t){let e;t._bindings.forEach(((i,n)=>{t._to.forEach((s=>{e=s.properties[i.callback?0:t._bindProperties.indexOf(n)],i.to.push([s.observable,e]),function(t,e,i,n){const s=t[z],o=s.get(i),r=o||{};r[n]||(r[n]=new Set);r[n].add(e),o||s.set(i,r)}(t._observable,i,s.observable,e)}))}))}(this),this._bindProperties.forEach((t=>{Q(this._observable,t)}))}function G(t,e,i){if(this._bindings.size>1)throw new v("observable-bind-to-many-not-one-binding",this);this.to(...function(t,e){const i=t.map((t=>[t,e]));return Array.prototype.concat.apply([],i)}(t,e),i)}function J(t){return t.every((t=>"string"==typeof t))}function Q(t,e){const i=t[H].get(e);let n;i.callback?n=i.callback.apply(t,i.to.map((t=>t[0][t[1]]))):(n=i.to[0],n=n[0][n[1]]),Object.prototype.hasOwnProperty.call(t,e)?t[e]=n:t.set(e,n)}["set","bind","unbind","decorate","on","once","off","listenTo","stopListening","fire","delegate","stopDelegating","_addEventListener","_removeEventListener"].forEach((t=>{q[t]=W.prototype[t]}));class Y{constructor(){this._replacedElements=[]}replace(t,e){this._replacedElements.push({element:t,newElement:e}),t.style.display="none",e&&t.parentNode.insertBefore(e,t.nextSibling)}restore(){this._replacedElements.forEach((({element:t,newElement:e})=>{t.style.display="",e&&e.remove()})),this._replacedElements=[]}}function Z(t){let e=0;for(const i of t)e++;return e}function X(t,e){const i=Math.min(t.length,e.length);for(let n=0;n-1};const Dt=function(t,e){var i=this.__data__,n=It(i,t);return n<0?(++this.size,i.push([t,e])):i[n][1]=e,this};function Ft(t){var e=-1,i=null==t?0:t.length;for(this.clear();++e-1&&t%1==0&&t-1&&t%1==0&&t<=ii};var si={};si["[object Float32Array]"]=si["[object Float64Array]"]=si["[object Int8Array]"]=si["[object Int16Array]"]=si["[object Int32Array]"]=si["[object Uint8Array]"]=si["[object Uint8ClampedArray]"]=si["[object Uint16Array]"]=si["[object Uint32Array]"]=!0,si["[object Arguments]"]=si["[object Array]"]=si["[object ArrayBuffer]"]=si["[object Boolean]"]=si["[object DataView]"]=si["[object Date]"]=si["[object Error]"]=si["[object Function]"]=si["[object Map]"]=si["[object Number]"]=si["[object Object]"]=si["[object RegExp]"]=si["[object Set]"]=si["[object String]"]=si["[object WeakMap]"]=!1;const oi=function(t){return wt(t)&&ni(t.length)&&!!si[gt(t)]};const ri=function(t){return function(e){return t(e)}};var ai="object"==typeof exports&&exports&&!exports.nodeType&&exports,li=ai&&"object"==typeof module&&module&&!module.nodeType&&module,ci=li&&li.exports===ai&&et.process;const hi=function(){try{var t=li&&li.require&&li.require("util").types;return t||ci&&ci.binding&&ci.binding("util")}catch(t){}}();var di=hi&&hi.isTypedArray;const ui=di?ri(di):oi;var fi=Object.prototype.hasOwnProperty;const mi=function(t,e){var i=pt(t),n=!i&&Ke(t),s=!i&&!n&&Ze(t),o=!i&&!n&&!s&&ui(t),r=i||n||s||o,a=r?He(t.length,String):[],l=a.length;for(var c in t)!e&&!fi.call(t,c)||r&&("length"==c||s&&("offset"==c||"parent"==c)||o&&("buffer"==c||"byteLength"==c||"byteOffset"==c)||ei(c,l))||a.push(c);return a};var gi=Object.prototype;const pi=function(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||gi)};const wi=yt(Object.keys,Object);var bi=Object.prototype.hasOwnProperty;const _i=function(t){if(!pi(t))return wi(t);var e=[];for(var i in Object(t))bi.call(t,i)&&"constructor"!=i&&e.push(i);return e};const vi=function(t){return null!=t&&ni(t.length)&&!Gt(t)};const yi=function(t){return vi(t)?mi(t):_i(t)};const ki=function(t,e){return t&&ze(e,yi(e),t)};const Ai=function(t){var e=[];if(null!=t)for(var i in Object(t))e.push(i);return e};var xi=Object.prototype.hasOwnProperty;const Ci=function(t){if(!F(t))return Ai(t);var e=pi(t),i=[];for(var n in t)("constructor"!=n||!e&&xi.call(t,n))&&i.push(n);return i};const Pi=function(t){return vi(t)?mi(t,!0):Ci(t)};const Ti=function(t,e){return t&&ze(e,Pi(e),t)};var Ei="object"==typeof exports&&exports&&!exports.nodeType&&exports,Si=Ei&&"object"==typeof module&&module&&!module.nodeType&&module,Ri=Si&&Si.exports===Ei?nt.Buffer:void 0,Oi=Ri?Ri.allocUnsafe:void 0;const Ii=function(t,e){if(e)return t.slice();var i=t.length,n=Oi?Oi(i):new t.constructor(i);return t.copy(n),n};const Vi=function(t,e){var i=-1,n=t.length;for(e||(e=Array(n));++i{this._setToTarget(t,n,e[n],i)}))}}function ds(t){return ls(t,us)}function us(t){return cs(t)?t:void 0}function fs(t){if(t){if(t.defaultView)return t instanceof t.defaultView.Document;if(t.ownerDocument&&t.ownerDocument.defaultView)return t instanceof t.ownerDocument.defaultView.Node}return!1}function ms(t){const e=Object.prototype.toString.apply(t);return"[object Window]"==e||"[object global]"==e}const gs=ps(R());function ps(t){if(!t)return gs;return class extends t{listenTo(t,e,i,n={}){if(fs(t)||ms(t)){const s={capture:!!n.useCapture,passive:!!n.usePassive},o=this._getProxyEmitter(t,s)||new ws(t,s);this.listenTo(o,e,i,n)}else super.listenTo(t,e,i,n)}stopListening(t,e,i){if(fs(t)||ms(t)){const n=this._getAllProxyEmitters(t);for(const t of n)this.stopListening(t,e,i)}else super.stopListening(t,e,i)}_getProxyEmitter(t,e){return function(t,e){const i=t[P];return i&&i[e]?i[e].emitter:null}(this,bs(t,e))}_getAllProxyEmitters(t){return[{capture:!1,passive:!1},{capture:!1,passive:!0},{capture:!0,passive:!1},{capture:!0,passive:!0}].map((e=>this._getProxyEmitter(t,e))).filter((t=>!!t))}}}["_getProxyEmitter","_getAllProxyEmitters","on","once","off","listenTo","stopListening","fire","delegate","stopDelegating","_addEventListener","_removeEventListener"].forEach((t=>{ps[t]=gs.prototype[t]}));class ws extends(R()){constructor(t,e){super(),O(this,bs(t,e)),this._domNode=t,this._options=e}attach(t){if(this._domListeners&&this._domListeners[t])return;const e=this._createDomListener(t);this._domNode.addEventListener(t,e,this._options),this._domListeners||(this._domListeners={}),this._domListeners[t]=e}detach(t){let e;!this._domListeners[t]||(e=this._events[t])&&e.callbacks.length||this._domListeners[t].removeListener()}_addEventListener(t,e,i){this.attach(t),R().prototype._addEventListener.call(this,t,e,i)}_removeEventListener(t,e){R().prototype._removeEventListener.call(this,t,e),this.detach(t)}_createDomListener(t){const e=e=>{this.fire(t,e)};return e.removeListener=()=>{this._domNode.removeEventListener(t,e,this._options),delete this._domListeners[t]},e}}function bs(t,e){let i=function(t){return t["data-ck-expando"]||(t["data-ck-expando"]=p())}(t);for(const t of Object.keys(e).sort())e[t]&&(i+="-"+t);return i}let _s;try{_s={window,document}}catch(t){_s={window:{},document:{}}}const vs=_s;function ys(t){const e=[];let i=t;for(;i&&i.nodeType!=Node.DOCUMENT_NODE;)e.unshift(i),i=i.parentNode;return e}function ks(t){return"[object Text]"==Object.prototype.toString.call(t)}function As(t){return"[object Range]"==Object.prototype.toString.apply(t)}function xs(t){const e=t.ownerDocument.defaultView.getComputedStyle(t);return{top:parseInt(e.borderTopWidth,10),right:parseInt(e.borderRightWidth,10),bottom:parseInt(e.borderBottomWidth,10),left:parseInt(e.borderLeftWidth,10)}}const Cs=["top","right","bottom","left","width","height"];class Ps{constructor(t){const e=As(t);if(Object.defineProperty(this,"_source",{value:t._source||t,writable:!0,enumerable:!1}),Ss(t)||e)if(e){const e=Ps.getDomRangeRects(t);Ts(this,Ps.getBoundingRect(e))}else Ts(this,t.getBoundingClientRect());else if(ms(t)){const{innerWidth:e,innerHeight:i}=t;Ts(this,{top:0,right:e,bottom:i,left:0,width:e,height:i})}else Ts(this,t)}clone(){return new Ps(this)}moveTo(t,e){return this.top=e,this.right=t+this.width,this.bottom=e+this.height,this.left=t,this}moveBy(t,e){return this.top+=e,this.right+=t,this.left+=t,this.bottom+=e,this}getIntersection(t){const e={top:Math.max(this.top,t.top),right:Math.min(this.right,t.right),bottom:Math.min(this.bottom,t.bottom),left:Math.max(this.left,t.left),width:0,height:0};return e.width=e.right-e.left,e.height=e.bottom-e.top,e.width<0||e.height<0?null:new Ps(e)}getIntersectionArea(t){const e=this.getIntersection(t);return e?e.getArea():0}getArea(){return this.width*this.height}getVisible(){const t=this._source;let e=this.clone();if(!Es(t)){let i=t.parentNode||t.commonAncestorContainer;for(;i&&!Es(i);){const t=new Ps(i),n=e.getIntersection(t);if(!n)return null;n.getArea(){for(const e of t){const t=Rs._getElementCallbacks(e.target);if(t)for(const i of t)i(e)}}))}}function Os(t,e){t instanceof HTMLTextAreaElement&&(t.value=e),t.innerHTML=e}function Is(t){return e=>e+t}function Vs(t){let e=0;for(;t.previousSibling;)t=t.previousSibling,e++;return e}function Ms(t,e,i){t.insertBefore(i,t.childNodes[e]||null)}function Ns(t){return t&&t.nodeType===Node.COMMENT_NODE}function Bs(t){return!!(t&&t.getClientRects&&t.getClientRects().length)}function Ds({element:t,target:e,positions:i,limiter:n,fitInViewport:s,viewportOffsetConfig:o}){Gt(e)&&(e=e()),Gt(n)&&(n=n());const r=function(t){return t&&t.parentNode?t.offsetParent===vs.document.body?null:t.offsetParent:null}(t),a=new Ps(t),l=new Ps(e);let c;const h=s&&function(t){t=Object.assign({top:0,bottom:0,left:0,right:0},t);const e=new Ps(vs.window);return e.top+=t.top,e.height-=t.top,e.bottom-=t.bottom,e.height-=t.bottom,e}(o)||null,d={targetRect:l,elementRect:a,positionedElementAncestor:r,viewportRect:h};if(n||s){const t=n&&new Ps(n).getVisible();Object.assign(d,{limiterRect:t,viewportRect:h}),c=function(t,e){const{elementRect:i}=e,n=i.getArea(),s=t.map((t=>new Ls(t,e))).filter((t=>!!t.name));let o=0,r=null;for(const t of s){const{limiterIntersectionArea:e,viewportIntersectionArea:i}=t;if(e===n)return t;const s=i**2+e**2;s>o&&(o=s,r=t)}return r}(i,d)||new Ls(i[0],d)}else c=new Ls(i[0],d);return c}function Fs(t){const{scrollX:e,scrollY:i}=vs.window;return t.clone().moveBy(e,i)}Rs._observerInstance=null,Rs._elementCallbacks=null;class Ls{constructor(t,e){const i=t(e.targetRect,e.elementRect,e.viewportRect);if(!i)return;const{left:n,top:s,name:o,config:r}=i;this.name=o,this.config=r,this._positioningFunctionCorrdinates={left:n,top:s},this._options=e}get left(){return this._absoluteRect.left}get top(){return this._absoluteRect.top}get limiterIntersectionArea(){const t=this._options.limiterRect;if(t){const e=this._options.viewportRect;if(!e)return t.getIntersectionArea(this._rect);{const i=t.getIntersection(e);if(i)return i.getIntersectionArea(this._rect)}}return 0}get viewportIntersectionArea(){const t=this._options.viewportRect;return t?t.getIntersectionArea(this._rect):0}get _rect(){return this._cachedRect||(this._cachedRect=this._options.elementRect.clone().moveTo(this._positioningFunctionCorrdinates.left,this._positioningFunctionCorrdinates.top)),this._cachedRect}get _absoluteRect(){return this._cachedAbsoluteRect||(this._cachedAbsoluteRect=Fs(this._rect),this._options.positionedElementAncestor&&function(t,e){const i=Fs(new Ps(e)),n=xs(e);let s=0,o=0;s-=i.left,o-=i.top,s+=e.scrollLeft,o+=e.scrollTop,s-=n.left,o-=n.top,t.moveBy(s,o)}(this._cachedAbsoluteRect,this._options.positionedElementAncestor)),this._cachedAbsoluteRect}}function zs(t){const e=t.parentNode;e&&e.removeChild(t)}function Hs(t,e,i){const n=e.clone().moveBy(0,i),s=e.clone().moveBy(0,-i),o=new Ps(t).excludeScrollbarsAndBorders();if(![s,n].every((t=>o.contains(t)))){let{scrollX:r,scrollY:a}=t;Ws(s,o)?a-=o.top-e.top+i:$s(n,o)&&(a+=e.bottom-o.bottom+i),qs(e,o)?r-=o.left-e.left+i:Us(e,o)&&(r+=e.right-o.right+i),t.scrollTo(r,a)}}function js(t,e){const i=Ks(t);let n,s;for(;t!=i.document.body;)s=e(),n=new Ps(t).excludeScrollbarsAndBorders(),n.contains(s)||(Ws(s,n)?t.scrollTop-=n.top-s.top:$s(s,n)&&(t.scrollTop+=s.bottom-n.bottom),qs(s,n)?t.scrollLeft-=n.left-s.left:Us(s,n)&&(t.scrollLeft+=s.right-n.right)),t=t.parentNode}function $s(t,e){return t.bottom>e.bottom}function Ws(t,e){return t.tope.right}function Ks(t){return As(t)?t.startContainer.ownerDocument.defaultView:t.ownerDocument.defaultView}function Gs(t){if(As(t)){let e=t.commonAncestorContainer;return ks(e)&&(e=e.parentNode),e}return t.parentNode}function Js(t,e){const i=Ks(t),n=new Ps(t);if(i===e)return n;{let t=i;for(;t!=e;){const e=t.frameElement,i=new Ps(e).excludeScrollbarsAndBorders();n.moveBy(i.left,i.top),t=t.parent}}return n}const Qs={ctrl:"⌃",cmd:"⌘",alt:"⌥",shift:"⇧"},Ys={ctrl:"Ctrl+",alt:"Alt+",shift:"Shift+"},Zs=function(){const t={arrowleft:37,arrowup:38,arrowright:39,arrowdown:40,backspace:8,delete:46,enter:13,space:32,esc:27,tab:9,ctrl:1114112,shift:2228224,alt:4456448,cmd:8912896};for(let e=65;e<=90;e++){t[String.fromCharCode(e).toLowerCase()]=e}for(let e=48;e<=57;e++)t[e-48]=e;for(let e=112;e<=123;e++)t["f"+(e-111)]=e;for(const e of"`-=[];',./\\")t[e]=e.charCodeAt(0);return t}(),Xs=Object.fromEntries(Object.entries(Zs).map((([t,e])=>[e,t.charAt(0).toUpperCase()+t.slice(1)])));function to(t){let e;if("string"==typeof t){if(e=Zs[t.toLowerCase()],!e)throw new v("keyboard-unknown-key",null,{key:t})}else e=t.keyCode+(t.altKey?Zs.alt:0)+(t.ctrlKey?Zs.ctrl:0)+(t.shiftKey?Zs.shift:0)+(t.metaKey?Zs.cmd:0);return e}function eo(t){return"string"==typeof t&&(t=function(t){return t.split("+").map((t=>t.trim()))}(t)),t.map((t=>"string"==typeof t?function(t){if(t.endsWith("!"))return to(t.slice(0,-1));const e=to(t);return r.isMac&&e==Zs.ctrl?Zs.cmd:e}(t):t)).reduce(((t,e)=>e+t),0)}function io(t){let e=eo(t);return Object.entries(r.isMac?Qs:Ys).reduce(((t,[i,n])=>(0!=(e&Zs[i])&&(e&=~Zs[i],t+=n),t)),"")+(e?Xs[e]:"")}function no(t,e){const i="ltr"===e;switch(t){case Zs.arrowleft:return i?"left":"right";case Zs.arrowright:return i?"right":"left";case Zs.arrowup:return"up";case Zs.arrowdown:return"down"}}function so(t){return Array.isArray(t)?t:[t]}function oo(t,e,i=1){if("number"!=typeof i)throw new v("translation-service-quantity-not-a-number",null,{quantity:i});const n=Object.keys(vs.window.CKEDITOR_TRANSLATIONS).length;1===n&&(t=Object.keys(vs.window.CKEDITOR_TRANSLATIONS)[0]);const s=e.id||e.string;if(0===n||!function(t,e){return!!vs.window.CKEDITOR_TRANSLATIONS[t]&&!!vs.window.CKEDITOR_TRANSLATIONS[t].dictionary[e]}(t,s))return 1!==i?e.plural:e.string;const o=vs.window.CKEDITOR_TRANSLATIONS[t].dictionary,r=vs.window.CKEDITOR_TRANSLATIONS[t].getPluralForm||(t=>1===t?0:1),a=o[s];if("string"==typeof a)return a;return a[Number(r(i))]}vs.window.CKEDITOR_TRANSLATIONS||(vs.window.CKEDITOR_TRANSLATIONS={});const ro=["ar","ara","fa","per","fas","he","heb","ku","kur","ug","uig"];function ao(t){return ro.includes(t)?"rtl":"ltr"}class lo{constructor({uiLanguage:t="en",contentLanguage:e}={}){this.uiLanguage=t,this.contentLanguage=e||this.uiLanguage,this.uiLanguageDirection=ao(this.uiLanguage),this.contentLanguageDirection=ao(this.contentLanguage),this.t=(t,e)=>this._t(t,e)}get language(){return console.warn("locale-deprecated-language-property: The Locale#language property has been deprecated and will be removed in the near future. Please use #uiLanguage and #contentLanguage properties instead."),this.uiLanguage}_t(t,e=[]){e=so(e),"string"==typeof t&&(t={string:t});const i=!!t.plural?e[0]:1;return function(t,e){return t.replace(/%(\d+)/g,((t,i)=>ithis._items.length||e<0)throw new v("collection-add-item-invalid-index",this);let i=0;for(const n of t){const t=this._getItemIdBeforeAdding(n),s=e+i;this._items.splice(s,0,n),this._itemMap.set(t,n),this.fire("add",n,s),i++}return this.fire("change",{added:t,removed:[],index:e}),this}get(t){let e;if("string"==typeof t)e=this._itemMap.get(t);else{if("number"!=typeof t)throw new v("collection-get-invalid-arg",this);e=this._items[t]}return e||null}has(t){if("string"==typeof t)return this._itemMap.has(t);{const e=t[this._idProperty];return e&&this._itemMap.has(e)}}getIndex(t){let e;return e="string"==typeof t?this._itemMap.get(t):t,e?this._items.indexOf(e):-1}remove(t){const[e,i]=this._remove(t);return this.fire("change",{added:[],removed:[e],index:i}),e}map(t,e){return this._items.map(t,e)}find(t,e){return this._items.find(t,e)}filter(t,e){return this._items.filter(t,e)}clear(){this._bindToCollection&&(this.stopListening(this._bindToCollection),this._bindToCollection=null);const t=Array.from(this._items);for(;this.length;)this._remove(0);this.fire("change",{added:[],removed:t,index:0})}bindTo(t){if(this._bindToCollection)throw new v("collection-bind-to-rebind",this);return this._bindToCollection=t,{as:t=>{this._setUpBindToBinding((e=>new t(e)))},using:t=>{"function"==typeof t?this._setUpBindToBinding(t):this._setUpBindToBinding((e=>e[t]))}}}_setUpBindToBinding(t){const e=this._bindToCollection,i=(i,n,s)=>{const o=e._bindToCollection==this,r=e._bindToInternalToExternalMap.get(n);if(o&&r)this._bindToExternalToInternalMap.set(n,r),this._bindToInternalToExternalMap.set(r,n);else{const i=t(n);if(!i)return void this._skippedIndexesFromExternal.push(s);let o=s;for(const t of this._skippedIndexesFromExternal)s>t&&o--;for(const t of e._skippedIndexesFromExternal)o>=t&&o++;this._bindToExternalToInternalMap.set(n,i),this._bindToInternalToExternalMap.set(i,n),this.add(i,o);for(let t=0;t{const n=this._bindToExternalToInternalMap.get(e);n&&this.remove(n),this._skippedIndexesFromExternal=this._skippedIndexesFromExternal.reduce(((t,e)=>(ie&&t.push(e),t)),[])}))}_getItemIdBeforeAdding(t){const e=this._idProperty;let i;if(e in t){if(i=t[e],"string"!=typeof i)throw new v("collection-add-invalid-id",this);if(this.get(i))throw new v("collection-add-item-already-exists",this)}else t[e]=i=p();return i}_remove(t){let e,i,n,s=!1;const o=this._idProperty;if("string"==typeof t?(i=t,n=this._itemMap.get(i),s=!n,n&&(e=this._items.indexOf(n))):"number"==typeof t?(e=t,n=this._items[e],s=!n,n&&(i=n[o])):(n=t,i=n[o],e=this._items.indexOf(n),s=-1==e||!this._itemMap.get(i)),s)throw new v("collection-remove-404",this);this._items.splice(e,1),this._itemMap.delete(i);const r=this._bindToInternalToExternalMap.get(n);return this._bindToInternalToExternalMap.delete(n),this._bindToExternalToInternalMap.delete(r),this.fire("remove",n,e),[n,e]}[Symbol.iterator](){return this._items[Symbol.iterator]()}}function ho(t){const e=t.next();return e.done?null:e.value}class uo extends(ps(q())){constructor(){super(),this._elements=new Set,this._nextEventLoopTimeout=null,this.set("isFocused",!1),this.set("focusedElement",null)}add(t){if(this._elements.has(t))throw new v("focustracker-add-element-already-exist",this);this.listenTo(t,"focus",(()=>this._focus(t)),{useCapture:!0}),this.listenTo(t,"blur",(()=>this._blur()),{useCapture:!0}),this._elements.add(t)}remove(t){t===this.focusedElement&&this._blur(),this._elements.has(t)&&(this.stopListening(t),this._elements.delete(t))}destroy(){this.stopListening()}_focus(t){clearTimeout(this._nextEventLoopTimeout),this.focusedElement=t,this.isFocused=!0}_blur(){clearTimeout(this._nextEventLoopTimeout),this._nextEventLoopTimeout=setTimeout((()=>{this.focusedElement=null,this.isFocused=!1}),0)}}class fo{constructor(){this._listener=new(ps())}listenTo(t){this._listener.listenTo(t,"keydown",((t,e)=>{this._listener.fire("_keydown:"+to(e),e)}))}set(t,e,i={}){const n=eo(t),s=i.priority;this._listener.listenTo(this._listener,"_keydown:"+n,((t,i)=>{e(i,(()=>{i.preventDefault(),i.stopPropagation(),t.stop()})),t.return=!0}),{priority:s})}press(t){return!!this._listener.fire("_keydown:"+to(t),t)}destroy(){this._listener.stopListening()}}function mo(t){return tt(t)?new Map(t):function(t){const e=new Map;for(const i in t)e.set(i,t[i]);return e}(t)}const go=1e4;function po(t,e){return!!(i=t.charAt(e-1))&&1==i.length&&/[\ud800-\udbff]/.test(i)&&function(t){return!!t&&1==t.length&&/[\udc00-\udfff]/.test(t)}(t.charAt(e));var i}function wo(t,e){return!!(i=t.charAt(e))&&1==i.length&&/[\u0300-\u036f\u1ab0-\u1aff\u1dc0-\u1dff\u20d0-\u20ff\ufe20-\ufe2f]/.test(i);var i}const bo=function(){const t=/\p{Regional_Indicator}{2}/u.source,e="(?:"+[/\p{Emoji}[\u{E0020}-\u{E007E}]+\u{E007F}/u,/\p{Emoji}\u{FE0F}?\u{20E3}/u,/\p{Emoji}\u{FE0F}/u,/(?=\p{General_Category=Other_Symbol})\p{Emoji}\p{Emoji_Modifier}*/u].map((t=>t.source)).join("|")+")";return new RegExp(`${t}|${e}(?:‍${e})*`,"ug")}();function _o(t,e){const i=String(t).matchAll(bo);return Array.from(i).some((t=>t.index{this._renderViewIntoCollectionParent(e,i)})),this.on("remove",((t,e)=>{e.element&&this._parentElement&&e.element.remove()})),this._parentElement=null}destroy(){this.map((t=>t.destroy()))}setParent(t){this._parentElement=t;for(const t of this)this._renderViewIntoCollectionParent(t)}delegate(...t){if(!t.length||!t.every((t=>"string"==typeof t)))throw new v("ui-viewcollection-delegate-wrong-events",this);return{to:e=>{for(const i of this)for(const n of t)i.delegate(n).to(e);this.on("add",((i,n)=>{for(const i of t)n.delegate(i).to(e)})),this.on("remove",((i,n)=>{for(const i of t)n.stopDelegating(i,e)}))}}}_renderViewIntoCollectionParent(t,e){t.isRendered||t.render(),t.element&&this._parentElement&&this._parentElement.insertBefore(t.element,this._parentElement.children[e])}}class yo extends(ps(q())){constructor(t){super(),this.element=null,this.isRendered=!1,this.locale=t,this.t=t&&t.t,this._viewCollections=new co,this._unboundChildren=this.createCollection(),this._viewCollections.on("add",((e,i)=>{i.locale=t,i.t=t&&t.t})),this.decorate("render")}get bindTemplate(){return this._bindTemplate?this._bindTemplate:this._bindTemplate=ko.bind(this,this)}createCollection(t){const e=new vo(t);return this._viewCollections.add(e),e}registerChild(t){tt(t)||(t=[t]);for(const e of t)this._unboundChildren.add(e)}deregisterChild(t){tt(t)||(t=[t]);for(const e of t)this._unboundChildren.remove(e)}setTemplate(t){this.template=new ko(t)}extendTemplate(t){ko.extend(this.template,t)}render(){if(this.isRendered)throw new v("ui-view-render-already-rendered",this);this.template&&(this.element=this.template.render(),this.registerChild(this.template.getViews())),this.isRendered=!0}destroy(){this.stopListening(),this._viewCollections.map((t=>t.destroy())),this.template&&this.template._revertData&&this.template.revert(this.element)}}class ko extends(R()){constructor(t){super(),Object.assign(this,Io(Oo(t))),this._isRendered=!1,this._revertData=null}render(){const t=this._renderNode({intoFragment:!0});return this._isRendered=!0,t}apply(t){return this._revertData={children:[],bindings:[],attributes:{}},this._renderNode({node:t,intoFragment:!1,isApplying:!0,revertData:this._revertData}),t}revert(t){if(!this._revertData)throw new v("ui-template-revert-not-applied",[this,t]);this._revertTemplateFromNode(t,this._revertData)}*getViews(){yield*function*t(e){if(e.children)for(const i of e.children)Fo(i)?yield i:Lo(i)&&(yield*t(i))}(this)}static bind(t,e){return{to:(i,n)=>new xo({eventNameOrFunction:i,attribute:i,observable:t,emitter:e,callback:n}),if:(i,n,s)=>new Co({observable:t,emitter:e,attribute:i,valueIfTrue:n,callback:s})}}static extend(t,e){if(t._isRendered)throw new v("template-extend-render",[this,t]);Bo(t,Io(Oo(e)))}_renderNode(t){let e;if(e=t.node?this.tag&&this.text:this.tag?this.text:!this.text,e)throw new v("ui-template-wrong-syntax",this);return this.text?this._renderText(t):this._renderElement(t)}_renderElement(t){let e=t.node;return e||(e=t.node=document.createElementNS(this.ns||"http://www.w3.org/1999/xhtml",this.tag)),this._renderAttributes(t),this._renderElementChildren(t),this._setUpListeners(t),e}_renderText(t){let e=t.node;return e?t.revertData.text=e.textContent:e=t.node=document.createTextNode(""),Po(this.text)?this._bindToObservable({schema:this.text,updater:Eo(e),data:t}):e.textContent=this.text.join(""),e}_renderAttributes(t){if(!this.attributes)return;const e=t.node,i=t.revertData;for(const n in this.attributes){const s=e.getAttribute(n),o=this.attributes[n];i&&(i.attributes[n]=s);const r=Ho(o)?o[0].ns:null;if(Po(o)){const a=Ho(o)?o[0].value:o;i&&jo(n)&&a.unshift(s),this._bindToObservable({schema:a,updater:So(e,n,r),data:t})}else if("style"==n&&"string"!=typeof o[0])this._renderStyleAttribute(o[0],t);else{i&&s&&jo(n)&&o.unshift(s);const t=o.map((t=>t&&t.value||t)).reduce(((t,e)=>t.concat(e)),[]).reduce(Mo,"");Do(t)||e.setAttributeNS(r,n,t)}}}_renderStyleAttribute(t,e){const i=e.node;for(const n in t){const s=t[n];Po(s)?this._bindToObservable({schema:[s],updater:Ro(i,n),data:e}):i.style[n]=s}}_renderElementChildren(t){const e=t.node,i=t.intoFragment?document.createDocumentFragment():e,n=t.isApplying;let s=0;for(const o of this.children)if(zo(o)){if(!n){o.setParent(e);for(const t of o)i.appendChild(t.element)}}else if(Fo(o))n||(o.isRendered||o.render(),i.appendChild(o.element));else if(fs(o))i.appendChild(o);else if(n){const e={children:[],bindings:[],attributes:{}};t.revertData.children.push(e),o._renderNode({intoFragment:!1,node:i.childNodes[s++],isApplying:!0,revertData:e})}else i.appendChild(o.render());t.intoFragment&&e.appendChild(i)}_setUpListeners(t){if(this.eventListeners)for(const e in this.eventListeners){const i=this.eventListeners[e].map((i=>{const[n,s]=e.split("@");return i.activateDomEventListener(n,s,t)}));t.revertData&&t.revertData.bindings.push(i)}}_bindToObservable({schema:t,updater:e,data:i}){const n=i.revertData;To(t,e,i);const s=t.filter((t=>!Do(t))).filter((t=>t.observable)).map((n=>n.activateAttributeListener(t,e,i)));n&&n.bindings.push(s)}_revertTemplateFromNode(t,e){for(const t of e.bindings)for(const e of t)e();if(e.text)return void(t.textContent=e.text);const i=t;for(const t in e.attributes){const n=e.attributes[t];null===n?i.removeAttribute(t):i.setAttribute(t,n)}for(let t=0;tTo(t,e,i);return this.emitter.listenTo(this.observable,`change:${this.attribute}`,n),()=>{this.emitter.stopListening(this.observable,`change:${this.attribute}`,n)}}}class xo extends Ao{constructor(t){super(t),this.eventNameOrFunction=t.eventNameOrFunction}activateDomEventListener(t,e,i){const n=(t,i)=>{e&&!i.target.matches(e)||("function"==typeof this.eventNameOrFunction?this.eventNameOrFunction(i):this.observable.fire(this.eventNameOrFunction,i))};return this.emitter.listenTo(i.node,t,n),()=>{this.emitter.stopListening(i.node,t,n)}}}class Co extends Ao{constructor(t){super(t),this.valueIfTrue=t.valueIfTrue}getValue(t){return!Do(super.getValue(t))&&(this.valueIfTrue||!0)}}function Po(t){return!!t&&(t.value&&(t=t.value),Array.isArray(t)?t.some(Po):t instanceof Ao)}function To(t,e,{node:i}){const n=function(t,e){return t.map((t=>t instanceof Ao?t.getValue(e):t))}(t,i);let s;s=1==t.length&&t[0]instanceof Co?n[0]:n.reduce(Mo,""),Do(s)?e.remove():e.set(s)}function Eo(t){return{set(e){t.textContent=e},remove(){t.textContent=""}}}function So(t,e,i){return{set(n){t.setAttributeNS(i,e,n)},remove(){t.removeAttributeNS(i,e)}}}function Ro(t,e){return{set(i){t.style[e]=i},remove(){t.style[e]=null}}}function Oo(t){return ls(t,(t=>{if(t&&(t instanceof Ao||Lo(t)||Fo(t)||zo(t)))return t}))}function Io(t){if("string"==typeof t?t=function(t){return{text:[t]}}(t):t.text&&function(t){t.text=so(t.text)}(t),t.on&&(t.eventListeners=function(t){for(const e in t)Vo(t,e);return t}(t.on),delete t.on),!t.text){t.attributes&&function(t){for(const e in t)t[e].value&&(t[e].value=so(t[e].value)),Vo(t,e)}(t.attributes);const e=[];if(t.children)if(zo(t.children))e.push(t.children);else for(const i of t.children)Lo(i)||Fo(i)||fs(i)?e.push(i):e.push(new ko(i));t.children=e}return t}function Vo(t,e){t[e]=so(t[e])}function Mo(t,e){return Do(e)?t:Do(t)?e:`${t} ${e}`}function No(t,e){for(const i in e)t[i]?t[i].push(...e[i]):t[i]=e[i]}function Bo(t,e){if(e.attributes&&(t.attributes||(t.attributes={}),No(t.attributes,e.attributes)),e.eventListeners&&(t.eventListeners||(t.eventListeners={}),No(t.eventListeners,e.eventListeners)),e.text&&t.text.push(...e.text),e.children&&e.children.length){if(t.children.length!=e.children.length)throw new v("ui-template-extend-children-mismatch",t);let i=0;for(const n of e.children)Bo(t.children[i++],n)}}function Do(t){return!t&&0!==t}function Fo(t){return t instanceof yo}function Lo(t){return t instanceof ko}function zo(t){return t instanceof vo}function Ho(t){return F(t[0])&&t[0].ns}function jo(t){return"class"==t||"style"==t}class $o extends vo{constructor(t,e=[]){super(e),this.locale=t}attachToDom(){this._bodyCollectionContainer=new ko({tag:"div",attributes:{class:["ck","ck-reset_all","ck-body","ck-rounded-corners"],dir:this.locale.uiLanguageDirection},children:this}).render();let t=document.querySelector(".ck-body-wrapper");t||(t=vt(document,"div",{class:"ck-body-wrapper"}),document.body.appendChild(t)),t.appendChild(this._bodyCollectionContainer)}detachFromDom(){super.destroy(),this._bodyCollectionContainer&&this._bodyCollectionContainer.remove();const t=document.querySelector(".ck-body-wrapper");t&&0==t.childElementCount&&t.remove()}}class Wo extends yo{constructor(){super();const t=this.bindTemplate;this.set("content",""),this.set("viewBox","0 0 20 20"),this.set("fillColor",""),this.set("isColorInherited",!0),this.setTemplate({tag:"svg",ns:"http://www.w3.org/2000/svg",attributes:{class:["ck","ck-icon","ck-reset_all-excluded",t.if("isColorInherited","ck-icon_inherit-color")],viewBox:t.to("viewBox")}})}render(){super.render(),this._updateXMLContent(),this._colorFillPaths(),this.on("change:content",(()=>{this._updateXMLContent(),this._colorFillPaths()})),this.on("change:fillColor",(()=>{this._colorFillPaths()}))}_updateXMLContent(){if(this.content){const t=(new DOMParser).parseFromString(this.content.trim(),"image/svg+xml").querySelector("svg"),e=t.getAttribute("viewBox");e&&(this.viewBox=e);for(const{name:e,value:i}of Array.from(t.attributes))Wo.presentationalAttributeNames.includes(e)&&this.element.setAttribute(e,i);for(;this.element.firstChild;)this.element.removeChild(this.element.firstChild);for(;t.childNodes.length>0;)this.element.appendChild(t.childNodes[0])}}_colorFillPaths(){this.fillColor&&this.element.querySelectorAll(".ck-icon__fill").forEach((t=>{t.style.fill=this.fillColor}))}}Wo.presentationalAttributeNames=["alignment-baseline","baseline-shift","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-rendering","cursor","direction","display","dominant-baseline","fill","fill-opacity","fill-rule","filter","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","image-rendering","letter-spacing","lighting-color","marker-end","marker-mid","marker-start","mask","opacity","overflow","paint-order","pointer-events","shape-rendering","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-anchor","text-decoration","text-overflow","text-rendering","transform","unicode-bidi","vector-effect","visibility","white-space","word-spacing","writing-mode"];class qo extends yo{constructor(t){super(t);const e=this.bindTemplate,i=p();this.set("class",void 0),this.set("labelStyle",void 0),this.set("icon",void 0),this.set("isEnabled",!0),this.set("isOn",!1),this.set("isVisible",!0),this.set("isToggleable",!1),this.set("keystroke",void 0),this.set("label",void 0),this.set("tabindex",-1),this.set("tooltip",!1),this.set("tooltipPosition","s"),this.set("type","button"),this.set("withText",!1),this.set("withKeystroke",!1),this.children=this.createCollection(),this.labelView=this._createLabelView(i),this.iconView=new Wo,this.iconView.extendTemplate({attributes:{class:"ck-button__icon"}}),this.keystrokeView=this._createKeystrokeView(),this.bind("_tooltipString").to(this,"tooltip",this,"label",this,"keystroke",this._getTooltipString.bind(this));const n={tag:"button",attributes:{class:["ck","ck-button",e.to("class"),e.if("isEnabled","ck-disabled",(t=>!t)),e.if("isVisible","ck-hidden",(t=>!t)),e.to("isOn",(t=>t?"ck-on":"ck-off")),e.if("withText","ck-button_with-text"),e.if("withKeystroke","ck-button_with-keystroke")],type:e.to("type",(t=>t||"button")),tabindex:e.to("tabindex"),"aria-labelledby":`ck-editor__aria-label_${i}`,"aria-disabled":e.if("isEnabled",!0,(t=>!t)),"aria-pressed":e.to("isOn",(t=>!!this.isToggleable&&String(!!t))),"data-cke-tooltip-text":e.to("_tooltipString"),"data-cke-tooltip-position":e.to("tooltipPosition")},children:this.children,on:{click:e.to((t=>{this.isEnabled?this.fire("execute"):t.preventDefault()}))}};r.isSafari&&(n.on.mousedown=e.to((t=>{this.focus(),t.preventDefault()}))),this.setTemplate(n)}render(){super.render(),this.icon&&(this.iconView.bind("content").to(this,"icon"),this.children.add(this.iconView)),this.children.add(this.labelView),this.withKeystroke&&this.keystroke&&this.children.add(this.keystrokeView)}focus(){this.element.focus()}_createLabelView(t){const e=new yo,i=this.bindTemplate;return e.setTemplate({tag:"span",attributes:{class:["ck","ck-button__label"],style:i.to("labelStyle"),id:`ck-editor__aria-label_${t}`},children:[{text:this.bindTemplate.to("label")}]}),e}_createKeystrokeView(){const t=new yo;return t.setTemplate({tag:"span",attributes:{class:["ck","ck-button__keystroke"]},children:[{text:this.bindTemplate.to("keystroke",(t=>io(t)))}]}),t}_getTooltipString(t,e,i){return t?"string"==typeof t?t:(i&&(i=io(i)),t instanceof Function?t(e,i):`${e}${i?` (${i})`:""}`):""}}class Uo extends qo{constructor(t){super(t),this.isToggleable=!0,this.toggleSwitchView=this._createToggleView(),this.extendTemplate({attributes:{class:"ck-switchbutton"}})}render(){super.render(),this.children.add(this.toggleSwitchView)}_createToggleView(){const t=new yo;return t.setTemplate({tag:"span",attributes:{class:["ck","ck-button__toggle"]},children:[{tag:"span",attributes:{class:["ck","ck-button__toggle__inner"]}}]}),t}}function Ko(t){return"string"==typeof t?{model:t,label:t,hasBorder:!1,view:{name:"span",styles:{color:t}}}:{model:t.color,label:t.label||t.color,hasBorder:void 0!==t.hasBorder&&t.hasBorder,view:{name:"span",styles:{color:`${t.color}`}}}}class Go extends qo{constructor(t){super(t);const e=this.bindTemplate;this.set("color",void 0),this.set("hasBorder",!1),this.icon='',this.extendTemplate({attributes:{style:{backgroundColor:e.to("color")},class:["ck","ck-color-grid__tile",e.if("hasBorder","ck-color-table__color-tile_bordered")]}})}render(){super.render(),this.iconView.fillColor="hsl(0, 0%, 100%)"}}class Jo extends yo{constructor(t,e){super(t);const i=e&&e.colorDefinitions||[];this.columns=e&&e.columns?e.columns:5;const n={gridTemplateColumns:`repeat( ${this.columns}, 1fr)`};this.set("selectedColor",void 0),this.items=this.createCollection(),this.focusTracker=new uo,this.keystrokes=new fo,this.items.on("add",((t,e)=>{e.isOn=e.color===this.selectedColor})),i.forEach((t=>{const e=new Go;e.set({color:t.color,label:t.label,tooltip:!0,hasBorder:t.options.hasBorder}),e.on("execute",(()=>{this.fire("execute",{value:t.color,hasBorder:t.options.hasBorder,label:t.label})})),this.items.add(e)})),this.setTemplate({tag:"div",children:this.items,attributes:{class:["ck","ck-color-grid"],style:n}}),this.on("change:selectedColor",((t,e,i)=>{for(const t of this.items)t.isOn=t.color===i}))}focus(){this.items.length&&this.items.first.focus()}focusLast(){this.items.length&&this.items.last.focus()}render(){super.render();for(const t of this.items)this.focusTracker.add(t.element);this.items.on("add",((t,e)=>{this.focusTracker.add(e.element)})),this.items.on("remove",((t,e)=>{this.focusTracker.remove(e.element)})),this.keystrokes.listenTo(this.element),n({keystrokeHandler:this.keystrokes,focusTracker:this.focusTracker,gridItems:this.items,numberOfColumns:this.columns,uiLanguageDirection:this.locale&&this.locale.uiLanguageDirection})}destroy(){super.destroy(),this.focusTracker.destroy(),this.keystrokes.destroy()}}class Qo{constructor(t){this.editor=t,this._components=new Map}*names(){for(const t of this._components.values())yield t.originalName}add(t,e){this._components.set(Yo(t),{callback:e,originalName:t})}create(t){if(!this.has(t))throw new v("componentfactory-item-missing",this,{name:t});return this._components.get(Yo(t)).callback(this.editor.locale)}has(t){return this._components.has(Yo(t))}}function Yo(t){return String(t).toLowerCase()}class Zo extends yo{constructor(t,e,i){super(t);const n=this.bindTemplate;this.buttonView=e,this.panelView=i,this.set("isOpen",!1),this.set("isEnabled",!0),this.set("class",void 0),this.set("id",void 0),this.set("panelPosition","auto"),this.keystrokes=new fo,this.focusTracker=new uo,this.setTemplate({tag:"div",attributes:{class:["ck","ck-dropdown",n.to("class"),n.if("isEnabled","ck-disabled",(t=>!t))],id:n.to("id"),"aria-describedby":n.to("ariaDescribedById")},children:[e,i]}),e.extendTemplate({attributes:{class:["ck-dropdown__button"],"data-cke-tooltip-disabled":n.to("isOpen")}})}render(){super.render(),this.focusTracker.add(this.buttonView.element),this.focusTracker.add(this.panelView.element),this.listenTo(this.buttonView,"open",(()=>{this.isOpen=!this.isOpen})),this.panelView.bind("isVisible").to(this,"isOpen"),this.on("change:isOpen",((t,e,i)=>{i&&("auto"===this.panelPosition?this.panelView.position=Zo._getOptimalPosition({element:this.panelView.element,target:this.buttonView.element,fitInViewport:!0,positions:this._panelPositions}).name:this.panelView.position=this.panelPosition)})),this.keystrokes.listenTo(this.element);const t=(t,e)=>{this.isOpen&&(this.isOpen=!1,e())};this.keystrokes.set("arrowdown",((t,e)=>{this.buttonView.isEnabled&&!this.isOpen&&(this.isOpen=!0,e())})),this.keystrokes.set("arrowright",((t,e)=>{this.isOpen&&e()})),this.keystrokes.set("arrowleft",t),this.keystrokes.set("esc",t)}focus(){this.buttonView.focus()}get _panelPositions(){const{south:t,north:e,southEast:i,southWest:n,northEast:s,northWest:o,southMiddleEast:r,southMiddleWest:a,northMiddleEast:l,northMiddleWest:c}=Zo.defaultPanelPositions;return"rtl"!==this.locale.uiLanguageDirection?[i,n,r,a,t,s,o,l,c,e]:[n,i,a,r,t,o,s,c,l,e]}}Zo.defaultPanelPositions={south:(t,e)=>({top:t.bottom,left:t.left-(e.width-t.width)/2,name:"s"}),southEast:t=>({top:t.bottom,left:t.left,name:"se"}),southWest:(t,e)=>({top:t.bottom,left:t.left-e.width+t.width,name:"sw"}),southMiddleEast:(t,e)=>({top:t.bottom,left:t.left-(e.width-t.width)/4,name:"sme"}),southMiddleWest:(t,e)=>({top:t.bottom,left:t.left-3*(e.width-t.width)/4,name:"smw"}),north:(t,e)=>({top:t.top-e.height,left:t.left-(e.width-t.width)/2,name:"n"}),northEast:(t,e)=>({top:t.top-e.height,left:t.left,name:"ne"}),northWest:(t,e)=>({top:t.top-e.height,left:t.left-e.width+t.width,name:"nw"}),northMiddleEast:(t,e)=>({top:t.top-e.height,left:t.left-(e.width-t.width)/4,name:"nme"}),northMiddleWest:(t,e)=>({top:t.top-e.height,left:t.left-3*(e.width-t.width)/4,name:"nmw"})},Zo._getOptimalPosition=Ds;const Xo='';class tr extends qo{constructor(t){super(t),this.arrowView=this._createArrowView(),this.extendTemplate({attributes:{"aria-haspopup":!0,"aria-expanded":this.bindTemplate.to("isOn",(t=>String(t)))}}),this.delegate("execute").to(this,"open")}render(){super.render(),this.children.add(this.arrowView)}_createArrowView(){const t=new Wo;return t.content=Xo,t.extendTemplate({attributes:{class:"ck-dropdown__arrow"}}),t}}class er extends yo{constructor(t){super(t);const e=this.bindTemplate;this.set("class",void 0),this.set("labelStyle",void 0),this.set("icon",void 0),this.set("isEnabled",!0),this.set("isOn",!1),this.set("isToggleable",!1),this.set("isVisible",!0),this.set("keystroke",void 0),this.set("withKeystroke",!1),this.set("label",void 0),this.set("tabindex",-1),this.set("tooltip",!1),this.set("tooltipPosition","s"),this.set("type","button"),this.set("withText",!1),this.children=this.createCollection(),this.actionView=this._createActionView(),this.arrowView=this._createArrowView(),this.keystrokes=new fo,this.focusTracker=new uo,this.setTemplate({tag:"div",attributes:{class:["ck","ck-splitbutton",e.to("class"),e.if("isVisible","ck-hidden",(t=>!t)),this.arrowView.bindTemplate.if("isOn","ck-splitbutton_open")]},children:this.children})}render(){super.render(),this.children.add(this.actionView),this.children.add(this.arrowView),this.focusTracker.add(this.actionView.element),this.focusTracker.add(this.arrowView.element),this.keystrokes.listenTo(this.element),this.keystrokes.set("arrowright",((t,e)=>{this.focusTracker.focusedElement===this.actionView.element&&(this.arrowView.focus(),e())})),this.keystrokes.set("arrowleft",((t,e)=>{this.focusTracker.focusedElement===this.arrowView.element&&(this.actionView.focus(),e())}))}destroy(){super.destroy(),this.focusTracker.destroy(),this.keystrokes.destroy()}focus(){this.actionView.focus()}_createActionView(){const t=new qo;return t.bind("icon","isEnabled","isOn","isToggleable","keystroke","label","tabindex","tooltip","tooltipPosition","type","withText").to(this),t.extendTemplate({attributes:{class:"ck-splitbutton__action"}}),t.delegate("execute").to(this),t}_createArrowView(){const t=new qo,e=t.bindTemplate;return t.icon=Xo,t.extendTemplate({attributes:{class:["ck-splitbutton__arrow"],"data-cke-tooltip-disabled":e.to("isOn"),"aria-haspopup":!0,"aria-expanded":e.to("isOn",(t=>String(t)))}}),t.bind("isEnabled").to(this),t.bind("label").to(this),t.bind("tooltip").to(this),t.delegate("execute").to(this,"open"),t}}class ir extends yo{constructor(t){super(t);const e=this.bindTemplate;this.set("isVisible",!1),this.set("position","se"),this.children=this.createCollection(),this.setTemplate({tag:"div",attributes:{class:["ck","ck-reset","ck-dropdown__panel",e.to("position",(t=>`ck-dropdown__panel_${t}`)),e.if("isVisible","ck-dropdown__panel-visible")]},children:this.children,on:{selectstart:e.to((t=>t.preventDefault()))}})}focus(){if(this.children.length){const t=this.children.first;"function"==typeof t.focus?t.focus():y("ui-dropdown-panel-focus-child-missing-focus",{childView:this.children.first,dropdownPanel:this})}}focusLast(){if(this.children.length){const t=this.children.last;"function"==typeof t.focusLast?t.focusLast():t.focus()}}}class nr{constructor(t){if(this.focusables=t.focusables,this.focusTracker=t.focusTracker,this.keystrokeHandler=t.keystrokeHandler,this.actions=t.actions,t.actions&&t.keystrokeHandler)for(const e in t.actions){let i=t.actions[e];"string"==typeof i&&(i=[i]);for(const n of i)t.keystrokeHandler.set(n,((t,i)=>{this[e](),i()}))}}get first(){return this.focusables.find(sr)||null}get last(){return this.focusables.filter(sr).slice(-1)[0]||null}get next(){return this._getFocusableItem(1)}get previous(){return this._getFocusableItem(-1)}get current(){let t=null;return null===this.focusTracker.focusedElement?null:(this.focusables.find(((e,i)=>{const n=e.element===this.focusTracker.focusedElement;return n&&(t=i),n})),t)}focusFirst(){this._focus(this.first)}focusLast(){this._focus(this.last)}focusNext(){this._focus(this.next)}focusPrevious(){this._focus(this.previous)}_focus(t){t&&t.focus()}_getFocusableItem(t){const e=this.current,i=this.focusables.length;if(!i)return null;if(null===e)return this[1===t?"first":"last"];let n=(e+i+t)%i;do{const e=this.focusables.get(n);if(sr(e))return e;n=(n+i+t)%i}while(n!==e);return null}}function sr(t){return!(!t.focus||!Bs(t.element))}class or extends yo{constructor(t){super(t),this.setTemplate({tag:"span",attributes:{class:["ck","ck-toolbar__separator"]}})}}class rr extends yo{constructor(t){super(t),this.setTemplate({tag:"span",attributes:{class:["ck","ck-toolbar__line-break"]}})}}function ar(t){return Array.isArray(t)?{items:t,removeItems:[]}:t?Object.assign({items:[],removeItems:[]},t):{items:[],removeItems:[]}}class lr extends(q()){constructor(t){super(),this.editor=t,this.set("isEnabled",!0),this._disableStack=new Set}forceDisabled(t){this._disableStack.add(t),1==this._disableStack.size&&(this.on("set:isEnabled",cr,{priority:"highest"}),this.isEnabled=!1)}clearForceDisabled(t){this._disableStack.delete(t),0==this._disableStack.size&&(this.off("set:isEnabled",cr),this.isEnabled=!0)}destroy(){this.stopListening()}static get isContextPlugin(){return!1}}function cr(t){t.return=!1,t.stop()}class hr extends(q()){constructor(t){super(),this.editor=t,this.set("value",void 0),this.set("isEnabled",!1),this._affectsData=!0,this._disableStack=new Set,this.decorate("execute"),this.listenTo(this.editor.model.document,"change",(()=>{this.refresh()})),this.on("execute",(t=>{this.isEnabled||t.stop()}),{priority:"high"}),this.listenTo(t,"change:isReadOnly",((t,e,i)=>{i&&this.affectsData?this.forceDisabled("readOnlyMode"):this.clearForceDisabled("readOnlyMode")}))}get affectsData(){return this._affectsData}set affectsData(t){this._affectsData=t}refresh(){this.isEnabled=!0}forceDisabled(t){this._disableStack.add(t),1==this._disableStack.size&&(this.on("set:isEnabled",dr,{priority:"highest"}),this.isEnabled=!1)}clearForceDisabled(t){this._disableStack.delete(t),0==this._disableStack.size&&(this.off("set:isEnabled",dr),this.refresh())}execute(...t){}destroy(){this.stopListening()}}function dr(t){t.return=!1,t.stop()}class ur extends hr{constructor(t){super(t),this._childCommandsDefinitions=[]}refresh(){}execute(...t){const e=this._getFirstEnabledCommand();return!!e&&e.execute(t)}registerChildCommand(t,e={}){b(this._childCommandsDefinitions,{command:t,priority:e.priority||"normal"}),t.on("change:isEnabled",(()=>this._checkEnabled())),this._checkEnabled()}_checkEnabled(){this.isEnabled=!!this._getFirstEnabledCommand()}_getFirstEnabledCommand(){const t=this._childCommandsDefinitions.find((({command:t})=>t.isEnabled));return t&&t.command}}class fr extends(R()){constructor(t,e=[],i=[]){super(),this._context=t,this._plugins=new Map,this._availablePlugins=new Map;for(const t of e)t.pluginName&&this._availablePlugins.set(t.pluginName,t);this._contextPlugins=new Map;for(const[t,e]of i)this._contextPlugins.set(t,e),this._contextPlugins.set(e,t),t.pluginName&&this._availablePlugins.set(t.pluginName,t)}*[Symbol.iterator](){for(const t of this._plugins)"function"==typeof t[0]&&(yield t)}get(t){const e=this._plugins.get(t);if(!e){let e=t;throw"function"==typeof t&&(e=t.pluginName||t.name),new v("plugincollection-plugin-not-loaded",this._context,{plugin:e})}return e}has(t){return this._plugins.has(t)}init(t,e=[],i=[]){const n=this,s=this._context;!function t(e,i=new Set){e.forEach((e=>{a(e)&&(i.has(e)||(i.add(e),e.pluginName&&!n._availablePlugins.has(e.pluginName)&&n._availablePlugins.set(e.pluginName,e),e.requires&&t(e.requires,i)))}))}(t),d(t);const o=[...function t(e,i=new Set){return e.map((t=>a(t)?t:n._availablePlugins.get(t))).reduce(((e,n)=>i.has(n)?e:(i.add(n),n.requires&&(d(n.requires,n),t(n.requires,i).forEach((t=>e.add(t)))),e.add(n))),new Set)}(t.filter((t=>!c(t,e))))];!function(t,e){for(const i of e){if("function"!=typeof i)throw new v("plugincollection-replace-plugin-invalid-type",null,{pluginItem:i});const e=i.pluginName;if(!e)throw new v("plugincollection-replace-plugin-missing-name",null,{pluginItem:i});if(i.requires&&i.requires.length)throw new v("plugincollection-plugin-for-replacing-cannot-have-dependencies",null,{pluginName:e});const s=n._availablePlugins.get(e);if(!s)throw new v("plugincollection-plugin-for-replacing-not-exist",null,{pluginName:e});const o=t.indexOf(s);if(-1===o){if(n._contextPlugins.has(s))return;throw new v("plugincollection-plugin-for-replacing-not-loaded",null,{pluginName:e})}if(s.requires&&s.requires.length)throw new v("plugincollection-replaced-plugin-cannot-have-dependencies",null,{pluginName:e});t.splice(o,1,i),n._availablePlugins.set(e,i)}}(o,i);const r=function(t){return t.map((t=>{let e=n._contextPlugins.get(t);return e=e||new t(s),n._add(t,e),e}))}(o);return u(r,"init").then((()=>u(r,"afterInit"))).then((()=>r));function a(t){return"function"==typeof t}function l(t){return a(t)&&t.isContextPlugin}function c(t,e){return e.some((e=>e===t||(h(t)===e||h(e)===t)))}function h(t){return a(t)?t.pluginName||t.name:t}function d(t,i=null){t.map((t=>a(t)?t:n._availablePlugins.get(t)||t)).forEach((t=>{!function(t,e){if(a(t))return;if(e)throw new v("plugincollection-soft-required",s,{missingPlugin:t,requiredBy:h(e)});throw new v("plugincollection-plugin-not-found",s,{plugin:t})}(t,i),function(t,e){if(!l(e))return;if(l(t))return;throw new v("plugincollection-context-required",s,{plugin:h(t),requiredBy:h(e)})}(t,i),function(t,i){if(!i)return;if(!c(t,e))return;throw new v("plugincollection-required",s,{plugin:h(t),requiredBy:h(i)})}(t,i)}))}function u(t,e){return t.reduce(((t,i)=>i[e]?n._contextPlugins.has(i)?t:t.then(i[e].bind(i)):t),Promise.resolve())}}destroy(){const t=[];for(const[,e]of this)"function"!=typeof e.destroy||this._contextPlugins.has(e)||t.push(e.destroy());return Promise.all(t)}_add(t,e){this._plugins.set(t,e);const i=t.pluginName;if(i){if(this._plugins.has(i))throw new v("plugincollection-plugin-name-conflict",null,{pluginName:i,plugin1:this._plugins.get(i).constructor,plugin2:t});this._plugins.set(i,e)}}}class mr{constructor(t){this.config=new hs(t,this.constructor.defaultConfig);const e=this.constructor.builtinPlugins;this.config.define("plugins",e),this.plugins=new fr(this,e);const i=this.config.get("language")||{};this.locale=new lo({uiLanguage:"string"==typeof i?i:i.ui,contentLanguage:this.config.get("language.content")}),this.t=this.locale.t,this.editors=new co,this._contextOwner=null}initPlugins(){const t=this.config.get("plugins")||[],e=this.config.get("substitutePlugins")||[];for(const i of t.concat(e)){if("function"!=typeof i)throw new v("context-initplugins-constructor-only",null,{Plugin:i});if(!0!==i.isContextPlugin)throw new v("context-initplugins-invalid-plugin",null,{Plugin:i})}return this.plugins.init(t,[],e)}destroy(){return Promise.all(Array.from(this.editors,(t=>t.destroy()))).then((()=>this.plugins.destroy()))}_addEditor(t,e){if(this._contextOwner)throw new v("context-addeditor-private-context");this.editors.add(t),e&&(this._contextOwner=t)}_removeEditor(t){return this.editors.has(t)&&this.editors.remove(t),this._contextOwner===t?this.destroy():Promise.resolve()}_getEditorConfig(){const t={};for(const e of this.config.names())["plugins","removePlugins","extraPlugins"].includes(e)||(t[e]=this.config.get(e));return t}static create(t){return new Promise((e=>{const i=new this(t);e(i.initPlugins().then((()=>i)))}))}}class gr extends(q()){constructor(t){super(),this.context=t}destroy(){this.stopListening()}static get isContextPlugin(){return!0}}const pr=new WeakMap;function wr(t,e){return!!e.hasClass("ck-placeholder")&&(t.removeClass("ck-placeholder",e),!0)}function br(t,e){const i=pr.get(t),n=[];let s=!1;for(const[t,o]of i)o.isDirectHost&&(n.push(t),_r(e,t,o)&&(s=!0));for(const[t,o]of i){if(o.isDirectHost)continue;const i=vr(t);i&&(n.includes(i)||(o.hostElement=i,_r(e,t,o)&&(s=!0)))}return s}function _r(t,e,i){const{text:n,isDirectHost:s,hostElement:o}=i;let r=!1;o.getAttribute("data-placeholder")!==n&&(t.setAttribute("data-placeholder",n,o),r=!0);return(s||1==e.childCount)&&function(t,e){if(!t.isAttached())return!1;const i=Array.from(t.getChildren()).some((t=>!t.is("uiElement")));if(i)return!1;const n=t.document,s=n.selection.anchor;return!(n.isComposing&&s&&s.parent===t||!e&&n.isFocused&&(!s||s.parent===t))}(o,i.keepOnFocus)?function(t,e){return!e.hasClass("ck-placeholder")&&(t.addClass("ck-placeholder",e),!0)}(t,o)&&(r=!0):wr(t,o)&&(r=!0),r}function vr(t){if(t.childCount){const e=t.getChild(0);if(e.is("element")&&!e.is("uiElement")&&!e.is("attributeElement"))return e}return null}class yr{is(){throw new Error("is() method is abstract")}}var kr=4;const Ar=function(t){return os(t,kr)};class xr extends(R(yr)){constructor(t){super(),this.document=t,this.parent=null}get index(){let t;if(!this.parent)return null;if(-1==(t=this.parent.getChildIndex(this)))throw new v("view-node-not-found-in-parent",this);return t}get nextSibling(){const t=this.index;return null!==t&&this.parent.getChild(t+1)||null}get previousSibling(){const t=this.index;return null!==t&&this.parent.getChild(t-1)||null}get root(){let t=this;for(;t.parent;)t=t.parent;return t}isAttached(){return this.root.is("rootElement")}getPath(){const t=[];let e=this;for(;e.parent;)t.unshift(e.index),e=e.parent;return t}getAncestors(t={}){const e=[];let i=t.includeSelf?this:this.parent;for(;i;)e[t.parentFirst?"push":"unshift"](i),i=i.parent;return e}getCommonAncestor(t,e={}){const i=this.getAncestors(e),n=t.getAncestors(e);let s=0;for(;i[s]==n[s]&&i[s];)s++;return 0===s?null:i[s-1]}isBefore(t){if(this==t)return!1;if(this.root!==t.root)return!1;const e=this.getPath(),i=t.getPath(),n=X(e,i);switch(n){case"prefix":return!0;case"extension":return!1;default:return e[n]t.data.length)throw new v("view-textproxy-wrong-offsetintext",this);if(i<0||e+i>t.data.length)throw new v("view-textproxy-wrong-length",this);this.data=t.data.substring(e,e+i),this.offsetInText=e}get offsetSize(){return this.data.length}get isPartial(){return this.data.length!==this.textNode.data.length}get parent(){return this.textNode.parent}get root(){return this.textNode.root}get document(){return this.textNode.document}getAncestors(t={}){const e=[];let i=t.includeSelf?this.textNode:this.parent;for(;null!==i;)e[t.parentFirst?"push":"unshift"](i),i=i.parent;return e}}Pr.prototype.is=function(t){return"$textProxy"===t||"view:$textProxy"===t||"textProxy"===t||"view:textProxy"===t};class Tr{constructor(...t){this._patterns=[],this.add(...t)}add(...t){for(let e of t)("string"==typeof e||e instanceof RegExp)&&(e={name:e}),this._patterns.push(e)}match(...t){for(const e of t)for(const t of this._patterns){const i=Er(e,t);if(i)return{element:e,pattern:t,match:i}}return null}matchAll(...t){const e=[];for(const i of t)for(const t of this._patterns){const n=Er(i,t);n&&e.push({element:i,pattern:t,match:n})}return e.length>0?e:null}getElementName(){if(1!==this._patterns.length)return null;const t=this._patterns[0],e=t.name;return"function"==typeof t||!e||e instanceof RegExp?null:e}}function Er(t,e){if("function"==typeof e)return e(t);const i={};return e.name&&(i.name=function(t,e){if(t instanceof RegExp)return!!e.match(t);return t===e}(e.name,t.name),!i.name)||e.attributes&&(i.attributes=function(t,e){const i=new Set(e.getAttributeKeys());St(t)?(void 0!==t.style&&y("matcher-pattern-deprecated-attributes-style-key",t),void 0!==t.class&&y("matcher-pattern-deprecated-attributes-class-key",t)):(i.delete("style"),i.delete("class"));return Sr(t,i,(t=>e.getAttribute(t)))}(e.attributes,t),!i.attributes)||e.classes&&(i.classes=function(t,e){return Sr(t,e.getClassNames(),(()=>{}))}(e.classes,t),!i.classes)||e.styles&&(i.styles=function(t,e){return Sr(t,e.getStyleNames(!0),(t=>e.getStyle(t)))}(e.styles,t),!i.styles)?null:i}function Sr(t,e,i){const n=function(t){if(Array.isArray(t))return t.map((t=>St(t)?(void 0!==t.key&&void 0!==t.value||y("matcher-pattern-missing-key-or-value",t),[t.key,t.value]):[t,!0]));if(St(t))return Object.entries(t);return[[t,!0]]}(t),s=Array.from(e),o=[];if(n.forEach((([t,e])=>{s.forEach((n=>{(function(t,e){return!0===t||t===e||t instanceof RegExp&&e.match(t)})(t,n)&&function(t,e,i){if(!0===t)return!0;const n=i(e);return t===n||t instanceof RegExp&&!!String(n).match(t)}(e,n,i)&&o.push(n)}))})),n.length&&!(o.lengths?0:s+e),(i=i>s?s:i)<0&&(i+=s),s=e>i?0:i-e>>>0,e>>>=0;for(var o=Array(s);++n0){if(++e>=ba)return arguments[0]}else e=0;return t.apply(void 0,arguments)}};const ka=ya(wa);const Aa=function(t,e){return ka(ga(t,e,ua),t+"")};const xa=function(t,e,i){if(!F(i))return!1;var n=typeof e;return!!("number"==n?vi(i)&&ei(e,i.length):"string"==n&&e in i)&&Ot(i[e],t)};const Ca=function(t){return Aa((function(e,i){var n=-1,s=i.length,o=s>1?i[s-1]:void 0,r=s>2?i[2]:void 0;for(o=t.length>3&&"function"==typeof o?(s--,o):void 0,r&&xa(i[0],i[1],r)&&(o=s<3?void 0:o,s=1),e=Object(e);++ne===t));return Array.isArray(e)}set(t,e){if(F(t))for(const[e,i]of Object.entries(t))this._styleProcessor.toNormalizedForm(e,i,this._styles);else this._styleProcessor.toNormalizedForm(t,e,this._styles)}remove(t){const e=Oa(t);na(this._styles,e),delete this._styles[t],this._cleanEmptyObjectsOnPath(e)}getNormalized(t){return this._styleProcessor.getNormalized(t,this._styles)}toString(){return this.isEmpty?"":this._getStylesEntries().map((t=>t.join(":"))).sort().join(";")+";"}getAsString(t){if(this.isEmpty)return;if(this._styles[t]&&!F(this._styles[t]))return this._styles[t];const e=this._styleProcessor.getReducedForm(t,this._styles).find((([e])=>e===t));return Array.isArray(e)?e[1]:void 0}getStyleNames(t=!1){if(this.isEmpty)return[];if(t)return this._styleProcessor.getStyleNames(this._styles);return this._getStylesEntries().map((([t])=>t))}clear(){this._styles={}}_getStylesEntries(){const t=[],e=Object.keys(this._styles);for(const i of e)t.push(...this._styleProcessor.getReducedForm(i,this._styles));return t}_cleanEmptyObjectsOnPath(t){const e=t.split(".");if(!(e.length>1))return;const i=e.splice(0,e.length-1).join("."),n=sa(this._styles,i);if(!n)return;!Array.from(Object.keys(n)).length&&this.remove(i)}}class Ra{constructor(){this._normalizers=new Map,this._extractors=new Map,this._reducers=new Map,this._consumables=new Map}toNormalizedForm(t,e,i){if(F(e))Ia(i,Oa(t),e);else if(this._normalizers.has(t)){const n=this._normalizers.get(t),{path:s,value:o}=n(e);Ia(i,s,o)}else Ia(i,t,e)}getNormalized(t,e){if(!t)return Pa({},e);if(void 0!==e[t])return e[t];if(this._extractors.has(t)){const i=this._extractors.get(t);if("string"==typeof i)return sa(e,i);const n=i(t,e);if(n)return n}return sa(e,Oa(t))}getReducedForm(t,e){const i=this.getNormalized(t,e);if(void 0===i)return[];if(this._reducers.has(t)){return this._reducers.get(t)(i)}return[[t,i]]}getStyleNames(t){const e=Array.from(this._consumables.keys()).filter((e=>{const i=this.getNormalized(e,t);return i&&"object"==typeof i?Object.keys(i).length:i})),i=new Set([...e,...Object.keys(t)]);return Array.from(i.values())}getRelatedStyles(t){return this._consumables.get(t)||[]}setNormalizer(t,e){this._normalizers.set(t,e)}setExtractor(t,e){this._extractors.set(t,e)}setReducer(t,e){this._reducers.set(t,e)}setStyleRelation(t,e){this._mapStyleNames(t,e);for(const i of e)this._mapStyleNames(i,[t])}_mapStyleNames(t,e){this._consumables.has(t)||this._consumables.set(t,[]),this._consumables.get(t).push(...e)}}function Oa(t){return t.replace("-",".")}function Ia(t,e,i){let n=i;F(i)&&(n=Pa({},sa(t,e),i)),Ea(t,e,n)}class Va extends xr{constructor(t,e,i,n){if(super(t),this.name=e,this._attrs=function(t){const e=mo(t);for(const[t,i]of e)null===i?e.delete(t):"string"!=typeof i&&e.set(t,String(i));return e}(i),this._children=[],n&&this._insertChild(0,n),this._classes=new Set,this._attrs.has("class")){const t=this._attrs.get("class");Ma(this._classes,t),this._attrs.delete("class")}this._styles=new Sa(this.document.stylesProcessor),this._attrs.has("style")&&(this._styles.setTo(this._attrs.get("style")),this._attrs.delete("style")),this._customProperties=new Map,this._unsafeAttributesToRender=[]}get childCount(){return this._children.length}get isEmpty(){return 0===this._children.length}getChild(t){return this._children[t]}getChildIndex(t){return this._children.indexOf(t)}getChildren(){return this._children[Symbol.iterator]()}*getAttributeKeys(){this._classes.size>0&&(yield"class"),this._styles.isEmpty||(yield"style"),yield*this._attrs.keys()}*getAttributes(){yield*this._attrs.entries(),this._classes.size>0&&(yield["class",this.getAttribute("class")]),this._styles.isEmpty||(yield["style",this.getAttribute("style")])}getAttribute(t){if("class"==t)return this._classes.size>0?[...this._classes].join(" "):void 0;if("style"==t){const t=this._styles.toString();return""==t?void 0:t}return this._attrs.get(t)}hasAttribute(t){return"class"==t?this._classes.size>0:"style"==t?!this._styles.isEmpty:this._attrs.has(t)}isSimilar(t){if(!(t instanceof Va))return!1;if(this===t)return!0;if(this.name!=t.name)return!1;if(this._attrs.size!==t._attrs.size||this._classes.size!==t._classes.size||this._styles.size!==t._styles.size)return!1;for(const[e,i]of this._attrs)if(!t._attrs.has(e)||t._attrs.get(e)!==i)return!1;for(const e of this._classes)if(!t._classes.has(e))return!1;for(const e of this._styles.getStyleNames())if(!t._styles.has(e)||t._styles.getAsString(e)!==this._styles.getAsString(e))return!1;return!0}hasClass(...t){for(const e of t)if(!this._classes.has(e))return!1;return!0}getClassNames(){return this._classes.keys()}getStyle(t){return this._styles.getAsString(t)}getNormalizedStyle(t){return this._styles.getNormalized(t)}getStyleNames(t){return this._styles.getStyleNames(t)}hasStyle(...t){for(const e of t)if(!this._styles.has(e))return!1;return!0}findAncestor(...t){const e=new Tr(...t);let i=this.parent;for(;i&&!i.is("documentFragment");){if(e.match(i))return i;i=i.parent}return null}getCustomProperty(t){return this._customProperties.get(t)}*getCustomProperties(){yield*this._customProperties.entries()}getIdentity(){const t=Array.from(this._classes).sort().join(","),e=this._styles.toString(),i=Array.from(this._attrs).map((t=>`${t[0]}="${t[1]}"`)).sort().join(" ");return this.name+(""==t?"":` class="${t}"`)+(e?` style="${e}"`:"")+(""==i?"":` ${i}`)}shouldRenderUnsafeAttribute(t){return this._unsafeAttributesToRender.includes(t)}_clone(t=!1){const e=[];if(t)for(const i of this.getChildren())e.push(i._clone(t));const i=new this.constructor(this.document,this.name,this._attrs,e);return i._classes=new Set(this._classes),i._styles.set(this._styles.getNormalized()),i._customProperties=new Map(this._customProperties),i.getFillerOffset=this.getFillerOffset,i._unsafeAttributesToRender=this._unsafeAttributesToRender,i}_appendChild(t){return this._insertChild(this.childCount,t)}_insertChild(t,e){this._fireChange("children",this);let i=0;const n=function(t,e){if("string"==typeof e)return[new Cr(t,e)];tt(e)||(e=[e]);return Array.from(e).map((e=>"string"==typeof e?new Cr(t,e):e instanceof Pr?new Cr(t,e.data):e))}(this.document,e);for(const e of n)null!==e.parent&&e._remove(),e.parent=this,e.document=this.document,this._children.splice(t,0,e),t++,i++;return i}_removeChildren(t,e=1){this._fireChange("children",this);for(let i=t;i0&&(this._classes.clear(),!0):"style"==t?!this._styles.isEmpty&&(this._styles.clear(),!0):this._attrs.delete(t)}_addClass(t){this._fireChange("attributes",this);for(const e of so(t))this._classes.add(e)}_removeClass(t){this._fireChange("attributes",this);for(const e of so(t))this._classes.delete(e)}_setStyle(t,e){this._fireChange("attributes",this),St(t)?this._styles.set(t):this._styles.set(t,e)}_removeStyle(t){this._fireChange("attributes",this);for(const e of so(t))this._styles.remove(e)}_setCustomProperty(t,e){this._customProperties.set(t,e)}_removeCustomProperty(t){return this._customProperties.delete(t)}}function Ma(t,e){const i=e.split(/\s+/);t.clear(),i.forEach((e=>t.add(e)))}Va.prototype.is=function(t,e){return e?e===this.name&&("element"===t||"view:element"===t):"element"===t||"view:element"===t||"node"===t||"view:node"===t};class Na extends Va{constructor(...t){super(...t),this.getFillerOffset=Ba}}function Ba(){const t=[...this.getChildren()],e=t[this.childCount-1];if(e&&e.is("element","br"))return this.childCount;for(const e of t)if(!e.is("uiElement"))return null;return this.childCount}Na.prototype.is=function(t,e){return e?e===this.name&&("containerElement"===t||"view:containerElement"===t||"element"===t||"view:element"===t):"containerElement"===t||"view:containerElement"===t||"element"===t||"view:element"===t||"node"===t||"view:node"===t};class Da extends(q(Na)){constructor(...t){super(...t);const e=t[0];this.set("isReadOnly",!1),this.set("isFocused",!1),this.bind("isReadOnly").to(e),this.bind("isFocused").to(e,"isFocused",(t=>t&&e.selection.editableElement==this)),this.listenTo(e.selection,"change",(()=>{this.isFocused=e.isFocused&&e.selection.editableElement==this}))}destroy(){this.stopListening()}}Da.prototype.is=function(t,e){return e?e===this.name&&("editableElement"===t||"view:editableElement"===t||"containerElement"===t||"view:containerElement"===t||"element"===t||"view:element"===t):"editableElement"===t||"view:editableElement"===t||"containerElement"===t||"view:containerElement"===t||"element"===t||"view:element"===t||"node"===t||"view:node"===t};const Fa=Symbol("rootName");class La extends Da{constructor(t,e){super(t,e),this.rootName="main"}get rootName(){return this.getCustomProperty(Fa)}set rootName(t){this._setCustomProperty(Fa,t)}set _name(t){this.name=t}}La.prototype.is=function(t,e){return e?e===this.name&&("rootElement"===t||"view:rootElement"===t||"editableElement"===t||"view:editableElement"===t||"containerElement"===t||"view:containerElement"===t||"element"===t||"view:element"===t):"rootElement"===t||"view:rootElement"===t||"editableElement"===t||"view:editableElement"===t||"containerElement"===t||"view:containerElement"===t||"element"===t||"view:element"===t||"node"===t||"view:node"===t};class za{constructor(t={}){if(!t.boundaries&&!t.startPosition)throw new v("view-tree-walker-no-start-position",null);if(t.direction&&"forward"!=t.direction&&"backward"!=t.direction)throw new v("view-tree-walker-unknown-direction",t.startPosition,{direction:t.direction});this.boundaries=t.boundaries||null,t.startPosition?this.position=Ha._createAt(t.startPosition):this.position=Ha._createAt(t.boundaries["backward"==t.direction?"end":"start"]),this.direction=t.direction||"forward",this.singleCharacters=!!t.singleCharacters,this.shallow=!!t.shallow,this.ignoreElementEnd=!!t.ignoreElementEnd,this._boundaryStartParent=this.boundaries?this.boundaries.start.parent:null,this._boundaryEndParent=this.boundaries?this.boundaries.end.parent:null}[Symbol.iterator](){return this}skip(t){let e,i,n;do{n=this.position,({done:e,value:i}=this.next())}while(!e&&t(i));e||(this.position=n)}next(){return"forward"==this.direction?this._next():this._previous()}_next(){let t=this.position.clone();const e=this.position,i=t.parent;if(null===i.parent&&t.offset===i.childCount)return{done:!0,value:void 0};if(i===this._boundaryEndParent&&t.offset==this.boundaries.end.offset)return{done:!0,value:void 0};let n;if(i instanceof Cr){if(t.isAtEnd)return this.position=Ha._createAfter(i),this._next();n=i.data[t.offset]}else n=i.getChild(t.offset);if(n instanceof Va)return this.shallow?t.offset++:t=new Ha(n,0),this.position=t,this._formatReturnValue("elementStart",n,e,t,1);if(n instanceof Cr){if(this.singleCharacters)return t=new Ha(n,0),this.position=t,this._next();{let i,s=n.data.length;return n==this._boundaryEndParent?(s=this.boundaries.end.offset,i=new Pr(n,0,s),t=Ha._createAfter(i)):(i=new Pr(n,0,n.data.length),t.offset++),this.position=t,this._formatReturnValue("text",i,e,t,s)}}if("string"==typeof n){let n;if(this.singleCharacters)n=1;else{n=(i===this._boundaryEndParent?this.boundaries.end.offset:i.data.length)-t.offset}const s=new Pr(i,t.offset,n);return t.offset+=n,this.position=t,this._formatReturnValue("text",s,e,t,n)}return t=Ha._createAfter(i),this.position=t,this.ignoreElementEnd?this._next():this._formatReturnValue("elementEnd",i,e,t)}_previous(){let t=this.position.clone();const e=this.position,i=t.parent;if(null===i.parent&&0===t.offset)return{done:!0,value:void 0};if(i==this._boundaryStartParent&&t.offset==this.boundaries.start.offset)return{done:!0,value:void 0};let n;if(i instanceof Cr){if(t.isAtStart)return this.position=Ha._createBefore(i),this._previous();n=i.data[t.offset-1]}else n=i.getChild(t.offset-1);if(n instanceof Va)return this.shallow?(t.offset--,this.position=t,this._formatReturnValue("elementStart",n,e,t,1)):(t=new Ha(n,n.childCount),this.position=t,this.ignoreElementEnd?this._previous():this._formatReturnValue("elementEnd",n,e,t));if(n instanceof Cr){if(this.singleCharacters)return t=new Ha(n,n.data.length),this.position=t,this._previous();{let i,s=n.data.length;if(n==this._boundaryStartParent){const e=this.boundaries.start.offset;i=new Pr(n,e,n.data.length-e),s=i.data.length,t=Ha._createBefore(i)}else i=new Pr(n,0,n.data.length),t.offset--;return this.position=t,this._formatReturnValue("text",i,e,t,s)}}if("string"==typeof n){let n;if(this.singleCharacters)n=1;else{const e=i===this._boundaryStartParent?this.boundaries.start.offset:0;n=t.offset-e}t.offset-=n;const s=new Pr(i,t.offset,n);return this.position=t,this._formatReturnValue("text",s,e,t,n)}return t=Ha._createBefore(i),this.position=t,this._formatReturnValue("elementStart",i,e,t,1)}_formatReturnValue(t,e,i,n,s){return e instanceof Pr&&(e.offsetInText+e.data.length==e.textNode.data.length&&("forward"!=this.direction||this.boundaries&&this.boundaries.end.isEqual(this.position)?i=Ha._createAfter(e.textNode):(n=Ha._createAfter(e.textNode),this.position=n)),0===e.offsetInText&&("backward"!=this.direction||this.boundaries&&this.boundaries.start.isEqual(this.position)?i=Ha._createBefore(e.textNode):(n=Ha._createBefore(e.textNode),this.position=n))),{done:!1,value:{type:t,item:e,previousPosition:i,nextPosition:n,length:s}}}}class Ha extends yr{constructor(t,e){super(),this.parent=t,this.offset=e}get nodeAfter(){return this.parent.is("$text")?null:this.parent.getChild(this.offset)||null}get nodeBefore(){return this.parent.is("$text")?null:this.parent.getChild(this.offset-1)||null}get isAtStart(){return 0===this.offset}get isAtEnd(){const t=this.parent.is("$text")?this.parent.data.length:this.parent.childCount;return this.offset===t}get root(){return this.parent.root}get editableElement(){let t=this.parent;for(;!(t instanceof Da);){if(!t.parent)return null;t=t.parent}return t}getShiftedBy(t){const e=Ha._createAt(this),i=e.offset+t;return e.offset=i<0?0:i,e}getLastMatchingPosition(t,e={}){e.startPosition=this;const i=new za(e);return i.skip(t),i.position}getAncestors(){return this.parent.is("documentFragment")?[this.parent]:this.parent.getAncestors({includeSelf:!0})}getCommonAncestor(t){const e=this.getAncestors(),i=t.getAncestors();let n=0;for(;e[n]==i[n]&&e[n];)n++;return 0===n?null:e[n-1]}isEqual(t){return this.parent==t.parent&&this.offset==t.offset}isBefore(t){return"before"==this.compareWith(t)}isAfter(t){return"after"==this.compareWith(t)}compareWith(t){if(this.root!==t.root)return"different";if(this.isEqual(t))return"same";const e=this.parent.is("node")?this.parent.getPath():[],i=t.parent.is("node")?t.parent.getPath():[];e.push(this.offset),i.push(t.offset);const n=X(e,i);switch(n){case"prefix":return"before";case"extension":return"after";default:return e[n]0?new this(i,n):new this(n,i)}static _createIn(t){return this._createFromParentsAndOffsets(t,0,t,t.childCount)}static _createOn(t){const e=t.is("$textProxy")?t.offsetSize:1;return this._createFromPositionAndShift(Ha._createBefore(t),e)}}function $a(t){return!(!t.item.is("attributeElement")&&!t.item.is("uiElement"))}ja.prototype.is=function(t){return"range"===t||"view:range"===t};class Wa extends(R(yr)){constructor(...t){super(),this._ranges=[],this._lastRangeBackward=!1,this._isFake=!1,this._fakeSelectionLabel="",t.length&&this.setTo(...t)}get isFake(){return this._isFake}get fakeSelectionLabel(){return this._fakeSelectionLabel}get anchor(){if(!this._ranges.length)return null;const t=this._ranges[this._ranges.length-1];return(this._lastRangeBackward?t.end:t.start).clone()}get focus(){if(!this._ranges.length)return null;const t=this._ranges[this._ranges.length-1];return(this._lastRangeBackward?t.start:t.end).clone()}get isCollapsed(){return 1===this.rangeCount&&this._ranges[0].isCollapsed}get rangeCount(){return this._ranges.length}get isBackward(){return!this.isCollapsed&&this._lastRangeBackward}get editableElement(){return this.anchor?this.anchor.editableElement:null}*getRanges(){for(const t of this._ranges)yield t.clone()}getFirstRange(){let t=null;for(const e of this._ranges)t&&!e.start.isBefore(t.start)||(t=e);return t?t.clone():null}getLastRange(){let t=null;for(const e of this._ranges)t&&!e.end.isAfter(t.end)||(t=e);return t?t.clone():null}getFirstPosition(){const t=this.getFirstRange();return t?t.start.clone():null}getLastPosition(){const t=this.getLastRange();return t?t.end.clone():null}isEqual(t){if(this.isFake!=t.isFake)return!1;if(this.isFake&&this.fakeSelectionLabel!=t.fakeSelectionLabel)return!1;if(this.rangeCount!=t.rangeCount)return!1;if(0===this.rangeCount)return!0;if(!this.anchor.isEqual(t.anchor)||!this.focus.isEqual(t.focus))return!1;for(const e of this._ranges){let i=!1;for(const n of t._ranges)if(e.isEqual(n)){i=!0;break}if(!i)return!1}return!0}isSimilar(t){if(this.isBackward!=t.isBackward)return!1;const e=Z(this.getRanges());if(e!=Z(t.getRanges()))return!1;if(0==e)return!0;for(let e of this.getRanges()){e=e.getTrimmed();let i=!1;for(let n of t.getRanges())if(n=n.getTrimmed(),e.start.isEqual(n.start)&&e.end.isEqual(n.end)){i=!0;break}if(!i)return!1}return!0}getSelectedElement(){return 1!==this.rangeCount?null:this.getFirstRange().getContainedElement()}setTo(...t){let[e,i,n]=t;if("object"==typeof i&&(n=i,i=void 0),null===e)this._setRanges([]),this._setFakeOptions(n);else if(e instanceof Wa||e instanceof qa)this._setRanges(e.getRanges(),e.isBackward),this._setFakeOptions({fake:e.isFake,label:e.fakeSelectionLabel});else if(e instanceof ja)this._setRanges([e],n&&n.backward),this._setFakeOptions(n);else if(e instanceof Ha)this._setRanges([new ja(e)]),this._setFakeOptions(n);else if(e instanceof xr){const t=!!n&&!!n.backward;let s;if(void 0===i)throw new v("view-selection-setto-required-second-parameter",this);s="in"==i?ja._createIn(e):"on"==i?ja._createOn(e):new ja(Ha._createAt(e,i)),this._setRanges([s],t),this._setFakeOptions(n)}else{if(!tt(e))throw new v("view-selection-setto-not-selectable",this);this._setRanges(e,n&&n.backward),this._setFakeOptions(n)}this.fire("change")}setFocus(t,e){if(null===this.anchor)throw new v("view-selection-setfocus-no-ranges",this);const i=Ha._createAt(t,e);if("same"==i.compareWith(this.focus))return;const n=this.anchor;this._ranges.pop(),"before"==i.compareWith(n)?this._addRange(new ja(i,n),!0):this._addRange(new ja(n,i)),this.fire("change")}_setRanges(t,e=!1){t=Array.from(t),this._ranges=[];for(const e of t)this._addRange(e);this._lastRangeBackward=!!e}_setFakeOptions(t={}){this._isFake=!!t.fake,this._fakeSelectionLabel=t.fake&&t.label||""}_addRange(t,e=!1){if(!(t instanceof ja))throw new v("view-selection-add-range-not-range",this);this._pushRange(t),this._lastRangeBackward=!!e}_pushRange(t){for(const e of this._ranges)if(t.isIntersecting(e))throw new v("view-selection-range-intersects",this,{addedRange:t,intersectingRange:e});this._ranges.push(new ja(t.start,t.end))}}Wa.prototype.is=function(t){return"selection"===t||"view:selection"===t};class qa extends(R(yr)){constructor(...t){super(),this._selection=new Wa,this._selection.delegate("change").to(this),t.length&&this._selection.setTo(...t)}get isFake(){return this._selection.isFake}get fakeSelectionLabel(){return this._selection.fakeSelectionLabel}get anchor(){return this._selection.anchor}get focus(){return this._selection.focus}get isCollapsed(){return this._selection.isCollapsed}get rangeCount(){return this._selection.rangeCount}get isBackward(){return this._selection.isBackward}get editableElement(){return this._selection.editableElement}get _ranges(){return this._selection._ranges}*getRanges(){yield*this._selection.getRanges()}getFirstRange(){return this._selection.getFirstRange()}getLastRange(){return this._selection.getLastRange()}getFirstPosition(){return this._selection.getFirstPosition()}getLastPosition(){return this._selection.getLastPosition()}getSelectedElement(){return this._selection.getSelectedElement()}isEqual(t){return this._selection.isEqual(t)}isSimilar(t){return this._selection.isSimilar(t)}_setTo(...t){this._selection.setTo(...t)}_setFocus(t,e){this._selection.setFocus(t,e)}}qa.prototype.is=function(t){return"selection"===t||"documentSelection"==t||"view:selection"==t||"view:documentSelection"==t};class Ua extends m{constructor(t,e,i){super(t,e),this.startRange=i,this._eventPhase="none",this._currentTarget=null}get eventPhase(){return this._eventPhase}get currentTarget(){return this._currentTarget}}const Ka=Symbol("bubbling contexts");function Ga(t){return class extends t{fire(t,...e){try{const i=t instanceof m?t:new m(this,t),n=Za(this);if(!n.size)return;if(Ja(i,"capturing",this),Qa(n,"$capture",i,...e))return i.return;const s=i.startRange||this.selection.getFirstRange(),o=s?s.getContainedElement():null,r=!!o&&Boolean(Ya(n,o));let a=o||function(t){if(!t)return null;const e=t.start.parent,i=t.end.parent,n=e.getPath(),s=i.getPath();return n.length>s.length?e:i}(s);if(Ja(i,"atTarget",a),!r){if(Qa(n,"$text",i,...e))return i.return;Ja(i,"bubbling",a)}for(;a;){if(a.is("rootElement")){if(Qa(n,"$root",i,...e))return i.return}else if(a.is("element")&&Qa(n,a.name,i,...e))return i.return;if(Qa(n,a,i,...e))return i.return;a=a.parent,Ja(i,"bubbling",a)}return Ja(i,"bubbling",this),Qa(n,"$document",i,...e),i.return}catch(t){v.rethrowUnexpectedError(t,this)}}_addEventListener(t,e,i){const n=so(i.context||"$document"),s=Za(this);for(const o of n){let n=s.get(o);n||(n=new(R()),s.set(o,n)),this.listenTo(n,t,e,i)}}_removeEventListener(t,e){const i=Za(this);for(const n of i.values())this.stopListening(n,t,e)}}}{const t=Ga(Object);["fire","_addEventListener","_removeEventListener"].forEach((e=>{Ga[e]=t.prototype[e]}))}function Ja(t,e,i){t instanceof Ua&&(t._eventPhase=e,t._currentTarget=i)}function Qa(t,e,i,...n){const s="string"==typeof e?t.get(e):Ya(t,e);return!!s&&(s.fire(i,...n),i.stop.called)}function Ya(t,e){for(const[i,n]of t)if("function"==typeof i&&i(e))return n;return null}function Za(t){return t[Ka]||(t[Ka]=new Map),t[Ka]}class Xa extends(Ga(q())){constructor(t){super(),this.selection=new qa,this.roots=new co({idProperty:"rootName"}),this.stylesProcessor=t,this.set("isReadOnly",!1),this.set("isFocused",!1),this.set("isSelecting",!1),this.set("isComposing",!1),this._postFixers=new Set}getRoot(t="main"){return this.roots.get(t)}registerPostFixer(t){this._postFixers.add(t)}destroy(){this.roots.map((t=>t.destroy())),this.stopListening()}_callPostFixers(t){let e=!1;do{for(const i of this._postFixers)if(e=i(t),e)break}while(e)}}class tl extends Va{constructor(...t){super(...t),this.getFillerOffset=el,this._priority=10,this._id=null,this._clonesGroup=null}get priority(){return this._priority}get id(){return this._id}getElementsWithSameId(){if(null===this.id)throw new v("attribute-element-get-elements-with-same-id-no-id",this);return new Set(this._clonesGroup)}isSimilar(t){return null!==this.id||null!==t.id?this.id===t.id:super.isSimilar(t)&&this.priority==t.priority}_clone(t=!1){const e=super._clone(t);return e._priority=this._priority,e._id=this._id,e}}function el(){if(il(this))return null;let t=this.parent;for(;t&&t.is("attributeElement");){if(il(t)>1)return null;t=t.parent}return!t||il(t)>1?null:this.childCount}function il(t){return Array.from(t.getChildren()).filter((t=>!t.is("uiElement"))).length}tl.DEFAULT_PRIORITY=10,tl.prototype.is=function(t,e){return e?e===this.name&&("attributeElement"===t||"view:attributeElement"===t||"element"===t||"view:element"===t):"attributeElement"===t||"view:attributeElement"===t||"element"===t||"view:element"===t||"node"===t||"view:node"===t};class nl extends Va{constructor(t,e,i,n){super(t,e,i,n),this.getFillerOffset=sl}_insertChild(t,e){if(e&&(e instanceof xr||Array.from(e).length>0))throw new v("view-emptyelement-cannot-add",[this,e]);return 0}}function sl(){return null}nl.prototype.is=function(t,e){return e?e===this.name&&("emptyElement"===t||"view:emptyElement"===t||"element"===t||"view:element"===t):"emptyElement"===t||"view:emptyElement"===t||"element"===t||"view:element"===t||"node"===t||"view:node"===t};class ol extends Va{constructor(...t){super(...t),this.getFillerOffset=al}_insertChild(t,e){if(e&&(e instanceof xr||Array.from(e).length>0))throw new v("view-uielement-cannot-add",[this,e]);return 0}render(t,e){return this.toDomElement(t)}toDomElement(t){const e=t.createElement(this.name);for(const t of this.getAttributeKeys())e.setAttribute(t,this.getAttribute(t));return e}}function rl(t){t.document.on("arrowKey",((e,i)=>function(t,e,i){if(e.keyCode==Zs.arrowright){const t=e.domTarget.ownerDocument.defaultView.getSelection(),n=1==t.rangeCount&&t.getRangeAt(0).collapsed;if(n||e.shiftKey){const e=t.focusNode,s=t.focusOffset,o=i.domPositionToView(e,s);if(null===o)return;let r=!1;const a=o.getLastMatchingPosition((t=>(t.item.is("uiElement")&&(r=!0),!(!t.item.is("uiElement")&&!t.item.is("attributeElement")))));if(r){const e=i.viewPositionToDom(a);n?t.collapse(e.parent,e.offset):t.extend(e.parent,e.offset)}}}}(0,i,t.domConverter)),{priority:"low"})}function al(){return null}ol.prototype.is=function(t,e){return e?e===this.name&&("uiElement"===t||"view:uiElement"===t||"element"===t||"view:element"===t):"uiElement"===t||"view:uiElement"===t||"element"===t||"view:element"===t||"node"===t||"view:node"===t};class ll extends Va{constructor(...t){super(...t),this.getFillerOffset=cl}_insertChild(t,e){if(e&&(e instanceof xr||Array.from(e).length>0))throw new v("view-rawelement-cannot-add",[this,e]);return 0}render(){}}function cl(){return null}ll.prototype.is=function(t,e){return e?e===this.name&&("rawElement"===t||"view:rawElement"===t||"element"===t||"view:element"===t):"rawElement"===t||"view:rawElement"===t||t===this.name||t==="view:"+this.name||"element"===t||"view:element"===t||"node"===t||"view:node"===t};class hl extends(R(yr)){constructor(t,e){super(),this.document=t,this._children=[],e&&this._insertChild(0,e),this._customProperties=new Map}[Symbol.iterator](){return this._children[Symbol.iterator]()}get childCount(){return this._children.length}get isEmpty(){return 0===this.childCount}get root(){return this}get parent(){return null}getCustomProperty(t){return this._customProperties.get(t)}*getCustomProperties(){yield*this._customProperties.entries()}_appendChild(t){return this._insertChild(this.childCount,t)}getChild(t){return this._children[t]}getChildIndex(t){return this._children.indexOf(t)}getChildren(){return this._children[Symbol.iterator]()}_insertChild(t,e){this._fireChange("children",this);let i=0;const n=function(t,e){if("string"==typeof e)return[new Cr(t,e)];tt(e)||(e=[e]);return Array.from(e).map((e=>"string"==typeof e?new Cr(t,e):e instanceof Pr?new Cr(t,e.data):e))}(this.document,e);for(const e of n)null!==e.parent&&e._remove(),e.parent=this,this._children.splice(t,0,e),t++,i++;return i}_removeChildren(t,e=1){this._fireChange("children",this);for(let i=t;i{const i=t[t.length-1],n=!e.is("uiElement");return i&&i.breakAttributes==n?i.nodes.push(e):t.push({breakAttributes:n,nodes:[e]}),t}),[]);let n=null,s=t;for(const{nodes:t,breakAttributes:e}of i){const i=this._insertNodes(s,t,e);n||(n=i.start),s=i.end}return n?new ja(n,s):new ja(t)}remove(t){const e=t instanceof ja?t:ja._createOn(t);if(vl(e,this.document),e.isCollapsed)return new hl(this.document);const{start:i,end:n}=this._breakAttributesRange(e,!0),s=i.parent,o=n.offset-i.offset,r=s._removeChildren(i.offset,o);for(const t of r)this._removeFromClonedElementsGroup(t);const a=this.mergeAttributes(i);return e.start=a,e.end=a.clone(),new hl(this.document,r)}clear(t,e){vl(t,this.document);const i=t.getWalker({direction:"backward",ignoreElementEnd:!0});for(const n of i){const i=n.item;let s;if(i.is("element")&&e.isSimilar(i))s=ja._createOn(i);else if(!n.nextPosition.isAfter(t.start)&&i.is("$textProxy")){const t=i.getAncestors().find((t=>t.is("element")&&e.isSimilar(t)));t&&(s=ja._createIn(t))}s&&(s.end.isAfter(t.end)&&(s.end=t.end),s.start.isBefore(t.start)&&(s.start=t.start),this.remove(s))}}move(t,e){let i;if(e.isAfter(t.end)){const n=(e=this._breakAttributes(e,!0)).parent,s=n.childCount;t=this._breakAttributesRange(t,!0),i=this.remove(t),e.offset+=n.childCount-s}else i=this.remove(t);return this.insert(e,i)}wrap(t,e){if(!(e instanceof tl))throw new v("view-writer-wrap-invalid-attribute",this.document);if(vl(t,this.document),t.isCollapsed){let n=t.start;n.parent.is("element")&&(i=n.parent,!Array.from(i.getChildren()).some((t=>!t.is("uiElement"))))&&(n=n.getLastMatchingPosition((t=>t.item.is("uiElement")))),n=this._wrapPosition(n,e);const s=this.document.selection;return s.isCollapsed&&s.getFirstPosition().isEqual(t.start)&&this.setSelection(n),new ja(n)}return this._wrapRange(t,e);var i}unwrap(t,e){if(!(e instanceof tl))throw new v("view-writer-unwrap-invalid-attribute",this.document);if(vl(t,this.document),t.isCollapsed)return t;const{start:i,end:n}=this._breakAttributesRange(t,!0),s=i.parent,o=this._unwrapChildren(s,i.offset,n.offset,e),r=this.mergeAttributes(o.start);r.isEqual(o.start)||o.end.offset--;const a=this.mergeAttributes(o.end);return new ja(r,a)}rename(t,e){const i=new Na(this.document,t,e.getAttributes());return this.insert(Ha._createAfter(e),i),this.move(ja._createIn(e),Ha._createAt(i,0)),this.remove(ja._createOn(e)),i}clearClonedElementsGroup(t){this._cloneGroups.delete(t)}createPositionAt(t,e){return Ha._createAt(t,e)}createPositionAfter(t){return Ha._createAfter(t)}createPositionBefore(t){return Ha._createBefore(t)}createRange(...t){return new ja(...t)}createRangeOn(t){return ja._createOn(t)}createRangeIn(t){return ja._createIn(t)}createSelection(...t){return new Wa(...t)}createSlot(t){if(!this._slotFactory)throw new v("view-writer-invalid-create-slot-context",this.document);return this._slotFactory(this,t)}_registerSlotFactory(t){this._slotFactory=t}_clearSlotFactory(){this._slotFactory=null}_insertNodes(t,e,i){let n,s;if(n=i?ul(t):t.parent.is("$text")?t.parent.parent:t.parent,!n)throw new v("view-writer-invalid-position-container",this.document);s=i?this._breakAttributes(t,!0):t.parent.is("$text")?gl(t):t;const o=n._insertChild(s.offset,e);for(const t of e)this._addToClonedElementsGroup(t);const r=s.getShiftedBy(o),a=this.mergeAttributes(s);a.isEqual(s)||r.offset--;const l=this.mergeAttributes(r);return new ja(a,l)}_wrapChildren(t,e,i,n){let s=e;const o=[];for(;s!1,t.parent._insertChild(t.offset,i);const n=new ja(t,t.getShiftedBy(1));this.wrap(n,e);const s=new Ha(i.parent,i.index);i._remove();const o=s.nodeBefore,r=s.nodeAfter;return o instanceof Cr&&r instanceof Cr?pl(o,r):ml(s)}_wrapAttributeElement(t,e){if(!yl(t,e))return!1;if(t.name!==e.name||t.priority!==e.priority)return!1;for(const i of t.getAttributeKeys())if("class"!==i&&"style"!==i&&e.hasAttribute(i)&&e.getAttribute(i)!==t.getAttribute(i))return!1;for(const i of t.getStyleNames())if(e.hasStyle(i)&&e.getStyle(i)!==t.getStyle(i))return!1;for(const i of t.getAttributeKeys())"class"!==i&&"style"!==i&&(e.hasAttribute(i)||this.setAttribute(i,t.getAttribute(i),e));for(const i of t.getStyleNames())e.hasStyle(i)||this.setStyle(i,t.getStyle(i),e);for(const i of t.getClassNames())e.hasClass(i)||this.addClass(i,e);return!0}_unwrapAttributeElement(t,e){if(!yl(t,e))return!1;if(t.name!==e.name||t.priority!==e.priority)return!1;for(const i of t.getAttributeKeys())if("class"!==i&&"style"!==i&&(!e.hasAttribute(i)||e.getAttribute(i)!==t.getAttribute(i)))return!1;if(!e.hasClass(...t.getClassNames()))return!1;for(const i of t.getStyleNames())if(!e.hasStyle(i)||e.getStyle(i)!==t.getStyle(i))return!1;for(const i of t.getAttributeKeys())"class"!==i&&"style"!==i&&this.removeAttribute(i,e);return this.removeClass(Array.from(t.getClassNames()),e),this.removeStyle(Array.from(t.getStyleNames()),e),!0}_breakAttributesRange(t,e=!1){const i=t.start,n=t.end;if(vl(t,this.document),t.isCollapsed){const i=this._breakAttributes(t.start,e);return new ja(i,i)}const s=this._breakAttributes(n,e),o=s.parent.childCount,r=this._breakAttributes(i,e);return s.offset+=s.parent.childCount-o,new ja(r,s)}_breakAttributes(t,e=!1){const i=t.offset,n=t.parent;if(t.parent.is("emptyElement"))throw new v("view-writer-cannot-break-empty-element",this.document);if(t.parent.is("uiElement"))throw new v("view-writer-cannot-break-ui-element",this.document);if(t.parent.is("rawElement"))throw new v("view-writer-cannot-break-raw-element",this.document);if(!e&&n.is("$text")&&_l(n.parent))return t.clone();if(_l(n))return t.clone();if(n.is("$text"))return this._breakAttributes(gl(t),e);if(i==n.childCount){const t=new Ha(n.parent,n.index+1);return this._breakAttributes(t,e)}if(0===i){const t=new Ha(n.parent,n.index);return this._breakAttributes(t,e)}{const t=n.index+1,s=n._clone();n.parent._insertChild(t,s),this._addToClonedElementsGroup(s);const o=n.childCount-i,r=n._removeChildren(i,o);s._appendChild(r);const a=new Ha(n.parent,t);return this._breakAttributes(a,e)}}_addToClonedElementsGroup(t){if(!t.root.is("rootElement"))return;if(t.is("element"))for(const e of t.getChildren())this._addToClonedElementsGroup(e);const e=t.id;if(!e)return;let i=this._cloneGroups.get(e);i||(i=new Set,this._cloneGroups.set(e,i)),i.add(t),t._clonesGroup=i}_removeFromClonedElementsGroup(t){if(t.is("element"))for(const e of t.getChildren())this._removeFromClonedElementsGroup(e);const e=t.id;if(!e)return;const i=this._cloneGroups.get(e);i&&i.delete(t)}}function ul(t){let e=t.parent;for(;!_l(e);){if(!e)return;e=e.parent}return e}function fl(t,e){return t.prioritye.priority)&&t.getIdentity()i instanceof t)))throw new v("view-writer-insert-invalid-node-type",e);i.is("$text")||bl(i.getChildren(),e)}}function _l(t){return t&&(t.is("containerElement")||t.is("documentFragment"))}function vl(t,e){const i=ul(t.start),n=ul(t.end);if(!i||!n||i!==n)throw new v("view-writer-invalid-range-container",e)}function yl(t,e){return null===t.id&&null===e.id}const kl=t=>t.createTextNode(" "),Al=t=>{const e=t.createElement("span");return e.dataset.ckeFiller="true",e.innerText=" ",e},xl=t=>{const e=t.createElement("br");return e.dataset.ckeFiller="true",e},Cl=7,Pl="⁠".repeat(Cl);function Tl(t){return ks(t)&&t.data.substr(0,Cl)===Pl}function El(t){return t.data.length==Cl&&Tl(t)}function Sl(t){return Tl(t)?t.data.slice(Cl):t.data}function Rl(t,e){if(e.keyCode==Zs.arrowleft){const t=e.domTarget.ownerDocument.defaultView.getSelection();if(1==t.rangeCount&&t.getRangeAt(0).collapsed){const e=t.getRangeAt(0).startContainer,i=t.getRangeAt(0).startOffset;Tl(e)&&i<=Cl&&t.collapse(e,0)}}}class Ol extends(q()){constructor(t,e){super(),this.domDocuments=new Set,this.domConverter=t,this.markedAttributes=new Set,this.markedChildren=new Set,this.markedTexts=new Set,this.selection=e,this.set("isFocused",!1),this.set("isSelecting",!1),r.isBlink&&!r.isAndroid&&this.on("change:isSelecting",(()=>{this.isSelecting||this.render()})),this.set("isComposing",!1),this.on("change:isComposing",(()=>{this.isComposing||this.render()})),this._inlineFiller=null,this._fakeSelectionContainer=null}markToSync(t,e){if("text"===t)this.domConverter.mapViewToDom(e.parent)&&this.markedTexts.add(e);else{if(!this.domConverter.mapViewToDom(e))return;if("attributes"===t)this.markedAttributes.add(e);else{if("children"!==t)throw new v("view-renderer-unknown-type",this);this.markedChildren.add(e)}}}render(){if(this.isComposing&&!r.isAndroid)return;let t=null;const e=!(r.isBlink&&!r.isAndroid)||!this.isSelecting;for(const t of this.markedChildren)this._updateChildrenMappings(t);e?(this._inlineFiller&&!this._isSelectionInInlineFiller()&&this._removeInlineFiller(),this._inlineFiller?t=this._getInlineFillerPosition():this._needsInlineFillerAtSelection()&&(t=this.selection.getFirstPosition(),this.markedChildren.add(t.parent))):this._inlineFiller&&this._inlineFiller.parentNode&&(t=this.domConverter.domPositionToView(this._inlineFiller),t&&t.parent.is("$text")&&(t=Ha._createBefore(t.parent)));for(const t of this.markedAttributes)this._updateAttrs(t);for(const e of this.markedChildren)this._updateChildren(e,{inlineFillerPosition:t});for(const e of this.markedTexts)!this.markedChildren.has(e.parent)&&this.domConverter.mapViewToDom(e.parent)&&this._updateText(e,{inlineFillerPosition:t});if(e)if(t){const e=this.domConverter.viewPositionToDom(t),i=e.parent.ownerDocument;Tl(e.parent)?this._inlineFiller=e.parent:this._inlineFiller=Il(i,e.parent,e.offset)}else this._inlineFiller=null;this._updateFocus(),this._updateSelection(),this.markedTexts.clear(),this.markedAttributes.clear(),this.markedChildren.clear()}_updateChildrenMappings(t){if(!this.domConverter.mapViewToDom(t))return;const e=Array.from(this.domConverter.mapViewToDom(t).childNodes),i=Array.from(this.domConverter.viewChildrenToDom(t,{withChildren:!1})),n=this._diffNodeLists(e,i),s=this._findReplaceActions(n,e,i);if(-1!==s.indexOf("replace")){const n={equal:0,insert:0,delete:0};for(const o of s)if("replace"===o){const s=n.equal+n.insert,o=n.equal+n.delete,r=t.getChild(s);!r||r.is("uiElement")||r.is("rawElement")||this._updateElementMappings(r,e[o]),zs(i[s]),n.equal++}else n[o]++}}_updateElementMappings(t,e){this.domConverter.unbindDomElement(e),this.domConverter.bindElements(e,t),this.markedChildren.add(t),this.markedAttributes.add(t)}_getInlineFillerPosition(){const t=this.selection.getFirstPosition();return t.parent.is("$text")?Ha._createBefore(t.parent):t}_isSelectionInInlineFiller(){if(1!=this.selection.rangeCount||!this.selection.isCollapsed)return!1;const t=this.selection.getFirstPosition(),e=this.domConverter.viewPositionToDom(t);return!!(e&&ks(e.parent)&&Tl(e.parent))}_removeInlineFiller(){const t=this._inlineFiller;if(!Tl(t))throw new v("view-renderer-filler-was-lost",this);El(t)?t.remove():t.data=t.data.substr(Cl),this._inlineFiller=null}_needsInlineFillerAtSelection(){if(1!=this.selection.rangeCount||!this.selection.isCollapsed)return!1;const t=this.selection.getFirstPosition(),e=t.parent,i=t.offset;if(!this.domConverter.mapViewToDom(e.root))return!1;if(!e.is("element"))return!1;if(!function(t){if("false"==t.getAttribute("contenteditable"))return!1;const e=t.findAncestor((t=>t.hasAttribute("contenteditable")));return!e||"true"==e.getAttribute("contenteditable")}(e))return!1;if(i===e.getFillerOffset())return!1;const n=t.nodeBefore,s=t.nodeAfter;return!(n instanceof Cr||s instanceof Cr)&&(!r.isAndroid||!n&&!s)}_updateText(t,e){const i=this.domConverter.findCorrespondingDomText(t);let n=this.domConverter.viewToDom(t).data;const s=e.inlineFillerPosition;s&&s.parent==t.parent&&s.offset==t.index&&(n=Pl+n),Bl(i,n)}_updateAttrs(t){const e=this.domConverter.mapViewToDom(t);if(!e)return;const i=Array.from(e.attributes).map((t=>t.name)),n=t.getAttributeKeys();for(const i of n)this.domConverter.setDomElementAttribute(e,i,t.getAttribute(i),t);for(const n of i)t.hasAttribute(n)||this.domConverter.removeDomElementAttribute(e,n)}_updateChildren(t,e){const i=this.domConverter.mapViewToDom(t);if(!i)return;if(r.isAndroid){let t=null;for(const e of Array.from(i.childNodes)){if(t&&ks(t)&&ks(e)){i.normalize();break}t=e}}const n=e.inlineFillerPosition,s=i.childNodes,o=Array.from(this.domConverter.viewChildrenToDom(t,{bind:!0}));n&&n.parent===t&&Il(i.ownerDocument,o,n.offset);const a=this._diffNodeLists(s,o),l=r.isAndroid?this._findReplaceActions(a,s,o,{replaceText:!0}):a;let c=0;const h=new Set;for(const t of l)"delete"===t?(h.add(s[c]),zs(s[c])):"equal"!==t&&"replace"!==t||c++;c=0;for(const t of l)"insert"===t?(Ms(i,c,o[c]),c++):"replace"===t?(Bl(s[c],o[c].data),c++):"equal"===t&&(this._markDescendantTextToSync(this.domConverter.domToView(o[c])),c++);for(const t of h)t.parentNode||this.domConverter.unbindDomElement(t)}_diffNodeLists(t,e){return t=function(t,e){const i=Array.from(t);if(0==i.length||!e)return i;const n=i[i.length-1];n==e&&i.pop();return i}(t,this._fakeSelectionContainer),d(t,e,Nl.bind(null,this.domConverter))}_findReplaceActions(t,e,i,n={}){if(-1===t.indexOf("insert")||-1===t.indexOf("delete"))return t;let s=[],o=[],r=[];const a={equal:0,insert:0,delete:0};for(const l of t)"insert"===l?r.push(i[a.equal+a.insert]):"delete"===l?o.push(e[a.equal+a.delete]):(s=s.concat(d(o,r,n.replaceText?Ml:Vl).map((t=>"equal"===t?"replace":t))),s.push("equal"),o=[],r=[]),a[l]++;return s.concat(d(o,r,n.replaceText?Ml:Vl).map((t=>"equal"===t?"replace":t)))}_markDescendantTextToSync(t){if(t)if(t.is("$text"))this.markedTexts.add(t);else if(t.is("element"))for(const e of t.getChildren())this._markDescendantTextToSync(e)}_updateSelection(){if(r.isBlink&&!r.isAndroid&&this.isSelecting&&!this.markedChildren.size)return;if(0===this.selection.rangeCount)return this._removeDomSelection(),void this._removeFakeSelection();const t=this.domConverter.mapViewToDom(this.selection.editableElement);this.isFocused&&t&&(this.selection.isFake?this._updateFakeSelection(t):this._fakeSelectionContainer&&this._fakeSelectionContainer.isConnected?(this._removeFakeSelection(),this._updateDomSelection(t)):this.isComposing&&r.isAndroid||this._updateDomSelection(t))}_updateFakeSelection(t){const e=t.ownerDocument;this._fakeSelectionContainer||(this._fakeSelectionContainer=function(t){const e=t.createElement("div");return e.className="ck-fake-selection-container",Object.assign(e.style,{position:"fixed",top:0,left:"-9999px",width:"42px"}),e.textContent=" ",e}(e));const i=this._fakeSelectionContainer;if(this.domConverter.bindFakeSelection(i,this.selection),!this._fakeSelectionNeedsUpdate(t))return;i.parentElement&&i.parentElement==t||t.appendChild(i),i.textContent=this.selection.fakeSelectionLabel||" ";const n=e.getSelection(),s=e.createRange();n.removeAllRanges(),s.selectNodeContents(i),n.addRange(s)}_updateDomSelection(t){const e=t.ownerDocument.defaultView.getSelection();if(!this._domSelectionNeedsUpdate(e))return;const i=this.domConverter.viewPositionToDom(this.selection.anchor),n=this.domConverter.viewPositionToDom(this.selection.focus);e.collapse(i.parent,i.offset),e.extend(n.parent,n.offset),r.isGecko&&function(t,e){const i=t.parent;if(i.nodeType!=Node.ELEMENT_NODE||t.offset!=i.childNodes.length-1)return;const n=i.childNodes[t.offset];n&&"BR"==n.tagName&&e.addRange(e.getRangeAt(0))}(n,e)}_domSelectionNeedsUpdate(t){if(!this.domConverter.isDomSelectionCorrect(t))return!0;const e=t&&this.domConverter.domSelectionToView(t);return(!e||!this.selection.isEqual(e))&&!(!this.selection.isCollapsed&&this.selection.isSimilar(e))}_fakeSelectionNeedsUpdate(t){const e=this._fakeSelectionContainer,i=t.ownerDocument.getSelection();return!e||e.parentElement!==t||(i.anchorNode!==e&&!e.contains(i.anchorNode)||e.textContent!==this.selection.fakeSelectionLabel)}_removeDomSelection(){for(const t of this.domDocuments){const e=t.getSelection();if(e.rangeCount){const i=t.activeElement,n=this.domConverter.mapDomToView(i);i&&n&&e.removeAllRanges()}}}_removeFakeSelection(){const t=this._fakeSelectionContainer;t&&t.remove()}_updateFocus(){if(this.isFocused){const t=this.selection.editableElement;t&&this.domConverter.focus(t)}}}function Il(t,e,i){const n=e instanceof Array?e:e.childNodes,s=n[i];if(ks(s))return s.data=Pl+s.data,s;{const s=t.createTextNode(Pl);return Array.isArray(e)?n.splice(i,0,s):Ms(e,i,s),s}}function Vl(t,e){return fs(t)&&fs(e)&&!ks(t)&&!ks(e)&&!Ns(t)&&!Ns(e)&&t.tagName.toLowerCase()===e.tagName.toLowerCase()}function Ml(t,e){return fs(t)&&fs(e)&&ks(t)&&ks(e)}function Nl(t,e,i){return e===i||(ks(e)&&ks(i)?e.data===i.data:!(!t.isBlockFiller(e)||!t.isBlockFiller(i)))}function Bl(t,e){const i=t.data;if(i==e)return;const n=l(i,e);for(const e of n)"insert"===e.type?t.insertData(e.index,e.values.join("")):t.deleteData(e.index,e.howMany)}const Dl=xl(vs.document),Fl=kl(vs.document),Ll=Al(vs.document),zl="data-ck-unsafe-attribute-",Hl="data-ck-unsafe-element";class jl{constructor(t,e={}){this.document=t,this.renderingMode=e.renderingMode||"editing",this.blockFillerMode=e.blockFillerMode||("editing"===this.renderingMode?"br":"nbsp"),this.preElements=["pre"],this.blockElements=["address","article","aside","blockquote","caption","center","dd","details","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","legend","li","main","menu","nav","ol","p","pre","section","summary","table","tbody","td","tfoot","th","thead","tr","ul"],this.inlineObjectElements=["object","iframe","input","button","textarea","select","option","video","embed","audio","img","canvas"],this.unsafeElements=["script","style"],this._domDocument="editing"===this.renderingMode?vs.document:vs.document.implementation.createHTMLDocument(""),this._domToViewMapping=new WeakMap,this._viewToDomMapping=new WeakMap,this._fakeSelectionMapping=new WeakMap,this._rawContentElementMatcher=new Tr,this._encounteredRawContentDomNodes=new WeakSet}bindFakeSelection(t,e){this._fakeSelectionMapping.set(t,new Wa(e))}fakeSelectionToView(t){return this._fakeSelectionMapping.get(t)}bindElements(t,e){this._domToViewMapping.set(t,e),this._viewToDomMapping.set(e,t)}unbindDomElement(t){const e=this._domToViewMapping.get(t);if(e){this._domToViewMapping.delete(t),this._viewToDomMapping.delete(e);for(const e of Array.from(t.children))this.unbindDomElement(e)}}bindDocumentFragments(t,e){this._domToViewMapping.set(t,e),this._viewToDomMapping.set(e,t)}shouldRenderAttribute(t,e,i){return"data"===this.renderingMode||!(t=t.toLowerCase()).startsWith("on")&&(("srcdoc"!==t||!e.match(/\bon\S+\s*=|javascript:|<\s*\/*script/i))&&("img"===i&&("src"===t||"srcset"===t)||("source"===i&&"srcset"===t||!e.match(/^\s*(javascript:|data:(image\/svg|text\/x?html))/i))))}setContentOf(t,e){if("data"===this.renderingMode)return void(t.innerHTML=e);const i=(new DOMParser).parseFromString(e,"text/html"),n=i.createDocumentFragment(),s=i.body.childNodes;for(;s.length>0;)n.appendChild(s[0]);const o=i.createTreeWalker(n,NodeFilter.SHOW_ELEMENT),r=[];let a;for(;a=o.nextNode();)r.push(a);for(const t of r){for(const e of t.getAttributeNames())this.setDomElementAttribute(t,e,t.getAttribute(e));const e=t.tagName.toLowerCase();this._shouldRenameElement(e)&&(ql(e),t.replaceWith(this._createReplacementDomElement(e,t)))}for(;t.firstChild;)t.firstChild.remove();t.append(n)}viewToDom(t,e={}){if(t.is("$text")){const e=this._processDataFromViewText(t);return this._domDocument.createTextNode(e)}{if(this.mapViewToDom(t))return this.mapViewToDom(t);let i;if(t.is("documentFragment"))i=this._domDocument.createDocumentFragment(),e.bind&&this.bindDocumentFragments(i,t);else{if(t.is("uiElement"))return i="$comment"===t.name?this._domDocument.createComment(t.getCustomProperty("$rawContent")):t.render(this._domDocument,this),e.bind&&this.bindElements(i,t),i;this._shouldRenameElement(t.name)?(ql(t.name),i=this._createReplacementDomElement(t.name)):i=t.hasAttribute("xmlns")?this._domDocument.createElementNS(t.getAttribute("xmlns"),t.name):this._domDocument.createElement(t.name),t.is("rawElement")&&t.render(i,this),e.bind&&this.bindElements(i,t);for(const e of t.getAttributeKeys())this.setDomElementAttribute(i,e,t.getAttribute(e),t)}if(!1!==e.withChildren)for(const n of this.viewChildrenToDom(t,e))i.appendChild(n);return i}}setDomElementAttribute(t,e,i,n){const s=this.shouldRenderAttribute(e,i,t.tagName.toLowerCase())||n&&n.shouldRenderUnsafeAttribute(e);s||y("domconverter-unsafe-attribute-detected",{domElement:t,key:e,value:i}),t.hasAttribute(e)&&!s?t.removeAttribute(e):t.hasAttribute(zl+e)&&s&&t.removeAttribute(zl+e),t.setAttribute(s?e:zl+e,i)}removeDomElementAttribute(t,e){e!=Hl&&(t.removeAttribute(e),t.removeAttribute(zl+e))}*viewChildrenToDom(t,e={}){const i=t.getFillerOffset&&t.getFillerOffset();let n=0;for(const s of t.getChildren()){i===n&&(yield this._getBlockFiller());const t=s.is("element")&&!!s.getCustomProperty("dataPipeline:transparentRendering")&&!ho(s.getAttributes());t&&"data"==this.renderingMode?yield*this.viewChildrenToDom(s,e):(t&&y("domconverter-transparent-rendering-unsupported-in-editing-pipeline",{viewElement:s}),yield this.viewToDom(s,e)),n++}i===n&&(yield this._getBlockFiller())}viewRangeToDom(t){const e=this.viewPositionToDom(t.start),i=this.viewPositionToDom(t.end),n=this._domDocument.createRange();return n.setStart(e.parent,e.offset),n.setEnd(i.parent,i.offset),n}viewPositionToDom(t){const e=t.parent;if(e.is("$text")){const i=this.findCorrespondingDomText(e);if(!i)return null;let n=t.offset;return Tl(i)&&(n+=Cl),{parent:i,offset:n}}{let i,n,s;if(0===t.offset){if(i=this.mapViewToDom(e),!i)return null;s=i.childNodes[0]}else{const e=t.nodeBefore;if(n=e.is("$text")?this.findCorrespondingDomText(e):this.mapViewToDom(e),!n)return null;i=n.parentNode,s=n.nextSibling}if(ks(s)&&Tl(s))return{parent:s,offset:Cl};return{parent:i,offset:n?Vs(n)+1:0}}}domToView(t,e={}){if(this.isBlockFiller(t))return null;const i=this.getHostViewElement(t);if(i)return i;if(Ns(t)&&e.skipComments)return null;if(ks(t)){if(El(t))return null;{const e=this._processDataFromDomText(t);return""===e?null:new Cr(this.document,e)}}{if(this.mapDomToView(t))return this.mapDomToView(t);let i;if(this.isDocumentFragment(t))i=new hl(this.document),e.bind&&this.bindDocumentFragments(t,i);else{i=this._createViewElement(t,e),e.bind&&this.bindElements(t,i);const n=t.attributes;if(n)for(let t=n.length,e=0;e{const{scrollLeft:e,scrollTop:i}=t;n.push([e,i])})),e.focus(),$l(e,(t=>{const[e,i]=n.shift();t.scrollLeft=e,t.scrollTop=i})),vs.window.scrollTo(t,i)}}isElement(t){return t&&t.nodeType==Node.ELEMENT_NODE}isDocumentFragment(t){return t&&t.nodeType==Node.DOCUMENT_FRAGMENT_NODE}isBlockFiller(t){return"br"==this.blockFillerMode?t.isEqualNode(Dl):!("BR"!==t.tagName||!Wl(t,this.blockElements)||1!==t.parentNode.childNodes.length)||(t.isEqualNode(Ll)||function(t,e){const i=t.isEqualNode(Fl);return i&&Wl(t,e)&&1===t.parentNode.childNodes.length}(t,this.blockElements))}isDomSelectionBackward(t){if(t.isCollapsed)return!1;const e=this._domDocument.createRange();try{e.setStart(t.anchorNode,t.anchorOffset),e.setEnd(t.focusNode,t.focusOffset)}catch(t){return!1}const i=e.collapsed;return e.detach(),i}getHostViewElement(t){const e=ys(t);for(e.pop();e.length;){const t=e.pop(),i=this._domToViewMapping.get(t);if(i&&(i.is("uiElement")||i.is("rawElement")))return i}return null}isDomSelectionCorrect(t){return this._isDomSelectionPositionCorrect(t.anchorNode,t.anchorOffset)&&this._isDomSelectionPositionCorrect(t.focusNode,t.focusOffset)}registerRawContentMatcher(t){this._rawContentElementMatcher.add(t)}_getBlockFiller(){switch(this.blockFillerMode){case"nbsp":return kl(this._domDocument);case"markedNbsp":return Al(this._domDocument);case"br":return xl(this._domDocument)}}_isDomSelectionPositionCorrect(t,e){if(ks(t)&&Tl(t)&&ethis.preElements.includes(t.name))))return e;if(" "==e.charAt(0)){const i=this._getTouchingInlineViewNode(t,!1);!(i&&i.is("$textProxy")&&this._nodeEndsWithSpace(i))&&i||(e=" "+e.substr(1))}if(" "==e.charAt(e.length-1)){const i=this._getTouchingInlineViewNode(t,!0),n=i&&i.is("$textProxy")&&" "==i.data.charAt(0);" "!=e.charAt(e.length-2)&&i&&!n||(e=e.substr(0,e.length-1)+" ")}return e.replace(/ {2}/g,"  ")}_nodeEndsWithSpace(t){if(t.getAncestors().some((t=>this.preElements.includes(t.name))))return!1;const e=this._processDataFromViewText(t);return" "==e.charAt(e.length-1)}_processDataFromDomText(t){let e=t.data;if(function(t,e){const i=ys(t);return i.some((t=>t.tagName&&e.includes(t.tagName.toLowerCase())))}(t,this.preElements))return Sl(t);e=e.replace(/[ \n\t\r]{1,}/g," ");const i=this._getTouchingInlineDomNode(t,!1),n=this._getTouchingInlineDomNode(t,!0),s=this._checkShouldLeftTrimDomText(t,i),o=this._checkShouldRightTrimDomText(t,n);s&&(e=e.replace(/^ /,"")),o&&(e=e.replace(/ $/,"")),e=Sl(new Text(e)),e=e.replace(/ \u00A0/g," ");const r=n&&this.isElement(n)&&"BR"!=n.tagName,a=n&&ks(n)&&" "==n.data.charAt(0);return(/( |\u00A0)\u00A0$/.test(e)||!n||r||a)&&(e=e.replace(/\u00A0$/," ")),(s||i&&this.isElement(i)&&"BR"!=i.tagName)&&(e=e.replace(/^\u00A0/," ")),e}_checkShouldLeftTrimDomText(t,e){return!e||(this.isElement(e)?"BR"===e.tagName:!this._encounteredRawContentDomNodes.has(t.previousSibling)&&/[^\S\u00A0]/.test(e.data.charAt(e.data.length-1)))}_checkShouldRightTrimDomText(t,e){return!e&&!Tl(t)}_getTouchingInlineViewNode(t,e){const i=new za({startPosition:e?Ha._createAfter(t):Ha._createBefore(t),direction:e?"forward":"backward"});for(const t of i){if(t.item.is("element")&&this.inlineObjectElements.includes(t.item.name))return t.item;if(t.item.is("containerElement"))return null;if(t.item.is("element","br"))return null;if(t.item.is("$textProxy"))return t.item}return null}_getTouchingInlineDomNode(t,e){if(!t.parentNode)return null;const i=e?"firstChild":"lastChild",n=e?"nextSibling":"previousSibling";let s=!0,o=t;do{if(!s&&o[i]?o=o[i]:o[n]?(o=o[n],s=!1):(o=o.parentNode,s=!0),!o||this._isBlockElement(o))return null}while(!ks(o)&&"BR"!=o.tagName&&!this._isInlineObjectElement(o));return o}_isBlockElement(t){return this.isElement(t)&&this.blockElements.includes(t.tagName.toLowerCase())}_isInlineObjectElement(t){return this.isElement(t)&&this.inlineObjectElements.includes(t.tagName.toLowerCase())}_createViewElement(t,e){if(Ns(t))return new ol(this.document,"$comment");const i=e.keepOriginalCase?t.tagName:t.tagName.toLowerCase();return new Va(this.document,i)}_isViewElementWithRawContent(t,e){return!1!==e.withChildren&&!!this._rawContentElementMatcher.match(t)}_shouldRenameElement(t){const e=t.toLowerCase();return"editing"===this.renderingMode&&this.unsafeElements.includes(e)}_createReplacementDomElement(t,e){const i=this._domDocument.createElement("span");if(i.setAttribute(Hl,t),e){for(;e.firstChild;)i.appendChild(e.firstChild);for(const t of e.getAttributeNames())i.setAttribute(t,e.getAttribute(t))}return i}}function $l(t,e){let i=t;for(;i;)e(i),i=i.parentElement}function Wl(t,e){const i=t.parentNode;return!!i&&!!i.tagName&&e.includes(i.tagName.toLowerCase())}function ql(t){"script"===t&&y("domconverter-unsafe-script-element-detected"),"style"===t&&y("domconverter-unsafe-style-element-detected")}class Ul extends(ps()){constructor(t){super(),this.view=t,this.document=t.document,this.isEnabled=!1}enable(){this.isEnabled=!0}disable(){this.isEnabled=!1}destroy(){this.disable(),this.stopListening()}checkShouldIgnoreEventFromTarget(t){return t&&3===t.nodeType&&(t=t.parentNode),!(!t||1!==t.nodeType)&&t.matches("[data-cke-ignore-events], [data-cke-ignore-events] *")}}const Kl=Ca((function(t,e){ze(e,Pi(e),t)}));class Gl{constructor(t,e,i){this.view=t,this.document=t.document,this.domEvent=e,this.domTarget=e.target,Kl(this,i)}get target(){return this.view.domConverter.mapDomToView(this.domTarget)}preventDefault(){this.domEvent.preventDefault()}stopPropagation(){this.domEvent.stopPropagation()}}class Jl extends Ul{constructor(t){super(t),this.useCapture=!1}observe(t){("string"==typeof this.domEventType?[this.domEventType]:this.domEventType).forEach((e=>{this.listenTo(t,e,((t,e)=>{this.isEnabled&&!this.checkShouldIgnoreEventFromTarget(e.target)&&this.onDomEvent(e)}),{useCapture:this.useCapture})}))}fire(t,e,i){this.isEnabled&&this.document.fire(t,new Gl(this.view,e,i))}}class Ql extends Jl{constructor(t){super(t),this.domEventType=["keydown","keyup"]}onDomEvent(t){const e={keyCode:t.keyCode,altKey:t.altKey,ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,metaKey:t.metaKey,get keystroke(){return to(this)}};this.fire(t.type,t,e)}}const Yl=function(){return nt.Date.now()};var Zl=/\s/;const Xl=function(t){for(var e=t.length;e--&&Zl.test(t.charAt(e)););return e};var tc=/^\s+/;const ec=function(t){return t?t.slice(0,Xl(t)+1).replace(tc,""):t};var ic=NaN,nc=/^[-+]0x[0-9a-f]+$/i,sc=/^0b[01]+$/i,oc=/^0o[0-7]+$/i,rc=parseInt;const ac=function(t){if("number"==typeof t)return t;if(Or(t))return ic;if(F(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=F(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=ec(t);var i=sc.test(t);return i||oc.test(t)?rc(t.slice(2),i?2:8):nc.test(t)?ic:+t};var lc="Expected a function",cc=Math.max,hc=Math.min;const dc=function(t,e,i){var n,s,o,r,a,l,c=0,h=!1,d=!1,u=!0;if("function"!=typeof t)throw new TypeError(lc);function f(e){var i=n,o=s;return n=s=void 0,c=e,r=t.apply(o,i)}function m(t){var i=t-l;return void 0===l||i>=e||i<0||d&&t-c>=o}function g(){var t=Yl();if(m(t))return p(t);a=setTimeout(g,function(t){var i=e-(t-l);return d?hc(i,o-(t-c)):i}(t))}function p(t){return a=void 0,u&&n?f(t):(n=s=void 0,r)}function w(){var t=Yl(),i=m(t);if(n=arguments,s=this,l=t,i){if(void 0===a)return function(t){return c=t,a=setTimeout(g,e),h?f(t):r}(l);if(d)return clearTimeout(a),a=setTimeout(g,e),f(l)}return void 0===a&&(a=setTimeout(g,e)),r}return e=ac(e)||0,F(i)&&(h=!!i.leading,o=(d="maxWait"in i)?cc(ac(i.maxWait)||0,e):o,u="trailing"in i?!!i.trailing:u),w.cancel=function(){void 0!==a&&clearTimeout(a),c=0,n=l=s=a=void 0},w.flush=function(){return void 0===a?r:p(Yl())},w};class uc extends Ul{constructor(t){super(t),this._fireSelectionChangeDoneDebounced=dc((t=>{this.document.fire("selectionChangeDone",t)}),200)}observe(){const t=this.document;t.on("arrowKey",((e,i)=>{t.selection.isFake&&this.isEnabled&&i.preventDefault()}),{context:"$capture"}),t.on("arrowKey",((e,i)=>{t.selection.isFake&&this.isEnabled&&this._handleSelectionMove(i.keyCode)}),{priority:"lowest"})}destroy(){super.destroy(),this._fireSelectionChangeDoneDebounced.cancel()}_handleSelectionMove(t){const e=this.document.selection,i=new Wa(e.getRanges(),{backward:e.isBackward,fake:!1});t!=Zs.arrowleft&&t!=Zs.arrowup||i.setTo(i.getFirstPosition()),t!=Zs.arrowright&&t!=Zs.arrowdown||i.setTo(i.getLastPosition());const n={oldSelection:e,newSelection:i,domSelection:null};this.document.fire("selectionChange",n),this._fireSelectionChangeDoneDebounced(n)}}var fc="__lodash_hash_undefined__";const mc=function(t){return this.__data__.set(t,fc),this};const gc=function(t){return this.__data__.has(t)};function pc(t){var e=-1,i=null==t?0:t.length;for(this.__data__=new Re;++ea))return!1;var c=o.get(t),h=o.get(e);if(c&&h)return c==e&&h==t;var d=-1,u=!0,f=i&yc?new wc:void 0;for(o.set(t,e),o.set(e,t);++d{this._isFocusChanging=!0,this._renderTimeoutId=setTimeout((()=>{this.flush(),t.change((()=>{}))}),50)})),e.on("blur",((i,n)=>{const s=e.selection.editableElement;null!==s&&s!==n.target||(e.isFocused=!1,this._isFocusChanging=!1,t.change((()=>{})))}))}flush(){this._isFocusChanging&&(this._isFocusChanging=!1,this.document.isFocused=!0)}onDomEvent(t){this.fire(t.type,t)}destroy(){this._renderTimeoutId&&clearTimeout(this._renderTimeoutId),super.destroy()}}class eh extends Ul{constructor(t){super(t),this.mutationObserver=t.getObserver(Zc),this.focusObserver=t.getObserver(th),this.selection=this.document.selection,this.domConverter=t.domConverter,this._documents=new WeakSet,this._fireSelectionChangeDoneDebounced=dc((t=>{this.document.fire("selectionChangeDone",t)}),200),this._clearInfiniteLoopInterval=setInterval((()=>this._clearInfiniteLoop()),1e3),this._documentIsSelectingInactivityTimeoutDebounced=dc((()=>this.document.isSelecting=!1),5e3),this._loopbackCounter=0}observe(t){const e=t.ownerDocument,i=()=>{this.document.isSelecting&&(this._handleSelectionChange(null,e),this.document.isSelecting=!1,this._documentIsSelectingInactivityTimeoutDebounced.cancel())};this.listenTo(t,"selectstart",(()=>{this.document.isSelecting=!0,this._documentIsSelectingInactivityTimeoutDebounced()}),{priority:"highest"}),this.listenTo(t,"keydown",i,{priority:"highest",useCapture:!0}),this.listenTo(t,"keyup",i,{priority:"highest",useCapture:!0}),this._documents.has(e)||(this.listenTo(e,"mouseup",i,{priority:"highest",useCapture:!0}),this.listenTo(e,"selectionchange",((t,i)=>{this.document.isComposing&&!r.isAndroid||(this._handleSelectionChange(i,e),this._documentIsSelectingInactivityTimeoutDebounced())})),this._documents.add(e))}destroy(){super.destroy(),clearInterval(this._clearInfiniteLoopInterval),this._fireSelectionChangeDoneDebounced.cancel(),this._documentIsSelectingInactivityTimeoutDebounced.cancel()}_handleSelectionChange(t,e){if(!this.isEnabled)return;const i=e.defaultView.getSelection();if(this.checkShouldIgnoreEventFromTarget(i.anchorNode))return;this.mutationObserver.flush();const n=this.domConverter.domSelectionToView(i);if(0!=n.rangeCount){if(this.view.hasDomSelection=!0,!(this.selection.isEqual(n)&&this.domConverter.isDomSelectionCorrect(i)||++this._loopbackCounter>60))if(this.focusObserver.flush(),this.selection.isSimilar(n))this.view.forceRender();else{const t={oldSelection:this.selection,newSelection:n,domSelection:i};this.document.fire("selectionChange",t),this._fireSelectionChangeDoneDebounced(t)}}else this.view.hasDomSelection=!1}_clearInfiniteLoop(){this._loopbackCounter=0}}class ih extends Jl{constructor(t){super(t),this.domEventType=["compositionstart","compositionupdate","compositionend"];const e=this.document;e.on("compositionstart",(()=>{e.isComposing=!0}),{priority:"low"}),e.on("compositionend",(()=>{e.isComposing=!1}),{priority:"low"})}onDomEvent(t){this.fire(t.type,t,{data:t.data})}}class nh{constructor(t){this.files=function(t){const e=Array.from(t.files||[]),i=Array.from(t.items||[]);if(e.length)return e;return i.filter((t=>"file"===t.kind)).map((t=>t.getAsFile()))}(t),this._native=t}get types(){return this._native.types}getData(t){return this._native.getData(t)}setData(t,e){this._native.setData(t,e)}set effectAllowed(t){this._native.effectAllowed=t}get effectAllowed(){return this._native.effectAllowed}set dropEffect(t){this._native.dropEffect=t}get dropEffect(){return this._native.dropEffect}get isCanceled(){return"none"==this._native.dropEffect||!!this._native.mozUserCancelled}}class sh extends Jl{constructor(t){super(t),this.domEventType=["beforeinput"]}onDomEvent(t){const e=t.getTargetRanges(),i=this.view,n=i.document;let s=null,o=null,a=[];if(t.dataTransfer&&(s=new nh(t.dataTransfer)),null!==t.data?o=t.data:s&&(o=s.getData("text/plain")),n.selection.isFake)a=Array.from(n.selection.getRanges());else if(e.length)a=e.map((t=>i.domConverter.domRangeToView(t)));else if(r.isAndroid){const e=t.target.ownerDocument.defaultView.getSelection();a=Array.from(i.domConverter.domSelectionToView(e).getRanges())}if(r.isAndroid&&"insertCompositionText"==t.inputType&&o&&o.endsWith("\n"))this.fire(t.type,t,{inputType:"insertParagraph",targetRanges:[i.createRange(a[0].end)]});else if("insertText"==t.inputType&&o&&o.includes("\n")){const e=o.split(/\n{1,2}/g);let i=a;for(let o=0;o{if(this.isEnabled&&((i=e.keyCode)==Zs.arrowright||i==Zs.arrowleft||i==Zs.arrowup||i==Zs.arrowdown)){const i=new Ua(this.document,"arrowKey",this.document.selection.getFirstRange());this.document.fire(i,e),i.stop.called&&t.stop()}var i}))}observe(){}}class rh extends Ul{constructor(t){super(t);const e=this.document;e.on("keydown",((t,i)=>{if(!this.isEnabled||i.keyCode!=Zs.tab||i.ctrlKey)return;const n=new Ua(e,"tab",e.selection.getFirstRange());e.fire(n,i),n.stop.called&&t.stop()}))}observe(){}}class ah extends(q()){constructor(t){super(),this.document=new Xa(t),this.domConverter=new jl(this.document),this.domRoots=new Map,this.set("isRenderingInProgress",!1),this.set("hasDomSelection",!1),this._renderer=new Ol(this.domConverter,this.document.selection),this._renderer.bind("isFocused","isSelecting","isComposing").to(this.document,"isFocused","isSelecting","isComposing"),this._initialDomRootAttributes=new WeakMap,this._observers=new Map,this._ongoingChange=!1,this._postFixersInProgress=!1,this._renderingDisabled=!1,this._hasChangedSinceTheLastRendering=!1,this._writer=new dl(this.document),this.addObserver(Zc),this.addObserver(th),this.addObserver(eh),this.addObserver(Ql),this.addObserver(uc),this.addObserver(ih),this.addObserver(oh),this.addObserver(sh),this.addObserver(rh),this.document.on("arrowKey",Rl,{priority:"low"}),rl(this),this.on("render",(()=>{this._render(),this.document.fire("layoutChanged"),this._hasChangedSinceTheLastRendering=!1})),this.listenTo(this.document.selection,"change",(()=>{this._hasChangedSinceTheLastRendering=!0})),this.listenTo(this.document,"change:isFocused",(()=>{this._hasChangedSinceTheLastRendering=!0}))}attachDomRoot(t,e="main"){const i=this.document.getRoot(e);i._name=t.tagName.toLowerCase();const n={};for(const{name:e,value:s}of Array.from(t.attributes))n[e]=s,"class"===e?this._writer.addClass(s.split(" "),i):this._writer.setAttribute(e,s,i);this._initialDomRootAttributes.set(t,n);const s=()=>{this._writer.setAttribute("contenteditable",(!i.isReadOnly).toString(),i),i.isReadOnly?this._writer.addClass("ck-read-only",i):this._writer.removeClass("ck-read-only",i)};s(),this.domRoots.set(e,t),this.domConverter.bindElements(t,i),this._renderer.markToSync("children",i),this._renderer.markToSync("attributes",i),this._renderer.domDocuments.add(t.ownerDocument),i.on("change:children",((t,e)=>this._renderer.markToSync("children",e))),i.on("change:attributes",((t,e)=>this._renderer.markToSync("attributes",e))),i.on("change:text",((t,e)=>this._renderer.markToSync("text",e))),i.on("change:isReadOnly",(()=>this.change(s))),i.on("change",(()=>{this._hasChangedSinceTheLastRendering=!0}));for(const i of this._observers.values())i.observe(t,e)}detachDomRoot(t){const e=this.domRoots.get(t);Array.from(e.attributes).forEach((({name:t})=>e.removeAttribute(t)));const i=this._initialDomRootAttributes.get(e);for(const t in i)e.setAttribute(t,i[t]);this.domRoots.delete(t),this.domConverter.unbindDomElement(e)}getDomRoot(t="main"){return this.domRoots.get(t)}addObserver(t){let e=this._observers.get(t);if(e)return e;e=new t(this),this._observers.set(t,e);for(const[t,i]of this.domRoots)e.observe(i,t);return e.enable(),e}getObserver(t){return this._observers.get(t)}disableObservers(){for(const t of this._observers.values())t.disable()}enableObservers(){for(const t of this._observers.values())t.enable()}scrollToTheSelection(){const t=this.document.selection.getFirstRange();t&&function({target:t,viewportOffset:e=0}){const i=Ks(t);let n=i,s=null;for(;n;){let o;o=Gs(n==i?t:s),js(o,(()=>Js(t,n)));const r=Js(t,n);if(Hs(n,r,e),n.parent!=n){if(s=n.frameElement,n=n.parent,!s)return}else n=null}}({target:this.domConverter.viewRangeToDom(t),viewportOffset:20})}focus(){if(!this.document.isFocused){const t=this.document.selection.editableElement;t&&(this.domConverter.focus(t),this.forceRender())}}change(t){if(this.isRenderingInProgress||this._postFixersInProgress)throw new v("cannot-change-view-tree",this);try{if(this._ongoingChange)return t(this._writer);this._ongoingChange=!0;const e=t(this._writer);return this._ongoingChange=!1,!this._renderingDisabled&&this._hasChangedSinceTheLastRendering&&(this._postFixersInProgress=!0,this.document._callPostFixers(this._writer),this._postFixersInProgress=!1,this.fire("render")),e}catch(t){v.rethrowUnexpectedError(t,this)}}forceRender(){this._hasChangedSinceTheLastRendering=!0,this.getObserver(th).flush(),this.change((()=>{}))}destroy(){for(const t of this._observers.values())t.destroy();this.document.destroy(),this.stopListening()}createPositionAt(t,e){return Ha._createAt(t,e)}createPositionAfter(t){return Ha._createAfter(t)}createPositionBefore(t){return Ha._createBefore(t)}createRange(...t){return new ja(...t)}createRangeOn(t){return ja._createOn(t)}createRangeIn(t){return ja._createIn(t)}createSelection(...t){return new Wa(...t)}_disableRendering(t){this._renderingDisabled=t,0==t&&this.change((()=>{}))}_render(){this.isRenderingInProgress=!0,this.disableObservers(),this._renderer.render(),this.enableObservers(),this.isRenderingInProgress=!1}}class lh{is(){throw new Error("is() method is abstract")}}class ch extends lh{constructor(t){super(),this.parent=null,this._attrs=mo(t)}get document(){return null}get index(){let t;if(!this.parent)return null;if(null===(t=this.parent.getChildIndex(this)))throw new v("model-node-not-found-in-parent",this);return t}get startOffset(){let t;if(!this.parent)return null;if(null===(t=this.parent.getChildStartOffset(this)))throw new v("model-node-not-found-in-parent",this);return t}get offsetSize(){return 1}get endOffset(){return this.parent?this.startOffset+this.offsetSize:null}get nextSibling(){const t=this.index;return null!==t&&this.parent.getChild(t+1)||null}get previousSibling(){const t=this.index;return null!==t&&this.parent.getChild(t-1)||null}get root(){let t=this;for(;t.parent;)t=t.parent;return t}isAttached(){return this.root.is("rootElement")}getPath(){const t=[];let e=this;for(;e.parent;)t.unshift(e.startOffset),e=e.parent;return t}getAncestors(t={}){const e=[];let i=t.includeSelf?this:this.parent;for(;i;)e[t.parentFirst?"push":"unshift"](i),i=i.parent;return e}getCommonAncestor(t,e={}){const i=this.getAncestors(e),n=t.getAncestors(e);let s=0;for(;i[s]==n[s]&&i[s];)s++;return 0===s?null:i[s-1]}isBefore(t){if(this==t)return!1;if(this.root!==t.root)return!1;const e=this.getPath(),i=t.getPath(),n=X(e,i);switch(n){case"prefix":return!0;case"extension":return!1;default:return e[n](t[e[0]]=e[1],t)),{})),t}_clone(t){return new this.constructor(this._attrs)}_remove(){this.parent._removeChildren(this.index)}_setAttribute(t,e){this._attrs.set(t,e)}_setAttributesTo(t){this._attrs=mo(t)}_removeAttribute(t){return this._attrs.delete(t)}_clearAttributes(){this._attrs.clear()}}ch.prototype.is=function(t){return"node"===t||"model:node"===t};class hh{constructor(t){this._nodes=[],t&&this._insertNodes(0,t)}[Symbol.iterator](){return this._nodes[Symbol.iterator]()}get length(){return this._nodes.length}get maxOffset(){return this._nodes.reduce(((t,e)=>t+e.offsetSize),0)}getNode(t){return this._nodes[t]||null}getNodeIndex(t){const e=this._nodes.indexOf(t);return-1==e?null:e}getNodeStartOffset(t){const e=this.getNodeIndex(t);return null===e?null:this._nodes.slice(0,e).reduce(((t,e)=>t+e.offsetSize),0)}indexToOffset(t){if(t==this._nodes.length)return this.maxOffset;const e=this._nodes[t];if(!e)throw new v("model-nodelist-index-out-of-bounds",this);return this.getNodeStartOffset(e)}offsetToIndex(t){let e=0;for(const i of this._nodes){if(t>=e&&tgo)return t.slice(0,i).concat(e).concat(t.slice(i+n,t.length));{const s=Array.from(t);return s.splice(i,n,...e),s}}(this._nodes,Array.from(e),t,0)}_removeNodes(t,e=1){return this._nodes.splice(t,e)}toJSON(){return this._nodes.map((t=>t.toJSON()))}}class dh extends ch{constructor(t,e){super(e),this._data=t||""}get offsetSize(){return this.data.length}get data(){return this._data}toJSON(){const t=super.toJSON();return t.data=this.data,t}_clone(){return new dh(this.data,this.getAttributes())}static fromJSON(t){return new dh(t.data,t.attributes)}}dh.prototype.is=function(t){return"$text"===t||"model:$text"===t||"text"===t||"model:text"===t||"node"===t||"model:node"===t};class uh extends lh{constructor(t,e,i){if(super(),this.textNode=t,e<0||e>t.offsetSize)throw new v("model-textproxy-wrong-offsetintext",this);if(i<0||e+i>t.offsetSize)throw new v("model-textproxy-wrong-length",this);this.data=t.data.substring(e,e+i),this.offsetInText=e}get startOffset(){return null!==this.textNode.startOffset?this.textNode.startOffset+this.offsetInText:null}get offsetSize(){return this.data.length}get endOffset(){return null!==this.startOffset?this.startOffset+this.offsetSize:null}get isPartial(){return this.offsetSize!==this.textNode.offsetSize}get parent(){return this.textNode.parent}get root(){return this.textNode.root}getPath(){const t=this.textNode.getPath();return t.length>0&&(t[t.length-1]+=this.offsetInText),t}getAncestors(t={}){const e=[];let i=t.includeSelf?this:this.parent;for(;i;)e[t.parentFirst?"push":"unshift"](i),i=i.parent;return e}hasAttribute(t){return this.textNode.hasAttribute(t)}getAttribute(t){return this.textNode.getAttribute(t)}getAttributes(){return this.textNode.getAttributes()}getAttributeKeys(){return this.textNode.getAttributeKeys()}}uh.prototype.is=function(t){return"$textProxy"===t||"model:$textProxy"===t||"textProxy"===t||"model:textProxy"===t};class fh extends ch{constructor(t,e,i){super(e),this._children=new hh,this.name=t,i&&this._insertChild(0,i)}get childCount(){return this._children.length}get maxOffset(){return this._children.maxOffset}get isEmpty(){return 0===this.childCount}getChild(t){return this._children.getNode(t)}getChildren(){return this._children[Symbol.iterator]()}getChildIndex(t){return this._children.getNodeIndex(t)}getChildStartOffset(t){return this._children.getNodeStartOffset(t)}offsetToIndex(t){return this._children.offsetToIndex(t)}getNodeByPath(t){let e=this;for(const i of t)e=e.getChild(e.offsetToIndex(i));return e}findAncestor(t,e={}){let i=e.includeSelf?this:this.parent;for(;i;){if(i.name===t)return i;i=i.parent}return null}toJSON(){const t=super.toJSON();if(t.name=this.name,this._children.length>0){t.children=[];for(const e of this._children)t.children.push(e.toJSON())}return t}_clone(t=!1){const e=t?Array.from(this._children).map((t=>t._clone(!0))):void 0;return new fh(this.name,this.getAttributes(),e)}_appendChild(t){this._insertChild(this.childCount,t)}_insertChild(t,e){const i=function(t){if("string"==typeof t)return[new dh(t)];tt(t)||(t=[t]);return Array.from(t).map((t=>"string"==typeof t?new dh(t):t instanceof uh?new dh(t.data,t.getAttributes()):t))}(e);for(const t of i)null!==t.parent&&t._remove(),t.parent=this;this._children._insertNodes(t,i)}_removeChildren(t,e=1){const i=this._children._removeNodes(t,e);for(const t of i)t.parent=null;return i}static fromJSON(t){let e;if(t.children){e=[];for(const i of t.children)i.name?e.push(fh.fromJSON(i)):e.push(dh.fromJSON(i))}return new fh(t.name,t.attributes,e)}}fh.prototype.is=function(t,e){return e?e===this.name&&("element"===t||"model:element"===t):"element"===t||"model:element"===t||"node"===t||"model:node"===t};class mh{constructor(t){if(!t||!t.boundaries&&!t.startPosition)throw new v("model-tree-walker-no-start-position",null);const e=t.direction||"forward";if("forward"!=e&&"backward"!=e)throw new v("model-tree-walker-unknown-direction",t,{direction:e});this.direction=e,this.boundaries=t.boundaries||null,t.startPosition?this.position=t.startPosition.clone():this.position=ph._createAt(this.boundaries["backward"==this.direction?"end":"start"]),this.position.stickiness="toNone",this.singleCharacters=!!t.singleCharacters,this.shallow=!!t.shallow,this.ignoreElementEnd=!!t.ignoreElementEnd,this._boundaryStartParent=this.boundaries?this.boundaries.start.parent:null,this._boundaryEndParent=this.boundaries?this.boundaries.end.parent:null,this._visitedParent=this.position.parent}[Symbol.iterator](){return this}skip(t){let e,i,n,s;do{n=this.position,s=this._visitedParent,({done:e,value:i}=this.next())}while(!e&&t(i));e||(this.position=n,this._visitedParent=s)}next(){return"forward"==this.direction?this._next():this._previous()}_next(){const t=this.position,e=this.position.clone(),i=this._visitedParent;if(null===i.parent&&e.offset===i.maxOffset)return{done:!0,value:void 0};if(i===this._boundaryEndParent&&e.offset==this.boundaries.end.offset)return{done:!0,value:void 0};const n=wh(e,i),s=n||bh(e,i,n);if(s instanceof fh)return this.shallow?e.offset++:(e.path.push(0),this._visitedParent=s),this.position=e,gh("elementStart",s,t,e,1);if(s instanceof dh){let n;if(this.singleCharacters)n=1;else{let t=s.endOffset;this._boundaryEndParent==i&&this.boundaries.end.offsett&&(t=this.boundaries.start.offset),n=e.offset-t}const s=e.offset-o.startOffset,r=new uh(o,s-n,n);return e.offset-=n,this.position=e,gh("text",r,t,e,n)}return e.path.pop(),this.position=e,this._visitedParent=i.parent,gh("elementStart",i,t,e,1)}}function gh(t,e,i,n,s){return{done:!1,value:{type:t,item:e,previousPosition:i,nextPosition:n,length:s}}}class ph extends lh{constructor(t,e,i="toNone"){if(super(),!t.is("element")&&!t.is("documentFragment"))throw new v("model-position-root-invalid",t);if(!(e instanceof Array)||0===e.length)throw new v("model-position-path-incorrect-format",t,{path:e});t.is("rootElement")?e=e.slice():(e=[...t.getPath(),...e],t=t.root),this.root=t,this.path=e,this.stickiness=i}get offset(){return this.path[this.path.length-1]}set offset(t){this.path[this.path.length-1]=t}get parent(){let t=this.root;for(let e=0;e1)return!1;if(1===e)return vh(t,this,i);if(-1===e)return vh(this,t,i)}return this.path.length===t.path.length||(this.path.length>t.path.length?yh(this.path,e):yh(t.path,e))}hasSameParentAs(t){if(this.root!==t.root)return!1;return"same"==X(this.getParentPath(),t.getParentPath())}getTransformedByOperation(t){let e;switch(t.type){case"insert":e=this._getTransformedByInsertOperation(t);break;case"move":case"remove":case"reinsert":e=this._getTransformedByMoveOperation(t);break;case"split":e=this._getTransformedBySplitOperation(t);break;case"merge":e=this._getTransformedByMergeOperation(t);break;default:e=ph._createAt(this)}return e}_getTransformedByInsertOperation(t){return this._getTransformedByInsertion(t.position,t.howMany)}_getTransformedByMoveOperation(t){return this._getTransformedByMove(t.sourcePosition,t.targetPosition,t.howMany)}_getTransformedBySplitOperation(t){const e=t.movedRange;return e.containsPosition(this)||e.start.isEqual(this)&&"toNext"==this.stickiness?this._getCombined(t.splitPosition,t.moveTargetPosition):t.graveyardPosition?this._getTransformedByMove(t.graveyardPosition,t.insertionPosition,1):this._getTransformedByInsertion(t.insertionPosition,1)}_getTransformedByMergeOperation(t){const e=t.movedRange;let i;return e.containsPosition(this)||e.start.isEqual(this)?(i=this._getCombined(t.sourcePosition,t.targetPosition),t.sourcePosition.isBefore(t.targetPosition)&&(i=i._getTransformedByDeletion(t.deletionPosition,1))):i=this.isEqual(t.deletionPosition)?ph._createAt(t.deletionPosition):this._getTransformedByMove(t.deletionPosition,t.graveyardPosition,1),i}_getTransformedByDeletion(t,e){const i=ph._createAt(this);if(this.root!=t.root)return i;if("same"==X(t.getParentPath(),this.getParentPath())){if(t.offsetthis.offset)return null;i.offset-=e}}else if("prefix"==X(t.getParentPath(),this.getParentPath())){const n=t.path.length-1;if(t.offset<=this.path[n]){if(t.offset+e>this.path[n])return null;i.path[n]-=e}}return i}_getTransformedByInsertion(t,e){const i=ph._createAt(this);if(this.root!=t.root)return i;if("same"==X(t.getParentPath(),this.getParentPath()))(t.offset=e;){if(t.path[n]+s!==i.maxOffset)return!1;s=1,n--,i=i.parent}return!0}(t,i+1))}function yh(t,e){for(;ee+1;){const e=n.maxOffset-i.offset;0!==e&&t.push(new kh(i,i.getShiftedBy(e))),i.path=i.path.slice(0,-1),i.offset++,n=n.parent}for(;i.path.length<=this.end.path.length;){const e=this.end.path[i.path.length-1],n=e-i.offset;0!==n&&t.push(new kh(i,i.getShiftedBy(n))),i.offset=e,i.path.push(0)}return t}getWalker(t={}){return t.boundaries=this,new mh(t)}*getItems(t={}){t.boundaries=this,t.ignoreElementEnd=!0;const e=new mh(t);for(const t of e)yield t.item}*getPositions(t={}){t.boundaries=this;const e=new mh(t);yield e.position;for(const t of e)yield t.nextPosition}getTransformedByOperation(t){switch(t.type){case"insert":return this._getTransformedByInsertOperation(t);case"move":case"remove":case"reinsert":return this._getTransformedByMoveOperation(t);case"split":return[this._getTransformedBySplitOperation(t)];case"merge":return[this._getTransformedByMergeOperation(t)]}return[new kh(this.start,this.end)]}getTransformedByOperations(t){const e=[new kh(this.start,this.end)];for(const i of t)for(let t=0;t0?new this(i,n):new this(n,i)}static _createIn(t){return new this(ph._createAt(t,0),ph._createAt(t,t.maxOffset))}static _createOn(t){return this._createFromPositionAndShift(ph._createBefore(t),t.offsetSize)}static _createFromRanges(t){if(0===t.length)throw new v("range-create-from-ranges-empty-array",null);if(1==t.length)return t[0].clone();const e=t[0];t.sort(((t,e)=>t.start.isAfter(e.start)?1:-1));const i=t.indexOf(e),n=new this(e.start,e.end);if(i>0)for(let e=i-1;t[e].end.isEqual(n.start);e++)n.start=ph._createAt(t[e].start);for(let e=i+1;e{if(e.viewPosition)return;const i=this._modelToViewMapping.get(e.modelPosition.parent);if(!i)throw new v("mapping-model-position-view-parent-not-found",this,{modelPosition:e.modelPosition});e.viewPosition=this.findPositionIn(i,e.modelPosition.offset)}),{priority:"low"}),this.on("viewToModelPosition",((t,e)=>{if(e.modelPosition)return;const i=this.findMappedViewAncestor(e.viewPosition),n=this._viewToModelMapping.get(i),s=this._toModelOffset(e.viewPosition.parent,e.viewPosition.offset,i);e.modelPosition=ph._createAt(n,s)}),{priority:"low"})}bindElements(t,e){this._modelToViewMapping.set(t,e),this._viewToModelMapping.set(e,t)}unbindViewElement(t,e={}){const i=this.toModelElement(t);if(this._elementToMarkerNames.has(t))for(const e of this._elementToMarkerNames.get(t))this._unboundMarkerNames.add(e);e.defer?this._deferredBindingRemovals.set(t,t.root):(this._viewToModelMapping.delete(t),this._modelToViewMapping.get(i)==t&&this._modelToViewMapping.delete(i))}unbindModelElement(t){const e=this.toViewElement(t);this._modelToViewMapping.delete(t),this._viewToModelMapping.get(e)==t&&this._viewToModelMapping.delete(e)}bindElementToMarker(t,e){const i=this._markerNameToElements.get(e)||new Set;i.add(t);const n=this._elementToMarkerNames.get(t)||new Set;n.add(e),this._markerNameToElements.set(e,i),this._elementToMarkerNames.set(t,n)}unbindElementFromMarkerName(t,e){const i=this._markerNameToElements.get(e);i&&(i.delete(t),0==i.size&&this._markerNameToElements.delete(e));const n=this._elementToMarkerNames.get(t);n&&(n.delete(e),0==n.size&&this._elementToMarkerNames.delete(t))}flushUnboundMarkerNames(){const t=Array.from(this._unboundMarkerNames);return this._unboundMarkerNames.clear(),t}flushDeferredBindings(){for(const[t,e]of this._deferredBindingRemovals)t.root==e&&this.unbindViewElement(t);this._deferredBindingRemovals=new Map}clearBindings(){this._modelToViewMapping=new WeakMap,this._viewToModelMapping=new WeakMap,this._markerNameToElements=new Map,this._elementToMarkerNames=new Map,this._unboundMarkerNames=new Set,this._deferredBindingRemovals=new Map}toModelElement(t){return this._viewToModelMapping.get(t)}toViewElement(t){return this._modelToViewMapping.get(t)}toModelRange(t){return new kh(this.toModelPosition(t.start),this.toModelPosition(t.end))}toViewRange(t){return new ja(this.toViewPosition(t.start),this.toViewPosition(t.end))}toModelPosition(t){const e={viewPosition:t,mapper:this};return this.fire("viewToModelPosition",e),e.modelPosition}toViewPosition(t,e={}){const i={modelPosition:t,mapper:this,isPhantom:e.isPhantom};return this.fire("modelToViewPosition",i),i.viewPosition}markerNameToElements(t){const e=this._markerNameToElements.get(t);if(!e)return null;const i=new Set;for(const t of e)if(t.is("attributeElement"))for(const e of t.getElementsWithSameId())i.add(e);else i.add(t);return i}registerViewToModelLength(t,e){this._viewToModelLengthCallbacks.set(t,e)}findMappedViewAncestor(t){let e=t.parent;for(;!this._viewToModelMapping.has(e);)e=e.parent;return e}_toModelOffset(t,e,i){if(i!=t){return this._toModelOffset(t.parent,t.index,i)+this._toModelOffset(t,e,t)}if(t.is("$text"))return e;let n=0;for(let i=0;i1?e[0]+":"+e[1]:e[0]}class Ph extends(R()){constructor(t){super(),this._conversionApi={dispatcher:this,...t},this._firedEventsMap=new WeakMap}convertChanges(t,e,i){const n=this._createConversionApi(i,t.getRefreshedItems());for(const e of t.getMarkersToRemove())this._convertMarkerRemove(e.name,e.range,n);const s=this._reduceChanges(t.getChanges());for(const t of s)"insert"===t.type?this._convertInsert(kh._createFromPositionAndShift(t.position,t.length),n):"reinsert"===t.type?this._convertReinsert(kh._createFromPositionAndShift(t.position,t.length),n):"remove"===t.type?this._convertRemove(t.position,t.length,t.name,n):this._convertAttribute(t.range,t.attributeKey,t.attributeOldValue,t.attributeNewValue,n);for(const t of n.mapper.flushUnboundMarkerNames()){const i=e.get(t).getRange();this._convertMarkerRemove(t,i,n),this._convertMarkerAdd(t,i,n)}for(const e of t.getMarkersToAdd())this._convertMarkerAdd(e.name,e.range,n);n.mapper.flushDeferredBindings(),n.consumable.verifyAllConsumed("insert")}convert(t,e,i,n={}){const s=this._createConversionApi(i,void 0,n);this._convertInsert(t,s);for(const[t,i]of e)this._convertMarkerAdd(t,i,s);s.consumable.verifyAllConsumed("insert")}convertSelection(t,e,i){const n=Array.from(e.getMarkersAtPosition(t.getFirstPosition())),s=this._createConversionApi(i);if(this._addConsumablesForSelection(s.consumable,t,n),this.fire("selection",{selection:t},s),t.isCollapsed){for(const e of n){const i=e.getRange();if(!Th(t.getFirstPosition(),e,s.mapper))continue;const n={item:t,markerName:e.name,markerRange:i};s.consumable.test(t,"addMarker:"+e.name)&&this.fire(`addMarker:${e.name}`,n,s)}for(const e of t.getAttributeKeys()){const i={item:t,range:t.getFirstRange(),attributeKey:e,attributeOldValue:null,attributeNewValue:t.getAttribute(e)};s.consumable.test(t,"attribute:"+i.attributeKey)&&this.fire(`attribute:${i.attributeKey}:$text`,i,s)}}}_convertInsert(t,e,i={}){i.doNotAddConsumables||this._addConsumablesForInsert(e.consumable,Array.from(t));for(const i of Array.from(t.getWalker({shallow:!0})).map(Eh))this._testAndFire("insert",i,e)}_convertRemove(t,e,i,n){this.fire(`remove:${i}`,{position:t,length:e},n)}_convertAttribute(t,e,i,n,s){this._addConsumablesForRange(s.consumable,t,`attribute:${e}`);for(const o of t){const t={item:o.item,range:kh._createFromPositionAndShift(o.previousPosition,o.length),attributeKey:e,attributeOldValue:i,attributeNewValue:n};this._testAndFire(`attribute:${e}`,t,s)}}_convertReinsert(t,e){const i=Array.from(t.getWalker({shallow:!0}));this._addConsumablesForInsert(e.consumable,i);for(const t of i.map(Eh))this._testAndFire("insert",{...t,reconversion:!0},e)}_convertMarkerAdd(t,e,i){if("$graveyard"==e.root.rootName)return;const n=`addMarker:${t}`;if(i.consumable.add(e,n),this.fire(n,{markerName:t,markerRange:e},i),i.consumable.consume(e,n)){this._addConsumablesForRange(i.consumable,e,n);for(const s of e.getItems()){if(!i.consumable.test(s,n))continue;const o={item:s,range:kh._createOn(s),markerName:t,markerRange:e};this.fire(n,o,i)}}}_convertMarkerRemove(t,e,i){"$graveyard"!=e.root.rootName&&this.fire(`removeMarker:${t}`,{markerName:t,markerRange:e},i)}_reduceChanges(t){const e={changes:t};return this.fire("reduceChanges",e),e.changes}_addConsumablesForInsert(t,e){for(const i of e){const e=i.item;if(null===t.test(e,"insert")){t.add(e,"insert");for(const i of e.getAttributeKeys())t.add(e,"attribute:"+i)}}return t}_addConsumablesForRange(t,e,i){for(const n of e.getItems())t.add(n,i);return t}_addConsumablesForSelection(t,e,i){t.add(e,"selection");for(const n of i)t.add(e,"addMarker:"+n.name);for(const i of e.getAttributeKeys())t.add(e,"attribute:"+i);return t}_testAndFire(t,e,i){const n=function(t,e){const i=e.item.is("element")?e.item.name:"$text";return`${t}:${i}`}(t,e),s=e.item.is("$textProxy")?i.consumable._getSymbolForTextProxy(e.item):e.item,o=this._firedEventsMap.get(i),r=o.get(s);if(r){if(r.has(n))return;r.add(n)}else o.set(s,new Set([n]));this.fire(n,e,i)}_testAndFireAddAttributes(t,e){const i={item:t,range:kh._createOn(t)};for(const t of i.item.getAttributeKeys())i.attributeKey=t,i.attributeOldValue=null,i.attributeNewValue=i.item.getAttribute(t),this._testAndFire(`attribute:${t}`,i,e)}_createConversionApi(t,e=new Set,i={}){const n={...this._conversionApi,consumable:new xh,writer:t,options:i,convertItem:t=>this._convertInsert(kh._createOn(t),n),convertChildren:t=>this._convertInsert(kh._createIn(t),n,{doNotAddConsumables:!0}),convertAttributes:t=>this._testAndFireAddAttributes(t,n),canReuseView:t=>!e.has(n.mapper.toModelElement(t))};return this._firedEventsMap.set(n,new Map),n}}function Th(t,e,i){const n=e.getRange(),s=Array.from(t.getAncestors());s.shift(),s.reverse();return!s.some((t=>{if(n.containsItem(t)){return!!i.toViewElement(t).getCustomProperty("addHighlight")}}))}function Eh(t){return{item:t.item,range:kh._createFromPositionAndShift(t.previousPosition,t.length)}}class Sh extends(R(lh)){constructor(...t){super(),this._lastRangeBackward=!1,this._attrs=new Map,this._ranges=[],t.length&&this.setTo(...t)}get anchor(){if(this._ranges.length>0){const t=this._ranges[this._ranges.length-1];return this._lastRangeBackward?t.end:t.start}return null}get focus(){if(this._ranges.length>0){const t=this._ranges[this._ranges.length-1];return this._lastRangeBackward?t.start:t.end}return null}get isCollapsed(){return 1===this._ranges.length&&this._ranges[0].isCollapsed}get rangeCount(){return this._ranges.length}get isBackward(){return!this.isCollapsed&&this._lastRangeBackward}isEqual(t){if(this.rangeCount!=t.rangeCount)return!1;if(0===this.rangeCount)return!0;if(!this.anchor.isEqual(t.anchor)||!this.focus.isEqual(t.focus))return!1;for(const e of this._ranges){let i=!1;for(const n of t._ranges)if(e.isEqual(n)){i=!0;break}if(!i)return!1}return!0}*getRanges(){for(const t of this._ranges)yield new kh(t.start,t.end)}getFirstRange(){let t=null;for(const e of this._ranges)t&&!e.start.isBefore(t.start)||(t=e);return t?new kh(t.start,t.end):null}getLastRange(){let t=null;for(const e of this._ranges)t&&!e.end.isAfter(t.end)||(t=e);return t?new kh(t.start,t.end):null}getFirstPosition(){const t=this.getFirstRange();return t?t.start.clone():null}getLastPosition(){const t=this.getLastRange();return t?t.end.clone():null}setTo(...t){let[e,i,n]=t;if("object"==typeof i&&(n=i,i=void 0),null===e)this._setRanges([]);else if(e instanceof Sh)this._setRanges(e.getRanges(),e.isBackward);else if(e&&"function"==typeof e.getRanges)this._setRanges(e.getRanges(),e.isBackward);else if(e instanceof kh)this._setRanges([e],!!n&&!!n.backward);else if(e instanceof ph)this._setRanges([new kh(e)]);else if(e instanceof ch){const t=!!n&&!!n.backward;let s;if("in"==i)s=kh._createIn(e);else if("on"==i)s=kh._createOn(e);else{if(void 0===i)throw new v("model-selection-setto-required-second-parameter",[this,e]);s=new kh(ph._createAt(e,i))}this._setRanges([s],t)}else{if(!tt(e))throw new v("model-selection-setto-not-selectable",[this,e]);this._setRanges(e,n&&!!n.backward)}}_setRanges(t,e=!1){const i=Array.from(t),n=i.some((e=>{if(!(e instanceof kh))throw new v("model-selection-set-ranges-not-range",[this,t]);return this._ranges.every((t=>!t.isEqual(e)))}));(i.length!==this._ranges.length||n)&&(this._replaceAllRanges(i),this._lastRangeBackward=!!e,this.fire("change:range",{directChange:!0}))}setFocus(t,e){if(null===this.anchor)throw new v("model-selection-setfocus-no-ranges",[this,t]);const i=ph._createAt(t,e);if("same"==i.compareWith(this.focus))return;const n=this.anchor;this._ranges.length&&this._popRange(),"before"==i.compareWith(n)?(this._pushRange(new kh(i,n)),this._lastRangeBackward=!0):(this._pushRange(new kh(n,i)),this._lastRangeBackward=!1),this.fire("change:range",{directChange:!0})}getAttribute(t){return this._attrs.get(t)}getAttributes(){return this._attrs.entries()}getAttributeKeys(){return this._attrs.keys()}hasAttribute(t){return this._attrs.has(t)}removeAttribute(t){this.hasAttribute(t)&&(this._attrs.delete(t),this.fire("change:attribute",{attributeKeys:[t],directChange:!0}))}setAttribute(t,e){this.getAttribute(t)!==e&&(this._attrs.set(t,e),this.fire("change:attribute",{attributeKeys:[t],directChange:!0}))}getSelectedElement(){return 1!==this.rangeCount?null:this.getFirstRange().getContainedElement()}*getSelectedBlocks(){const t=new WeakSet;for(const e of this.getRanges()){const i=Ih(e.start,t);i&&Vh(i,e)&&(yield i);for(const i of e.getWalker()){const n=i.item;"elementEnd"==i.type&&Oh(n,t,e)&&(yield n)}const n=Ih(e.end,t);n&&!e.end.isTouching(ph._createAt(n,0))&&Vh(n,e)&&(yield n)}}containsEntireContent(t=this.anchor.root){const e=ph._createAt(t,0),i=ph._createAt(t,"end");return e.isTouching(this.getFirstPosition())&&i.isTouching(this.getLastPosition())}_pushRange(t){this._checkRange(t),this._ranges.push(new kh(t.start,t.end))}_checkRange(t){for(let e=0;e0;)this._popRange()}_popRange(){this._ranges.pop()}}function Rh(t,e){return!e.has(t)&&(e.add(t),t.root.document.model.schema.isBlock(t)&&!!t.parent)}function Oh(t,e,i){return Rh(t,e)&&Vh(t,i)}function Ih(t,e){const i=t.parent.root.document.model.schema,n=t.parent.getAncestors({parentFirst:!0,includeSelf:!0});let s=!1;const o=n.find((t=>!s&&(s=i.isLimit(t),!s&&Rh(t,e))));return n.forEach((t=>e.add(t))),o}function Vh(t,e){const i=function(t){const e=t.root.document.model.schema;let i=t.parent;for(;i;){if(e.isBlock(i))return i;i=i.parent}}(t);if(!i)return!0;return!e.containsRange(kh._createOn(i),!0)}Sh.prototype.is=function(t){return"selection"===t||"model:selection"===t};class Mh extends(R(kh)){constructor(t,e){super(t,e),Nh.call(this)}detach(){this.stopListening()}toRange(){return new kh(this.start,this.end)}static fromRange(t){return new Mh(t.start,t.end)}}function Nh(){this.listenTo(this.root.document.model,"applyOperation",((t,e)=>{const i=e[0];i.isDocumentOperation&&Bh.call(this,i)}),{priority:"low"})}function Bh(t){const e=this.getTransformedByOperation(t),i=kh._createFromRanges(e),n=!i.isEqual(this),s=function(t,e){switch(e.type){case"insert":return t.containsPosition(e.position);case"move":case"remove":case"reinsert":case"merge":return t.containsPosition(e.sourcePosition)||t.start.isEqual(e.sourcePosition)||t.containsPosition(e.targetPosition);case"split":return t.containsPosition(e.splitPosition)||t.containsPosition(e.insertionPosition)}return!1}(this,t);let o=null;if(n){"$graveyard"==i.root.rootName&&(o="remove"==t.type?t.sourcePosition:t.deletionPosition);const e=this.toRange();this.start=i.start,this.end=i.end,this.fire("change:range",e,{deletionPosition:o})}else s&&this.fire("change:content",this.toRange(),{deletionPosition:o})}Mh.prototype.is=function(t){return"liveRange"===t||"model:liveRange"===t||"range"==t||"model:range"===t};const Dh="selection:";class Fh extends(R(lh)){constructor(t){super(),this._selection=new Lh(t),this._selection.delegate("change:range").to(this),this._selection.delegate("change:attribute").to(this),this._selection.delegate("change:marker").to(this)}get isCollapsed(){return this._selection.isCollapsed}get anchor(){return this._selection.anchor}get focus(){return this._selection.focus}get rangeCount(){return this._selection.rangeCount}get hasOwnRange(){return this._selection.hasOwnRange}get isBackward(){return this._selection.isBackward}get isGravityOverridden(){return this._selection.isGravityOverridden}get markers(){return this._selection.markers}get _ranges(){return this._selection._ranges}getRanges(){return this._selection.getRanges()}getFirstPosition(){return this._selection.getFirstPosition()}getLastPosition(){return this._selection.getLastPosition()}getFirstRange(){return this._selection.getFirstRange()}getLastRange(){return this._selection.getLastRange()}getSelectedBlocks(){return this._selection.getSelectedBlocks()}getSelectedElement(){return this._selection.getSelectedElement()}containsEntireContent(t){return this._selection.containsEntireContent(t)}destroy(){this._selection.destroy()}getAttributeKeys(){return this._selection.getAttributeKeys()}getAttributes(){return this._selection.getAttributes()}getAttribute(t){return this._selection.getAttribute(t)}hasAttribute(t){return this._selection.hasAttribute(t)}refresh(){this._selection.updateMarkers(),this._selection._updateAttributes(!1)}observeMarkers(t){this._selection.observeMarkers(t)}_setFocus(t,e){this._selection.setFocus(t,e)}_setTo(...t){this._selection.setTo(...t)}_setAttribute(t,e){this._selection.setAttribute(t,e)}_removeAttribute(t){this._selection.removeAttribute(t)}_getStoredAttributes(){return this._selection.getStoredAttributes()}_overrideGravity(){return this._selection.overrideGravity()}_restoreGravity(t){this._selection.restoreGravity(t)}static _getStoreAttributeKey(t){return Dh+t}static _isStoreAttributeKey(t){return t.startsWith(Dh)}}Fh.prototype.is=function(t){return"selection"===t||"model:selection"==t||"documentSelection"==t||"model:documentSelection"==t};class Lh extends Sh{constructor(t){super(),this.markers=new co({idProperty:"name"}),this._attributePriority=new Map,this._selectionRestorePosition=null,this._hasChangedRange=!1,this._overriddenGravityRegister=new Set,this._observedMarkers=new Set,this._model=t.model,this._document=t,this.listenTo(this._model,"applyOperation",((t,e)=>{const i=e[0];i.isDocumentOperation&&"marker"!=i.type&&"rename"!=i.type&&"noop"!=i.type&&(0==this._ranges.length&&this._selectionRestorePosition&&this._fixGraveyardSelection(this._selectionRestorePosition),this._selectionRestorePosition=null,this._hasChangedRange&&(this._hasChangedRange=!1,this.fire("change:range",{directChange:!1})))}),{priority:"lowest"}),this.on("change:range",(()=>{this._validateSelectionRanges(this.getRanges())})),this.listenTo(this._model.markers,"update",((t,e,i,n)=>{this._updateMarker(e,n)})),this.listenTo(this._document,"change",((t,e)=>{!function(t,e){const i=t.document.differ;for(const n of i.getChanges()){if("insert"!=n.type)continue;const i=n.position.parent;n.length===i.maxOffset&&t.enqueueChange(e,(t=>{const e=Array.from(i.getAttributeKeys()).filter((t=>t.startsWith(Dh)));for(const n of e)t.removeAttribute(n,i)}))}}(this._model,e)}))}get isCollapsed(){return 0===this._ranges.length?this._document._getDefaultRange().isCollapsed:super.isCollapsed}get anchor(){return super.anchor||this._document._getDefaultRange().start}get focus(){return super.focus||this._document._getDefaultRange().end}get rangeCount(){return this._ranges.length?this._ranges.length:1}get hasOwnRange(){return this._ranges.length>0}get isGravityOverridden(){return!!this._overriddenGravityRegister.size}destroy(){for(let t=0;t{if(this._hasChangedRange=!0,e.root==this._document.graveyard){this._selectionRestorePosition=n.deletionPosition;const t=this._ranges.indexOf(e);this._ranges.splice(t,1),e.detach()}})),e}updateMarkers(){if(!this._observedMarkers.size)return;const t=[];let e=!1;for(const e of this._model.markers){const i=e.name.split(":",1)[0];if(!this._observedMarkers.has(i))continue;const n=e.getRange();for(const i of this.getRanges())n.containsRange(i,!i.isCollapsed)&&t.push(e)}const i=Array.from(this.markers);for(const i of t)this.markers.has(i)||(this.markers.add(i),e=!0);for(const i of Array.from(this.markers))t.includes(i)||(this.markers.remove(i),e=!0);e&&this.fire("change:marker",{oldMarkers:i,directChange:!1})}_updateMarker(t,e){const i=t.name.split(":",1)[0];if(!this._observedMarkers.has(i))return;let n=!1;const s=Array.from(this.markers),o=this.markers.has(t);if(e){let i=!1;for(const t of this.getRanges())if(e.containsRange(t,!t.isCollapsed)){i=!0;break}i&&!o?(this.markers.add(t),n=!0):!i&&o&&(this.markers.remove(t),n=!0)}else o&&(this.markers.remove(t),n=!0);n&&this.fire("change:marker",{oldMarkers:s,directChange:!1})}_updateAttributes(t){const e=mo(this._getSurroundingAttributes()),i=mo(this.getAttributes());if(t)this._attributePriority=new Map,this._attrs=new Map;else for(const[t,e]of this._attributePriority)"low"==e&&(this._attrs.delete(t),this._attributePriority.delete(t));this._setAttributesTo(e);const n=[];for(const[t,e]of this.getAttributes())i.has(t)&&i.get(t)===e||n.push(t);for(const[t]of i)this.hasAttribute(t)||n.push(t);n.length>0&&this.fire("change:attribute",{attributeKeys:n,directChange:!1})}_setAttribute(t,e,i=!0){const n=i?"normal":"low";if("low"==n&&"normal"==this._attributePriority.get(t))return!1;return super.getAttribute(t)!==e&&(this._attrs.set(t,e),this._attributePriority.set(t,n),!0)}_removeAttribute(t,e=!0){const i=e?"normal":"low";return("low"!=i||"normal"!=this._attributePriority.get(t))&&(this._attributePriority.set(t,i),!!super.hasAttribute(t)&&(this._attrs.delete(t),!0))}_setAttributesTo(t){const e=new Set;for(const[e,i]of this.getAttributes())t.get(e)!==i&&this._removeAttribute(e,!1);for(const[i,n]of t){this._setAttribute(i,n,!1)&&e.add(i)}return e}*getStoredAttributes(){const t=this.getFirstPosition().parent;if(this.isCollapsed&&t.isEmpty)for(const e of t.getAttributeKeys())if(e.startsWith(Dh)){const i=e.substr(Dh.length);yield[i,t.getAttribute(e)]}}_getSurroundingAttributes(){const t=this.getFirstPosition(),e=this._model.schema;let i=null;if(this.isCollapsed){const n=t.textNode?t.textNode:t.nodeBefore,s=t.textNode?t.textNode:t.nodeAfter;if(this.isGravityOverridden||(i=zh(n)),i||(i=zh(s)),!this.isGravityOverridden&&!i){let t=n;for(;t&&!e.isInline(t)&&!i;)t=t.previousSibling,i=zh(t)}if(!i){let t=s;for(;t&&!e.isInline(t)&&!i;)t=t.nextSibling,i=zh(t)}i||(i=this.getStoredAttributes())}else{const t=this.getFirstRange();for(const n of t){if(n.item.is("element")&&e.isObject(n.item))break;if("text"==n.type){i=n.item.getAttributes();break}}}return i}_fixGraveyardSelection(t){const e=this._model.schema.getNearestSelectionRange(t);e&&this._pushRange(e)}}function zh(t){return t instanceof uh||t instanceof dh?t.getAttributes():null}class Hh{constructor(t){this._dispatchers=t}add(t){for(const e of this._dispatchers)t(e);return this}}var jh=1,$h=4;const Wh=function(t){return os(t,jh|$h)};class qh extends Hh{elementToElement(t){return this.add(function(t){const e=Gh(t.model),i=Jh(t.view,"container");e.attributes.length&&(e.children=!0);return n=>{n.on(`insert:${e.name}`,function(t,e=nd){return(i,n,s)=>{if(!e(n.item,s.consumable,{preflight:!0}))return;const o=t(n.item,s,n);if(!o)return;e(n.item,s.consumable);const r=s.mapper.toViewPosition(n.range.start);s.mapper.bindElements(n.item,o),s.writer.insert(r,o),s.convertAttributes(n.item),ed(o,n.item.getChildren(),s,{reconversion:n.reconversion})}}(i,td(e)),{priority:t.converterPriority||"normal"}),(e.children||e.attributes.length)&&n.on("reduceChanges",Xh(e),{priority:"low"})}}(t))}elementToStructure(t){return this.add(function(t){const e=Gh(t.model),i=Jh(t.view,"container");return e.children=!0,n=>{if(n._conversionApi.schema.checkChild(e.name,"$text"))throw new v("conversion-element-to-structure-disallowed-text",n,{elementName:e.name});var s,o;n.on(`insert:${e.name}`,(s=i,o=td(e),(t,e,i)=>{if(!o(e.item,i.consumable,{preflight:!0}))return;const n=new Map;i.writer._registerSlotFactory(function(t,e,i){return(n,s="children")=>{const o=n.createContainerElement("$slot");let r=null;if("children"===s)r=Array.from(t.getChildren());else{if("function"!=typeof s)throw new v("conversion-slot-mode-unknown",i.dispatcher,{modeOrFilter:s});r=Array.from(t.getChildren()).filter((t=>s(t)))}return e.set(o,r),o}}(e.item,n,i));const r=s(e.item,i,e);if(i.writer._clearSlotFactory(),!r)return;!function(t,e,i){const n=Array.from(e.values()).flat(),s=new Set(n);if(s.size!=n.length)throw new v("conversion-slot-filter-overlap",i.dispatcher,{element:t});if(s.size!=t.childCount)throw new v("conversion-slot-filter-incomplete",i.dispatcher,{element:t})}(e.item,n,i),o(e.item,i.consumable);const a=i.mapper.toViewPosition(e.range.start);i.mapper.bindElements(e.item,r),i.writer.insert(a,r),i.convertAttributes(e.item),function(t,e,i,n){i.mapper.on("modelToViewPosition",r,{priority:"highest"});let s=null,o=null;for([s,o]of e)ed(t,o,i,n),i.writer.move(i.writer.createRangeIn(s),i.writer.createPositionBefore(s)),i.writer.remove(s);function r(t,e){const i=e.modelPosition.nodeAfter,n=o.indexOf(i);n<0||(e.viewPosition=e.mapper.findPositionIn(s,n))}i.mapper.off("modelToViewPosition",r)}(r,n,i,{reconversion:e.reconversion})}),{priority:t.converterPriority||"normal"}),n.on("reduceChanges",Xh(e),{priority:"low"})}}(t))}attributeToElement(t){return this.add(function(t){t=Wh(t);let e=t.model;"string"==typeof e&&(e={key:e});let i=`attribute:${e.key}`;e.name&&(i+=":"+e.name);if(e.values)for(const i of e.values)t.view[i]=Jh(t.view[i],"attribute");else t.view=Jh(t.view,"attribute");const n=Qh(t);return e=>{e.on(i,function(t){return(e,i,n)=>{if(!n.consumable.test(i.item,e.name))return;const s=t(i.attributeOldValue,n,i),o=t(i.attributeNewValue,n,i);if(!s&&!o)return;n.consumable.consume(i.item,e.name);const r=n.writer,a=r.document.selection;if(i.item instanceof Sh||i.item instanceof Fh)r.wrap(a.getFirstRange(),o);else{let t=n.mapper.toViewRange(i.range);null!==i.attributeOldValue&&s&&(t=r.unwrap(t,s)),null!==i.attributeNewValue&&o&&r.wrap(t,o)}}}(n),{priority:t.converterPriority||"normal"})}}(t))}attributeToAttribute(t){return this.add(function(t){t=Wh(t);let e=t.model;"string"==typeof e&&(e={key:e});let i=`attribute:${e.key}`;e.name&&(i+=":"+e.name);if(e.values)for(const i of e.values)t.view[i]=Yh(t.view[i]);else t.view=Yh(t.view);const n=Qh(t);return e=>{var s;e.on(i,(s=n,(t,e,i)=>{if(!i.consumable.test(e.item,t.name))return;const n=s(e.attributeOldValue,i,e),o=s(e.attributeNewValue,i,e);if(!n&&!o)return;i.consumable.consume(e.item,t.name);const r=i.mapper.toViewElement(e.item),a=i.writer;if(!r)throw new v("conversion-attribute-to-attribute-on-text",i.dispatcher,e);if(null!==e.attributeOldValue&&n)if("class"==n.key){const t=so(n.value);for(const e of t)a.removeClass(e,r)}else if("style"==n.key){const t=Object.keys(n.value);for(const e of t)a.removeStyle(e,r)}else a.removeAttribute(n.key,r);if(null!==e.attributeNewValue&&o)if("class"==o.key){const t=so(o.value);for(const e of t)a.addClass(e,r)}else if("style"==o.key){const t=Object.keys(o.value);for(const e of t)a.setStyle(e,o.value[e],r)}else a.setAttribute(o.key,o.value,r)}),{priority:t.converterPriority||"normal"})}}(t))}markerToElement(t){return this.add(function(t){const e=Jh(t.view,"ui");return i=>{var n;i.on(`addMarker:${t.model}`,(n=e,(t,e,i)=>{e.isOpening=!0;const s=n(e,i);e.isOpening=!1;const o=n(e,i);if(!s||!o)return;const r=e.markerRange;if(r.isCollapsed&&!i.consumable.consume(r,t.name))return;for(const e of r)if(!i.consumable.consume(e.item,t.name))return;const a=i.mapper,l=i.writer;l.insert(a.toViewPosition(r.start),s),i.mapper.bindElementToMarker(s,e.markerName),r.isCollapsed||(l.insert(a.toViewPosition(r.end),o),i.mapper.bindElementToMarker(o,e.markerName)),t.stop()}),{priority:t.converterPriority||"normal"}),i.on(`removeMarker:${t.model}`,((t,e,i)=>{const n=i.mapper.markerNameToElements(e.markerName);if(n){for(const t of n)i.mapper.unbindElementFromMarkerName(t,e.markerName),i.writer.clear(i.writer.createRangeOn(t),t);i.writer.clearClonedElementsGroup(e.markerName),t.stop()}}),{priority:t.converterPriority||"normal"})}}(t))}markerToHighlight(t){return this.add(function(t){return e=>{var i;e.on(`addMarker:${t.model}`,(i=t.view,(t,e,n)=>{if(!e.item)return;if(!(e.item instanceof Sh||e.item instanceof Fh||e.item.is("$textProxy")))return;const s=Zh(i,e,n);if(!s)return;if(!n.consumable.consume(e.item,t.name))return;const o=n.writer,r=Uh(o,s),a=o.document.selection;if(e.item instanceof Sh||e.item instanceof Fh)o.wrap(a.getFirstRange(),r);else{const t=n.mapper.toViewRange(e.range),i=o.wrap(t,r);for(const t of i.getItems())if(t.is("attributeElement")&&t.isSimilar(r)){n.mapper.bindElementToMarker(t,e.markerName);break}}}),{priority:t.converterPriority||"normal"}),e.on(`addMarker:${t.model}`,function(t){return(e,i,n)=>{if(!i.item)return;if(!(i.item instanceof fh))return;const s=Zh(t,i,n);if(!s)return;if(!n.consumable.test(i.item,e.name))return;const o=n.mapper.toViewElement(i.item);if(o&&o.getCustomProperty("addHighlight")){n.consumable.consume(i.item,e.name);for(const t of kh._createIn(i.item))n.consumable.consume(t.item,e.name);o.getCustomProperty("addHighlight")(o,s,n.writer),n.mapper.bindElementToMarker(o,i.markerName)}}}(t.view),{priority:t.converterPriority||"normal"}),e.on(`removeMarker:${t.model}`,function(t){return(e,i,n)=>{if(i.markerRange.isCollapsed)return;const s=Zh(t,i,n);if(!s)return;const o=Uh(n.writer,s),r=n.mapper.markerNameToElements(i.markerName);if(r){for(const t of r)if(n.mapper.unbindElementFromMarkerName(t,i.markerName),t.is("attributeElement"))n.writer.unwrap(n.writer.createRangeOn(t),o);else{t.getCustomProperty("removeHighlight")(t,s.id,n.writer)}n.writer.clearClonedElementsGroup(i.markerName),e.stop()}}}(t.view),{priority:t.converterPriority||"normal"})}}(t))}markerToData(t){return this.add(function(t){t=Wh(t);const e=t.model;let i=t.view;i||(i=i=>({group:e,name:i.substr(t.model.length+1)}));return n=>{var s;n.on(`addMarker:${e}`,(s=i,(t,e,i)=>{const n=s(e.markerName,i);if(!n)return;const o=e.markerRange;i.consumable.consume(o,t.name)&&(Kh(o,!1,i,e,n),Kh(o,!0,i,e,n),t.stop())}),{priority:t.converterPriority||"normal"}),n.on(`removeMarker:${e}`,function(t){return(e,i,n)=>{const s=t(i.markerName,n);if(!s)return;const o=n.mapper.markerNameToElements(i.markerName);if(o){for(const t of o)n.mapper.unbindElementFromMarkerName(t,i.markerName),t.is("containerElement")?(r(`data-${s.group}-start-before`,t),r(`data-${s.group}-start-after`,t),r(`data-${s.group}-end-before`,t),r(`data-${s.group}-end-after`,t)):n.writer.clear(n.writer.createRangeOn(t),t);n.writer.clearClonedElementsGroup(i.markerName),e.stop()}function r(t,e){if(e.hasAttribute(t)){const i=new Set(e.getAttribute(t).split(","));i.delete(s.name),0==i.size?n.writer.removeAttribute(t,e):n.writer.setAttribute(t,Array.from(i).join(","),e)}}}}(i),{priority:t.converterPriority||"normal"})}}(t))}}function Uh(t,e){const i=t.createAttributeElement("span",e.attributes);return e.classes&&i._addClass(e.classes),"number"==typeof e.priority&&(i._priority=e.priority),i._id=e.id,i}function Kh(t,e,i,n,s){const o=e?t.start:t.end,r=o.nodeAfter&&o.nodeAfter.is("element")?o.nodeAfter:null,a=o.nodeBefore&&o.nodeBefore.is("element")?o.nodeBefore:null;if(r||a){let t,o;e&&r||!e&&!a?(t=r,o=!0):(t=a,o=!1);const l=i.mapper.toViewElement(t);if(l)return void function(t,e,i,n,s,o){const r=`data-${o.group}-${e?"start":"end"}-${i?"before":"after"}`,a=t.hasAttribute(r)?t.getAttribute(r).split(","):[];a.unshift(o.name),n.writer.setAttribute(r,a.join(","),t),n.mapper.bindElementToMarker(t,s.markerName)}(l,e,o,i,n,s)}!function(t,e,i,n,s){const o=`${s.group}-${e?"start":"end"}`,r=s.name?{name:s.name}:null,a=i.writer.createUIElement(o,r);i.writer.insert(t,a),i.mapper.bindElementToMarker(a,n.markerName)}(i.mapper.toViewPosition(o),e,i,n,s)}function Gh(t){return"string"==typeof t&&(t={name:t}),t.attributes?Array.isArray(t.attributes)||(t.attributes=[t.attributes]):t.attributes=[],t.children=!!t.children,t}function Jh(t,e){return"function"==typeof t?t:(i,n)=>function(t,e,i){"string"==typeof t&&(t={name:t});let n;const s=e.writer,o=Object.assign({},t.attributes);if("container"==i)n=s.createContainerElement(t.name,o);else if("attribute"==i){const e={priority:t.priority||tl.DEFAULT_PRIORITY};n=s.createAttributeElement(t.name,o,e)}else n=s.createUIElement(t.name,o);if(t.styles){const e=Object.keys(t.styles);for(const i of e)s.setStyle(i,t.styles[i],n)}if(t.classes){const e=t.classes;if("string"==typeof e)s.addClass(e,n);else for(const t of e)s.addClass(t,n)}return n}(t,n,e)}function Qh(t){return t.model.values?(e,i,n)=>{const s=t.view[e];return s?s(e,i,n):null}:t.view}function Yh(t){return"string"==typeof t?e=>({key:t,value:e}):"object"==typeof t?t.value?()=>t:e=>({key:t.key,value:e}):t}function Zh(t,e,i){const n="function"==typeof t?t(e,i):t;return n?(n.priority||(n.priority=10),n.id||(n.id=e.markerName),n):null}function Xh(t){const e=function(t){return(e,i)=>{if(!e.is("element",t.name))return!1;if("attribute"==i.type){if(t.attributes.includes(i.attributeKey))return!0}else if(t.children)return!0;return!1}}(t);return(t,i)=>{const n=[];i.reconvertedElements||(i.reconvertedElements=new Set);for(const t of i.changes){const s="attribute"==t.type?t.range.start.nodeAfter:t.position.parent;if(s&&e(s,t)){if(!i.reconvertedElements.has(s)){i.reconvertedElements.add(s);const t=ph._createBefore(s);n.push({type:"remove",name:s.name,position:t,length:1},{type:"reinsert",name:s.name,position:t,length:1})}}else n.push(t)}i.changes=n}}function td(t){return(e,i,n={})=>{const s=["insert"];for(const i of t.attributes)e.hasAttribute(i)&&s.push(`attribute:${i}`);return!!s.every((t=>i.test(e,t)))&&(n.preflight||s.forEach((t=>i.consume(e,t))),!0)}}function ed(t,e,i,n){for(const s of e)id(t.root,s,i,n)||i.convertItem(s)}function id(t,e,i,n){const{writer:s,mapper:o}=i;if(!n.reconversion)return!1;const r=o.toViewElement(e);return!(!r||r.root==t)&&(!!i.canReuseView(r)&&(s.move(s.createRangeOn(r),o.toViewPosition(ph._createBefore(e))),!0))}function nd(t,e,{preflight:i}={}){return i?e.test(t,"insert"):e.consume(t,"insert")}function sd(t){const{schema:e,document:i}=t.model;for(const n of i.getRootNames()){const s=i.getRoot(n);if(s.isEmpty&&!e.checkChild(s,"$text")&&e.checkChild(s,"paragraph"))return t.insertElement("paragraph",s),!0}return!1}function od(t,e,i){const n=i.createContext(t);return!!i.checkChild(n,"paragraph")&&!!i.checkChild(n.push("paragraph"),e)}function rd(t,e){const i=e.createElement("paragraph");return e.insert(i,t),e.createPositionAt(i,0)}class ad extends Hh{elementToElement(t){return this.add(ld(t))}elementToAttribute(t){return this.add(function(t){t=Wh(t),dd(t);const e=ud(t,!1),i=cd(t.view),n=i?`element:${i}`:"element";return i=>{i.on(n,e,{priority:t.converterPriority||"low"})}}(t))}attributeToAttribute(t){return this.add(function(t){t=Wh(t);let e=null;("string"==typeof t.view||t.view.key)&&(e=function(t){"string"==typeof t.view&&(t.view={key:t.view});const e=t.view.key;let i;if("class"==e||"style"==e){i={["class"==e?"classes":"styles"]:t.view.value}}else{i={attributes:{[e]:void 0===t.view.value?/[\s\S]*/:t.view.value}}}t.view.name&&(i.name=t.view.name);return t.view=i,e}(t));dd(t,e);const i=ud(t,!0);return e=>{e.on("element",i,{priority:t.converterPriority||"low"})}}(t))}elementToMarker(t){return this.add(function(t){const e=function(t){return(e,i)=>{const n="string"==typeof t?t:t(e,i);return i.writer.createElement("$marker",{"data-name":n})}}(t.model);return ld({...t,model:e})}(t))}dataToMarker(t){return this.add(function(t){t=Wh(t),t.model||(t.model=e=>e?t.view+":"+e:t.view);const e={view:t.view,model:t.model},i=hd(fd(e,"start")),n=hd(fd(e,"end"));return s=>{s.on(`element:${t.view}-start`,i,{priority:t.converterPriority||"normal"}),s.on(`element:${t.view}-end`,n,{priority:t.converterPriority||"normal"});const o=w.get("low"),r=w.get("highest"),a=w.get(t.converterPriority)/r;s.on("element",function(t){return(e,i,n)=>{const s=`data-${t.view}`;function o(e,s){for(const o of s){const s=t.model(o,n),r=n.writer.createElement("$marker",{"data-name":s});n.writer.insert(r,e),i.modelCursor.isEqual(e)?i.modelCursor=i.modelCursor.getShiftedBy(1):i.modelCursor=i.modelCursor._getTransformedByInsertion(e,1),i.modelRange=i.modelRange._getTransformedByInsertion(e,1)[0]}}(n.consumable.test(i.viewItem,{attributes:s+"-end-after"})||n.consumable.test(i.viewItem,{attributes:s+"-start-after"})||n.consumable.test(i.viewItem,{attributes:s+"-end-before"})||n.consumable.test(i.viewItem,{attributes:s+"-start-before"}))&&(i.modelRange||Object.assign(i,n.convertChildren(i.viewItem,i.modelCursor)),n.consumable.consume(i.viewItem,{attributes:s+"-end-after"})&&o(i.modelRange.end,i.viewItem.getAttribute(s+"-end-after").split(",")),n.consumable.consume(i.viewItem,{attributes:s+"-start-after"})&&o(i.modelRange.end,i.viewItem.getAttribute(s+"-start-after").split(",")),n.consumable.consume(i.viewItem,{attributes:s+"-end-before"})&&o(i.modelRange.start,i.viewItem.getAttribute(s+"-end-before").split(",")),n.consumable.consume(i.viewItem,{attributes:s+"-start-before"})&&o(i.modelRange.start,i.viewItem.getAttribute(s+"-start-before").split(",")))}}(e),{priority:o+a})}}(t))}}function ld(t){const e=hd(t=Wh(t)),i=cd(t.view),n=i?`element:${i}`:"element";return i=>{i.on(n,e,{priority:t.converterPriority||"normal"})}}function cd(t){return"string"==typeof t?t:"object"==typeof t&&"string"==typeof t.name?t.name:null}function hd(t){const e=new Tr(t.view);return(i,n,s)=>{const o=e.match(n.viewItem);if(!o)return;const r=o.match;if(r.name=!0,!s.consumable.test(n.viewItem,r))return;const a=function(t,e,i){return t instanceof Function?t(e,i):i.writer.createElement(t)}(t.model,n.viewItem,s);a&&s.safeInsert(a,n.modelCursor)&&(s.consumable.consume(n.viewItem,r),s.convertChildren(n.viewItem,a),s.updateConversionResult(a,n))}}function dd(t,e=null){const i=null===e||(t=>t.getAttribute(e)),n="object"!=typeof t.model?t.model:t.model.key,s="object"!=typeof t.model||void 0===t.model.value?i:t.model.value;t.model={key:n,value:s}}function ud(t,e){const i=new Tr(t.view);return(n,s,o)=>{if(!s.modelRange&&e)return;const r=i.match(s.viewItem);if(!r)return;if(!function(t,e){const i="function"==typeof t?t(e):t;if("object"==typeof i&&!cd(i))return!1;return!i.classes&&!i.attributes&&!i.styles}(t.view,s.viewItem)?delete r.match.name:r.match.name=!0,!o.consumable.test(s.viewItem,r.match))return;const a=t.model.key,l="function"==typeof t.model.value?t.model.value(s.viewItem,o):t.model.value;if(null===l)return;s.modelRange||Object.assign(s,o.convertChildren(s.viewItem,s.modelCursor));const c=function(t,e,i,n){let s=!1;for(const o of Array.from(t.getItems({shallow:i})))n.schema.checkAttribute(o,e.key)&&(s=!0,o.hasAttribute(e.key)||n.writer.setAttribute(e.key,e.value,o));return s}(s.modelRange,{key:a,value:l},e,o);c&&(o.consumable.test(s.viewItem,{name:!0})&&(r.match.name=!0),o.consumable.consume(s.viewItem,r.match))}}function fd(t,e){return{view:`${t.view}-${e}`,model:(e,i)=>{const n=e.getAttribute("name"),s=t.model(n,i);return i.writer.createElement("$marker",{"data-name":s})}}}class md extends(q()){constructor(t,e){super(),this.model=t,this.view=new ah(e),this.mapper=new Ah,this.downcastDispatcher=new Ph({mapper:this.mapper,schema:t.schema});const i=this.model.document,n=i.selection,s=this.model.markers;this.listenTo(this.model,"_beforeChanges",(()=>{this.view._disableRendering(!0)}),{priority:"highest"}),this.listenTo(this.model,"_afterChanges",(()=>{this.view._disableRendering(!1)}),{priority:"lowest"}),this.listenTo(i,"change",(()=>{this.view.change((t=>{this.downcastDispatcher.convertChanges(i.differ,s,t),this.downcastDispatcher.convertSelection(n,s,t)}))}),{priority:"low"}),this.listenTo(this.view.document,"selectionChange",function(t,e){return(i,n)=>{const s=n.newSelection,o=[];for(const t of s.getRanges())o.push(e.toModelRange(t));const r=t.createSelection(o,{backward:s.isBackward});r.isEqual(t.document.selection)||t.change((t=>{t.setSelection(r)}))}}(this.model,this.mapper)),this.downcastDispatcher.on("insert:$text",((t,e,i)=>{if(!i.consumable.consume(e.item,t.name))return;const n=i.writer,s=i.mapper.toViewPosition(e.range.start),o=n.createText(e.item.data);n.insert(s,o)}),{priority:"lowest"}),this.downcastDispatcher.on("insert",((t,e,i)=>{i.convertAttributes(e.item),e.reconversion||!e.item.is("element")||e.item.isEmpty||i.convertChildren(e.item)}),{priority:"lowest"}),this.downcastDispatcher.on("remove",((t,e,i)=>{const n=i.mapper.toViewPosition(e.position),s=e.position.getShiftedBy(e.length),o=i.mapper.toViewPosition(s,{isPhantom:!0}),r=i.writer.createRange(n,o),a=i.writer.remove(r.getTrimmed());for(const t of i.writer.createRangeIn(a).getItems())i.mapper.unbindViewElement(t,{defer:!0})}),{priority:"low"}),this.downcastDispatcher.on("selection",((t,e,i)=>{const n=i.writer,s=n.document.selection;for(const t of s.getRanges())t.isCollapsed&&t.end.parent.isAttached()&&i.writer.mergeAttributes(t.start);n.setSelection(null)}),{priority:"high"}),this.downcastDispatcher.on("selection",((t,e,i)=>{const n=e.selection;if(n.isCollapsed)return;if(!i.consumable.consume(n,"selection"))return;const s=[];for(const t of n.getRanges())s.push(i.mapper.toViewRange(t));i.writer.setSelection(s,{backward:n.isBackward})}),{priority:"low"}),this.downcastDispatcher.on("selection",((t,e,i)=>{const n=e.selection;if(!n.isCollapsed)return;if(!i.consumable.consume(n,"selection"))return;const s=i.writer,o=n.getFirstPosition(),r=i.mapper.toViewPosition(o),a=s.breakAttributes(r);s.setSelection(a)}),{priority:"low"}),this.view.document.roots.bindTo(this.model.document.roots).using((t=>{if("$graveyard"==t.rootName)return null;const e=new La(this.view.document,t.name);return e.rootName=t.rootName,this.mapper.bindElements(t,e),e}))}destroy(){this.view.destroy(),this.stopListening()}reconvertMarker(t){const e="string"==typeof t?t:t.name,i=this.model.markers.get(e);if(!i)throw new v("editingcontroller-reconvertmarker-marker-not-exist",this,{markerName:e});this.model.change((()=>{this.model.markers._refresh(i)}))}reconvertItem(t){this.model.change((()=>{this.model.document.differ._refreshItem(t)}))}}class gd{constructor(){this._consumables=new Map}add(t,e){let i;t.is("$text")||t.is("documentFragment")?this._consumables.set(t,!0):(this._consumables.has(t)?i=this._consumables.get(t):(i=new wd(t),this._consumables.set(t,i)),i.add(e))}test(t,e){const i=this._consumables.get(t);return void 0===i?null:t.is("$text")||t.is("documentFragment")?i:i.test(e)}consume(t,e){return!!this.test(t,e)&&(t.is("$text")||t.is("documentFragment")?this._consumables.set(t,!1):this._consumables.get(t).consume(e),!0)}revert(t,e){const i=this._consumables.get(t);void 0!==i&&(t.is("$text")||t.is("documentFragment")?this._consumables.set(t,!0):i.revert(e))}static consumablesFromElement(t){const e={element:t,name:!0,attributes:[],classes:[],styles:[]},i=t.getAttributeKeys();for(const t of i)"style"!=t&&"class"!=t&&e.attributes.push(t);const n=t.getClassNames();for(const t of n)e.classes.push(t);const s=t.getStyleNames();for(const t of s)e.styles.push(t);return e}static createFrom(t,e){if(e||(e=new gd),t.is("$text"))return e.add(t),e;t.is("element")&&e.add(t,gd.consumablesFromElement(t)),t.is("documentFragment")&&e.add(t);for(const i of t.getChildren())e=gd.createFrom(i,e);return e}}const pd=["attributes","classes","styles"];class wd{constructor(t){this.element=t,this._canConsumeName=null,this._consumables={attributes:new Map,styles:new Map,classes:new Map}}add(t){t.name&&(this._canConsumeName=!0);for(const e of pd)e in t&&this._add(e,t[e])}test(t){if(t.name&&!this._canConsumeName)return this._canConsumeName;for(const e of pd)if(e in t){const i=this._test(e,t[e]);if(!0!==i)return i}return!0}consume(t){t.name&&(this._canConsumeName=!1);for(const e of pd)e in t&&this._consume(e,t[e])}revert(t){t.name&&(this._canConsumeName=!0);for(const e of pd)e in t&&this._revert(e,t[e])}_add(t,e){const i=pt(e)?e:[e],n=this._consumables[t];for(const e of i){if("attributes"===t&&("class"===e||"style"===e))throw new v("viewconsumable-invalid-attribute",this);if(n.set(e,!0),"styles"===t)for(const t of this.element.document.stylesProcessor.getRelatedStyles(e))n.set(t,!0)}}_test(t,e){const i=pt(e)?e:[e],n=this._consumables[t];for(const e of i)if("attributes"!==t||"class"!==e&&"style"!==e){const t=n.get(e);if(void 0===t)return null;if(!t)return!1}else{const t="class"==e?"classes":"styles",i=this._test(t,[...this._consumables[t].keys()]);if(!0!==i)return i}return!0}_consume(t,e){const i=pt(e)?e:[e],n=this._consumables[t];for(const e of i)if("attributes"!==t||"class"!==e&&"style"!==e){if(n.set(e,!1),"styles"==t)for(const t of this.element.document.stylesProcessor.getRelatedStyles(e))n.set(t,!1)}else{const t="class"==e?"classes":"styles";this._consume(t,[...this._consumables[t].keys()])}}_revert(t,e){const i=pt(e)?e:[e],n=this._consumables[t];for(const e of i)if("attributes"!==t||"class"!==e&&"style"!==e){!1===n.get(e)&&n.set(e,!0)}else{const t="class"==e?"classes":"styles";this._revert(t,[...this._consumables[t].keys()])}}}class bd extends(q()){constructor(){super(),this._sourceDefinitions={},this._attributeProperties={},this.decorate("checkChild"),this.decorate("checkAttribute"),this.on("checkAttribute",((t,e)=>{e[0]=new _d(e[0])}),{priority:"highest"}),this.on("checkChild",((t,e)=>{e[0]=new _d(e[0]),e[1]=this.getDefinition(e[1])}),{priority:"highest"})}register(t,e){if(this._sourceDefinitions[t])throw new v("schema-cannot-register-item-twice",this,{itemName:t});this._sourceDefinitions[t]=[Object.assign({},e)],this._clearCache()}extend(t,e){if(!this._sourceDefinitions[t])throw new v("schema-cannot-extend-missing-item",this,{itemName:t});this._sourceDefinitions[t].push(Object.assign({},e)),this._clearCache()}getDefinitions(){return this._compiledDefinitions||this._compile(),this._compiledDefinitions}getDefinition(t){let e;return e="string"==typeof t?t:"is"in t&&(t.is("$text")||t.is("$textProxy"))?"$text":t.name,this.getDefinitions()[e]}isRegistered(t){return!!this.getDefinition(t)}isBlock(t){const e=this.getDefinition(t);return!(!e||!e.isBlock)}isLimit(t){const e=this.getDefinition(t);return!!e&&!(!e.isLimit&&!e.isObject)}isObject(t){const e=this.getDefinition(t);return!!e&&!!(e.isObject||e.isLimit&&e.isSelectable&&e.isContent)}isInline(t){const e=this.getDefinition(t);return!(!e||!e.isInline)}isSelectable(t){const e=this.getDefinition(t);return!!e&&!(!e.isSelectable&&!e.isObject)}isContent(t){const e=this.getDefinition(t);return!!e&&!(!e.isContent&&!e.isObject)}checkChild(t,e){return!!e&&this._checkContextMatch(e,t)}checkAttribute(t,e){const i=this.getDefinition(t.last);return!!i&&i.allowAttributes.includes(e)}checkMerge(t,e){if(t instanceof ph){const e=t.nodeBefore,i=t.nodeAfter;if(!(e instanceof fh))throw new v("schema-check-merge-no-element-before",this);if(!(i instanceof fh))throw new v("schema-check-merge-no-element-after",this);return this.checkMerge(e,i)}for(const i of e.getChildren())if(!this.checkChild(t,i))return!1;return!0}addChildCheck(t){this.on("checkChild",((e,[i,n])=>{if(!n)return;const s=t(i,n);"boolean"==typeof s&&(e.stop(),e.return=s)}),{priority:"high"})}addAttributeCheck(t){this.on("checkAttribute",((e,[i,n])=>{const s=t(i,n);"boolean"==typeof s&&(e.stop(),e.return=s)}),{priority:"high"})}setAttributeProperties(t,e){this._attributeProperties[t]=Object.assign(this.getAttributeProperties(t),e)}getAttributeProperties(t){return this._attributeProperties[t]||{}}getLimitElement(t){let e;if(t instanceof ph)e=t.parent;else{e=(t instanceof kh?[t]:Array.from(t.getRanges())).reduce(((t,e)=>{const i=e.getCommonAncestor();return t?t.getCommonAncestor(i,{includeSelf:!0}):i}),null)}for(;!this.isLimit(e)&&e.parent;)e=e.parent;return e}checkAttributeInSelection(t,e){if(t.isCollapsed){const i=[...t.getFirstPosition().getAncestors(),new dh("",t.getAttributes())];return this.checkAttribute(i,e)}{const i=t.getRanges();for(const t of i)for(const i of t)if(this.checkAttribute(i.item,e))return!0}return!1}*getValidRanges(t,e){t=function*(t){for(const e of t)yield*e.getMinimalFlatRanges()}(t);for(const i of t)yield*this._getValidRangesForRange(i,e)}getNearestSelectionRange(t,e="both"){if(this.checkChild(t,"$text"))return new kh(t);let i,n;const s=t.getAncestors().reverse().find((t=>this.isLimit(t)))||t.root;"both"!=e&&"backward"!=e||(i=new mh({boundaries:kh._createIn(s),startPosition:t,direction:"backward"})),"both"!=e&&"forward"!=e||(n=new mh({boundaries:kh._createIn(s),startPosition:t}));for(const t of function*(t,e){let i=!1;for(;!i;){if(i=!0,t){const e=t.next();e.done||(i=!1,yield{walker:t,value:e.value})}if(e){const t=e.next();t.done||(i=!1,yield{walker:e,value:t.value})}}}(i,n)){const e=t.walker==i?"elementEnd":"elementStart",n=t.value;if(n.type==e&&this.isObject(n.item))return kh._createOn(n.item);if(this.checkChild(n.nextPosition,"$text"))return new kh(n.nextPosition)}return null}findAllowedParent(t,e){let i=t.parent;for(;i;){if(this.checkChild(i,e))return i;if(this.isLimit(i))return null;i=i.parent}return null}setAllowedAttributes(t,e,i){const n=i.model;for(const[s,o]of Object.entries(e))n.schema.checkAttribute(t,s)&&i.setAttribute(s,o,t)}removeDisallowedAttributes(t,e){for(const i of t)if(i.is("$text"))Id(this,i,e);else{const t=kh._createIn(i).getPositions();for(const i of t){Id(this,i.nodeBefore||i.parent,e)}}}getAttributesWithProperty(t,e,i){const n={};for(const[s,o]of t.getAttributes()){const t=this.getAttributeProperties(s);void 0!==t[e]&&(void 0!==i&&i!==t[e]||(n[s]=o))}return n}createContext(t){return new _d(t)}_clearCache(){this._compiledDefinitions=null}_compile(){const t={},e=this._sourceDefinitions,i=Object.keys(e);for(const n of i)t[n]=vd(e[n],n);for(const e of i)yd(t,e);for(const e of i)kd(t,e);for(const e of i)Ad(t,e);for(const e of i)xd(t,e),Cd(t,e);for(const e of i)Pd(t,e),Td(t,e),Ed(t,e);this._compiledDefinitions=t}_checkContextMatch(t,e,i=e.length-1){const n=e.getItem(i);if(t.allowIn.includes(n.name)){if(0==i)return!0;{const t=this.getDefinition(n);return this._checkContextMatch(t,e,i-1)}}return!1}*_getValidRangesForRange(t,e){let i=t.start,n=t.start;for(const s of t.getItems({shallow:!0}))s.is("element")&&(yield*this._getValidRangesForRange(kh._createIn(s),e)),this.checkAttribute(s,e)||(i.isEqual(n)||(yield new kh(i,n)),i=ph._createAfter(s)),n=ph._createAfter(s);i.isEqual(n)||(yield new kh(i,n))}}class _d{constructor(t){if(t instanceof _d)return t;let e;e="string"==typeof t?[t]:Array.isArray(t)?t:t.getAncestors({includeSelf:!0}),this._items=e.map(Od)}get length(){return this._items.length}get last(){return this._items[this._items.length-1]}[Symbol.iterator](){return this._items[Symbol.iterator]()}push(t){const e=new _d([t]);return e._items=[...this._items,...e._items],e}getItem(t){return this._items[t]}*getNames(){yield*this._items.map((t=>t.name))}endsWith(t){return Array.from(this.getNames()).join(" ").endsWith(t)}startsWith(t){return Array.from(this.getNames()).join(" ").startsWith(t)}}function vd(t,e){const i={name:e,allowIn:[],allowContentOf:[],allowWhere:[],allowAttributes:[],allowAttributesOf:[],allowChildren:[],inheritTypesFrom:[]};return function(t,e){for(const i of t){const t=Object.keys(i).filter((t=>t.startsWith("is")));for(const n of t)e[n]=!!i[n]}}(t,i),Sd(t,i,"allowIn"),Sd(t,i,"allowContentOf"),Sd(t,i,"allowWhere"),Sd(t,i,"allowAttributes"),Sd(t,i,"allowAttributesOf"),Sd(t,i,"allowChildren"),Sd(t,i,"inheritTypesFrom"),function(t,e){for(const i of t){const t=i.inheritAllFrom;t&&(e.allowContentOf.push(t),e.allowWhere.push(t),e.allowAttributesOf.push(t),e.inheritTypesFrom.push(t))}}(t,i),i}function yd(t,e){const i=t[e];for(const n of i.allowChildren){const i=t[n];i&&i.allowIn.push(e)}i.allowChildren.length=0}function kd(t,e){for(const i of t[e].allowContentOf)if(t[i]){Rd(t,i).forEach((t=>{t.allowIn.push(e)}))}delete t[e].allowContentOf}function Ad(t,e){for(const i of t[e].allowWhere){const n=t[i];if(n){const i=n.allowIn;t[e].allowIn.push(...i)}}delete t[e].allowWhere}function xd(t,e){for(const i of t[e].allowAttributesOf){const n=t[i];if(n){const i=n.allowAttributes;t[e].allowAttributes.push(...i)}}delete t[e].allowAttributesOf}function Cd(t,e){const i=t[e];for(const e of i.inheritTypesFrom){const n=t[e];if(n){const t=Object.keys(n).filter((t=>t.startsWith("is")));for(const e of t)e in i||(i[e]=n[e])}}delete i.inheritTypesFrom}function Pd(t,e){const i=t[e],n=i.allowIn.filter((e=>t[e]));i.allowIn=Array.from(new Set(n))}function Td(t,e){const i=t[e];for(const n of i.allowIn){t[n].allowChildren.push(e)}}function Ed(t,e){const i=t[e];i.allowAttributes=Array.from(new Set(i.allowAttributes))}function Sd(t,e,i){for(const n of t){const t=n[i];"string"==typeof t?e[i].push(t):Array.isArray(t)&&e[i].push(...t)}}function Rd(t,e){const i=t[e];return(n=t,Object.keys(n).map((t=>n[t]))).filter((t=>t.allowIn.includes(i.name)));var n}function Od(t){return"string"==typeof t||t.is("documentFragment")?{name:"string"==typeof t?t:"$documentFragment",*getAttributeKeys(){},getAttribute(){}}:{name:t.is("element")?t.name:"$text",*getAttributeKeys(){yield*t.getAttributeKeys()},getAttribute:e=>t.getAttribute(e)}}function Id(t,e,i){for(const n of e.getAttributeKeys())t.checkAttribute(e,n)||i.removeAttribute(n,e)}class Vd extends(R()){constructor(t){super(),this._splitParts=new Map,this._cursorParents=new Map,this._modelCursor=null,this._emptyElementsToKeep=new Set,this.conversionApi={...t,consumable:null,writer:null,store:null,convertItem:(t,e)=>this._convertItem(t,e),convertChildren:(t,e)=>this._convertChildren(t,e),safeInsert:(t,e)=>this._safeInsert(t,e),updateConversionResult:(t,e)=>this._updateConversionResult(t,e),splitToAllowedParent:(t,e)=>this._splitToAllowedParent(t,e),getSplitParts:t=>this._getSplitParts(t),keepEmptyElement:t=>this._keepEmptyElement(t)}}convert(t,e,i=["$root"]){this.fire("viewCleanup",t),this._modelCursor=function(t,e){let i;for(const n of new _d(t)){const t={};for(const e of n.getAttributeKeys())t[e]=n.getAttribute(e);const s=e.createElement(n.name,t);i&&e.insert(s,i),i=ph._createAt(s,0)}return i}(i,e),this.conversionApi.writer=e,this.conversionApi.consumable=gd.createFrom(t),this.conversionApi.store={};const{modelRange:n}=this._convertItem(t,this._modelCursor),s=e.createDocumentFragment();if(n){this._removeEmptyElements();for(const t of Array.from(this._modelCursor.parent.getChildren()))e.append(t,s);s.markers=function(t,e){const i=new Set,n=new Map,s=kh._createIn(t).getItems();for(const t of s)t.is("element","$marker")&&i.add(t);for(const t of i){const i=t.getAttribute("data-name"),s=e.createPositionBefore(t);n.has(i)?n.get(i).end=s.clone():n.set(i,new kh(s.clone())),e.remove(t)}return n}(s,e)}return this._modelCursor=null,this._splitParts.clear(),this._cursorParents.clear(),this._emptyElementsToKeep.clear(),this.conversionApi.writer=null,this.conversionApi.store=null,s}_convertItem(t,e){const i={viewItem:t,modelCursor:e,modelRange:null};if(t.is("element")?this.fire(`element:${t.name}`,i,this.conversionApi):t.is("$text")?this.fire("text",i,this.conversionApi):this.fire("documentFragment",i,this.conversionApi),i.modelRange&&!(i.modelRange instanceof kh))throw new v("view-conversion-dispatcher-incorrect-result",this);return{modelRange:i.modelRange,modelCursor:i.modelCursor}}_convertChildren(t,e){let i=e.is("position")?e:ph._createAt(e,0);const n=new kh(i);for(const e of Array.from(t.getChildren())){const t=this._convertItem(e,i);t.modelRange instanceof kh&&(n.end=t.modelRange.end,i=t.modelCursor)}return{modelRange:n,modelCursor:i}}_safeInsert(t,e){const i=this._splitToAllowedParent(t,e);return!!i&&(this.conversionApi.writer.insert(t,i.position),!0)}_updateConversionResult(t,e){const i=this._getSplitParts(t),n=this.conversionApi.writer;e.modelRange||(e.modelRange=n.createRange(n.createPositionBefore(t),n.createPositionAfter(i[i.length-1])));const s=this._cursorParents.get(t);e.modelCursor=s?n.createPositionAt(s,0):e.modelRange.end}_splitToAllowedParent(t,e){const{schema:i,writer:n}=this.conversionApi;let s=i.findAllowedParent(e,t);if(s){if(s===e.parent)return{position:e};this._modelCursor.parent.getAncestors().includes(s)&&(s=null)}if(!s)return od(e,t,i)?{position:rd(e,n)}:null;const o=this.conversionApi.writer.split(e,s),r=[];for(const t of o.range.getWalker())if("elementEnd"==t.type)r.push(t.item);else{const e=r.pop(),i=t.item;this._registerSplitPair(e,i)}const a=o.range.end.parent;return this._cursorParents.set(t,a),{position:o.position,cursorParent:a}}_registerSplitPair(t,e){this._splitParts.has(t)||this._splitParts.set(t,[t]);const i=this._splitParts.get(t);this._splitParts.set(e,i),i.push(e)}_getSplitParts(t){let e;return e=this._splitParts.has(t)?this._splitParts.get(t):[t],e}_keepEmptyElement(t){this._emptyElementsToKeep.add(t)}_removeEmptyElements(){let t=!1;for(const e of this._splitParts.keys())e.isEmpty&&!this._emptyElementsToKeep.has(e)&&(this.conversionApi.writer.remove(e),this._splitParts.delete(e),t=!0);t&&this._removeEmptyElements()}}class Md{getHtml(t){const e=document.implementation.createHTMLDocument("").createElement("div");return e.appendChild(t),e.innerHTML}}class Nd{constructor(t){this.skipComments=!0,this.domParser=new DOMParser,this.domConverter=new jl(t,{renderingMode:"data"}),this.htmlWriter=new Md}toData(t){const e=this.domConverter.viewToDom(t);return this.htmlWriter.getHtml(e)}toView(t){const e=this._toDom(t);return this.domConverter.domToView(e,{skipComments:this.skipComments})}registerRawContentMatcher(t){this.domConverter.registerRawContentMatcher(t)}useFillerType(t){this.domConverter.blockFillerMode="marked"==t?"markedNbsp":"nbsp"}_toDom(t){t.match(/<(?:html|body|head|meta)(?:\s[^>]*)?>/i)||(t=`${t}`);const e=this.domParser.parseFromString(t,"text/html"),i=e.createDocumentFragment(),n=e.body.childNodes;for(;n.length>0;)i.appendChild(n[0]);return i}}class Bd extends(R()){constructor(t,e){super(),this.model=t,this.mapper=new Ah,this.downcastDispatcher=new Ph({mapper:this.mapper,schema:t.schema}),this.downcastDispatcher.on("insert:$text",((t,e,i)=>{if(!i.consumable.consume(e.item,t.name))return;const n=i.writer,s=i.mapper.toViewPosition(e.range.start),o=n.createText(e.item.data);n.insert(s,o)}),{priority:"lowest"}),this.downcastDispatcher.on("insert",((t,e,i)=>{i.convertAttributes(e.item),e.reconversion||!e.item.is("element")||e.item.isEmpty||i.convertChildren(e.item)}),{priority:"lowest"}),this.upcastDispatcher=new Vd({schema:t.schema}),this.viewDocument=new Xa(e),this.stylesProcessor=e,this.htmlProcessor=new Nd(this.viewDocument),this.processor=this.htmlProcessor,this._viewWriter=new dl(this.viewDocument),this.upcastDispatcher.on("text",((t,e,{schema:i,consumable:n,writer:s})=>{let o=e.modelCursor;if(!n.test(e.viewItem))return;if(!i.checkChild(o,"$text")){if(!od(o,"$text",i))return;if(0==e.viewItem.data.trim().length)return;const t=o.nodeBefore;o=rd(o,s),t&&t.is("element","$marker")&&(s.move(s.createRangeOn(t),o),o=s.createPositionAfter(t))}n.consume(e.viewItem);const r=s.createText(e.viewItem.data);s.insert(r,o),e.modelRange=s.createRange(o,o.getShiftedBy(r.offsetSize)),e.modelCursor=e.modelRange.end}),{priority:"lowest"}),this.upcastDispatcher.on("element",((t,e,i)=>{if(!e.modelRange&&i.consumable.consume(e.viewItem,{name:!0})){const{modelRange:t,modelCursor:n}=i.convertChildren(e.viewItem,e.modelCursor);e.modelRange=t,e.modelCursor=n}}),{priority:"lowest"}),this.upcastDispatcher.on("documentFragment",((t,e,i)=>{if(!e.modelRange&&i.consumable.consume(e.viewItem,{name:!0})){const{modelRange:t,modelCursor:n}=i.convertChildren(e.viewItem,e.modelCursor);e.modelRange=t,e.modelCursor=n}}),{priority:"lowest"}),q().prototype.decorate.call(this,"init"),q().prototype.decorate.call(this,"set"),q().prototype.decorate.call(this,"get"),q().prototype.decorate.call(this,"toView"),q().prototype.decorate.call(this,"toModel"),this.on("init",(()=>{this.fire("ready")}),{priority:"lowest"}),this.on("ready",(()=>{this.model.enqueueChange({isUndoable:!1},sd)}),{priority:"lowest"})}get(t={}){const{rootName:e="main",trim:i="empty"}=t;if(!this._checkIfRootsExists([e]))throw new v("datacontroller-get-non-existent-root",this);const n=this.model.document.getRoot(e);return"empty"!==i||this.model.hasContent(n,{ignoreWhitespaces:!0})?this.stringify(n,t):""}stringify(t,e={}){const i=this.toView(t,e);return this.processor.toData(i)}toView(t,e={}){const i=this.viewDocument,n=this._viewWriter;this.mapper.clearBindings();const s=kh._createIn(t),o=new hl(i);this.mapper.bindElements(t,o);const r=t.is("documentFragment")?t.markers:function(t){const e=[],i=t.root.document;if(!i)return new Map;const n=kh._createIn(t);for(const t of i.model.markers){const i=t.getRange(),s=i.isCollapsed,o=i.start.isEqual(n.start)||i.end.isEqual(n.end);if(s&&o)e.push([t.name,i]);else{const s=n.getIntersection(i);s&&e.push([t.name,s])}}return e.sort((([t,e],[i,n])=>{if("after"!==e.end.compareWith(n.start))return 1;if("before"!==e.start.compareWith(n.end))return-1;switch(e.start.compareWith(n.start)){case"before":return 1;case"after":return-1;default:switch(e.end.compareWith(n.end)){case"before":return 1;case"after":return-1;default:return i.localeCompare(t)}}})),new Map(e)}(t);return this.downcastDispatcher.convert(s,r,n,e),o}init(t){if(this.model.document.version)throw new v("datacontroller-init-document-not-empty",this);let e={};if("string"==typeof t?e.main=t:e=t,!this._checkIfRootsExists(Object.keys(e)))throw new v("datacontroller-init-non-existent-root",this);return this.model.enqueueChange({isUndoable:!1},(t=>{for(const i of Object.keys(e)){const n=this.model.document.getRoot(i);t.insert(this.parse(e[i],n),n,0)}})),Promise.resolve()}set(t,e={}){let i={};if("string"==typeof t?i.main=t:i=t,!this._checkIfRootsExists(Object.keys(i)))throw new v("datacontroller-set-non-existent-root",this);this.model.enqueueChange(e.batchType||{},(t=>{t.setSelection(null),t.removeSelectionAttribute(this.model.document.selection.getAttributeKeys());for(const e of Object.keys(i)){const n=this.model.document.getRoot(e);t.remove(t.createRangeIn(n)),t.insert(this.parse(i[e],n),n,0)}}))}parse(t,e="$root"){const i=this.processor.toView(t);return this.toModel(i,e)}toModel(t,e="$root"){return this.model.change((i=>this.upcastDispatcher.convert(t,i,e)))}addStyleProcessorRules(t){t(this.stylesProcessor)}registerRawContentMatcher(t){this.processor&&this.processor!==this.htmlProcessor&&this.processor.registerRawContentMatcher(t),this.htmlProcessor.registerRawContentMatcher(t)}destroy(){this.stopListening()}_checkIfRootsExists(t){for(const e of t)if(!this.model.document.getRootNames().includes(e))return!1;return!0}}class Dd{constructor(t,e){this._helpers=new Map,this._downcast=so(t),this._createConversionHelpers({name:"downcast",dispatchers:this._downcast,isDowncast:!0}),this._upcast=so(e),this._createConversionHelpers({name:"upcast",dispatchers:this._upcast,isDowncast:!1})}addAlias(t,e){const i=this._downcast.includes(e);if(!this._upcast.includes(e)&&!i)throw new v("conversion-add-alias-dispatcher-not-registered",this);this._createConversionHelpers({name:t,dispatchers:[e],isDowncast:i})}for(t){if(!this._helpers.has(t))throw new v("conversion-for-unknown-group",this);return this._helpers.get(t)}elementToElement(t){this.for("downcast").elementToElement(t);for(const{model:e,view:i}of Fd(t))this.for("upcast").elementToElement({model:e,view:i,converterPriority:t.converterPriority})}attributeToElement(t){this.for("downcast").attributeToElement(t);for(const{model:e,view:i}of Fd(t))this.for("upcast").elementToAttribute({view:i,model:e,converterPriority:t.converterPriority})}attributeToAttribute(t){this.for("downcast").attributeToAttribute(t);for(const{model:e,view:i}of Fd(t))this.for("upcast").attributeToAttribute({view:i,model:e})}_createConversionHelpers({name:t,dispatchers:e,isDowncast:i}){if(this._helpers.has(t))throw new v("conversion-group-exists",this);const n=i?new qh(e):new ad(e);this._helpers.set(t,n)}}function*Fd(t){if(t.model.values)for(const e of t.model.values){const i={key:t.model.key,value:e},n=t.view[e],s=t.upcastAlso?t.upcastAlso[e]:void 0;yield*Ld(i,n,s)}else yield*Ld(t.model,t.view,t.upcastAlso)}function*Ld(t,e,i){if(yield{model:t,view:e},i)for(const e of so(i))yield{model:t,view:e}}class zd{constructor(t){this.baseVersion=t,this.isDocumentOperation=null!==this.baseVersion,this.batch=null}_validate(){}toJSON(){const t=Object.assign({},this);return t.__className=this.constructor.className,delete t.batch,delete t.isDocumentOperation,t}static get className(){return"Operation"}static fromJSON(t,e){return new this(t.baseVersion)}}function Hd(t,e){const i=Wd(e),n=i.reduce(((t,e)=>t+e.offsetSize),0),s=t.parent;Ud(t);const o=t.index;return s._insertChild(o,i),qd(s,o+i.length),qd(s,o),new kh(t,t.getShiftedBy(n))}function jd(t){if(!t.isFlat)throw new v("operation-utils-remove-range-not-flat",this);const e=t.start.parent;Ud(t.start),Ud(t.end);const i=e._removeChildren(t.start.index,t.end.index-t.start.index);return qd(e,t.start.index),i}function $d(t,e){if(!t.isFlat)throw new v("operation-utils-move-range-not-flat",this);const i=jd(t);return Hd(e=e._getTransformedByDeletion(t.start,t.end.offset-t.start.offset),i)}function Wd(t){const e=[];!function t(i){if("string"==typeof i)e.push(new dh(i));else if(i instanceof uh)e.push(new dh(i.data,i.getAttributes()));else if(i instanceof ch)e.push(i);else if(tt(i))for(const e of i)t(e)}(t);for(let t=1;tt.maxOffset)throw new v("move-operation-nodes-do-not-exist",this);if(t===e&&i=i&&this.targetPosition.path[t]t._clone(!0)))),e=new Jd(this.position,t,this.baseVersion);return e.shouldReceiveAttributes=this.shouldReceiveAttributes,e}getReversed(){const t=this.position.root.document.graveyard,e=new ph(t,[0]);return new Gd(this.position,this.nodes.maxOffset,e,this.baseVersion+1)}_validate(){const t=this.position.parent;if(!t||t.maxOffsett._clone(!0)))),Hd(this.position,t)}toJSON(){const t=super.toJSON();return t.position=this.position.toJSON(),t.nodes=this.nodes.toJSON(),t}static get className(){return"InsertOperation"}static fromJSON(t,e){const i=[];for(const e of t.nodes)e.name?i.push(fh.fromJSON(e)):i.push(dh.fromJSON(e));const n=new Jd(ph.fromJSON(t.position,e),i,t.baseVersion);return n.shouldReceiveAttributes=t.shouldReceiveAttributes,n}}class Qd extends zd{constructor(t,e,i,n,s,o){super(o),this.name=t,this.oldRange=e?e.clone():null,this.newRange=i?i.clone():null,this.affectsData=s,this._markers=n}get type(){return"marker"}clone(){return new Qd(this.name,this.oldRange,this.newRange,this._markers,this.affectsData,this.baseVersion)}getReversed(){return new Qd(this.name,this.newRange,this.oldRange,this._markers,this.affectsData,this.baseVersion+1)}_execute(){this.newRange?this._markers._set(this.name,this.newRange,!0,this.affectsData):this._markers._remove(this.name)}toJSON(){const t=super.toJSON();return this.oldRange&&(t.oldRange=this.oldRange.toJSON()),this.newRange&&(t.newRange=this.newRange.toJSON()),delete t._markers,t}static get className(){return"MarkerOperation"}static fromJSON(t,e){return new Qd(t.name,t.oldRange?kh.fromJSON(t.oldRange,e):null,t.newRange?kh.fromJSON(t.newRange,e):null,e.model.markers,t.affectsData,t.baseVersion)}}const Yd=function(t,e){return Qc(t,e)};class Zd extends zd{constructor(t,e,i,n,s){super(s),this.range=t.clone(),this.key=e,this.oldValue=void 0===i?null:i,this.newValue=void 0===n?null:n}get type(){return null===this.oldValue?"addAttribute":null===this.newValue?"removeAttribute":"changeAttribute"}clone(){return new Zd(this.range,this.key,this.oldValue,this.newValue,this.baseVersion)}getReversed(){return new Zd(this.range,this.key,this.newValue,this.oldValue,this.baseVersion+1)}toJSON(){const t=super.toJSON();return t.range=this.range.toJSON(),t}_validate(){if(!this.range.isFlat)throw new v("attribute-operation-range-not-flat",this);for(const t of this.range.getItems({shallow:!0})){if(null!==this.oldValue&&!Yd(t.getAttribute(this.key),this.oldValue))throw new v("attribute-operation-wrong-old-value",this,{item:t,key:this.key,value:this.oldValue});if(null===this.oldValue&&null!==this.newValue&&t.hasAttribute(this.key))throw new v("attribute-operation-attribute-exists",this,{node:t,key:this.key})}}_execute(){Yd(this.oldValue,this.newValue)||function(t,e,i){Ud(t.start),Ud(t.end);for(const n of t.getItems({shallow:!0})){const t=n.is("$textProxy")?n.textNode:n;null!==i?t._setAttribute(e,i):t._removeAttribute(e),qd(t.parent,t.index)}qd(t.end.parent,t.end.index)}(this.range,this.key,this.newValue)}static get className(){return"AttributeOperation"}static fromJSON(t,e){return new Zd(kh.fromJSON(t.range,e),t.key,t.oldValue,t.newValue,t.baseVersion)}}class Xd extends zd{get type(){return"noop"}clone(){return new Xd(this.baseVersion)}getReversed(){return new Xd(this.baseVersion+1)}_execute(){}static get className(){return"NoOperation"}}class tu extends zd{constructor(t,e,i,n){super(n),this.position=t,this.position.stickiness="toNext",this.oldName=e,this.newName=i}get type(){return"rename"}clone(){return new tu(this.position.clone(),this.oldName,this.newName,this.baseVersion)}getReversed(){return new tu(this.position.clone(),this.newName,this.oldName,this.baseVersion+1)}_validate(){const t=this.position.nodeAfter;if(!(t instanceof fh))throw new v("rename-operation-wrong-position",this);if(t.name!==this.oldName)throw new v("rename-operation-wrong-name",this)}_execute(){this.position.nodeAfter.name=this.newName}toJSON(){const t=super.toJSON();return t.position=this.position.toJSON(),t}static get className(){return"RenameOperation"}static fromJSON(t,e){return new tu(ph.fromJSON(t.position,e),t.oldName,t.newName,t.baseVersion)}}class eu extends zd{constructor(t,e,i,n,s){super(s),this.root=t,this.key=e,this.oldValue=i,this.newValue=n}get type(){return null===this.oldValue?"addRootAttribute":null===this.newValue?"removeRootAttribute":"changeRootAttribute"}clone(){return new eu(this.root,this.key,this.oldValue,this.newValue,this.baseVersion)}getReversed(){return new eu(this.root,this.key,this.newValue,this.oldValue,this.baseVersion+1)}_validate(){if(this.root!=this.root.root||this.root.is("documentFragment"))throw new v("rootattribute-operation-not-a-root",this,{root:this.root,key:this.key});if(null!==this.oldValue&&this.root.getAttribute(this.key)!==this.oldValue)throw new v("rootattribute-operation-wrong-old-value",this,{root:this.root,key:this.key});if(null===this.oldValue&&null!==this.newValue&&this.root.hasAttribute(this.key))throw new v("rootattribute-operation-attribute-exists",this,{root:this.root,key:this.key})}_execute(){null!==this.newValue?this.root._setAttribute(this.key,this.newValue):this.root._removeAttribute(this.key)}toJSON(){const t=super.toJSON();return t.root=this.root.toJSON(),t}static get className(){return"RootAttributeOperation"}static fromJSON(t,e){if(!e.getRoot(t.root))throw new v("rootattribute-operation-fromjson-no-root",this,{rootName:t.root});return new eu(e.getRoot(t.root),t.key,t.oldValue,t.newValue,t.baseVersion)}}class iu extends zd{constructor(t,e,i,n,s){super(s),this.sourcePosition=t.clone(),this.sourcePosition.stickiness="toPrevious",this.howMany=e,this.targetPosition=i.clone(),this.targetPosition.stickiness="toNext",this.graveyardPosition=n.clone()}get type(){return"merge"}get deletionPosition(){return new ph(this.sourcePosition.root,this.sourcePosition.path.slice(0,-1))}get movedRange(){const t=this.sourcePosition.getShiftedBy(Number.POSITIVE_INFINITY);return new kh(this.sourcePosition,t)}clone(){return new iu(this.sourcePosition,this.howMany,this.targetPosition,this.graveyardPosition,this.baseVersion)}getReversed(){const t=this.targetPosition._getTransformedByMergeOperation(this),e=this.sourcePosition.path.slice(0,-1),i=new ph(this.sourcePosition.root,e)._getTransformedByMergeOperation(this);return new nu(t,this.howMany,i,this.graveyardPosition,this.baseVersion+1)}_validate(){const t=this.sourcePosition.parent,e=this.targetPosition.parent;if(!t.parent)throw new v("merge-operation-source-position-invalid",this);if(!e.parent)throw new v("merge-operation-target-position-invalid",this);if(this.howMany!=t.maxOffset)throw new v("merge-operation-how-many-invalid",this)}_execute(){const t=this.sourcePosition.parent;$d(kh._createIn(t),this.targetPosition),$d(kh._createOn(t),this.graveyardPosition)}toJSON(){const t=super.toJSON();return t.sourcePosition=t.sourcePosition.toJSON(),t.targetPosition=t.targetPosition.toJSON(),t.graveyardPosition=t.graveyardPosition.toJSON(),t}static get className(){return"MergeOperation"}static fromJSON(t,e){const i=ph.fromJSON(t.sourcePosition,e),n=ph.fromJSON(t.targetPosition,e),s=ph.fromJSON(t.graveyardPosition,e);return new this(i,t.howMany,n,s,t.baseVersion)}}class nu extends zd{constructor(t,e,i,n,s){super(s),this.splitPosition=t.clone(),this.splitPosition.stickiness="toNext",this.howMany=e,this.insertionPosition=i,this.graveyardPosition=n?n.clone():null,this.graveyardPosition&&(this.graveyardPosition.stickiness="toNext")}get type(){return"split"}get moveTargetPosition(){const t=this.insertionPosition.path.slice();return t.push(0),new ph(this.insertionPosition.root,t)}get movedRange(){const t=this.splitPosition.getShiftedBy(Number.POSITIVE_INFINITY);return new kh(this.splitPosition,t)}clone(){return new nu(this.splitPosition,this.howMany,this.insertionPosition,this.graveyardPosition,this.baseVersion)}getReversed(){const t=this.splitPosition.root.document.graveyard,e=new ph(t,[0]);return new iu(this.moveTargetPosition,this.howMany,this.splitPosition,e,this.baseVersion+1)}_validate(){const t=this.splitPosition.parent,e=this.splitPosition.offset;if(!t||t.maxOffset{if(t.key===e.key&&t.range.start.hasSameParentAs(e.range.start)){const n=t.range.getDifference(e.range).map((e=>new Zd(e,t.key,t.oldValue,t.newValue,0))),s=t.range.getIntersection(e.range);return s&&i.aIsStrong&&n.push(new Zd(s,e.key,e.newValue,t.newValue,0)),0==n.length?[new Xd(0)]:n}return[t]})),au(Zd,Jd,((t,e)=>{if(t.range.start.hasSameParentAs(e.position)&&t.range.containsPosition(e.position)){const i=t.range._getTransformedByInsertion(e.position,e.howMany,!e.shouldReceiveAttributes).map((e=>new Zd(e,t.key,t.oldValue,t.newValue,t.baseVersion)));if(e.shouldReceiveAttributes){const n=mu(e,t.key,t.oldValue);n&&i.unshift(n)}return i}return t.range=t.range._getTransformedByInsertion(e.position,e.howMany,!1)[0],[t]})),au(Zd,iu,((t,e)=>{const i=[];t.range.start.hasSameParentAs(e.deletionPosition)&&(t.range.containsPosition(e.deletionPosition)||t.range.start.isEqual(e.deletionPosition))&&i.push(kh._createFromPositionAndShift(e.graveyardPosition,1));const n=t.range._getTransformedByMergeOperation(e);return n.isCollapsed||i.push(n),i.map((e=>new Zd(e,t.key,t.oldValue,t.newValue,t.baseVersion)))})),au(Zd,Gd,((t,e)=>{const i=function(t,e){const i=kh._createFromPositionAndShift(e.sourcePosition,e.howMany);let n=null,s=[];i.containsRange(t,!0)?n=t:t.start.hasSameParentAs(i.start)?(s=t.getDifference(i),n=t.getIntersection(i)):s=[t];const o=[];for(let t of s){t=t._getTransformedByDeletion(e.sourcePosition,e.howMany);const i=e.getMovedRangeStart(),n=t.start.hasSameParentAs(i),s=t._getTransformedByInsertion(i,e.howMany,n);o.push(...s)}n&&o.push(n._getTransformedByMove(e.sourcePosition,e.targetPosition,e.howMany,!1)[0]);return o}(t.range,e);return i.map((e=>new Zd(e,t.key,t.oldValue,t.newValue,t.baseVersion)))})),au(Zd,nu,((t,e)=>{if(t.range.end.isEqual(e.insertionPosition))return e.graveyardPosition||t.range.end.offset++,[t];if(t.range.start.hasSameParentAs(e.splitPosition)&&t.range.containsPosition(e.splitPosition)){const i=t.clone();return i.range=new kh(e.moveTargetPosition.clone(),t.range.end._getCombined(e.splitPosition,e.moveTargetPosition)),t.range.end=e.splitPosition.clone(),t.range.end.stickiness="toPrevious",[t,i]}return t.range=t.range._getTransformedBySplitOperation(e),[t]})),au(Jd,Zd,((t,e)=>{const i=[t];if(t.shouldReceiveAttributes&&t.position.hasSameParentAs(e.range.start)&&e.range.containsPosition(t.position)){const n=mu(t,e.key,e.newValue);n&&i.push(n)}return i})),au(Jd,Jd,((t,e,i)=>(t.position.isEqual(e.position)&&i.aIsStrong||(t.position=t.position._getTransformedByInsertOperation(e)),[t]))),au(Jd,Gd,((t,e)=>(t.position=t.position._getTransformedByMoveOperation(e),[t]))),au(Jd,nu,((t,e)=>(t.position=t.position._getTransformedBySplitOperation(e),[t]))),au(Jd,iu,((t,e)=>(t.position=t.position._getTransformedByMergeOperation(e),[t]))),au(Qd,Jd,((t,e)=>(t.oldRange&&(t.oldRange=t.oldRange._getTransformedByInsertOperation(e)[0]),t.newRange&&(t.newRange=t.newRange._getTransformedByInsertOperation(e)[0]),[t]))),au(Qd,Qd,((t,e,i)=>{if(t.name==e.name){if(!i.aIsStrong)return[new Xd(0)];t.oldRange=e.newRange?e.newRange.clone():null}return[t]})),au(Qd,iu,((t,e)=>(t.oldRange&&(t.oldRange=t.oldRange._getTransformedByMergeOperation(e)),t.newRange&&(t.newRange=t.newRange._getTransformedByMergeOperation(e)),[t]))),au(Qd,Gd,((t,e,i)=>{if(t.oldRange&&(t.oldRange=kh._createFromRanges(t.oldRange._getTransformedByMoveOperation(e))),t.newRange){if(i.abRelation){const n=kh._createFromRanges(t.newRange._getTransformedByMoveOperation(e));if("left"==i.abRelation.side&&e.targetPosition.isEqual(t.newRange.start))return t.newRange.end=n.end,t.newRange.start.path=i.abRelation.path,[t];if("right"==i.abRelation.side&&e.targetPosition.isEqual(t.newRange.end))return t.newRange.start=n.start,t.newRange.end.path=i.abRelation.path,[t]}t.newRange=kh._createFromRanges(t.newRange._getTransformedByMoveOperation(e))}return[t]})),au(Qd,nu,((t,e,i)=>{if(t.oldRange&&(t.oldRange=t.oldRange._getTransformedBySplitOperation(e)),t.newRange){if(i.abRelation){const n=t.newRange._getTransformedBySplitOperation(e);return t.newRange.start.isEqual(e.splitPosition)&&i.abRelation.wasStartBeforeMergedElement?t.newRange.start=ph._createAt(e.insertionPosition):t.newRange.start.isEqual(e.splitPosition)&&!i.abRelation.wasInLeftElement&&(t.newRange.start=ph._createAt(e.moveTargetPosition)),t.newRange.end.isEqual(e.splitPosition)&&i.abRelation.wasInRightElement?t.newRange.end=ph._createAt(e.moveTargetPosition):t.newRange.end.isEqual(e.splitPosition)&&i.abRelation.wasEndBeforeMergedElement?t.newRange.end=ph._createAt(e.insertionPosition):t.newRange.end=n.end,[t]}t.newRange=t.newRange._getTransformedBySplitOperation(e)}return[t]})),au(iu,Jd,((t,e)=>(t.sourcePosition.hasSameParentAs(e.position)&&(t.howMany+=e.howMany),t.sourcePosition=t.sourcePosition._getTransformedByInsertOperation(e),t.targetPosition=t.targetPosition._getTransformedByInsertOperation(e),[t]))),au(iu,iu,((t,e,i)=>{if(t.sourcePosition.isEqual(e.sourcePosition)&&t.targetPosition.isEqual(e.targetPosition)){if(i.bWasUndone){const i=e.graveyardPosition.path.slice();return i.push(0),t.sourcePosition=new ph(e.graveyardPosition.root,i),t.howMany=0,[t]}return[new Xd(0)]}if(t.sourcePosition.isEqual(e.sourcePosition)&&!t.targetPosition.isEqual(e.targetPosition)&&!i.bWasUndone&&"splitAtSource"!=i.abRelation){const n="$graveyard"==t.targetPosition.root.rootName,s="$graveyard"==e.targetPosition.root.rootName;if(s&&!n||!(n&&!s)&&i.aIsStrong){const i=e.targetPosition._getTransformedByMergeOperation(e),n=t.targetPosition._getTransformedByMergeOperation(e);return[new Gd(i,t.howMany,n,0)]}return[new Xd(0)]}return t.sourcePosition.hasSameParentAs(e.targetPosition)&&(t.howMany+=e.howMany),t.sourcePosition=t.sourcePosition._getTransformedByMergeOperation(e),t.targetPosition=t.targetPosition._getTransformedByMergeOperation(e),t.graveyardPosition.isEqual(e.graveyardPosition)&&i.aIsStrong||(t.graveyardPosition=t.graveyardPosition._getTransformedByMergeOperation(e)),[t]})),au(iu,Gd,((t,e,i)=>{const n=kh._createFromPositionAndShift(e.sourcePosition,e.howMany);return"remove"==e.type&&!i.bWasUndone&&!i.forceWeakRemove&&t.deletionPosition.hasSameParentAs(e.sourcePosition)&&n.containsPosition(t.sourcePosition)?[new Xd(0)]:(t.sourcePosition.hasSameParentAs(e.targetPosition)&&(t.howMany+=e.howMany),t.sourcePosition.hasSameParentAs(e.sourcePosition)&&(t.howMany-=e.howMany),t.sourcePosition=t.sourcePosition._getTransformedByMoveOperation(e),t.targetPosition=t.targetPosition._getTransformedByMoveOperation(e),t.graveyardPosition.isEqual(e.targetPosition)||(t.graveyardPosition=t.graveyardPosition._getTransformedByMoveOperation(e)),[t])})),au(iu,nu,((t,e,i)=>{if(e.graveyardPosition&&(t.graveyardPosition=t.graveyardPosition._getTransformedByDeletion(e.graveyardPosition,1),t.deletionPosition.isEqual(e.graveyardPosition)&&(t.howMany=e.howMany)),t.targetPosition.isEqual(e.splitPosition)){const n=0!=e.howMany,s=e.graveyardPosition&&t.deletionPosition.isEqual(e.graveyardPosition);if(n||s||"mergeTargetNotMoved"==i.abRelation)return t.sourcePosition=t.sourcePosition._getTransformedBySplitOperation(e),[t]}if(t.sourcePosition.isEqual(e.splitPosition)){if("mergeSourceNotMoved"==i.abRelation)return t.howMany=0,t.targetPosition=t.targetPosition._getTransformedBySplitOperation(e),[t];if("mergeSameElement"==i.abRelation||t.sourcePosition.offset>0)return t.sourcePosition=e.moveTargetPosition.clone(),t.targetPosition=t.targetPosition._getTransformedBySplitOperation(e),[t]}return t.sourcePosition.hasSameParentAs(e.splitPosition)&&(t.howMany=e.splitPosition.offset),t.sourcePosition=t.sourcePosition._getTransformedBySplitOperation(e),t.targetPosition=t.targetPosition._getTransformedBySplitOperation(e),[t]})),au(Gd,Jd,((t,e)=>{const i=kh._createFromPositionAndShift(t.sourcePosition,t.howMany)._getTransformedByInsertOperation(e,!1)[0];return t.sourcePosition=i.start,t.howMany=i.end.offset-i.start.offset,t.targetPosition.isEqual(e.position)||(t.targetPosition=t.targetPosition._getTransformedByInsertOperation(e)),[t]})),au(Gd,Gd,((t,e,i)=>{const n=kh._createFromPositionAndShift(t.sourcePosition,t.howMany),s=kh._createFromPositionAndShift(e.sourcePosition,e.howMany);let o,r=i.aIsStrong,a=!i.aIsStrong;if("insertBefore"==i.abRelation||"insertAfter"==i.baRelation?a=!0:"insertAfter"!=i.abRelation&&"insertBefore"!=i.baRelation||(a=!1),o=t.targetPosition.isEqual(e.targetPosition)&&a?t.targetPosition._getTransformedByDeletion(e.sourcePosition,e.howMany):t.targetPosition._getTransformedByMove(e.sourcePosition,e.targetPosition,e.howMany),gu(t,e)&&gu(e,t))return[e.getReversed()];if(n.containsPosition(e.targetPosition)&&n.containsRange(s,!0))return n.start=n.start._getTransformedByMove(e.sourcePosition,e.targetPosition,e.howMany),n.end=n.end._getTransformedByMove(e.sourcePosition,e.targetPosition,e.howMany),pu([n],o);if(s.containsPosition(t.targetPosition)&&s.containsRange(n,!0))return n.start=n.start._getCombined(e.sourcePosition,e.getMovedRangeStart()),n.end=n.end._getCombined(e.sourcePosition,e.getMovedRangeStart()),pu([n],o);const l=X(t.sourcePosition.getParentPath(),e.sourcePosition.getParentPath());if("prefix"==l||"extension"==l)return n.start=n.start._getTransformedByMove(e.sourcePosition,e.targetPosition,e.howMany),n.end=n.end._getTransformedByMove(e.sourcePosition,e.targetPosition,e.howMany),pu([n],o);"remove"!=t.type||"remove"==e.type||i.aWasUndone||i.forceWeakRemove?"remove"==t.type||"remove"!=e.type||i.bWasUndone||i.forceWeakRemove||(r=!1):r=!0;const c=[],h=n.getDifference(s);for(const t of h){t.start=t.start._getTransformedByDeletion(e.sourcePosition,e.howMany),t.end=t.end._getTransformedByDeletion(e.sourcePosition,e.howMany);const i="same"==X(t.start.getParentPath(),e.getMovedRangeStart().getParentPath()),n=t._getTransformedByInsertion(e.getMovedRangeStart(),e.howMany,i);c.push(...n)}const d=n.getIntersection(s);return null!==d&&r&&(d.start=d.start._getCombined(e.sourcePosition,e.getMovedRangeStart()),d.end=d.end._getCombined(e.sourcePosition,e.getMovedRangeStart()),0===c.length?c.push(d):1==c.length?s.start.isBefore(n.start)||s.start.isEqual(n.start)?c.unshift(d):c.push(d):c.splice(1,0,d)),0===c.length?[new Xd(t.baseVersion)]:pu(c,o)})),au(Gd,nu,((t,e,i)=>{let n=t.targetPosition.clone();t.targetPosition.isEqual(e.insertionPosition)&&e.graveyardPosition&&"moveTargetAfter"!=i.abRelation||(n=t.targetPosition._getTransformedBySplitOperation(e));const s=kh._createFromPositionAndShift(t.sourcePosition,t.howMany);if(s.end.isEqual(e.insertionPosition))return e.graveyardPosition||t.howMany++,t.targetPosition=n,[t];if(s.start.hasSameParentAs(e.splitPosition)&&s.containsPosition(e.splitPosition)){let t=new kh(e.splitPosition,s.end);t=t._getTransformedBySplitOperation(e);return pu([new kh(s.start,e.splitPosition),t],n)}t.targetPosition.isEqual(e.splitPosition)&&"insertAtSource"==i.abRelation&&(n=e.moveTargetPosition),t.targetPosition.isEqual(e.insertionPosition)&&"insertBetween"==i.abRelation&&(n=t.targetPosition);const o=[s._getTransformedBySplitOperation(e)];if(e.graveyardPosition){const n=s.start.isEqual(e.graveyardPosition)||s.containsPosition(e.graveyardPosition);t.howMany>1&&n&&!i.aWasUndone&&o.push(kh._createFromPositionAndShift(e.insertionPosition,1))}return pu(o,n)})),au(Gd,iu,((t,e,i)=>{const n=kh._createFromPositionAndShift(t.sourcePosition,t.howMany);if(e.deletionPosition.hasSameParentAs(t.sourcePosition)&&n.containsPosition(e.sourcePosition))if("remove"!=t.type||i.forceWeakRemove){if(1==t.howMany)return i.bWasUndone?(t.sourcePosition=e.graveyardPosition.clone(),t.targetPosition=t.targetPosition._getTransformedByMergeOperation(e),[t]):[new Xd(0)]}else if(!i.aWasUndone){const i=[];let n=e.graveyardPosition.clone(),s=e.targetPosition._getTransformedByMergeOperation(e);t.howMany>1&&(i.push(new Gd(t.sourcePosition,t.howMany-1,t.targetPosition,0)),n=n._getTransformedByMove(t.sourcePosition,t.targetPosition,t.howMany-1),s=s._getTransformedByMove(t.sourcePosition,t.targetPosition,t.howMany-1));const o=e.deletionPosition._getCombined(t.sourcePosition,t.targetPosition),r=new Gd(n,1,o,0),a=r.getMovedRangeStart().path.slice();a.push(0);const l=new ph(r.targetPosition.root,a);s=s._getTransformedByMove(n,o,1);const c=new Gd(s,e.howMany,l,0);return i.push(r),i.push(c),i}const s=kh._createFromPositionAndShift(t.sourcePosition,t.howMany)._getTransformedByMergeOperation(e);return t.sourcePosition=s.start,t.howMany=s.end.offset-s.start.offset,t.targetPosition=t.targetPosition._getTransformedByMergeOperation(e),[t]})),au(tu,Jd,((t,e)=>(t.position=t.position._getTransformedByInsertOperation(e),[t]))),au(tu,iu,((t,e)=>t.position.isEqual(e.deletionPosition)?(t.position=e.graveyardPosition.clone(),t.position.stickiness="toNext",[t]):(t.position=t.position._getTransformedByMergeOperation(e),[t]))),au(tu,Gd,((t,e)=>(t.position=t.position._getTransformedByMoveOperation(e),[t]))),au(tu,tu,((t,e,i)=>{if(t.position.isEqual(e.position)){if(!i.aIsStrong)return[new Xd(0)];t.oldName=e.newName}return[t]})),au(tu,nu,((t,e)=>{if("same"==X(t.position.path,e.splitPosition.getParentPath())&&!e.graveyardPosition){const e=new tu(t.position.getShiftedBy(1),t.oldName,t.newName,0);return[t,e]}return t.position=t.position._getTransformedBySplitOperation(e),[t]})),au(eu,eu,((t,e,i)=>{if(t.root===e.root&&t.key===e.key){if(!i.aIsStrong||t.newValue===e.newValue)return[new Xd(0)];t.oldValue=e.newValue}return[t]})),au(nu,Jd,((t,e)=>(t.splitPosition.hasSameParentAs(e.position)&&t.splitPosition.offset{if(!t.graveyardPosition&&!i.bWasUndone&&t.splitPosition.hasSameParentAs(e.sourcePosition)){const i=e.graveyardPosition.path.slice();i.push(0);const n=new ph(e.graveyardPosition.root,i),s=nu.getInsertionPosition(new ph(e.graveyardPosition.root,i)),o=new nu(n,0,s,null,0);return t.splitPosition=t.splitPosition._getTransformedByMergeOperation(e),t.insertionPosition=nu.getInsertionPosition(t.splitPosition),t.graveyardPosition=o.insertionPosition.clone(),t.graveyardPosition.stickiness="toNext",[o,t]}return t.splitPosition.hasSameParentAs(e.deletionPosition)&&!t.splitPosition.isAfter(e.deletionPosition)&&t.howMany--,t.splitPosition.hasSameParentAs(e.targetPosition)&&(t.howMany+=e.howMany),t.splitPosition=t.splitPosition._getTransformedByMergeOperation(e),t.insertionPosition=nu.getInsertionPosition(t.splitPosition),t.graveyardPosition&&(t.graveyardPosition=t.graveyardPosition._getTransformedByMergeOperation(e)),[t]})),au(nu,Gd,((t,e,i)=>{const n=kh._createFromPositionAndShift(e.sourcePosition,e.howMany);if(t.graveyardPosition){const s=n.start.isEqual(t.graveyardPosition)||n.containsPosition(t.graveyardPosition);if(!i.bWasUndone&&s){const i=t.splitPosition._getTransformedByMoveOperation(e),n=t.graveyardPosition._getTransformedByMoveOperation(e),s=n.path.slice();s.push(0);const o=new ph(n.root,s);return[new Gd(i,t.howMany,o,0)]}t.graveyardPosition=t.graveyardPosition._getTransformedByMoveOperation(e)}const s=t.splitPosition.isEqual(e.targetPosition);if(s&&("insertAtSource"==i.baRelation||"splitBefore"==i.abRelation))return t.howMany+=e.howMany,t.splitPosition=t.splitPosition._getTransformedByDeletion(e.sourcePosition,e.howMany),t.insertionPosition=nu.getInsertionPosition(t.splitPosition),[t];if(s&&i.abRelation&&i.abRelation.howMany){const{howMany:e,offset:n}=i.abRelation;return t.howMany+=e,t.splitPosition=t.splitPosition.getShiftedBy(n),[t]}if(t.splitPosition.hasSameParentAs(e.sourcePosition)&&n.containsPosition(t.splitPosition)){const i=e.howMany-(t.splitPosition.offset-e.sourcePosition.offset);return t.howMany-=i,t.splitPosition.hasSameParentAs(e.targetPosition)&&t.splitPosition.offset{if(t.splitPosition.isEqual(e.splitPosition)){if(!t.graveyardPosition&&!e.graveyardPosition)return[new Xd(0)];if(t.graveyardPosition&&e.graveyardPosition&&t.graveyardPosition.isEqual(e.graveyardPosition))return[new Xd(0)];if("splitBefore"==i.abRelation)return t.howMany=0,t.graveyardPosition=t.graveyardPosition._getTransformedBySplitOperation(e),[t]}if(t.graveyardPosition&&e.graveyardPosition&&t.graveyardPosition.isEqual(e.graveyardPosition)){const n="$graveyard"==t.splitPosition.root.rootName,s="$graveyard"==e.splitPosition.root.rootName;if(s&&!n||!(n&&!s)&&i.aIsStrong){const i=[];return e.howMany&&i.push(new Gd(e.moveTargetPosition,e.howMany,e.splitPosition,0)),t.howMany&&i.push(new Gd(t.splitPosition,t.howMany,t.moveTargetPosition,0)),i}return[new Xd(0)]}if(t.graveyardPosition&&(t.graveyardPosition=t.graveyardPosition._getTransformedBySplitOperation(e)),t.splitPosition.isEqual(e.insertionPosition)&&"splitBefore"==i.abRelation)return t.howMany++,[t];if(e.splitPosition.isEqual(t.insertionPosition)&&"splitBefore"==i.baRelation){const i=e.insertionPosition.path.slice();i.push(0);const n=new ph(e.insertionPosition.root,i);return[t,new Gd(t.insertionPosition,1,n,0)]}return t.splitPosition.hasSameParentAs(e.splitPosition)&&t.splitPosition.offset{const i=e[0];i.isDocumentOperation&&_u.call(this,i)}),{priority:"low"})}function _u(t){const e=this.getTransformedByOperation(t);if(!this.isEqual(e)){const t=this.toPosition();this.path=e.path,this.root=e.root,this.fire("change",t)}}wu.prototype.is=function(t){return"livePosition"===t||"model:livePosition"===t||"position"==t||"model:position"===t};class vu{constructor(t={}){"string"==typeof t&&(t="transparent"===t?{isUndoable:!1}:{},y("batch-constructor-deprecated-string-type"));const{isUndoable:e=!0,isLocal:i=!0,isUndo:n=!1,isTyping:s=!1}=t;this.operations=[],this.isUndoable=e,this.isLocal=i,this.isUndo=n,this.isTyping=s}get type(){return y("batch-type-deprecated"),"default"}get baseVersion(){for(const t of this.operations)if(null!==t.baseVersion)return t.baseVersion;return null}addOperation(t){return t.batch=this,this.operations.push(t),t}}class yu{constructor(t){this._changesInElement=new Map,this._elementSnapshots=new Map,this._changedMarkers=new Map,this._changeCount=0,this._cachedChanges=null,this._cachedChangesWithGraveyard=null,this._refreshedItems=new Set,this._markerCollection=t}get isEmpty(){return 0==this._changesInElement.size&&0==this._changedMarkers.size}bufferOperation(t){const e=t;switch(e.type){case"insert":if(this._isInInsertedElement(e.position.parent))return;this._markInsert(e.position.parent,e.position.offset,e.nodes.maxOffset);break;case"addAttribute":case"removeAttribute":case"changeAttribute":for(const t of e.range.getItems({shallow:!0}))this._isInInsertedElement(t.parent)||this._markAttribute(t);break;case"remove":case"move":case"reinsert":{if(e.sourcePosition.isEqual(e.targetPosition)||e.sourcePosition.getShiftedBy(e.howMany).isEqual(e.targetPosition))return;const t=this._isInInsertedElement(e.sourcePosition.parent),i=this._isInInsertedElement(e.targetPosition.parent);t||this._markRemove(e.sourcePosition.parent,e.sourcePosition.offset,e.howMany),i||this._markInsert(e.targetPosition.parent,e.getMovedRangeStart().offset,e.howMany);break}case"rename":{if(this._isInInsertedElement(e.position.parent))return;this._markRemove(e.position.parent,e.position.offset,1),this._markInsert(e.position.parent,e.position.offset,1);const t=kh._createFromPositionAndShift(e.position,1);for(const e of this._markerCollection.getMarkersIntersectingRange(t)){const t=e.getData();this.bufferMarkerChange(e.name,t,t)}break}case"split":{const t=e.splitPosition.parent;this._isInInsertedElement(t)||this._markRemove(t,e.splitPosition.offset,e.howMany),this._isInInsertedElement(e.insertionPosition.parent)||this._markInsert(e.insertionPosition.parent,e.insertionPosition.offset,1),e.graveyardPosition&&this._markRemove(e.graveyardPosition.parent,e.graveyardPosition.offset,1);break}case"merge":{const t=e.sourcePosition.parent;this._isInInsertedElement(t.parent)||this._markRemove(t.parent,t.startOffset,1);const i=e.graveyardPosition.parent;this._markInsert(i,e.graveyardPosition.offset,1);const n=e.targetPosition.parent;this._isInInsertedElement(n)||this._markInsert(n,e.targetPosition.offset,t.maxOffset);break}}this._cachedChanges=null}bufferMarkerChange(t,e,i){const n=this._changedMarkers.get(t);n?(n.newMarkerData=i,null==n.oldMarkerData.range&&null==i.range&&this._changedMarkers.delete(t)):this._changedMarkers.set(t,{newMarkerData:i,oldMarkerData:e})}getMarkersToRemove(){const t=[];for(const[e,i]of this._changedMarkers)null!=i.oldMarkerData.range&&t.push({name:e,range:i.oldMarkerData.range});return t}getMarkersToAdd(){const t=[];for(const[e,i]of this._changedMarkers)null!=i.newMarkerData.range&&t.push({name:e,range:i.newMarkerData.range});return t}getChangedMarkers(){return Array.from(this._changedMarkers).map((([t,e])=>({name:t,data:{oldRange:e.oldMarkerData.range,newRange:e.newMarkerData.range}})))}hasDataChanges(){if(this._changesInElement.size>0)return!0;for(const{newMarkerData:t,oldMarkerData:e}of this._changedMarkers.values()){if(t.affectsData!==e.affectsData)return!0;if(t.affectsData){const i=t.range&&!e.range,n=!t.range&&e.range,s=t.range&&e.range&&!t.range.isEqual(e.range);if(i||n||s)return!0}}return!1}getChanges(t={}){if(this._cachedChanges)return t.includeChangesInGraveyard?this._cachedChangesWithGraveyard.slice():this._cachedChanges.slice();let e=[];for(const t of this._changesInElement.keys()){const i=this._changesInElement.get(t).sort(((t,e)=>t.offset===e.offset?t.type!=e.type?"remove"==t.type?-1:1:0:t.offsett.position.root!=e.position.root?t.position.root.rootNamet));for(const t of e)delete t.changeCount,"attribute"==t.type&&(delete t.position,delete t.length);return this._changeCount=0,this._cachedChangesWithGraveyard=e,this._cachedChanges=e.filter(xu),t.includeChangesInGraveyard?this._cachedChangesWithGraveyard.slice():this._cachedChanges.slice()}getRefreshedItems(){return new Set(this._refreshedItems)}reset(){this._changesInElement.clear(),this._elementSnapshots.clear(),this._changedMarkers.clear(),this._refreshedItems=new Set,this._cachedChanges=null}_refreshItem(t){if(this._isInInsertedElement(t.parent))return;this._markRemove(t.parent,t.startOffset,t.offsetSize),this._markInsert(t.parent,t.startOffset,t.offsetSize),this._refreshedItems.add(t);const e=kh._createOn(t);for(const t of this._markerCollection.getMarkersIntersectingRange(e)){const e=t.getData();this.bufferMarkerChange(t.name,e,e)}this._cachedChanges=null}_markInsert(t,e,i){const n={type:"insert",offset:e,howMany:i,count:this._changeCount++};this._markChange(t,n)}_markRemove(t,e,i){const n={type:"remove",offset:e,howMany:i,count:this._changeCount++};this._markChange(t,n),this._removeAllNestedChanges(t,e,i)}_markAttribute(t){const e={type:"attribute",offset:t.startOffset,howMany:t.offsetSize,count:this._changeCount++};this._markChange(t.parent,e)}_markChange(t,e){this._makeSnapshot(t);const i=this._getChangesForElement(t);this._handleChange(e,i),i.push(e);for(let t=0;ti.offset){if(n>s){const t={type:"attribute",offset:s,howMany:n-s,count:this._changeCount++};this._handleChange(t,e),e.push(t)}t.nodesToHandle=i.offset-t.offset,t.howMany=t.nodesToHandle}else t.offset>=i.offset&&t.offsets?(t.nodesToHandle=n-s,t.offset=s):t.nodesToHandle=0);if("remove"==i.type&&t.offseti.offset){const s={type:"attribute",offset:i.offset,howMany:n-i.offset,count:this._changeCount++};this._handleChange(s,e),e.push(s),t.nodesToHandle=i.offset-t.offset,t.howMany=t.nodesToHandle}"attribute"==i.type&&(t.offset>=i.offset&&n<=s?(t.nodesToHandle=0,t.howMany=0,t.offset=0):t.offset<=i.offset&&n>=s&&(i.howMany=0))}}t.howMany=t.nodesToHandle,delete t.nodesToHandle}_getInsertDiff(t,e,i){return{type:"insert",position:ph._createAt(t,e),name:i.name,attributes:new Map(i.attributes),length:1,changeCount:this._changeCount++}}_getRemoveDiff(t,e,i){return{type:"remove",position:ph._createAt(t,e),name:i.name,attributes:new Map(i.attributes),length:1,changeCount:this._changeCount++}}_getAttributesDiff(t,e,i){const n=[];i=new Map(i);for(const[s,o]of e){const e=i.has(s)?i.get(s):null;e!==o&&n.push({type:"attribute",position:t.start,range:t.clone(),length:1,attributeKey:s,attributeOldValue:o,attributeNewValue:e,changeCount:this._changeCount++}),i.delete(s)}for(const[e,s]of i)n.push({type:"attribute",position:t.start,range:t.clone(),length:1,attributeKey:e,attributeOldValue:null,attributeNewValue:s,changeCount:this._changeCount++});return n}_isInInsertedElement(t){const e=t.parent;if(!e)return!1;const i=this._changesInElement.get(e),n=t.startOffset;if(i)for(const t of i)if("insert"==t.type&&n>=t.offset&&nn){for(let e=0;ethis._version+1&&this._gaps.set(this._version,t),this._version=t}get lastOperation(){return this._operations[this._operations.length-1]}addOperation(t){if(t.baseVersion!==this.version)throw new v("model-document-history-addoperation-incorrect-version",this,{operation:t,historyVersion:this.version});this._operations.push(t),this._version++,this._baseVersionToOperationIndex.set(t.baseVersion,this._operations.length-1)}getOperations(t,e=this.version){if(!this._operations.length)return[];const i=this._operations[0];void 0===t&&(t=i.baseVersion);let n=e-1;for(const[e,i]of this._gaps)t>e&&te&&nthis.lastOperation.baseVersion)return[];let s=this._baseVersionToOperationIndex.get(t);void 0===s&&(s=0);let o=this._baseVersionToOperationIndex.get(n);return void 0===o&&(o=this._operations.length-1),this._operations.slice(s,o+1)}getOperation(t){const e=this._baseVersionToOperationIndex.get(t);if(void 0!==e)return this._operations[e]}setOperationAsUndone(t,e){this._undoPairs.set(e,t),this._undoneOperations.add(t)}isUndoingOperation(t){return this._undoPairs.has(t)}isUndoneOperation(t){return this._undoneOperations.has(t)}getUndoneOperation(t){return this._undoPairs.get(t)}reset(){this._version=0,this._undoPairs=new Map,this._operations=[],this._undoneOperations=new Set,this._gaps=new Map,this._baseVersionToOperationIndex=new Map}}class Pu extends fh{constructor(t,e,i="main"){super(e),this._document=t,this.rootName=i}get document(){return this._document}toJSON(){return this.rootName}}Pu.prototype.is=function(t,e){return e?e===this.name&&("rootElement"===t||"model:rootElement"===t||"element"===t||"model:element"===t):"rootElement"===t||"model:rootElement"===t||"element"===t||"model:element"===t||"node"===t||"model:node"===t};const Tu="$graveyard";class Eu extends(R()){constructor(t){super(),this.model=t,this.history=new Cu,this.selection=new Fh(this),this.roots=new co({idProperty:"rootName"}),this.differ=new yu(t.markers),this._postFixers=new Set,this._hasSelectionChangedFromTheLastChangeBlock=!1,this.createRoot("$root",Tu),this.listenTo(t,"applyOperation",((t,e)=>{const i=e[0];i.isDocumentOperation&&this.differ.bufferOperation(i)}),{priority:"high"}),this.listenTo(t,"applyOperation",((t,e)=>{const i=e[0];i.isDocumentOperation&&this.history.addOperation(i)}),{priority:"low"}),this.listenTo(this.selection,"change",(()=>{this._hasSelectionChangedFromTheLastChangeBlock=!0})),this.listenTo(t.markers,"update",((t,e,i,n,s)=>{const o={...e.getData(),range:n};this.differ.bufferMarkerChange(e.name,s,o),null===i&&e.on("change",((t,i)=>{const n=e.getData();this.differ.bufferMarkerChange(e.name,{...n,range:i},n)}))}))}get version(){return this.history.version}set version(t){this.history.version=t}get graveyard(){return this.getRoot(Tu)}createRoot(t="$root",e="main"){if(this.roots.get(e))throw new v("model-document-createroot-name-exists",this,{name:e});const i=new Pu(this,t,e);return this.roots.add(i),i}destroy(){this.selection.destroy(),this.stopListening()}getRoot(t="main"){return this.roots.get(t)}getRootNames(){return Array.from(this.roots,(t=>t.rootName)).filter((t=>t!=Tu))}registerPostFixer(t){this._postFixers.add(t)}toJSON(){const t=Ar(this);return t.selection="[engine.model.DocumentSelection]",t.model="[engine.model.Model]",t}_handleChangeBlock(t){this._hasDocumentChangedFromTheLastChangeBlock()&&(this._callPostFixers(t),this.selection.refresh(),this.differ.hasDataChanges()?this.fire("change:data",t.batch):this.fire("change",t.batch),this.selection.refresh(),this.differ.reset()),this._hasSelectionChangedFromTheLastChangeBlock=!1}_hasDocumentChangedFromTheLastChangeBlock(){return!this.differ.isEmpty||this._hasSelectionChangedFromTheLastChangeBlock}_getDefaultRoot(){for(const t of this.roots)if(t!==this.graveyard)return t;return this.graveyard}_getDefaultRange(){const t=this._getDefaultRoot(),e=this.model,i=e.schema,n=e.createPositionFromPath(t,[0]);return i.getNearestSelectionRange(n)||e.createRange(n)}_validateSelectionRange(t){return Su(t.start)&&Su(t.end)}_callPostFixers(t){let e=!1;do{for(const i of this._postFixers)if(this.selection.refresh(),e=i(t),e)break}while(e)}}function Su(t){const e=t.textNode;if(e){const i=e.data,n=t.offset-e.startOffset;return!po(i,n)&&!wo(i,n)}return!0}class Ru extends(R()){constructor(){super(...arguments),this._markers=new Map}[Symbol.iterator](){return this._markers.values()}has(t){const e=t instanceof Ou?t.name:t;return this._markers.has(e)}get(t){return this._markers.get(t)||null}_set(t,e,i=!1,n=!1){const s=t instanceof Ou?t.name:t;if(s.includes(","))throw new v("markercollection-incorrect-marker-name",this);const o=this._markers.get(s);if(o){const t=o.getData(),r=o.getRange();let a=!1;return r.isEqual(e)||(o._attachLiveRange(Mh.fromRange(e)),a=!0),i!=o.managedUsingOperations&&(o._managedUsingOperations=i,a=!0),"boolean"==typeof n&&n!=o.affectsData&&(o._affectsData=n,a=!0),a&&this.fire(`update:${s}`,o,r,e,t),o}const r=Mh.fromRange(e),a=new Ou(s,r,i,n);return this._markers.set(s,a),this.fire(`update:${s}`,a,null,e,{...a.getData(),range:null}),a}_remove(t){const e=t instanceof Ou?t.name:t,i=this._markers.get(e);return!!i&&(this._markers.delete(e),this.fire(`update:${e}`,i,i.getRange(),null,i.getData()),this._destroyMarker(i),!0)}_refresh(t){const e=t instanceof Ou?t.name:t,i=this._markers.get(e);if(!i)throw new v("markercollection-refresh-marker-not-exists",this);const n=i.getRange();this.fire(`update:${e}`,i,n,n,i.getData())}*getMarkersAtPosition(t){for(const e of this)e.getRange().containsPosition(t)&&(yield e)}*getMarkersIntersectingRange(t){for(const e of this)null!==e.getRange().getIntersection(t)&&(yield e)}destroy(){for(const t of this._markers.values())this._destroyMarker(t);this._markers=null,this.stopListening()}*getMarkersGroup(t){for(const e of this._markers.values())e.name.startsWith(t+":")&&(yield e)}_destroyMarker(t){t.stopListening(),t._detachLiveRange()}}class Ou extends(R(lh)){constructor(t,e,i,n){super(),this.name=t,this._liveRange=this._attachLiveRange(e),this._managedUsingOperations=i,this._affectsData=n}get managedUsingOperations(){if(!this._liveRange)throw new v("marker-destroyed",this);return this._managedUsingOperations}get affectsData(){if(!this._liveRange)throw new v("marker-destroyed",this);return this._affectsData}getData(){return{range:this.getRange(),affectsData:this.affectsData,managedUsingOperations:this.managedUsingOperations}}getStart(){if(!this._liveRange)throw new v("marker-destroyed",this);return this._liveRange.start.clone()}getEnd(){if(!this._liveRange)throw new v("marker-destroyed",this);return this._liveRange.end.clone()}getRange(){if(!this._liveRange)throw new v("marker-destroyed",this);return this._liveRange.toRange()}_attachLiveRange(t){return this._liveRange&&this._detachLiveRange(),t.delegate("change:range").to(this),t.delegate("change:content").to(this),this._liveRange=t,t}_detachLiveRange(){this._liveRange.stopDelegating("change:range",this),this._liveRange.stopDelegating("change:content",this),this._liveRange.detach(),this._liveRange=null}}Ou.prototype.is=function(t){return"marker"===t||"model:marker"===t};class Iu extends zd{constructor(t,e){super(null),this.sourcePosition=t.clone(),this.howMany=e}get type(){return"detach"}toJSON(){const t=super.toJSON();return t.sourcePosition=this.sourcePosition.toJSON(),t}_validate(){if(this.sourcePosition.root.document)throw new v("detach-operation-on-document-node",this)}_execute(){jd(kh._createFromPositionAndShift(this.sourcePosition,this.howMany))}static get className(){return"DetachOperation"}}class Vu extends lh{constructor(t){super(),this.markers=new Map,this._children=new hh,t&&this._insertChild(0,t)}[Symbol.iterator](){return this.getChildren()}get childCount(){return this._children.length}get maxOffset(){return this._children.maxOffset}get isEmpty(){return 0===this.childCount}get nextSibling(){return null}get previousSibling(){return null}get root(){return this}get parent(){return null}get document(){return null}getAncestors(){return[]}getChild(t){return this._children.getNode(t)}getChildren(){return this._children[Symbol.iterator]()}getChildIndex(t){return this._children.getNodeIndex(t)}getChildStartOffset(t){return this._children.getNodeStartOffset(t)}getPath(){return[]}getNodeByPath(t){let e=this;for(const i of t)e=e.getChild(e.offsetToIndex(i));return e}offsetToIndex(t){return this._children.offsetToIndex(t)}toJSON(){const t=[];for(const e of this._children)t.push(e.toJSON());return t}static fromJSON(t){const e=[];for(const i of t)i.name?e.push(fh.fromJSON(i)):e.push(dh.fromJSON(i));return new Vu(e)}_appendChild(t){this._insertChild(this.childCount,t)}_insertChild(t,e){const i=function(t){if("string"==typeof t)return[new dh(t)];tt(t)||(t=[t]);return Array.from(t).map((t=>"string"==typeof t?new dh(t):t instanceof uh?new dh(t.data,t.getAttributes()):t))}(e);for(const t of i)null!==t.parent&&t._remove(),t.parent=this;this._children._insertNodes(t,i)}_removeChildren(t,e=1){const i=this._children._removeNodes(t,e);for(const t of i)t.parent=null;return i}}Vu.prototype.is=function(t){return"documentFragment"===t||"model:documentFragment"===t};class Mu{constructor(t,e){this.model=t,this.batch=e}createText(t,e){return new dh(t,e)}createElement(t,e){return new fh(t,e)}createDocumentFragment(){return new Vu}cloneElement(t,e=!0){return t._clone(e)}insert(t,e,i=0){if(this._assertWriterUsedCorrectly(),t instanceof dh&&""==t.data)return;const n=ph._createAt(e,i);if(t.parent){if(Lu(t.root,n.root))return void this.move(kh._createOn(t),n);if(t.root.document)throw new v("model-writer-insert-forbidden-move",this);this.remove(t)}const s=n.root.document?n.root.document.version:null,o=new Jd(n,t,s);if(t instanceof dh&&(o.shouldReceiveAttributes=!0),this.batch.addOperation(o),this.model.applyOperation(o),t instanceof Vu)for(const[e,i]of t.markers){const t=ph._createAt(i.root,0),s={range:new kh(i.start._getCombined(t,n),i.end._getCombined(t,n)),usingOperation:!0,affectsData:!0};this.model.markers.has(e)?this.updateMarker(e,s):this.addMarker(e,s)}}insertText(t,e,i,n){e instanceof Vu||e instanceof fh||e instanceof ph?this.insert(this.createText(t),e,i):this.insert(this.createText(t,e),i,n)}insertElement(t,e,i,n){e instanceof Vu||e instanceof fh||e instanceof ph?this.insert(this.createElement(t),e,i):this.insert(this.createElement(t,e),i,n)}append(t,e){this.insert(t,e,"end")}appendText(t,e,i){e instanceof Vu||e instanceof fh?this.insert(this.createText(t),e,"end"):this.insert(this.createText(t,e),i,"end")}appendElement(t,e,i){e instanceof Vu||e instanceof fh?this.insert(this.createElement(t),e,"end"):this.insert(this.createElement(t,e),i,"end")}setAttribute(t,e,i){if(this._assertWriterUsedCorrectly(),i instanceof kh){const n=i.getMinimalFlatRanges();for(const i of n)Nu(this,t,e,i)}else Bu(this,t,e,i)}setAttributes(t,e){for(const[i,n]of mo(t))this.setAttribute(i,n,e)}removeAttribute(t,e){if(this._assertWriterUsedCorrectly(),e instanceof kh){const i=e.getMinimalFlatRanges();for(const e of i)Nu(this,t,null,e)}else Bu(this,t,null,e)}clearAttributes(t){this._assertWriterUsedCorrectly();const e=t=>{for(const e of t.getAttributeKeys())this.removeAttribute(e,t)};if(t instanceof kh)for(const i of t.getItems())e(i);else e(t)}move(t,e,i){if(this._assertWriterUsedCorrectly(),!(t instanceof kh))throw new v("writer-move-invalid-range",this);if(!t.isFlat)throw new v("writer-move-range-not-flat",this);const n=ph._createAt(e,i);if(n.isEqual(t.start))return;if(this._addOperationForAffectedMarkers("move",t),!Lu(t.root,n.root))throw new v("writer-move-different-document",this);const s=t.root.document?t.root.document.version:null,o=new Gd(t.start,t.end.offset-t.start.offset,n,s);this.batch.addOperation(o),this.model.applyOperation(o)}remove(t){this._assertWriterUsedCorrectly();const e=(t instanceof kh?t:kh._createOn(t)).getMinimalFlatRanges().reverse();for(const t of e)this._addOperationForAffectedMarkers("move",t),Fu(t.start,t.end.offset-t.start.offset,this.batch,this.model)}merge(t){this._assertWriterUsedCorrectly();const e=t.nodeBefore,i=t.nodeAfter;if(this._addOperationForAffectedMarkers("merge",t),!(e instanceof fh))throw new v("writer-merge-no-element-before",this);if(!(i instanceof fh))throw new v("writer-merge-no-element-after",this);t.root.document?this._merge(t):this._mergeDetached(t)}createPositionFromPath(t,e,i){return this.model.createPositionFromPath(t,e,i)}createPositionAt(t,e){return this.model.createPositionAt(t,e)}createPositionAfter(t){return this.model.createPositionAfter(t)}createPositionBefore(t){return this.model.createPositionBefore(t)}createRange(t,e){return this.model.createRange(t,e)}createRangeIn(t){return this.model.createRangeIn(t)}createRangeOn(t){return this.model.createRangeOn(t)}createSelection(...t){return this.model.createSelection(...t)}_mergeDetached(t){const e=t.nodeBefore,i=t.nodeAfter;this.move(kh._createIn(i),ph._createAt(e,"end")),this.remove(i)}_merge(t){const e=ph._createAt(t.nodeBefore,"end"),i=ph._createAt(t.nodeAfter,0),n=t.root.document.graveyard,s=new ph(n,[0]),o=t.root.document.version,r=new iu(i,t.nodeAfter.maxOffset,e,s,o);this.batch.addOperation(r),this.model.applyOperation(r)}rename(t,e){if(this._assertWriterUsedCorrectly(),!(t instanceof fh))throw new v("writer-rename-not-element-instance",this);const i=t.root.document?t.root.document.version:null,n=new tu(ph._createBefore(t),t.name,e,i);this.batch.addOperation(n),this.model.applyOperation(n)}split(t,e){this._assertWriterUsedCorrectly();let i,n,s=t.parent;if(!s.parent)throw new v("writer-split-element-no-parent",this);if(e||(e=s.parent),!t.parent.getAncestors({includeSelf:!0}).includes(e))throw new v("writer-split-invalid-limit-element",this);do{const e=s.root.document?s.root.document.version:null,o=s.maxOffset-t.offset,r=nu.getInsertionPosition(t),a=new nu(t,o,r,null,e);this.batch.addOperation(a),this.model.applyOperation(a),i||n||(i=s,n=t.parent.nextSibling),s=(t=this.createPositionAfter(t.parent)).parent}while(s!==e);return{position:t,range:new kh(ph._createAt(i,"end"),ph._createAt(n,0))}}wrap(t,e){if(this._assertWriterUsedCorrectly(),!t.isFlat)throw new v("writer-wrap-range-not-flat",this);const i=e instanceof fh?e:new fh(e);if(i.childCount>0)throw new v("writer-wrap-element-not-empty",this);if(null!==i.parent)throw new v("writer-wrap-element-attached",this);this.insert(i,t.start);const n=new kh(t.start.getShiftedBy(1),t.end.getShiftedBy(1));this.move(n,ph._createAt(i,0))}unwrap(t){if(this._assertWriterUsedCorrectly(),null===t.parent)throw new v("writer-unwrap-element-no-parent",this);this.move(kh._createIn(t),this.createPositionAfter(t)),this.remove(t)}addMarker(t,e){if(this._assertWriterUsedCorrectly(),!e||"boolean"!=typeof e.usingOperation)throw new v("writer-addmarker-no-usingoperation",this);const i=e.usingOperation,n=e.range,s=void 0!==e.affectsData&&e.affectsData;if(this.model.markers.has(t))throw new v("writer-addmarker-marker-exists",this);if(!n)throw new v("writer-addmarker-no-range",this);return i?(Du(this,t,null,n,s),this.model.markers.get(t)):this.model.markers._set(t,n,i,s)}updateMarker(t,e){this._assertWriterUsedCorrectly();const i="string"==typeof t?t:t.name,n=this.model.markers.get(i);if(!n)throw new v("writer-updatemarker-marker-not-exists",this);if(!e)return y("writer-updatemarker-reconvert-using-editingcontroller",{markerName:i}),void this.model.markers._refresh(n);const s="boolean"==typeof e.usingOperation,o="boolean"==typeof e.affectsData,r=o?e.affectsData:n.affectsData;if(!s&&!e.range&&!o)throw new v("writer-updatemarker-wrong-options",this);const a=n.getRange(),l=e.range?e.range:a;s&&e.usingOperation!==n.managedUsingOperations?e.usingOperation?Du(this,i,null,l,r):(Du(this,i,a,null,r),this.model.markers._set(i,l,void 0,r)):n.managedUsingOperations?Du(this,i,a,l,r):this.model.markers._set(i,l,void 0,r)}removeMarker(t){this._assertWriterUsedCorrectly();const e="string"==typeof t?t:t.name;if(!this.model.markers.has(e))throw new v("writer-removemarker-no-marker",this);const i=this.model.markers.get(e);if(!i.managedUsingOperations)return void this.model.markers._remove(e);Du(this,e,i.getRange(),null,i.affectsData)}setSelection(...t){this._assertWriterUsedCorrectly(),this.model.document.selection._setTo(...t)}setSelectionFocus(t,e){this._assertWriterUsedCorrectly(),this.model.document.selection._setFocus(t,e)}setSelectionAttribute(t,e){if(this._assertWriterUsedCorrectly(),"string"==typeof t)this._setSelectionAttribute(t,e);else for(const[e,i]of mo(t))this._setSelectionAttribute(e,i)}removeSelectionAttribute(t){if(this._assertWriterUsedCorrectly(),"string"==typeof t)this._removeSelectionAttribute(t);else for(const e of t)this._removeSelectionAttribute(e)}overrideSelectionGravity(){return this.model.document.selection._overrideGravity()}restoreSelectionGravity(t){this.model.document.selection._restoreGravity(t)}_setSelectionAttribute(t,e){const i=this.model.document.selection;if(i.isCollapsed&&i.anchor.parent.isEmpty){const n=Fh._getStoreAttributeKey(t);this.setAttribute(n,e,i.anchor.parent)}i._setAttribute(t,e)}_removeSelectionAttribute(t){const e=this.model.document.selection;if(e.isCollapsed&&e.anchor.parent.isEmpty){const i=Fh._getStoreAttributeKey(t);this.removeAttribute(i,e.anchor.parent)}e._removeAttribute(t)}_assertWriterUsedCorrectly(){if(this.model._currentWriter!==this)throw new v("writer-incorrect-use",this)}_addOperationForAffectedMarkers(t,e){for(const i of this.model.markers){if(!i.managedUsingOperations)continue;const n=i.getRange();let s=!1;if("move"===t){const t=e;s=t.containsPosition(n.start)||t.start.isEqual(n.start)||t.containsPosition(n.end)||t.end.isEqual(n.end)}else{const t=e,i=t.nodeBefore,o=t.nodeAfter,r=n.start.parent==i&&n.start.isAtEnd,a=n.end.parent==o&&0==n.end.offset,l=n.end.nodeAfter==o,c=n.start.nodeAfter==o;s=r||a||l||c}s&&this.updateMarker(i.name,{range:n})}}}function Nu(t,e,i,n){const s=t.model,o=s.document;let r,a,l,c=n.start;for(const t of n.getWalker({shallow:!0}))l=t.item.getAttribute(e),r&&a!=l&&(a!=i&&h(),c=r),r=t.nextPosition,a=l;function h(){const n=new kh(c,r),l=n.root.document?o.version:null,h=new Zd(n,e,a,i,l);t.batch.addOperation(h),s.applyOperation(h)}r instanceof ph&&r!=c&&a!=i&&h()}function Bu(t,e,i,n){const s=t.model,o=s.document,r=n.getAttribute(e);let a,l;if(r!=i){if(n.root===n){const t=n.document?o.version:null;l=new eu(n,e,r,i,t)}else{a=new kh(ph._createBefore(n),t.createPositionAfter(n));const s=a.root.document?o.version:null;l=new Zd(a,e,r,i,s)}t.batch.addOperation(l),s.applyOperation(l)}}function Du(t,e,i,n,s){const o=t.model,r=o.document,a=new Qd(e,i,n,o.markers,!!s,r.version);t.batch.addOperation(a),o.applyOperation(a)}function Fu(t,e,i,n){let s;if(t.root.document){const i=n.document,o=new ph(i.graveyard,[0]);s=new Gd(t,e,o,i.version)}else s=new Iu(t,e);i.addOperation(s),n.applyOperation(s)}function Lu(t,e){return t===e||t instanceof Pu&&e instanceof Pu}function zu(t){t.document.registerPostFixer((e=>function(t,e){const i=e.document.selection,n=e.schema,s=[];let o=!1;for(const t of i.getRanges()){const e=Hu(t,n);e&&!e.isEqual(t)?(s.push(e),o=!0):s.push(t)}o&&t.setSelection(function(t){const e=[...t],i=new Set;let n=1;for(;n!i.has(e)))}(s),{backward:i.isBackward});return!1}(e,t)))}function Hu(t,e){return t.isCollapsed?function(t,e){const i=t.start,n=e.getNearestSelectionRange(i);if(!n){const t=i.getAncestors().reverse().find((t=>e.isObject(t)));return t?kh._createOn(t):null}if(!n.isCollapsed)return n;const s=n.start;if(i.isEqual(s))return null;return new kh(s)}(t,e):function(t,e){const{start:i,end:n}=t,s=e.checkChild(i,"$text"),o=e.checkChild(n,"$text"),r=e.getLimitElement(i),a=e.getLimitElement(n);if(r===a){if(s&&o)return null;if(function(t,e,i){const n=t.nodeAfter&&!i.isLimit(t.nodeAfter)||i.checkChild(t,"$text"),s=e.nodeBefore&&!i.isLimit(e.nodeBefore)||i.checkChild(e,"$text");return n||s}(i,n,e)){const t=i.nodeAfter&&e.isSelectable(i.nodeAfter)?null:e.getNearestSelectionRange(i,"forward"),s=n.nodeBefore&&e.isSelectable(n.nodeBefore)?null:e.getNearestSelectionRange(n,"backward"),o=t?t.start:i,r=s?s.end:n;return new kh(o,r)}}const l=r&&!r.is("rootElement"),c=a&&!a.is("rootElement");if(l||c){const t=i.nodeAfter&&n.nodeBefore&&i.nodeAfter.parent===n.nodeBefore.parent,s=l&&(!t||!$u(i.nodeAfter,e)),o=c&&(!t||!$u(n.nodeBefore,e));let h=i,d=n;return s&&(h=ph._createBefore(ju(r,e))),o&&(d=ph._createAfter(ju(a,e))),new kh(h,d)}return null}(t,e)}function ju(t,e){let i=t,n=i;for(;e.isLimit(n)&&n.parent;)i=n,n=n.parent;return i}function $u(t,e){return t&&e.isSelectable(t)}function Wu(t,e,i={}){if(e.isCollapsed)return;const n=e.getFirstRange();if("$graveyard"==n.root.rootName)return;const s=t.schema;t.change((t=>{if(!i.doNotResetEntireContent&&function(t,e){const i=t.getLimitElement(e);if(!e.containsEntireContent(i))return!1;const n=e.getFirstRange();if(n.start.parent==n.end.parent)return!1;return t.checkChild(i,"paragraph")}(s,e))return void function(t,e){const i=t.model.schema.getLimitElement(e);t.remove(t.createRangeIn(i)),Gu(t,t.createPositionAt(i,0),e)}(t,e);const o={};if(!i.doNotAutoparagraph){const t=e.getSelectedElement();t&&Object.assign(o,s.getAttributesWithProperty(t,"copyOnReplace",!0))}const[r,a]=function(t){const e=t.root.document.model,i=t.start;let n=t.end;if(e.hasContent(t,{ignoreMarkers:!0})){const i=function(t){const e=t.parent,i=e.root.document.model.schema,n=e.getAncestors({parentFirst:!0,includeSelf:!0});for(const t of n){if(i.isLimit(t))return null;if(i.isBlock(t))return t}}(n);if(i&&n.isTouching(e.createPositionAt(i,0))){const i=e.createSelection(t);e.modifySelection(i,{direction:"backward"});const s=i.getLastPosition(),o=e.createRange(s,n);e.hasContent(o,{ignoreMarkers:!0})||(n=s)}}return[wu.fromPosition(i,"toPrevious"),wu.fromPosition(n,"toNext")]}(n);r.isTouching(a)||t.remove(t.createRange(r,a)),i.leaveUnmerged||(!function(t,e,i){const n=t.model;if(!Ku(t.model.schema,e,i))return;const[s,o]=function(t,e){const i=t.getAncestors(),n=e.getAncestors();let s=0;for(;i[s]&&i[s]==n[s];)s++;return[i[s],n[s]]}(e,i);if(!s||!o)return;!n.hasContent(s,{ignoreMarkers:!0})&&n.hasContent(o,{ignoreMarkers:!0})?Uu(t,e,i,s.parent):qu(t,e,i,s.parent)}(t,r,a),s.removeDisallowedAttributes(r.parent.getChildren(),t)),Ju(t,e,r),!i.doNotAutoparagraph&&function(t,e){const i=t.checkChild(e,"$text"),n=t.checkChild(e,"paragraph");return!i&&n}(s,r)&&Gu(t,r,e,o),r.detach(),a.detach()}))}function qu(t,e,i,n){const s=e.parent,o=i.parent;if(s!=n&&o!=n){for(e=t.createPositionAfter(s),(i=t.createPositionBefore(o)).isEqual(e)||t.insert(o,e),t.merge(e);i.parent.isEmpty;){const e=i.parent;i=t.createPositionBefore(e),t.remove(e)}Ku(t.model.schema,e,i)&&qu(t,e,i,n)}}function Uu(t,e,i,n){const s=e.parent,o=i.parent;if(s!=n&&o!=n){for(e=t.createPositionAfter(s),(i=t.createPositionBefore(o)).isEqual(e)||t.insert(s,i);e.parent.isEmpty;){const i=e.parent;e=t.createPositionBefore(i),t.remove(i)}i=t.createPositionBefore(o),function(t,e){const i=e.nodeBefore,n=e.nodeAfter;i.name!=n.name&&t.rename(i,n.name);t.clearAttributes(i),t.setAttributes(Object.fromEntries(n.getAttributes()),i),t.merge(e)}(t,i),Ku(t.model.schema,e,i)&&Uu(t,e,i,n)}}function Ku(t,e,i){const n=e.parent,s=i.parent;return n!=s&&(!t.isLimit(n)&&!t.isLimit(s)&&function(t,e,i){const n=new kh(t,e);for(const t of n.getWalker())if(i.isLimit(t.item))return!1;return!0}(e,i,t))}function Gu(t,e,i,n={}){const s=t.createElement("paragraph");t.model.schema.setAllowedAttributes(s,n,t),t.insert(s,e),Ju(t,i,t.createPositionAt(s,0))}function Ju(t,e,i){e instanceof Fh?t.setSelection(i):e.setTo(i)}function Qu(t,e){const i=[];Array.from(t.getItems({direction:"backward"})).map((t=>e.createRangeOn(t))).filter((e=>(e.start.isAfter(t.start)||e.start.isEqual(t.start))&&(e.end.isBefore(t.end)||e.end.isEqual(t.end)))).forEach((t=>{i.push(t.start.parent),e.remove(t)})),i.forEach((t=>{let i=t;for(;i.parent&&i.isEmpty;){const t=e.createRangeOn(i);i=i.parent,e.remove(t)}}))}class Yu{constructor(t,e,i){this._firstNode=null,this._lastNode=null,this._lastAutoParagraph=null,this._filterAttributesOf=[],this._affectedStart=null,this._affectedEnd=null,this._nodeToSelect=null,this.model=t,this.writer=e,this.position=i,this.canMergeWith=new Set([this.position.parent]),this.schema=t.schema,this._documentFragment=e.createDocumentFragment(),this._documentFragmentPosition=e.createPositionAt(this._documentFragment,0)}handleNodes(t){for(const e of Array.from(t))this._handleNode(e);this._insertPartialFragment(),this._lastAutoParagraph&&this._updateLastNodeFromAutoParagraph(this._lastAutoParagraph),this._mergeOnRight(),this.schema.removeDisallowedAttributes(this._filterAttributesOf,this.writer),this._filterAttributesOf=[]}_updateLastNodeFromAutoParagraph(t){const e=this.writer.createPositionAfter(this._lastNode),i=this.writer.createPositionAfter(t);if(i.isAfter(e)){if(this._lastNode=t,this.position.parent!=t||!this.position.isAtEnd)throw new v("insertcontent-invalid-insertion-position",this);this.position=i,this._setAffectedBoundaries(this.position)}}getSelectionRange(){return this._nodeToSelect?kh._createOn(this._nodeToSelect):this.model.schema.getNearestSelectionRange(this.position)}getAffectedRange(){return this._affectedStart?new kh(this._affectedStart,this._affectedEnd):null}destroy(){this._affectedStart&&this._affectedStart.detach(),this._affectedEnd&&this._affectedEnd.detach()}_handleNode(t){if(this.schema.isObject(t))return void this._handleObject(t);let e=this._checkAndAutoParagraphToAllowedPosition(t);e||(e=this._checkAndSplitToAllowedPosition(t),e)?(this._appendToFragment(t),this._firstNode||(this._firstNode=t),this._lastNode=t):this._handleDisallowedNode(t)}_insertPartialFragment(){if(this._documentFragment.isEmpty)return;const t=wu.fromPosition(this.position,"toNext");this._setAffectedBoundaries(this.position),this._documentFragment.getChild(0)==this._firstNode&&(this.writer.insert(this._firstNode,this.position),this._mergeOnLeft(),this.position=t.toPosition()),this._documentFragment.isEmpty||this.writer.insert(this._documentFragment,this.position),this._documentFragmentPosition=this.writer.createPositionAt(this._documentFragment,0),this.position=t.toPosition(),t.detach()}_handleObject(t){this._checkAndSplitToAllowedPosition(t)?this._appendToFragment(t):this._tryAutoparagraphing(t)}_handleDisallowedNode(t){t.is("element")?this.handleNodes(t.getChildren()):this._tryAutoparagraphing(t)}_appendToFragment(t){if(!this.schema.checkChild(this.position,t))throw new v("insertcontent-wrong-position",this,{node:t,position:this.position});this.writer.insert(t,this._documentFragmentPosition),this._documentFragmentPosition=this._documentFragmentPosition.getShiftedBy(t.offsetSize),this.schema.isObject(t)&&!this.schema.checkChild(this.position,"$text")?this._nodeToSelect=t:this._nodeToSelect=null,this._filterAttributesOf.push(t)}_setAffectedBoundaries(t){this._affectedStart||(this._affectedStart=wu.fromPosition(t,"toPrevious")),this._affectedEnd&&!this._affectedEnd.isBefore(t)||(this._affectedEnd&&this._affectedEnd.detach(),this._affectedEnd=wu.fromPosition(t,"toNext"))}_mergeOnLeft(){const t=this._firstNode;if(!(t instanceof fh))return;if(!this._canMergeLeft(t))return;const e=wu._createBefore(t);e.stickiness="toNext";const i=wu.fromPosition(this.position,"toNext");this._affectedStart.isEqual(e)&&(this._affectedStart.detach(),this._affectedStart=wu._createAt(e.nodeBefore,"end","toPrevious")),this._firstNode===this._lastNode&&(this._firstNode=e.nodeBefore,this._lastNode=e.nodeBefore),this.writer.merge(e),e.isEqual(this._affectedEnd)&&this._firstNode===this._lastNode&&(this._affectedEnd.detach(),this._affectedEnd=wu._createAt(e.nodeBefore,"end","toNext")),this.position=i.toPosition(),i.detach(),this._filterAttributesOf.push(this.position.parent),e.detach()}_mergeOnRight(){const t=this._lastNode;if(!(t instanceof fh))return;if(!this._canMergeRight(t))return;const e=wu._createAfter(t);if(e.stickiness="toNext",!this.position.isEqual(e))throw new v("insertcontent-invalid-insertion-position",this);this.position=ph._createAt(e.nodeBefore,"end");const i=wu.fromPosition(this.position,"toPrevious");this._affectedEnd.isEqual(e)&&(this._affectedEnd.detach(),this._affectedEnd=wu._createAt(e.nodeBefore,"end","toNext")),this._firstNode===this._lastNode&&(this._firstNode=e.nodeBefore,this._lastNode=e.nodeBefore),this.writer.merge(e),e.getShiftedBy(-1).isEqual(this._affectedStart)&&this._firstNode===this._lastNode&&(this._affectedStart.detach(),this._affectedStart=wu._createAt(e.nodeBefore,0,"toPrevious")),this.position=i.toPosition(),i.detach(),this._filterAttributesOf.push(this.position.parent),e.detach()}_canMergeLeft(t){const e=t.previousSibling;return e instanceof fh&&this.canMergeWith.has(e)&&this.model.schema.checkMerge(e,t)}_canMergeRight(t){const e=t.nextSibling;return e instanceof fh&&this.canMergeWith.has(e)&&this.model.schema.checkMerge(t,e)}_tryAutoparagraphing(t){const e=this.writer.createElement("paragraph");this._getAllowedIn(this.position.parent,e)&&this.schema.checkChild(e,t)&&(e._appendChild(t),this._handleNode(e))}_checkAndAutoParagraphToAllowedPosition(t){if(this.schema.checkChild(this.position.parent,t))return!0;if(!this.schema.checkChild(this.position.parent,"paragraph")||!this.schema.checkChild("paragraph",t))return!1;this._insertPartialFragment();const e=this.writer.createElement("paragraph");return this.writer.insert(e,this.position),this._setAffectedBoundaries(this.position),this._lastAutoParagraph=e,this.position=this.writer.createPositionAt(e,0),!0}_checkAndSplitToAllowedPosition(t){const e=this._getAllowedIn(this.position.parent,t);if(!e)return!1;for(e!=this.position.parent&&this._insertPartialFragment();e!=this.position.parent;)if(this.position.isAtStart){const t=this.position.parent;this.position=this.writer.createPositionBefore(t),t.isEmpty&&t.parent===e&&this.writer.remove(t)}else if(this.position.isAtEnd)this.position=this.writer.createPositionAfter(this.position.parent);else{const t=this.writer.createPositionAfter(this.position.parent);this._setAffectedBoundaries(this.position),this.writer.split(this.position),this.position=t,this.canMergeWith.add(this.position.nodeAfter)}return!0}_getAllowedIn(t,e){return this.schema.checkChild(t,e)?t:this.schema.isLimit(t)?null:this._getAllowedIn(t.parent,e)}}function Zu(t,e,i="auto"){const n=t.getSelectedElement();if(n&&e.schema.isObject(n)&&!e.schema.isInline(n))return"before"==i||"after"==i?e.createRange(e.createPositionAt(n,i)):e.createRangeOn(n);const s=ho(t.getSelectedBlocks());if(!s)return e.createRange(t.focus);if(s.isEmpty)return e.createRange(e.createPositionAt(s,0));const o=e.createPositionAfter(s);return t.focus.isTouching(o)?e.createRange(o):e.createRange(e.createPositionBefore(s))}function Xu(t,e,i,n,s={}){if(!t.schema.isObject(e))throw new v("insertobject-element-not-an-object",t,{object:e});let o;o=i?i instanceof Sh||i instanceof Fh?i:t.createSelection(i,n):t.document.selection;let r=o;s.findOptimalPosition&&t.schema.isBlock(e)&&(r=t.createSelection(Zu(o,t,s.findOptimalPosition)));const a=ho(o.getSelectedBlocks()),l={};return a&&Object.assign(l,t.schema.getAttributesWithProperty(a,"copyOnReplace",!0)),t.change((i=>{r.isCollapsed||t.deleteContent(r,{doNotAutoparagraph:!0});let n=e;const o=r.anchor.parent;!t.schema.checkChild(o,e)&&t.schema.checkChild(o,"paragraph")&&t.schema.checkChild("paragraph",e)&&(n=i.createElement("paragraph"),i.insert(e,n)),t.schema.setAllowedAttributes(n,l,i);const a=t.insertContent(n,r);return a.isCollapsed||s.setSelection&&function(t,e,i,n){const s=t.model;if("on"==i)return void t.setSelection(e,"on");if("after"!=i)throw new v("insertobject-invalid-place-parameter-value",s);let o=e.nextSibling;if(s.schema.isInline(e))return void t.setSelection(e,"after");const r=o&&s.schema.checkChild(o,"$text");!r&&s.schema.checkChild(e.parent,"paragraph")&&(o=t.createElement("paragraph"),s.schema.setAllowedAttributes(o,n,t),s.insertContent(o,t.createPositionAfter(e)));o&&t.setSelection(o,0)}(i,e,s.setSelection,l),a}))}const tf=' ,.?!:;"-()';function ef(t,e){const{isForward:i,walker:n,unit:s,schema:o,treatEmojiAsSingleUnit:r}=t,{type:a,item:l,nextPosition:c}=e;if("text"==a)return"word"===t.unit?function(t,e){let i=t.position.textNode;i||(i=e?t.position.nodeAfter:t.position.nodeBefore);for(;i&&i.is("$text");){const n=t.position.offset-i.startOffset;if(of(i,n,e))i=e?t.position.nodeAfter:t.position.nodeBefore;else{if(sf(i.data,n,e))break;t.next()}}return t.position}(n,i):function(t,e,i){const n=t.position.textNode;if(n){const s=n.data;let o=t.position.offset-n.startOffset;for(;po(s,o)||"character"==e&&wo(s,o)||i&&_o(s,o);)t.next(),o=t.position.offset-n.startOffset}return t.position}(n,s,r);if(a==(i?"elementStart":"elementEnd")){if(o.isSelectable(l))return ph._createAt(l,i?"after":"before");if(o.checkChild(c,"$text"))return c}else{if(o.isLimit(l))return void n.skip((()=>!0));if(o.checkChild(c,"$text"))return c}}function nf(t,e){const i=t.root,n=ph._createAt(i,e?"end":0);return e?new kh(t,n):new kh(n,t)}function sf(t,e,i){const n=e+(i?0:-1);return tf.includes(t.charAt(n))}function of(t,e,i){return e===(i?t.offsetSize:0)}class rf extends(q()){constructor(){super(),this.markers=new Ru,this.document=new Eu(this),this.schema=new bd,this._pendingChanges=[],this._currentWriter=null,["insertContent","insertObject","deleteContent","modifySelection","getSelectedContent","applyOperation"].forEach((t=>this.decorate(t))),this.on("applyOperation",((t,e)=>{e[0]._validate()}),{priority:"highest"}),this.schema.register("$root",{isLimit:!0}),this.schema.register("$container",{allowIn:["$root","$container"]}),this.schema.register("$block",{allowIn:["$root","$container"],isBlock:!0}),this.schema.register("$blockObject",{allowWhere:"$block",isBlock:!0,isObject:!0}),this.schema.register("$inlineObject",{allowWhere:"$text",allowAttributesOf:"$text",isInline:!0,isObject:!0}),this.schema.register("$text",{allowIn:"$block",isInline:!0,isContent:!0}),this.schema.register("$clipboardHolder",{allowContentOf:"$root",allowChildren:"$text",isLimit:!0}),this.schema.register("$documentFragment",{allowContentOf:"$root",allowChildren:"$text",isLimit:!0}),this.schema.register("$marker"),this.schema.addChildCheck(((t,e)=>{if("$marker"===e.name)return!0})),zu(this),this.document.registerPostFixer(sd)}change(t){try{return 0===this._pendingChanges.length?(this._pendingChanges.push({batch:new vu,callback:t}),this._runPendingChanges()[0]):t(this._currentWriter)}catch(t){v.rethrowUnexpectedError(t,this)}}enqueueChange(t,e){try{t?"function"==typeof t?(e=t,t=new vu):t instanceof vu||(t=new vu(t)):t=new vu,this._pendingChanges.push({batch:t,callback:e}),1==this._pendingChanges.length&&this._runPendingChanges()}catch(t){v.rethrowUnexpectedError(t,this)}}applyOperation(t){t._execute()}insertContent(t,e,i){return function(t,e,i,n){return t.change((s=>{let o;o=i?i instanceof Sh||i instanceof Fh?i:s.createSelection(i,n):t.document.selection,o.isCollapsed||t.deleteContent(o,{doNotAutoparagraph:!0});const r=new Yu(t,s,o.anchor),a=[];let l;if(e.is("documentFragment")){if(e.markers.size){const t=[];for(const[i,n]of e.markers){const{start:e,end:s}=n,o=e.isEqual(s);t.push({position:e,name:i,isCollapsed:o},{position:s,name:i,isCollapsed:o})}t.sort((({position:t},{position:e})=>t.isBefore(e)?1:-1));for(const{position:i,name:n,isCollapsed:o}of t){let t=null,r=null;const l=i.parent===e&&i.isAtStart,c=i.parent===e&&i.isAtEnd;l||c?o&&(r=l?"start":"end"):(t=s.createElement("$marker"),s.insert(t,i)),a.push({name:n,element:t,collapsed:r})}}l=e.getChildren()}else l=[e];r.handleNodes(l);let c=r.getSelectionRange();if(e.is("documentFragment")&&a.length){const t=c?Mh.fromRange(c):null,e={};for(let t=a.length-1;t>=0;t--){const{name:i,element:n,collapsed:o}=a[t],l=!e[i];if(l&&(e[i]=[]),n){const t=s.createPositionAt(n,"before");e[i].push(t),s.remove(n)}else{const t=r.getAffectedRange();if(!t){o&&e[i].push(r.position);continue}o?e[i].push(t[o]):e[i].push(l?t.start:t.end)}}for(const[t,[i,n]]of Object.entries(e))i&&n&&i.root===n.root&&s.addMarker(t,{usingOperation:!0,affectsData:!0,range:new kh(i,n)});t&&(c=t.toRange(),t.detach())}c&&(o instanceof Fh?s.setSelection(c):o.setTo(c));const h=r.getAffectedRange()||t.createRange(o.anchor);return r.destroy(),h}))}(this,t,e,i)}insertObject(t,e,i,n){return Xu(this,t,e,i,n)}deleteContent(t,e){Wu(this,t,e)}modifySelection(t,e){!function(t,e,i={}){const n=t.schema,s="backward"!=i.direction,o=i.unit?i.unit:"character",r=!!i.treatEmojiAsSingleUnit,a=e.focus,l=new mh({boundaries:nf(a,s),singleCharacters:!0,direction:s?"forward":"backward"}),c={walker:l,schema:n,isForward:s,unit:o,treatEmojiAsSingleUnit:r};let h;for(;h=l.next();){if(h.done)return;const i=ef(c,h.value);if(i)return void(e instanceof Fh?t.change((t=>{t.setSelectionFocus(i)})):e.setFocus(i))}}(this,t,e)}getSelectedContent(t){return function(t,e){return t.change((t=>{const i=t.createDocumentFragment(),n=e.getFirstRange();if(!n||n.isCollapsed)return i;const s=n.start.root,o=n.start.getCommonPath(n.end),r=s.getNodeByPath(o);let a;a=n.start.parent==n.end.parent?n:t.createRange(t.createPositionAt(r,n.start.path[o.length]),t.createPositionAt(r,n.end.path[o.length]+1));const l=a.end.offset-a.start.offset;for(const e of a.getItems({shallow:!0}))e.is("$textProxy")?t.appendText(e.data,e.getAttributes(),i):t.append(t.cloneElement(e,!0),i);if(a!=n){const e=n._getTransformedByMove(a.start,t.createPositionAt(i,0),l)[0],s=t.createRange(t.createPositionAt(i,0),e.start);Qu(t.createRange(e.end,t.createPositionAt(i,"end")),t),Qu(s,t)}return i}))}(this,t)}hasContent(t,e={}){const i=t instanceof kh?t:kh._createIn(t);if(i.isCollapsed)return!1;const{ignoreWhitespaces:n=!1,ignoreMarkers:s=!1}=e;if(!s)for(const t of this.markers.getMarkersIntersectingRange(i))if(t.affectsData)return!0;for(const t of i.getItems())if(this.schema.isContent(t)){if(!t.is("$textProxy"))return!0;if(!n)return!0;if(-1!==t.data.search(/\S/))return!0}return!1}createPositionFromPath(t,e,i){return new ph(t,e,i)}createPositionAt(t,e){return ph._createAt(t,e)}createPositionAfter(t){return ph._createAfter(t)}createPositionBefore(t){return ph._createBefore(t)}createRange(t,e){return new kh(t,e)}createRangeIn(t){return kh._createIn(t)}createRangeOn(t){return kh._createOn(t)}createSelection(...t){return new Sh(...t)}createBatch(t){return new vu(t)}createOperationFromJSON(t){return ou.fromJSON(t,this.document)}destroy(){this.document.destroy(),this.stopListening()}_runPendingChanges(){const t=[];this.fire("_beforeChanges");try{for(;this._pendingChanges.length;){const e=this._pendingChanges[0].batch;this._currentWriter=new Mu(this,e);const i=this._pendingChanges[0].callback(this._currentWriter);t.push(i),this.document._handleChangeBlock(this._currentWriter),this._pendingChanges.shift(),this._currentWriter=null}}finally{this._pendingChanges.length=0,this._currentWriter=null,this.fire("_afterChanges")}return t}}class af extends Jl{constructor(t){super(t),this.domEventType="click"}onDomEvent(t){this.fire(t.type,t)}}class lf extends Jl{constructor(t){super(t),this.domEventType=["mousedown","mouseup","mouseover","mouseout"]}onDomEvent(t){this.fire(t.type,t)}}class cf{constructor(t){this.document=t}createDocumentFragment(t){return new hl(this.document,t)}createElement(t,e,i){return new Va(this.document,t,e,i)}createText(t){return new Cr(this.document,t)}clone(t,e=!1){return t._clone(e)}appendChild(t,e){return e._appendChild(t)}insertChild(t,e,i){return i._insertChild(t,e)}removeChildren(t,e,i){return i._removeChildren(t,e)}remove(t){const e=t.parent;return e?this.removeChildren(e.getChildIndex(t),1,e):[]}replace(t,e){const i=t.parent;if(i){const n=i.getChildIndex(t);return this.removeChildren(n,1,i),this.insertChild(n,e,i),!0}return!1}unwrapElement(t){const e=t.parent;if(e){const i=e.getChildIndex(t);this.remove(t),this.insertChild(i,t.getChildren(),e)}}rename(t,e){const i=new Va(this.document,t,e.getAttributes(),e.getChildren());return this.replace(e,i)?i:null}setAttribute(t,e,i){i._setAttribute(t,e)}removeAttribute(t,e){e._removeAttribute(t)}addClass(t,e){e._addClass(t)}removeClass(t,e){e._removeClass(t)}setStyle(t,e,i){St(t)&&void 0===i?e._setStyle(t):i._setStyle(t,e)}removeStyle(t,e){e._removeStyle(t)}setCustomProperty(t,e,i){i._setCustomProperty(t,e)}removeCustomProperty(t,e){return e._removeCustomProperty(t)}createPositionAt(t,e){return Ha._createAt(t,e)}createPositionAfter(t){return Ha._createAfter(t)}createPositionBefore(t){return Ha._createBefore(t)}createRange(t,e){return new ja(t,e)}createRangeOn(t){return ja._createOn(t)}createRangeIn(t){return ja._createIn(t)}createSelection(...t){return new Wa(...t)}}new Set(["black","silver","gray","white","maroon","red","purple","fuchsia","green","lime","olive","yellow","navy","blue","teal","aqua","orange","aliceblue","antiquewhite","aquamarine","azure","beige","bisque","blanchedalmond","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","gainsboro","ghostwhite","gold","goldenrod","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","limegreen","linen","magenta","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","oldlace","olivedrab","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","thistle","tomato","turquoise","violet","wheat","whitesmoke","yellowgreen","activeborder","activecaption","appworkspace","background","buttonface","buttonhighlight","buttonshadow","buttontext","captiontext","graytext","highlight","highlighttext","inactiveborder","inactivecaption","inactivecaptiontext","infobackground","infotext","menu","menutext","scrollbar","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","window","windowframe","windowtext","rebeccapurple","currentcolor","transparent"]);const hf=/^([+-]?[0-9]*([.][0-9]+)?(px|cm|mm|in|pc|pt|ch|em|ex|rem|vh|vw|vmin|vmax)|0)$/;const df=/^[+-]?[0-9]*([.][0-9]+)?%$/;function uf(t=""){if(""===t)return{top:void 0,right:void 0,bottom:void 0,left:void 0};const e=t.replace(/, /g,",").split(" ").map((t=>t.replace(/,/g,", ")));const i=e[0],n=e[2]||i,s=e[1]||i;return{top:i,bottom:n,right:s,left:e[3]||s}}function ff({top:t,right:e,bottom:i,left:n}){const s=[];return n!==e?s.push(t,e,i,n):i!==t?s.push(t,e,i):e!==t?s.push(t,e):s.push(t),s.join(" ")}function mf(t){var e,i;t.setNormalizer("margin",(e="margin",t=>({path:e,value:uf(t)}))),t.setNormalizer("margin-top",(t=>({path:"margin.top",value:t}))),t.setNormalizer("margin-right",(t=>({path:"margin.right",value:t}))),t.setNormalizer("margin-bottom",(t=>({path:"margin.bottom",value:t}))),t.setNormalizer("margin-left",(t=>({path:"margin.left",value:t}))),t.setReducer("margin",(i="margin",t=>{const{top:e,right:n,bottom:s,left:o}=t,r=[];return[e,n,o,s].every((t=>!!t))?r.push([i,ff(t)]):(e&&r.push([i+"-top",e]),n&&r.push([i+"-right",n]),s&&r.push([i+"-bottom",s]),o&&r.push([i+"-left",o])),r})),t.setStyleRelation("margin",["margin-top","margin-right","margin-bottom","margin-left"])}class gf{constructor(){this._commands=new Map}add(t,e){this._commands.set(t,e)}get(t){return this._commands.get(t)}execute(t,...e){const i=this.get(t);if(!i)throw new v("commandcollection-command-not-found",this,{commandName:t});return i.execute(...e)}*names(){yield*this._commands.keys()}*commands(){yield*this._commands.values()}[Symbol.iterator](){return this._commands[Symbol.iterator]()}destroy(){for(const t of this.commands())t.destroy()}}class pf extends fo{constructor(t){super(),this.editor=t}set(t,e,i={}){if("string"==typeof e){const t=e;e=(e,i)=>{this.editor.execute(t),i()}}super.set(t,e,i)}}class wf extends(q()){constructor(t={}){super();const e=this.constructor,i=t.language||e.defaultConfig&&e.defaultConfig.language;this._context=t.context||new mr({language:i}),this._context._addEditor(this,!t.context);const n=Array.from(e.builtinPlugins||[]);this.config=new hs(t,e.defaultConfig),this.config.define("plugins",n),this.config.define(this._context._getEditorConfig()),this.plugins=new fr(this,n,this._context.plugins),this.locale=this._context.locale,this.t=this.locale.t,this._readOnlyLocks=new Set,this.commands=new gf,this.set("state","initializing"),this.once("ready",(()=>this.state="ready"),{priority:"high"}),this.once("destroy",(()=>this.state="destroyed"),{priority:"high"}),this.model=new rf;const s=new Ra;this.data=new Bd(this.model,s),this.editing=new md(this.model,s),this.editing.view.document.bind("isReadOnly").to(this),this.conversion=new Dd([this.editing.downcastDispatcher,this.data.downcastDispatcher],this.data.upcastDispatcher),this.conversion.addAlias("dataDowncast",this.data.downcastDispatcher),this.conversion.addAlias("editingDowncast",this.editing.downcastDispatcher),this.keystrokes=new pf(this),this.keystrokes.listenTo(this.editing.view.document)}get isReadOnly(){return this._readOnlyLocks.size>0}set isReadOnly(t){throw new v("editor-isreadonly-has-no-setter")}enableReadOnlyMode(t){if("string"!=typeof t&&"symbol"!=typeof t)throw new v("editor-read-only-lock-id-invalid",null,{lockId:t});this._readOnlyLocks.has(t)||(this._readOnlyLocks.add(t),1===this._readOnlyLocks.size&&this.fire("change:isReadOnly","isReadOnly",!0,!1))}disableReadOnlyMode(t){if("string"!=typeof t&&"symbol"!=typeof t)throw new v("editor-read-only-lock-id-invalid",null,{lockId:t});this._readOnlyLocks.has(t)&&(this._readOnlyLocks.delete(t),0===this._readOnlyLocks.size&&this.fire("change:isReadOnly","isReadOnly",!1,!0))}initPlugins(){const t=this.config,e=t.get("plugins"),i=t.get("removePlugins")||[],n=t.get("extraPlugins")||[],s=t.get("substitutePlugins")||[];return this.plugins.init(e.concat(n),i,s)}destroy(){let t=Promise.resolve();return"initializing"==this.state&&(t=new Promise((t=>this.once("ready",t)))),t.then((()=>{this.fire("destroy"),this.stopListening(),this.commands.destroy()})).then((()=>this.plugins.destroy())).then((()=>{this.model.destroy(),this.data.destroy(),this.editing.destroy(),this.keystrokes.destroy()})).then((()=>this._context._removeEditor(this)))}execute(t,...e){try{return this.commands.execute(t,...e)}catch(t){v.rethrowUnexpectedError(t,this)}}focus(){this.editing.view.focus()}}function bf(t){return class extends t{setData(t){this.data.set(t)}getData(t){return this.data.get(t)}}}{const t=bf(Object);bf.setData=t.prototype.setData,bf.getData=t.prototype.getData}function _f(t){return class extends t{updateSourceElement(t=this.data.get()){if(!this.sourceElement)throw new v("editor-missing-sourceelement",this);const e=this.config.get("updateSourceElementOnDestroy"),i=this.sourceElement instanceof HTMLTextAreaElement;Os(this.sourceElement,e||i?t:"")}}}_f.updateSourceElement=_f(Object).prototype.updateSourceElement;class vf extends gr{static get pluginName(){return"PendingActions"}init(){this.set("hasAny",!1),this._actions=new co({idProperty:"_id"}),this._actions.delegate("add","remove").to(this)}add(t){if("string"!=typeof t)throw new v("pendingactions-add-invalid-message",this);const e=new(q());return e.set("message",t),this._actions.add(e),this.hasAny=!0,e}remove(t){this._actions.remove(t),this.hasAny=!!this._actions.length}get first(){return this._actions.get(0)}[Symbol.iterator](){return this._actions[Symbol.iterator]()}}const yf={bold:'',cancel:'',caption:'',check:'',cog:'',eraser:'',image:'',lowVision:'',importExport:'',paragraph:'',plus:'',text:'',alignBottom:'',alignMiddle:'',alignTop:'',alignLeft:'',alignCenter:'',alignRight:'',alignJustify:'',objectLeft:'',objectCenter:'',objectRight:'',objectFullWidth:'',objectInline:'',objectBlockLeft:'',objectBlockRight:'',objectSizeFull:'',objectSizeLarge:'',objectSizeSmall:'',objectSizeMedium:'',pencil:'',pilcrow:'',quote:'',threeVerticalDots:''},{threeVerticalDots:kf}=yf,Af={alignLeft:yf.alignLeft,bold:yf.bold,importExport:yf.importExport,paragraph:yf.paragraph,plus:yf.plus,text:yf.text,threeVerticalDots:yf.threeVerticalDots};class xf extends yo{constructor(t,e){super(t);const i=this.bindTemplate,n=this.t;this.options=e||{},this.set("ariaLabel",n("Editor toolbar")),this.set("maxWidth","auto"),this.items=this.createCollection(),this.focusTracker=new uo,this.keystrokes=new fo,this.set("class",void 0),this.set("isCompact",!1),this.itemsView=new Cf(t),this.children=this.createCollection(),this.children.add(this.itemsView),this.focusables=this.createCollection();const s="rtl"===t.uiLanguageDirection;this._focusCycler=new nr({focusables:this.focusables,focusTracker:this.focusTracker,keystrokeHandler:this.keystrokes,actions:{focusPrevious:[s?"arrowright":"arrowleft","arrowup"],focusNext:[s?"arrowleft":"arrowright","arrowdown"]}});const o=["ck","ck-toolbar",i.to("class"),i.if("isCompact","ck-toolbar_compact")];var r;this.options.shouldGroupWhenFull&&this.options.isFloating&&o.push("ck-toolbar_floating"),this.setTemplate({tag:"div",attributes:{class:o,role:"toolbar","aria-label":i.to("ariaLabel"),style:{maxWidth:i.to("maxWidth")}},children:this.children,on:{mousedown:(r=this,r.bindTemplate.to((t=>{t.target===r.element&&t.preventDefault()})))}}),this._behavior=this.options.shouldGroupWhenFull?new Tf(this):new Pf(this)}render(){super.render();for(const t of this.items)this.focusTracker.add(t.element);this.items.on("add",((t,e)=>{this.focusTracker.add(e.element)})),this.items.on("remove",((t,e)=>{this.focusTracker.remove(e.element)})),this.keystrokes.listenTo(this.element),this._behavior.render(this)}destroy(){return this._behavior.destroy(),this.focusTracker.destroy(),this.keystrokes.destroy(),super.destroy()}focus(){this._focusCycler.focusFirst()}focusLast(){this._focusCycler.focusLast()}fillFromConfig(t,e,i){this.items.addMany(this._buildItemsFromConfig(t,e,i))}_buildItemsFromConfig(t,e,i){const n=ar(t),s=i||n.removeItems;return this._cleanItemsConfiguration(n.items,e,s).map((t=>F(t)?this._createNestedToolbarDropdown(t,e,s):"|"===t?new or:"-"===t?new rr:e.create(t))).filter((t=>!!t))}_cleanItemsConfiguration(t,e,i){const n=t.filter(((t,n,s)=>"|"===t||-1===i.indexOf(t)&&("-"===t?!this.options.shouldGroupWhenFull||(y("toolbarview-line-break-ignored-when-grouping-items",s),!1):!(!F(t)&&!e.has(t))||(y("toolbarview-item-unavailable",{item:t}),!1))));return this._cleanSeparatorsAndLineBreaks(n)}_cleanSeparatorsAndLineBreaks(t){const e=t=>"-"!==t&&"|"!==t,i=t.length,n=t.findIndex(e);if(-1===n)return[];const s=i-t.slice().reverse().findIndex(e);return t.slice(n,s).filter(((t,i,n)=>{if(e(t))return!0;return!(i>0&&n[i-1]===t)}))}_createNestedToolbarDropdown(t,e,i){let{label:n,icon:s,items:o,tooltip:r=!0,withText:a=!1}=t;if(o=this._cleanItemsConfiguration(o,e,i),!o.length)return null;const l=Of(this.locale);return n||y("toolbarview-nested-toolbar-dropdown-missing-label",t),l.class="ck-toolbar__nested-toolbar-dropdown",l.buttonView.set({label:n,tooltip:r,withText:!!a}),!1!==s?l.buttonView.icon=Af[s]||s||kf:l.buttonView.withText=!0,If(l,(()=>l.toolbarView._buildItemsFromConfig(o,e,i))),l}}class Cf extends yo{constructor(t){super(t),this.children=this.createCollection(),this.setTemplate({tag:"div",attributes:{class:["ck","ck-toolbar__items"]},children:this.children})}}class Pf{constructor(t){const e=t.bindTemplate;t.set("isVertical",!1),t.itemsView.children.bindTo(t.items).using((t=>t)),t.focusables.bindTo(t.items).using((t=>t)),t.extendTemplate({attributes:{class:[e.if("isVertical","ck-toolbar_vertical")]}})}render(){}destroy(){}}class Tf{constructor(t){this.view=t,this.viewChildren=t.children,this.viewFocusables=t.focusables,this.viewItemsView=t.itemsView,this.viewFocusTracker=t.focusTracker,this.viewLocale=t.locale,this.ungroupedItems=t.createCollection(),this.groupedItems=t.createCollection(),this.groupedItemsDropdown=this._createGroupedItemsDropdown(),this.resizeObserver=null,this.cachedPadding=null,this.shouldUpdateGroupingOnNextResize=!1,t.itemsView.children.bindTo(this.ungroupedItems).using((t=>t)),this.ungroupedItems.on("change",this._updateFocusCycleableItems.bind(this)),t.children.on("change",this._updateFocusCycleableItems.bind(this)),t.items.on("change",((t,e)=>{const i=e.index,n=Array.from(e.added);for(const t of e.removed)i>=this.ungroupedItems.length?this.groupedItems.remove(t):this.ungroupedItems.remove(t);for(let t=i;tthis.ungroupedItems.length?this.groupedItems.add(e,t-this.ungroupedItems.length):this.ungroupedItems.add(e,t)}this._updateGrouping()})),t.extendTemplate({attributes:{class:["ck-toolbar_grouping"]}})}render(t){this.viewElement=t.element,this._enableGroupingOnResize(),this._enableGroupingOnMaxWidthChange(t)}destroy(){this.groupedItemsDropdown.destroy(),this.resizeObserver.destroy()}_updateGrouping(){if(!this.viewElement.ownerDocument.body.contains(this.viewElement))return;if(!Bs(this.viewElement))return void(this.shouldUpdateGroupingOnNextResize=!0);const t=this.groupedItems.length;let e;for(;this._areItemsOverflowing;)this._groupLastItem(),e=!0;if(!e&&this.groupedItems.length){for(;this.groupedItems.length&&!this._areItemsOverflowing;)this._ungroupFirstItem();this._areItemsOverflowing&&this._groupLastItem()}this.groupedItems.length!==t&&this.view.fire("groupedItemsUpdate")}get _areItemsOverflowing(){if(!this.ungroupedItems.length)return!1;const t=this.viewElement,e=this.viewLocale.uiLanguageDirection,i=new Ps(t.lastChild),n=new Ps(t);if(!this.cachedPadding){const i=vs.window.getComputedStyle(t),n="ltr"===e?"paddingRight":"paddingLeft";this.cachedPadding=Number.parseInt(i[n])}return"ltr"===e?i.right>n.right-this.cachedPadding:i.left{t&&t===e.contentRect.width&&!this.shouldUpdateGroupingOnNextResize||(this.shouldUpdateGroupingOnNextResize=!1,this._updateGrouping(),t=e.contentRect.width)})),this._updateGrouping()}_enableGroupingOnMaxWidthChange(t){t.on("change:maxWidth",(()=>{this._updateGrouping()}))}_groupLastItem(){this.groupedItems.length||(this.viewChildren.add(new or),this.viewChildren.add(this.groupedItemsDropdown),this.viewFocusTracker.add(this.groupedItemsDropdown.element)),this.groupedItems.add(this.ungroupedItems.remove(this.ungroupedItems.last),0)}_ungroupFirstItem(){this.ungroupedItems.add(this.groupedItems.remove(this.groupedItems.first)),this.groupedItems.length||(this.viewChildren.remove(this.groupedItemsDropdown),this.viewChildren.remove(this.viewChildren.last),this.viewFocusTracker.remove(this.groupedItemsDropdown.element))}_createGroupedItemsDropdown(){const t=this.viewLocale,e=t.t,i=Of(t);return i.class="ck-toolbar__grouped-dropdown",i.panelPosition="ltr"===t.uiLanguageDirection?"sw":"se",If(i,this.groupedItems),i.buttonView.set({label:e("Show more items"),tooltip:!0,tooltipPosition:"rtl"===t.uiLanguageDirection?"se":"sw",icon:kf}),i}_updateFocusCycleableItems(){this.viewFocusables.clear(),this.ungroupedItems.map((t=>{this.viewFocusables.add(t)})),this.groupedItems.length&&this.viewFocusables.add(this.groupedItemsDropdown)}}class Ef extends yo{constructor(t){super(t);const e=this.bindTemplate;this.items=this.createCollection(),this.focusTracker=new uo,this.keystrokes=new fo,this._focusCycler=new nr({focusables:this.items,focusTracker:this.focusTracker,keystrokeHandler:this.keystrokes,actions:{focusPrevious:"arrowup",focusNext:"arrowdown"}}),this.set("ariaLabel",void 0),this.setTemplate({tag:"ul",attributes:{class:["ck","ck-reset","ck-list"],"aria-label":e.to("ariaLabel")},children:this.items})}render(){super.render();for(const t of this.items)this.focusTracker.add(t.element);this.items.on("add",((t,e)=>{this.focusTracker.add(e.element)})),this.items.on("remove",((t,e)=>{this.focusTracker.remove(e.element)})),this.keystrokes.listenTo(this.element)}destroy(){super.destroy(),this.focusTracker.destroy(),this.keystrokes.destroy()}focus(){this._focusCycler.focusFirst()}focusLast(){this._focusCycler.focusLast()}}class Sf extends yo{constructor(t){super(t);const e=this.bindTemplate;this.set("isVisible",!0),this.children=this.createCollection(),this.setTemplate({tag:"li",attributes:{class:["ck","ck-list__item",e.if("isVisible","ck-hidden",(t=>!t))]},children:this.children})}focus(){this.children.first.focus()}}class Rf extends yo{constructor(t){super(t),this.setTemplate({tag:"li",attributes:{class:["ck","ck-list__separator"]}})}}function Of(t,e=tr){const n=new e(t),s=new ir(t),o=new Zo(t,n,s);return n.bind("isEnabled").to(o),n instanceof er?n.arrowView.bind("isOn").to(o,"isOpen"):n.bind("isOn").to(o,"isOpen"),function(t){(function(t){t.on("render",(()=>{i({emitter:t,activator:()=>t.isOpen,callback:()=>{t.isOpen=!1},contextElements:[t.element]})}))})(t),function(t){t.on("execute",(e=>{e.source instanceof Uo||(t.isOpen=!1)}))}(t),function(t){t.focusTracker.on("change:isFocused",((e,i,n)=>{t.isOpen&&!n&&(t.isOpen=!1)}))}(t),function(t){t.keystrokes.set("arrowdown",((e,i)=>{t.isOpen&&(t.panelView.focus(),i())})),t.keystrokes.set("arrowup",((e,i)=>{t.isOpen&&(t.panelView.focusLast(),i())}))}(t),function(t){t.on("change:isOpen",((e,i,n)=>{if(n)return;const s=t.panelView.element;s&&s.contains(vs.document.activeElement)&&t.buttonView.focus()}))}(t),function(t){t.on("change:isOpen",((e,i,n)=>{n&&t.panelView.focus()}),{priority:"low"})}(t)}(o),o}function If(t,e,i={}){t.extendTemplate({attributes:{class:["ck-toolbar-dropdown"]}}),t.isOpen?Vf(t,e,i):t.once("change:isOpen",(()=>Vf(t,e,i)),{priority:"highest"}),i.enableActiveItemFocusOnDropdownOpen&&Bf(t,(()=>t.toolbarView.items.find((t=>t.isOn))))}function Vf(t,e,i){const n=t.locale,s=n.t,o=t.toolbarView=new xf(n),r="function"==typeof e?e():e;o.ariaLabel=i.ariaLabel||s("Dropdown toolbar"),i.maxWidth&&(o.maxWidth=i.maxWidth),i.class&&(o.class=i.class),i.isCompact&&(o.isCompact=i.isCompact),i.isVertical&&(o.isVertical=!0),r instanceof vo?o.items.bindTo(r).using((t=>t)):o.items.addMany(r),t.panelView.children.add(o),o.items.delegate("execute").to(t)}function Mf(t,e,i={}){t.isOpen?Nf(t,e,i):t.once("change:isOpen",(()=>Nf(t,e,i)),{priority:"highest"}),Bf(t,(()=>t.listView.items.find((t=>t instanceof Sf&&t.children.first.isOn))))}function Nf(t,e,i){const n=t.locale,s=t.listView=new Ef(n),o="function"==typeof e?e():e;s.ariaLabel=i.ariaLabel,s.items.bindTo(o).using((t=>{if("separator"===t.type)return new Rf(n);if("button"===t.type||"switchbutton"===t.type){const e=new Sf(n);let i;return i="button"===t.type?new qo(n):new Uo(n),i.bind(...Object.keys(t.model)).to(t.model),i.delegate("execute").to(e),e.children.add(i),e}return null})),t.panelView.children.add(s),s.items.delegate("execute").to(t)}function Bf(t,e){t.on("change:isOpen",(()=>{if(!t.isOpen)return;const i=e();i&&("function"==typeof i.focus?i.focus():y("ui-dropdown-focus-child-on-open-child-missing-focus",{view:i}))}),{priority:w.low-10})}const Df=Is("px"),Ff=vs.document.body;class Lf extends yo{constructor(t){super(t);const e=this.bindTemplate;this.set("top",0),this.set("left",0),this.set("position","arrow_nw"),this.set("isVisible",!1),this.set("withArrow",!0),this.set("class",void 0),this._pinWhenIsVisibleCallback=null,this.content=this.createCollection(),this.setTemplate({tag:"div",attributes:{class:["ck","ck-balloon-panel",e.to("position",(t=>`ck-balloon-panel_${t}`)),e.if("isVisible","ck-balloon-panel_visible"),e.if("withArrow","ck-balloon-panel_with-arrow"),e.to("class")],style:{top:e.to("top",Df),left:e.to("left",Df)}},children:this.content})}show(){this.isVisible=!0}hide(){this.isVisible=!1}attachTo(t){this.show();const e=Lf.defaultPositions,i=Object.assign({},{element:this.element,positions:[e.southArrowNorth,e.southArrowNorthMiddleWest,e.southArrowNorthMiddleEast,e.southArrowNorthWest,e.southArrowNorthEast,e.northArrowSouth,e.northArrowSouthMiddleWest,e.northArrowSouthMiddleEast,e.northArrowSouthWest,e.northArrowSouthEast,e.viewportStickyNorth],limiter:Ff,fitInViewport:!0},t),n=Lf._getOptimalPosition(i),s=parseInt(n.left),o=parseInt(n.top),r=n.name,a=n.config||{},{withArrow:l=!0}=a;this.top=o,this.left=s,this.position=r,this.withArrow=l}pin(t){this.unpin(),this._pinWhenIsVisibleCallback=()=>{this.isVisible?this._startPinning(t):this._stopPinning()},this._startPinning(t),this.listenTo(this,"change:isVisible",this._pinWhenIsVisibleCallback)}unpin(){this._pinWhenIsVisibleCallback&&(this._stopPinning(),this.stopListening(this,"change:isVisible",this._pinWhenIsVisibleCallback),this._pinWhenIsVisibleCallback=null,this.hide())}_startPinning(t){this.attachTo(t);const e=zf(t.target),i=t.limiter?zf(t.limiter):Ff;this.listenTo(vs.document,"scroll",((n,s)=>{const o=s.target,r=e&&o.contains(e),a=i&&o.contains(i);!r&&!a&&e&&i||this.attachTo(t)}),{useCapture:!0}),this.listenTo(vs.window,"resize",(()=>{this.attachTo(t)}))}_stopPinning(){this.stopListening(vs.document,"scroll"),this.stopListening(vs.window,"resize")}}function zf(t){return cs(t)?t:As(t)?t.commonAncestorContainer:"function"==typeof t?zf(t()):null}function Hf(t={}){const{sideOffset:e=Lf.arrowSideOffset,heightOffset:i=Lf.arrowHeightOffset,stickyVerticalOffset:n=Lf.stickyVerticalOffset,config:s}=t;return{northWestArrowSouthWest:(t,i)=>({top:o(t,i),left:t.left-e,name:"arrow_sw",...s&&{config:s}}),northWestArrowSouthMiddleWest:(t,i)=>({top:o(t,i),left:t.left-.25*i.width-e,name:"arrow_smw",...s&&{config:s}}),northWestArrowSouth:(t,e)=>({top:o(t,e),left:t.left-e.width/2,name:"arrow_s",...s&&{config:s}}),northWestArrowSouthMiddleEast:(t,i)=>({top:o(t,i),left:t.left-.75*i.width+e,name:"arrow_sme",...s&&{config:s}}),northWestArrowSouthEast:(t,i)=>({top:o(t,i),left:t.left-i.width+e,name:"arrow_se",...s&&{config:s}}),northArrowSouthWest:(t,i)=>({top:o(t,i),left:t.left+t.width/2-e,name:"arrow_sw",...s&&{config:s}}),northArrowSouthMiddleWest:(t,i)=>({top:o(t,i),left:t.left+t.width/2-.25*i.width-e,name:"arrow_smw",...s&&{config:s}}),northArrowSouth:(t,e)=>({top:o(t,e),left:t.left+t.width/2-e.width/2,name:"arrow_s",...s&&{config:s}}),northArrowSouthMiddleEast:(t,i)=>({top:o(t,i),left:t.left+t.width/2-.75*i.width+e,name:"arrow_sme",...s&&{config:s}}),northArrowSouthEast:(t,i)=>({top:o(t,i),left:t.left+t.width/2-i.width+e,name:"arrow_se",...s&&{config:s}}),northEastArrowSouthWest:(t,i)=>({top:o(t,i),left:t.right-e,name:"arrow_sw",...s&&{config:s}}),northEastArrowSouthMiddleWest:(t,i)=>({top:o(t,i),left:t.right-.25*i.width-e,name:"arrow_smw",...s&&{config:s}}),northEastArrowSouth:(t,e)=>({top:o(t,e),left:t.right-e.width/2,name:"arrow_s",...s&&{config:s}}),northEastArrowSouthMiddleEast:(t,i)=>({top:o(t,i),left:t.right-.75*i.width+e,name:"arrow_sme",...s&&{config:s}}),northEastArrowSouthEast:(t,i)=>({top:o(t,i),left:t.right-i.width+e,name:"arrow_se",...s&&{config:s}}),southWestArrowNorthWest:t=>({top:r(t),left:t.left-e,name:"arrow_nw",...s&&{config:s}}),southWestArrowNorthMiddleWest:(t,i)=>({top:r(t),left:t.left-.25*i.width-e,name:"arrow_nmw",...s&&{config:s}}),southWestArrowNorth:(t,e)=>({top:r(t),left:t.left-e.width/2,name:"arrow_n",...s&&{config:s}}),southWestArrowNorthMiddleEast:(t,i)=>({top:r(t),left:t.left-.75*i.width+e,name:"arrow_nme",...s&&{config:s}}),southWestArrowNorthEast:(t,i)=>({top:r(t),left:t.left-i.width+e,name:"arrow_ne",...s&&{config:s}}),southArrowNorthWest:t=>({top:r(t),left:t.left+t.width/2-e,name:"arrow_nw",...s&&{config:s}}),southArrowNorthMiddleWest:(t,i)=>({top:r(t),left:t.left+t.width/2-.25*i.width-e,name:"arrow_nmw",...s&&{config:s}}),southArrowNorth:(t,e)=>({top:r(t),left:t.left+t.width/2-e.width/2,name:"arrow_n",...s&&{config:s}}),southArrowNorthMiddleEast:(t,i)=>({top:r(t),left:t.left+t.width/2-.75*i.width+e,name:"arrow_nme",...s&&{config:s}}),southArrowNorthEast:(t,i)=>({top:r(t),left:t.left+t.width/2-i.width+e,name:"arrow_ne",...s&&{config:s}}),southEastArrowNorthWest:t=>({top:r(t),left:t.right-e,name:"arrow_nw",...s&&{config:s}}),southEastArrowNorthMiddleWest:(t,i)=>({top:r(t),left:t.right-.25*i.width-e,name:"arrow_nmw",...s&&{config:s}}),southEastArrowNorth:(t,e)=>({top:r(t),left:t.right-e.width/2,name:"arrow_n",...s&&{config:s}}),southEastArrowNorthMiddleEast:(t,i)=>({top:r(t),left:t.right-.75*i.width+e,name:"arrow_nme",...s&&{config:s}}),southEastArrowNorthEast:(t,i)=>({top:r(t),left:t.right-i.width+e,name:"arrow_ne",...s&&{config:s}}),westArrowEast:(t,e)=>({top:t.top+t.height/2-e.height/2,left:t.left-e.width-i,name:"arrow_e",...s&&{config:s}}),eastArrowWest:(t,e)=>({top:t.top+t.height/2-e.height/2,left:t.right+i,name:"arrow_w",...s&&{config:s}}),viewportStickyNorth:(t,e,i)=>t.getIntersection(i)?{top:i.top+n,left:t.left+t.width/2-e.width/2,name:"arrowless",config:{withArrow:!1,...s}}:null};function o(t,e){return t.top-e.height-i}function r(t){return t.bottom+i}}Lf.arrowSideOffset=25,Lf.arrowHeightOffset=10,Lf.stickyVerticalOffset=20,Lf._getOptimalPosition=Ds,Lf.defaultPositions=Hf();const jf="ck-tooltip";class $f extends(ps()){constructor(t){if(super(),$f._editors.add(t),$f._instance)return $f._instance;$f._instance=this,this.tooltipTextView=new yo(t.locale),this.tooltipTextView.set("text",""),this.tooltipTextView.setTemplate({tag:"span",attributes:{class:["ck","ck-tooltip__text"]},children:[{text:this.tooltipTextView.bindTemplate.to("text")}]}),this.balloonPanelView=new Lf(t.locale),this.balloonPanelView.class=jf,this.balloonPanelView.content.add(this.tooltipTextView),this._resizeObserver=null,this._currentElementWithTooltip=null,this._currentTooltipPosition=null,this._pinTooltipDebounced=dc(this._pinTooltip,600),this.listenTo(vs.document,"mouseenter",this._onEnterOrFocus.bind(this),{useCapture:!0}),this.listenTo(vs.document,"mouseleave",this._onLeaveOrBlur.bind(this),{useCapture:!0}),this.listenTo(vs.document,"focus",this._onEnterOrFocus.bind(this),{useCapture:!0}),this.listenTo(vs.document,"blur",this._onLeaveOrBlur.bind(this),{useCapture:!0}),this.listenTo(vs.document,"scroll",this._onScroll.bind(this),{useCapture:!0}),this._watchdogExcluded=!0}destroy(t){const e=t.ui.view&&t.ui.view.body;$f._editors.delete(t),this.stopListening(t.ui),e&&e.has(this.balloonPanelView)&&e.remove(this.balloonPanelView),$f._editors.size||(this._unpinTooltip(),this.balloonPanelView.destroy(),this.stopListening(),$f._instance=null)}static getPositioningFunctions(t){const e=$f.defaultBalloonPositions;return{s:[e.southArrowNorth,e.southArrowNorthEast,e.southArrowNorthWest],n:[e.northArrowSouth],e:[e.eastArrowWest],w:[e.westArrowEast],sw:[e.southArrowNorthEast],se:[e.southArrowNorthWest]}[t]}_onEnterOrFocus(t,{target:e}){const i=Wf(e);var n;i&&(i!==this._currentElementWithTooltip&&(this._unpinTooltip(),this._pinTooltipDebounced(i,{text:(n=i).dataset.ckeTooltipText,position:n.dataset.ckeTooltipPosition||"s",cssClass:n.dataset.ckeTooltipClass||""})))}_onLeaveOrBlur(t,{target:e,relatedTarget:i}){if("mouseleave"===t.name){if(!cs(e))return;if(this._currentElementWithTooltip&&e!==this._currentElementWithTooltip)return;const t=Wf(e),n=Wf(i);t&&t!==n&&this._unpinTooltip()}else{if(this._currentElementWithTooltip&&e!==this._currentElementWithTooltip)return;this._unpinTooltip()}}_onScroll(t,{target:e}){this._currentElementWithTooltip&&(e.contains(this.balloonPanelView.element)&&e.contains(this._currentElementWithTooltip)||this._unpinTooltip())}_pinTooltip(t,{text:e,position:i,cssClass:n}){const s=ho($f._editors.values()).ui.view.body;s.has(this.balloonPanelView)||s.add(this.balloonPanelView),this.tooltipTextView.text=e,this.balloonPanelView.pin({target:t,positions:$f.getPositioningFunctions(i)}),this._resizeObserver=new Rs(t,(()=>{Bs(t)||this._unpinTooltip()})),this.balloonPanelView.class=[jf,n].filter((t=>t)).join(" ");for(const t of $f._editors)this.listenTo(t.ui,"update",this._updateTooltipPosition.bind(this),{priority:"low"});this._currentElementWithTooltip=t,this._currentTooltipPosition=i}_unpinTooltip(){this._pinTooltipDebounced.cancel(),this.balloonPanelView.unpin();for(const t of $f._editors)this.stopListening(t.ui,"update");this._currentElementWithTooltip=null,this._currentTooltipPosition=null,this._resizeObserver&&this._resizeObserver.destroy()}_updateTooltipPosition(){Bs(this._currentElementWithTooltip)?this.balloonPanelView.pin({target:this._currentElementWithTooltip,positions:$f.getPositioningFunctions(this._currentTooltipPosition)}):this._unpinTooltip()}}function Wf(t){return cs(t)?t.closest("[data-cke-tooltip-text]:not([data-cke-tooltip-disabled])"):null}$f.defaultBalloonPositions=Hf({heightOffset:5,sideOffset:13}),$f._editors=new Set,$f._instance=null;class qf extends(q()){constructor(t){super(),this.editor=t,this.componentFactory=new Qo(t),this.focusTracker=new uo,this.tooltipManager=new $f(t),this.set("viewportOffset",this._readViewportOffsetFromConfig()),this.isReady=!1,this.once("ready",(()=>{this.isReady=!0})),this._editableElementsMap=new Map,this._focusableToolbarDefinitions=[],this.listenTo(t.editing.view.document,"layoutChanged",(()=>this.update())),this._initFocusTracking()}get element(){return null}update(){this.fire("update")}destroy(){this.stopListening(),this.focusTracker.destroy(),this.tooltipManager.destroy(this.editor);for(const t of this._editableElementsMap.values())t.ckeditorInstance=null;this._editableElementsMap=new Map,this._focusableToolbarDefinitions=[]}setEditableElement(t,e){this._editableElementsMap.set(t,e),e.ckeditorInstance||(e.ckeditorInstance=this.editor),this.focusTracker.add(e);const i=()=>{this.editor.editing.view.getDomRoot(t)||this.editor.keystrokes.listenTo(e)};this.isReady?i():this.once("ready",i)}getEditableElement(t="main"){return this._editableElementsMap.get(t)}getEditableElementsNames(){return this._editableElementsMap.keys()}addToolbar(t,e={}){t.isRendered?(this.focusTracker.add(t.element),this.editor.keystrokes.listenTo(t.element)):t.once("render",(()=>{this.focusTracker.add(t.element),this.editor.keystrokes.listenTo(t.element)})),this._focusableToolbarDefinitions.push({toolbarView:t,options:e})}get _editableElements(){return console.warn("editor-ui-deprecated-editable-elements: The EditorUI#_editableElements property has been deprecated and will be removed in the near future.",{editorUI:this}),this._editableElementsMap}_readViewportOffsetFromConfig(){const t=this.editor,e=t.config.get("ui.viewportOffset");if(e)return e;const i=t.config.get("toolbar.viewportTopOffset");return i?(console.warn("editor-ui-deprecated-viewport-offset-config: The `toolbar.vieportTopOffset` configuration option is deprecated. It will be removed from future CKEditor versions. Use `ui.viewportOffset.top` instead."),{top:i}):{top:0}}_initFocusTracking(){const t=this.editor,e=t.editing.view;let i,n;t.keystrokes.set("Alt+F10",((t,s)=>{const o=this.focusTracker.focusedElement;Array.from(this._editableElementsMap.values()).includes(o)&&!Array.from(e.domRoots.values()).includes(o)&&(i=o);const r=this._getCurrentFocusedToolbarDefinition();r&&n||(n=this._getFocusableCandidateToolbarDefinitions());for(let t=0;t{const s=this._getCurrentFocusedToolbarDefinition();s&&(i?(i.focus(),i=null):t.editing.view.focus(),s.options.afterBlur&&s.options.afterBlur(),n())}))}_getFocusableCandidateToolbarDefinitions(){const t=[];for(const e of this._focusableToolbarDefinitions){const{toolbarView:i,options:n}=e;(Bs(i.element)||n.beforeFocus)&&t.push(e)}return t.sort(((t,e)=>Uf(t)-Uf(e))),t}_getCurrentFocusedToolbarDefinition(){for(const t of this._focusableToolbarDefinitions)if(t.toolbarView.element&&t.toolbarView.element.contains(this.focusTracker.focusedElement))return t;return null}_focusFocusableCandidateToolbar(t){const{toolbarView:e,options:{beforeFocus:i}}=t;return i&&i(),!!Bs(e.element)&&(e.focus(),!0)}}function Uf(t){const{toolbarView:e,options:i}=t;let n=10;return Bs(e.element)&&n--,i.isContextual&&n--,n}class Kf extends yo{constructor(t){super(t),this.body=new $o(t)}render(){super.render(),this.body.attachToDom()}destroy(){return this.body.detachFromDom(),super.destroy()}}class Gf extends yo{constructor(t){super(t),this.set("text",void 0),this.set("for",void 0),this.id=`ck-editor__label_${p()}`;const e=this.bindTemplate;this.setTemplate({tag:"label",attributes:{class:["ck","ck-label"],id:this.id,for:e.to("for")},children:[{text:e.to("text")}]})}}class Jf extends Kf{constructor(t){super(t),this.top=this.createCollection(),this.main=this.createCollection(),this._voiceLabelView=this._createVoiceLabel(),this.setTemplate({tag:"div",attributes:{class:["ck","ck-reset","ck-editor","ck-rounded-corners"],role:"application",dir:t.uiLanguageDirection,lang:t.uiLanguage,"aria-labelledby":this._voiceLabelView.id},children:[this._voiceLabelView,{tag:"div",attributes:{class:["ck","ck-editor__top","ck-reset_all"],role:"presentation"},children:this.top},{tag:"div",attributes:{class:["ck","ck-editor__main"],role:"presentation"},children:this.main}]})}_createVoiceLabel(){const t=this.t,e=new Gf;return e.text=t("Rich Text Editor"),e.extendTemplate({attributes:{class:"ck-voice-label"}}),e}}class Qf extends yo{constructor(t,e,i){super(t),this.setTemplate({tag:"div",attributes:{class:["ck","ck-content","ck-editor__editable","ck-rounded-corners"],lang:t.contentLanguage,dir:t.contentLanguageDirection}}),this.name=null,this.set("isFocused",!1),this._editableElement=i,this._hasExternalElement=!!this._editableElement,this._editingView=e}render(){super.render(),this._hasExternalElement?this.template.apply(this.element=this._editableElement):this._editableElement=this.element,this.on("change:isFocused",(()=>this._updateIsFocusedClasses())),this._updateIsFocusedClasses()}destroy(){this._hasExternalElement&&this.template.revert(this._editableElement),super.destroy()}_updateIsFocusedClasses(){const t=this._editingView;function e(e){t.change((i=>{const n=t.document.getRoot(e.name);i.addClass(e.isFocused?"ck-focused":"ck-blurred",n),i.removeClass(e.isFocused?"ck-blurred":"ck-focused",n)}))}t.isRenderingInProgress?function i(n){t.once("change:isRenderingInProgress",((t,s,o)=>{o?i(n):e(n)}))}(this):e(this)}}class Yf extends Qf{constructor(t,e,i,n={}){super(t,e,i);const s=t.t;this.extendTemplate({attributes:{role:"textbox",class:"ck-editor__editable_inline"}}),this._generateLabel=n.label||(()=>s("Editor editing area: %0",this.name))}render(){super.render();const t=this._editingView;t.change((e=>{const i=t.document.getRoot(this.name);e.setAttribute("aria-label",this._generateLabel(this),i)}))}}class Zf extends yo{constructor(t){super(t),this.set("value",void 0),this.set("id",void 0),this.set("placeholder",void 0),this.set("isReadOnly",!1),this.set("hasError",!1),this.set("ariaDescribedById",void 0),this.focusTracker=new uo,this.bind("isFocused").to(this.focusTracker),this.set("isEmpty",!0),this.set("inputMode","text");const e=this.bindTemplate;this.setTemplate({tag:"input",attributes:{class:["ck","ck-input",e.if("isFocused","ck-input_focused"),e.if("isEmpty","ck-input-text_empty"),e.if("hasError","ck-error")],id:e.to("id"),placeholder:e.to("placeholder"),readonly:e.to("isReadOnly"),inputmode:e.to("inputMode"),"aria-invalid":e.if("hasError",!0),"aria-describedby":e.to("ariaDescribedById")},on:{input:e.to(((...t)=>{this.fire("input",...t),this._updateIsEmpty()})),change:e.to(this._updateIsEmpty.bind(this))}})}render(){super.render(),this.focusTracker.add(this.element),this._setDomElementValue(this.value),this._updateIsEmpty(),this.on("change:value",((t,e,i)=>{this._setDomElementValue(i),this._updateIsEmpty()}))}destroy(){super.destroy(),this.focusTracker.destroy()}select(){this.element.select()}focus(){this.element.focus()}_updateIsEmpty(){this.isEmpty=!this.element.value}_setDomElementValue(t){this.element.value=t||0===t?t:""}}class Xf extends Zf{constructor(t){super(t),this.extendTemplate({attributes:{type:"text",class:["ck-input-text"]}})}}class tm extends Zf{constructor(t,{min:e,max:i,step:n}={}){super(t);const s=this.bindTemplate;this.set("min",e),this.set("max",i),this.set("step",n),this.extendTemplate({attributes:{type:"number",class:["ck-input-number"],min:s.to("min"),max:s.to("max"),step:s.to("step")}})}}class em extends yo{constructor(t,e){super(t);const i=`ck-labeled-field-view-${p()}`,n=`ck-labeled-field-view-status-${p()}`;this.fieldView=e(this,i,n),this.set("label",void 0),this.set("isEnabled",!0),this.set("isEmpty",!0),this.set("isFocused",!1),this.set("errorText",null),this.set("infoText",null),this.set("class",void 0),this.set("placeholder",void 0),this.labelView=this._createLabelView(i),this.statusView=this._createStatusView(n),this.fieldWrapperChildren=this.createCollection([this.fieldView,this.labelView]),this.bind("_statusText").to(this,"errorText",this,"infoText",((t,e)=>t||e));const s=this.bindTemplate;this.setTemplate({tag:"div",attributes:{class:["ck","ck-labeled-field-view",s.to("class"),s.if("isEnabled","ck-disabled",(t=>!t)),s.if("isEmpty","ck-labeled-field-view_empty"),s.if("isFocused","ck-labeled-field-view_focused"),s.if("placeholder","ck-labeled-field-view_placeholder"),s.if("errorText","ck-error")]},children:[{tag:"div",attributes:{class:["ck","ck-labeled-field-view__input-wrapper"]},children:this.fieldWrapperChildren},this.statusView]})}_createLabelView(t){const e=new Gf(this.locale);return e.for=t,e.bind("text").to(this,"label"),e}_createStatusView(t){const e=new yo(this.locale),i=this.bindTemplate;return e.setTemplate({tag:"div",attributes:{class:["ck","ck-labeled-field-view__status",i.if("errorText","ck-labeled-field-view__status_error"),i.if("_statusText","ck-hidden",(t=>!t))],id:t,role:i.if("errorText","alert")},children:[{text:i.to("_statusText")}]}),e}focus(){this.fieldView.focus()}}function im(t,e,i){const n=new Xf(t.locale);return n.set({id:e,ariaDescribedById:i}),n.bind("isReadOnly").to(t,"isEnabled",(t=>!t)),n.bind("hasError").to(t,"errorText",(t=>!!t)),n.on("input",(()=>{t.errorText=null})),t.bind("isEmpty","isFocused","placeholder").to(n),n}function nm(t,e,i){const n=new tm(t.locale);return n.set({id:e,ariaDescribedById:i,inputMode:"numeric"}),n.bind("isReadOnly").to(t,"isEnabled",(t=>!t)),n.bind("hasError").to(t,"errorText",(t=>!!t)),n.on("input",(()=>{t.errorText=null})),t.bind("isEmpty","isFocused","placeholder").to(n),n}class sm extends(q()){constructor(t,e){super(),e&&Kl(this,e),t&&this.set(t)}}const om=Is("px");class rm extends lr{static get pluginName(){return"ContextualBalloon"}constructor(t){super(t),this._view=null,this._rotatorView=null,this._fakePanelsView=null,this.positionLimiter=()=>{const t=this.editor.editing.view,e=t.document.selection.editableElement;return e?t.domConverter.mapViewToDom(e.root):null},this.set("visibleView",null),this._viewToStack=new Map,this._idToStack=new Map,this.set("_numberOfStacks",0),this.set("_singleViewMode",!1),this._rotatorView=null,this._fakePanelsView=null}destroy(){super.destroy(),this._view&&this._view.destroy(),this._rotatorView&&this._rotatorView.destroy(),this._fakePanelsView&&this._fakePanelsView.destroy()}get view(){return this._view||this._createPanelView(),this._view}hasView(t){return Array.from(this._viewToStack.keys()).includes(t)}add(t){if(this._view||this._createPanelView(),this.hasView(t.view))throw new v("contextualballoon-add-view-exist",[this,t]);const e=t.stackId||"main";if(!this._idToStack.has(e))return this._idToStack.set(e,new Map([[t.view,t]])),this._viewToStack.set(t.view,this._idToStack.get(e)),this._numberOfStacks=this._idToStack.size,void(this._visibleStack&&!t.singleViewMode||this.showStack(e));const i=this._idToStack.get(e);t.singleViewMode&&this.showStack(e),i.set(t.view,t),this._viewToStack.set(t.view,i),i===this._visibleStack&&this._showView(t)}remove(t){if(!this.hasView(t))throw new v("contextualballoon-remove-view-not-exist",[this,t]);const e=this._viewToStack.get(t);this._singleViewMode&&this.visibleView===t&&(this._singleViewMode=!1),this.visibleView===t&&(1===e.size?this._idToStack.size>1?this._showNextStack():(this.view.hide(),this.visibleView=null,this._rotatorView.hideView()):this._showView(Array.from(e.values())[e.size-2])),1===e.size?(this._idToStack.delete(this._getStackId(e)),this._numberOfStacks=this._idToStack.size):e.delete(t),this._viewToStack.delete(t)}updatePosition(t){t&&(this._visibleStack.get(this.visibleView).position=t),this.view.pin(this._getBalloonPosition()),this._fakePanelsView.updatePosition()}showStack(t){this.visibleStack=t;const e=this._idToStack.get(t);if(!e)throw new v("contextualballoon-showstack-stack-not-exist",this);this._visibleStack!==e&&this._showView(Array.from(e.values()).pop())}_createPanelView(){this._view=new Lf(this.editor.locale),this.editor.ui.view.body.add(this._view),this.editor.ui.focusTracker.add(this._view.element),this._rotatorView=this._createRotatorView(),this._fakePanelsView=this._createFakePanelsView()}get _visibleStack(){return this._viewToStack.get(this.visibleView)}_getStackId(t){return Array.from(this._idToStack.entries()).find((e=>e[1]===t))[0]}_showNextStack(){const t=Array.from(this._idToStack.values());let e=t.indexOf(this._visibleStack)+1;t[e]||(e=0),this.showStack(this._getStackId(t[e]))}_showPrevStack(){const t=Array.from(this._idToStack.values());let e=t.indexOf(this._visibleStack)-1;t[e]||(e=t.length-1),this.showStack(this._getStackId(t[e]))}_createRotatorView(){const t=new am(this.editor.locale),e=this.editor.locale.t;return this.view.content.add(t),t.bind("isNavigationVisible").to(this,"_numberOfStacks",this,"_singleViewMode",((t,e)=>!e&&t>1)),t.on("change:isNavigationVisible",(()=>this.updatePosition()),{priority:"low"}),t.bind("counter").to(this,"visibleView",this,"_numberOfStacks",((t,i)=>{if(i<2)return"";const n=Array.from(this._idToStack.values()).indexOf(this._visibleStack)+1;return e("%0 of %1",[n,i])})),t.buttonNextView.on("execute",(()=>{t.focusTracker.isFocused&&this.editor.editing.view.focus(),this._showNextStack()})),t.buttonPrevView.on("execute",(()=>{t.focusTracker.isFocused&&this.editor.editing.view.focus(),this._showPrevStack()})),t}_createFakePanelsView(){const t=new lm(this.editor.locale,this.view);return t.bind("numberOfPanels").to(this,"_numberOfStacks",this,"_singleViewMode",((t,e)=>!e&&t>=2?Math.min(t-1,2):0)),t.listenTo(this.view,"change:top",(()=>t.updatePosition())),t.listenTo(this.view,"change:left",(()=>t.updatePosition())),this.editor.ui.view.body.add(t),t}_showView({view:t,balloonClassName:e="",withArrow:i=!0,singleViewMode:n=!1}){this.view.class=e,this.view.withArrow=i,this._rotatorView.showView(t),this.visibleView=t,this.view.pin(this._getBalloonPosition()),this._fakePanelsView.updatePosition(),n&&(this._singleViewMode=!0)}_getBalloonPosition(){let t=Array.from(this._visibleStack.values()).pop().position;return t&&(t.limiter||(t=Object.assign({},t,{limiter:this.positionLimiter})),t=Object.assign({},t,{viewportOffsetConfig:this.editor.ui.viewportOffset})),t}}class am extends yo{constructor(t){super(t);const e=t.t,i=this.bindTemplate;this.set("isNavigationVisible",!0),this.focusTracker=new uo,this.buttonPrevView=this._createButtonView(e("Previous"),''),this.buttonNextView=this._createButtonView(e("Next"),''),this.content=this.createCollection(),this.setTemplate({tag:"div",attributes:{class:["ck","ck-balloon-rotator"],"z-index":"-1"},children:[{tag:"div",attributes:{class:["ck-balloon-rotator__navigation",i.to("isNavigationVisible",(t=>t?"":"ck-hidden"))]},children:[this.buttonPrevView,{tag:"span",attributes:{class:["ck-balloon-rotator__counter"]},children:[{text:i.to("counter")}]},this.buttonNextView]},{tag:"div",attributes:{class:"ck-balloon-rotator__content"},children:this.content}]})}render(){super.render(),this.focusTracker.add(this.element)}destroy(){super.destroy(),this.focusTracker.destroy()}showView(t){this.hideView(),this.content.add(t)}hideView(){this.content.clear()}_createButtonView(t,e){const i=new qo(this.locale);return i.set({label:t,icon:e,tooltip:!0}),i}}class lm extends yo{constructor(t,e){super(t);const i=this.bindTemplate;this.set("top",0),this.set("left",0),this.set("height",0),this.set("width",0),this.set("numberOfPanels",0),this.content=this.createCollection(),this._balloonPanelView=e,this.setTemplate({tag:"div",attributes:{class:["ck-fake-panel",i.to("numberOfPanels",(t=>t?"":"ck-hidden"))],style:{top:i.to("top",om),left:i.to("left",om),width:i.to("width",om),height:i.to("height",om)}},children:this.content}),this.on("change:numberOfPanels",((t,e,i,n)=>{i>n?this._addPanels(i-n):this._removePanels(n-i),this.updatePosition()}))}_addPanels(t){for(;t--;){const t=new yo;t.setTemplate({tag:"div"}),this.content.add(t),this.registerChild(t)}}_removePanels(t){for(;t--;){const t=this.content.last;this.content.remove(t),this.deregisterChild(t),t.destroy()}}updatePosition(){if(this.numberOfPanels){const{top:t,left:e}=this._balloonPanelView,{width:i,height:n}=new Ps(this._balloonPanelView.element);Object.assign(this,{top:t,left:e,width:i,height:n})}}}const cm=Is("px");class hm extends yo{constructor(t){super(t);const e=this.bindTemplate;this.set("isActive",!1),this.set("isSticky",!1),this.set("limiterElement",null),this.set("limiterBottomOffset",50),this.set("viewportTopOffset",0),this.set("_marginLeft",null),this.set("_isStickyToTheLimiter",!1),this.set("_hasViewportTopOffset",!1),this.content=this.createCollection(),this._contentPanelPlaceholder=new ko({tag:"div",attributes:{class:["ck","ck-sticky-panel__placeholder"],style:{display:e.to("isSticky",(t=>t?"block":"none")),height:e.to("isSticky",(t=>t?cm(this._panelRect.height):null))}}}).render(),this._contentPanel=new ko({tag:"div",attributes:{class:["ck","ck-sticky-panel__content",e.if("isSticky","ck-sticky-panel__content_sticky"),e.if("_isStickyToTheLimiter","ck-sticky-panel__content_sticky_bottom-limit")],style:{width:e.to("isSticky",(t=>t?cm(this._contentPanelPlaceholder.getBoundingClientRect().width):null)),top:e.to("_hasViewportTopOffset",(t=>t?cm(this.viewportTopOffset):null)),bottom:e.to("_isStickyToTheLimiter",(t=>t?cm(this.limiterBottomOffset):null)),marginLeft:e.to("_marginLeft")}},children:this.content}).render(),this.setTemplate({tag:"div",attributes:{class:["ck","ck-sticky-panel"]},children:[this._contentPanelPlaceholder,this._contentPanel]})}render(){super.render(),this._checkIfShouldBeSticky(),this.listenTo(vs.window,"scroll",(()=>{this._checkIfShouldBeSticky()})),this.listenTo(this,"change:isActive",(()=>{this._checkIfShouldBeSticky()}))}_checkIfShouldBeSticky(){const t=this._panelRect=this._contentPanel.getBoundingClientRect();let e;this.limiterElement?(e=this._limiterRect=this.limiterElement.getBoundingClientRect(),this.isSticky=this.isActive&&e.topt||0)),t.toolbar.fillFromConfig(this._toolbarConfig,this.componentFactory),this.addToolbar(t.toolbar)}_initPlaceholder(){const t=this.editor,e=t.editing.view,i=e.document.getRoot(),n=t.sourceElement,s=t.config.get("placeholder")||n&&"textarea"===n.tagName.toLowerCase()&&n.getAttribute("placeholder");s&&function(t){const{view:e,element:i,text:n,isDirectHost:s=!0,keepOnFocus:o=!1}=t,r=e.document;pr.has(r)||(pr.set(r,new Map),r.registerPostFixer((t=>br(r,t))),r.on("change:isComposing",(()=>{e.change((t=>br(r,t)))}),{priority:"high"})),pr.get(r).set(i,{text:n,isDirectHost:s,keepOnFocus:o,hostElement:s?i:null}),e.change((t=>br(r,t)))}({view:e,element:i,text:s,isDirectHost:!1,keepOnFocus:!0})}}class fm extends Jf{constructor(t,e,i={}){super(t),this.stickyPanel=new hm(t),this.toolbar=new xf(t,{shouldGroupWhenFull:i.shouldToolbarGroupWhenFull}),this.editable=new Yf(t,e)}render(){super.render(),this.stickyPanel.content.add(this.toolbar),this.top.add(this.stickyPanel),this.main.add(this.editable)}}class mm extends(bf(_f(wf))){constructor(t,e={}){if(!gm(t)&&void 0!==e.initialData)throw new v("editor-create-initial-data",null);super(e),void 0===this.config.get("initialData")&&this.config.set("initialData",function(t){return gm(t)?(e=t,e instanceof HTMLTextAreaElement?e.value:e.innerHTML):t;var e}(t)),gm(t)&&(this.sourceElement=t),this.model.document.createRoot();const i=!this.config.get("toolbar.shouldNotGroupWhenFull"),n=new fm(this.locale,this.editing.view,{shouldToolbarGroupWhenFull:i});this.ui=new um(this,n),function(t){if(!Gt(t.updateSourceElement))throw new v("attachtoform-missing-elementapi-interface",t);const e=t.sourceElement;if(function(t){return!!t&&"textarea"===t.tagName.toLowerCase()}(e)&&e.form){let i;const n=e.form,s=()=>t.updateSourceElement();Gt(n.submit)&&(i=n.submit,n.submit=()=>{s(),i.apply(n)}),n.addEventListener("submit",s),t.on("destroy",(()=>{n.removeEventListener("submit",s),i&&(n.submit=i)}))}}(this)}destroy(){return this.sourceElement&&this.updateSourceElement(),this.ui.destroy(),super.destroy()}static create(t,e={}){return new Promise((i=>{const n=new this(t,e);i(n.initPlugins().then((()=>n.ui.init(gm(t)?t:null))).then((()=>n.data.init(n.config.get("initialData")))).then((()=>n.fire("ready"))).then((()=>n)))}))}}function gm(t){return cs(t)}const pm=["left","right","center","justify"];function wm(t){return pm.includes(t)}function bm(t,e){return"rtl"==e.contentLanguageDirection?"right"===t:"left"===t}function _m(t){const e=t.map((t=>{let e;return e="string"==typeof t?{name:t}:t,e})).filter((t=>{const e=pm.includes(t.name);return e||y("alignment-config-name-not-recognized",{option:t}),e})),i=e.filter((t=>Boolean(t.className))).length;if(i&&i{const s=n.slice(i+1);if(s.some((t=>t.name==e.name)))throw new v("alignment-config-name-already-defined",{option:e,configuredOptions:t});if(e.className){if(s.some((t=>t.className==e.className)))throw new v("alignment-config-classname-already-defined",{option:e,configuredOptions:t})}})),e}const vm="alignment";class ym extends hr{refresh(){const t=this.editor.locale,e=ho(this.editor.model.document.selection.getSelectedBlocks());this.isEnabled=Boolean(e)&&this._canBeAligned(e),this.isEnabled&&e.hasAttribute("alignment")?this.value=e.getAttribute("alignment"):this.value="rtl"===t.contentLanguageDirection?"right":"left"}execute(t={}){const e=this.editor,i=e.locale,n=e.model,s=n.document,o=t.value;n.change((t=>{const e=Array.from(s.selection.getSelectedBlocks()).filter((t=>this._canBeAligned(t))),n=e[0].getAttribute("alignment");bm(o,i)||n===o||!o?function(t,e){for(const i of t)e.removeAttribute(vm,i)}(e,t):function(t,e,i){for(const n of t)e.setAttribute(vm,i,n)}(e,t,o)}))}_canBeAligned(t){return this.editor.model.schema.checkAttribute(t,vm)}}class km extends lr{static get pluginName(){return"AlignmentEditing"}constructor(t){super(t),t.config.define("alignment",{options:pm.map((t=>({name:t})))})}init(){const t=this.editor,e=t.locale,i=t.model.schema,n=_m(t.config.get("alignment.options")).filter((t=>wm(t.name)&&!bm(t.name,e))),s=n.some((t=>!!t.className));i.extend("$block",{allowAttributes:"alignment"}),t.model.schema.setAttributeProperties("alignment",{isFormatting:!0}),s?t.conversion.attributeToAttribute(function(t){const e={};for(const i of t)e[i.name]={key:"class",value:i.className};const i={model:{key:"alignment",values:t.map((t=>t.name))},view:e};return i}(n)):t.conversion.for("downcast").attributeToAttribute(function(t){const e={};for(const{name:i}of t)e[i]={key:"style",value:{"text-align":i}};const i={model:{key:"alignment",values:t.map((t=>t.name))},view:e};return i}(n));const o=function(t){const e=[];for(const{name:i}of t)e.push({view:{key:"style",value:{"text-align":i}},model:{key:"alignment",value:i}});return e}(n);for(const e of o)t.conversion.for("upcast").attributeToAttribute(e);const r=function(t){const e=[];for(const{name:i}of t)e.push({view:{key:"align",value:i},model:{key:"alignment",value:i}});return e}(n);for(const e of r)t.conversion.for("upcast").attributeToAttribute(e);t.commands.add("alignment",new ym(t))}}const Am=new Map([["left",yf.alignLeft],["right",yf.alignRight],["center",yf.alignCenter],["justify",yf.alignJustify]]);class xm extends lr{get localizedOptionTitles(){const t=this.editor.t;return{left:t("Align left"),right:t("Align right"),center:t("Align center"),justify:t("Justify")}}static get pluginName(){return"AlignmentUI"}init(){const t=this.editor,e=t.ui.componentFactory,i=t.t,n=_m(t.config.get("alignment.options"));n.map((t=>t.name)).filter(wm).forEach((t=>this._addButton(t))),e.add("alignment",(s=>{const o=Of(s);If(o,(()=>n.map((t=>e.create(`alignment:${t.name}`)))),{enableActiveItemFocusOnDropdownOpen:!0,isVertical:!0,ariaLabel:i("Text alignment toolbar")}),o.buttonView.set({label:i("Text alignment"),tooltip:!0}),o.extendTemplate({attributes:{class:"ck-alignment-dropdown"}});const r="rtl"===s.contentLanguageDirection?Am.get("right"):Am.get("left"),a=t.commands.get("alignment");return o.buttonView.bind("icon").to(a,"value",(t=>Am.get(t)||r)),o.bind("isEnabled").to(a,"isEnabled"),this.listenTo(o,"execute",(()=>{t.editing.view.focus()})),o}))}_addButton(t){const e=this.editor;e.ui.componentFactory.add(`alignment:${t}`,(i=>{const n=e.commands.get("alignment"),s=new qo(i);return s.set({label:this.localizedOptionTitles[t],icon:Am.get(t),tooltip:!0,isToggleable:!0}),s.bind("isEnabled").to(n),s.bind("isOn").to(n,"value",(e=>e===t)),this.listenTo(s,"execute",(()=>{e.execute("alignment",{value:t}),e.editing.view.focus()})),s}))}}class Cm{constructor(t,e=20){this._batch=null,this.model=t,this._size=0,this.limit=e,this._isLocked=!1,this._changeCallback=(t,e)=>{e.isLocal&&e.isUndoable&&e!==this._batch&&this._reset(!0)},this._selectionChangeCallback=()=>{this._reset()},this.model.document.on("change",this._changeCallback),this.model.document.selection.on("change:range",this._selectionChangeCallback),this.model.document.selection.on("change:attribute",this._selectionChangeCallback)}get batch(){return this._batch||(this._batch=this.model.createBatch({isTyping:!0})),this._batch}get size(){return this._size}input(t){this._size+=t,this._size>=this.limit&&this._reset(!0)}get isLocked(){return this._isLocked}lock(){this._isLocked=!0}unlock(){this._isLocked=!1}destroy(){this.model.document.off("change",this._changeCallback),this.model.document.selection.off("change:range",this._selectionChangeCallback),this.model.document.selection.off("change:attribute",this._selectionChangeCallback)}_reset(t=!1){this.isLocked&&!t||(this._batch=null,this._size=0)}}class Pm extends hr{constructor(t,e){super(t),this._buffer=new Cm(t.model,e)}get buffer(){return this._buffer}destroy(){super.destroy(),this._buffer.destroy()}execute(t={}){const e=this.editor.model,i=e.document,n=t.text||"",s=n.length;let o=i.selection;t.selection?o=t.selection:t.range&&(o=e.createSelection(t.range));const r=t.resultRange;e.enqueueChange(this._buffer.batch,(t=>{this._buffer.lock(),e.deleteContent(o),n&&e.insertContent(t.createText(n,i.selection.getAttributes()),o),r?t.setSelection(r):o.is("documentSelection")||t.setSelection(o),this._buffer.unlock(),this._buffer.input(s)}))}}const Tm=["insertText","insertReplacementText"];class Em extends Ul{constructor(t){super(t),r.isAndroid&&Tm.push("insertCompositionText");const e=t.document;e.on("beforeinput",((i,n)=>{if(!this.isEnabled)return;const{data:s,targetRanges:o,inputType:r,domEvent:a}=n;if(!Tm.includes(r))return;const l=new m(e,"insertText");e.fire(l,new Gl(t,a,{text:s,selection:t.createSelection(o)})),l.stop.called&&i.stop()})),e.on("compositionend",((i,{data:n,domEvent:s})=>{this.isEnabled&&!r.isAndroid&&n&&e.fire("insertText",new Gl(t,s,{text:n,selection:e.selection}))}),{priority:"lowest"})}observe(){}}class Sm extends lr{static get pluginName(){return"Input"}init(){const t=this.editor,e=t.model,i=t.editing.view,n=e.document.selection;i.addObserver(Em);const s=new Pm(t,t.config.get("typing.undoStep")||20);t.commands.add("insertText",s),t.commands.add("input",s),this.listenTo(i.document,"insertText",((n,s)=>{i.document.isComposing||s.preventDefault();const{text:o,selection:a,resultRange:l}=s,c=Array.from(a.getRanges()).map((e=>t.editing.mapper.toModelRange(e)));let h=o;if(r.isAndroid){const t=Array.from(c[0].getItems()).reduce(((t,e)=>t+(e.is("$textProxy")?e.data:"")),"");t&&(t.length<=h.length?h.startsWith(t)&&(h=h.substring(t.length),c[0].start=c[0].start.getShiftedBy(t.length)):t.startsWith(h)&&(c[0].start=c[0].start.getShiftedBy(h.length),h=""))}const d={text:h,selection:e.createSelection(c)};l&&(d.resultRange=t.editing.mapper.toModelRange(l)),t.execute("insertText",d)})),r.isAndroid?this.listenTo(i.document,"keydown",((t,o)=>{!n.isCollapsed&&229==o.keyCode&&i.document.isComposing&&Rm(e,s)})):this.listenTo(i.document,"compositionstart",(()=>{n.isCollapsed||Rm(e,s)}))}}function Rm(t,e){if(!e.isEnabled)return;const i=e.buffer;i.lock(),t.enqueueChange(i.batch,(()=>{t.deleteContent(t.document.selection)})),i.unlock()}class Om extends hr{constructor(t,e){super(t),this.direction=e,this._buffer=new Cm(t.model,t.config.get("typing.undoStep"))}get buffer(){return this._buffer}execute(t={}){const e=this.editor.model,i=e.document;e.enqueueChange(this._buffer.batch,(n=>{this._buffer.lock();const s=n.createSelection(t.selection||i.selection),o=t.sequence||1,r=s.isCollapsed;if(s.isCollapsed&&e.modifySelection(s,{direction:this.direction,unit:t.unit,treatEmojiAsSingleUnit:!0}),this._shouldEntireContentBeReplacedWithParagraph(o))return void this._replaceEntireContentWithParagraph(n);if(this._shouldReplaceFirstBlockWithParagraph(s,o))return void this.editor.execute("paragraph",{selection:s});if(s.isCollapsed)return;let a=0;s.getFirstRange().getMinimalFlatRanges().forEach((t=>{a+=Z(t.getWalker({singleCharacters:!0,ignoreElementEnd:!0,shallow:!0}))})),e.deleteContent(s,{doNotResetEntireContent:r,direction:this.direction}),this._buffer.input(a),n.setSelection(s),this._buffer.unlock()}))}_shouldEntireContentBeReplacedWithParagraph(t){if(t>1)return!1;const e=this.editor.model,i=e.document.selection,n=e.schema.getLimitElement(i);if(!(i.isCollapsed&&i.containsEntireContent(n)))return!1;if(!e.schema.checkChild(n,"paragraph"))return!1;const s=n.getChild(0);return!s||!s.is("element","paragraph")}_replaceEntireContentWithParagraph(t){const e=this.editor.model,i=e.document.selection,n=e.schema.getLimitElement(i),s=t.createElement("paragraph");t.remove(t.createRangeIn(n)),t.insert(s,n),t.setSelection(s,0)}_shouldReplaceFirstBlockWithParagraph(t,e){const i=this.editor.model;if(e>1||"backward"!=this.direction)return!1;if(!t.isCollapsed)return!1;const n=t.getFirstPosition(),s=i.schema.getLimitElement(n),o=s.getChild(0);return n.parent==o&&(!!t.containsEntireContent(o)&&(!!i.schema.checkChild(s,"paragraph")&&"paragraph"!=o.name))}}const Im="word",Vm="selection",Mm="backward",Nm="forward",Bm={deleteContent:{unit:Vm,direction:Mm},deleteContentBackward:{unit:"codePoint",direction:Mm},deleteWordBackward:{unit:Im,direction:Mm},deleteHardLineBackward:{unit:Vm,direction:Mm},deleteSoftLineBackward:{unit:Vm,direction:Mm},deleteContentForward:{unit:"character",direction:Nm},deleteWordForward:{unit:Im,direction:Nm},deleteHardLineForward:{unit:Vm,direction:Nm},deleteSoftLineForward:{unit:Vm,direction:Nm}};class Dm extends Ul{constructor(t){super(t);const e=t.document;let i=0;e.on("keydown",(()=>{i++})),e.on("keyup",(()=>{i=0})),e.on("beforeinput",((n,s)=>{if(!this.isEnabled)return;const{targetRanges:o,domEvent:a,inputType:l}=s,c=Bm[l];if(!c)return;const h={direction:c.direction,unit:c.unit,sequence:i};h.unit==Vm&&(h.selectionToRemove=t.createSelection(o[0])),r.isAndroid&&"deleteContentBackward"===l&&(h.sequence=1,1!=o.length||o[0].start.parent==o[0].end.parent&&o[0].start.offset+1==o[0].end.offset||(h.unit=Vm,h.selectionToRemove=t.createSelection(o)));const d=new Ua(e,"delete",o[0]);e.fire(d,new Gl(t,a,h)),d.stop.called&&n.stop()})),r.isBlink&&function(t){const e=t.view,i=e.document;let n=null,s=!1;function o(t){return t==Zs.backspace||t==Zs.delete}function r(t){return t==Zs.backspace?Mm:Nm}i.on("keydown",((t,{keyCode:e})=>{n=e,s=!1})),i.on("keyup",((a,{keyCode:l,domEvent:c})=>{const h=i.selection,d=t.isEnabled&&l==n&&o(l)&&!h.isCollapsed&&!s;if(n=null,d){const t=h.getFirstRange(),n=new Ua(i,"delete",t),s={unit:Vm,direction:r(l),selectionToRemove:h};i.fire(n,new Gl(e,c,s))}})),i.on("beforeinput",((t,{inputType:e})=>{const i=Bm[e];o(n)&&i&&i.direction==r(n)&&(s=!0)}),{priority:"high"}),i.on("beforeinput",((t,{inputType:e,data:i})=>{n==Zs.delete&&"insertText"==e&&""==i&&t.stop()}),{priority:"high"})}(this)}observe(){}}class Fm extends lr{static get pluginName(){return"Delete"}init(){const t=this.editor,e=t.editing.view,i=e.document,n=t.model.document;e.addObserver(Dm),this._undoOnBackspace=!1;const s=new Om(t,"forward");t.commands.add("deleteForward",s),t.commands.add("forwardDelete",s),t.commands.add("delete",new Om(t,"backward")),this.listenTo(i,"delete",((n,s)=>{i.isComposing||s.preventDefault();const{direction:o,sequence:r,selectionToRemove:a,unit:l}=s,c="forward"===o?"deleteForward":"delete",h={sequence:r};if("selection"==l){const e=Array.from(a.getRanges()).map((e=>t.editing.mapper.toModelRange(e)));h.selection=t.model.createSelection(e)}else h.unit=l;t.execute(c,h),e.scrollToTheSelection()}),{priority:"low"}),this.editor.plugins.has("UndoEditing")&&(this.listenTo(i,"delete",((e,i)=>{this._undoOnBackspace&&"backward"==i.direction&&1==i.sequence&&"codePoint"==i.unit&&(this._undoOnBackspace=!1,t.execute("undo"),i.preventDefault(),e.stop())}),{context:"$capture"}),this.listenTo(n,"change",(()=>{this._undoOnBackspace=!1})))}requestUndoOnBackspace(){this.editor.plugins.has("UndoEditing")&&(this._undoOnBackspace=!0)}}class Lm extends lr{static get requires(){return[Sm,Fm]}static get pluginName(){return"Typing"}}function zm(t,e){let i=t.start;return{text:Array.from(t.getItems()).reduce(((t,n)=>n.is("$text")||n.is("$textProxy")?t+n.data:(i=e.createPositionAfter(n),"")),""),range:e.createRange(i,t.end)}}class Hm extends(q()){constructor(t,e){super(),this.model=t,this.testCallback=e,this._hasMatch=!1,this.set("isEnabled",!0),this.on("change:isEnabled",(()=>{this.isEnabled?this._startListening():(this.stopListening(t.document.selection),this.stopListening(t.document))})),this._startListening()}get hasMatch(){return this._hasMatch}_startListening(){const t=this.model.document;this.listenTo(t.selection,"change:range",((e,{directChange:i})=>{i&&(t.selection.isCollapsed?this._evaluateTextBeforeSelection("selection"):this.hasMatch&&(this.fire("unmatched"),this._hasMatch=!1))})),this.listenTo(t,"change:data",((t,e)=>{!e.isUndo&&e.isLocal&&this._evaluateTextBeforeSelection("data",{batch:e})}))}_evaluateTextBeforeSelection(t,e={}){const i=this.model,n=i.document.selection,s=i.createRange(i.createPositionAt(n.focus.parent,0),n.focus),{text:o,range:r}=zm(s,i),a=this.testCallback(o);if(!a&&this.hasMatch&&this.fire("unmatched"),this._hasMatch=!!a,a){const i=Object.assign(e,{text:o,range:r});"object"==typeof a&&Object.assign(i,a),this.fire(`matched:${t}`,i)}}}class jm extends lr{static get pluginName(){return"TwoStepCaretMovement"}constructor(t){super(t),this.attributes=new Set,this._overrideUid=null}init(){const t=this.editor,e=t.model,i=t.editing.view,n=t.locale,s=e.document.selection;this.listenTo(i.document,"arrowKey",((t,e)=>{if(!s.isCollapsed)return;if(e.shiftKey||e.altKey||e.ctrlKey)return;const i=e.keyCode==Zs.arrowright,o=e.keyCode==Zs.arrowleft;if(!i&&!o)return;const r=n.contentLanguageDirection;let a=!1;a="ltr"===r&&i||"rtl"===r&&o?this._handleForwardMovement(e):this._handleBackwardMovement(e),!0===a&&t.stop()}),{context:"$text",priority:"highest"}),this._isNextGravityRestorationSkipped=!1,this.listenTo(s,"change:range",((t,e)=>{this._isNextGravityRestorationSkipped?this._isNextGravityRestorationSkipped=!1:this._isGravityOverridden&&(!e.directChange&&Um(s.getFirstPosition(),this.attributes)||this._restoreGravity())}))}registerAttribute(t){this.attributes.add(t)}_handleForwardMovement(t){const e=this.attributes,i=this.editor.model.document.selection,n=i.getFirstPosition();return!this._isGravityOverridden&&((!n.isAtStart||!$m(i,e))&&(!!Um(n,e)&&(qm(t),this._overrideGravity(),!0)))}_handleBackwardMovement(t){const e=this.attributes,i=this.editor.model,n=i.document.selection,s=n.getFirstPosition();return this._isGravityOverridden?(qm(t),this._restoreGravity(),Wm(i,e,s),!0):s.isAtStart?!!$m(n,e)&&(qm(t),Wm(i,e,s),!0):!!function(t,e){const i=t.getShiftedBy(-1);return Um(i,e)}(s,e)&&(s.isAtEnd&&!$m(n,e)&&Um(s,e)?(qm(t),Wm(i,e,s),!0):(this._isNextGravityRestorationSkipped=!0,this._overrideGravity(),!1))}get _isGravityOverridden(){return!!this._overrideUid}_overrideGravity(){this._overrideUid=this.editor.model.change((t=>t.overrideSelectionGravity()))}_restoreGravity(){this.editor.model.change((t=>{t.restoreSelectionGravity(this._overrideUid),this._overrideUid=null}))}}function $m(t,e){for(const i of e)if(t.hasAttribute(i))return!0;return!1}function Wm(t,e,i){const n=i.nodeBefore;t.change((t=>{n?t.setSelectionAttribute(n.getAttributes()):t.removeSelectionAttribute(e)}))}function qm(t){t.preventDefault()}function Um(t,e){const{nodeBefore:i,nodeAfter:n}=t;for(const t of e){const e=i?i.getAttribute(t):void 0;if((n?n.getAttribute(t):void 0)!==e)return!0}return!1}var Km=/[\\^$.*+?()[\]{}|]/g,Gm=RegExp(Km.source);const Jm=function(t){return(t=Gr(t))&&Gm.test(t)?t.replace(Km,"\\$&"):t},Qm={copyright:{from:"(c)",to:"©"},registeredTrademark:{from:"(r)",to:"®"},trademark:{from:"(tm)",to:"™"},oneHalf:{from:/(^|[^/a-z0-9])(1\/2)([^/a-z0-9])$/i,to:[null,"½",null]},oneThird:{from:/(^|[^/a-z0-9])(1\/3)([^/a-z0-9])$/i,to:[null,"⅓",null]},twoThirds:{from:/(^|[^/a-z0-9])(2\/3)([^/a-z0-9])$/i,to:[null,"⅔",null]},oneForth:{from:/(^|[^/a-z0-9])(1\/4)([^/a-z0-9])$/i,to:[null,"¼",null]},threeQuarters:{from:/(^|[^/a-z0-9])(3\/4)([^/a-z0-9])$/i,to:[null,"¾",null]},lessThanOrEqual:{from:"<=",to:"≤"},greaterThanOrEqual:{from:">=",to:"≥"},notEqual:{from:"!=",to:"≠"},arrowLeft:{from:"<-",to:"←"},arrowRight:{from:"->",to:"→"},horizontalEllipsis:{from:"...",to:"…"},enDash:{from:/(^| )(--)( )$/,to:[null,"–",null]},emDash:{from:/(^| )(---)( )$/,to:[null,"—",null]},quotesPrimary:{from:ig('"'),to:[null,"“",null,"”"]},quotesSecondary:{from:ig("'"),to:[null,"‘",null,"’"]},quotesPrimaryEnGb:{from:ig("'"),to:[null,"‘",null,"’"]},quotesSecondaryEnGb:{from:ig('"'),to:[null,"“",null,"”"]},quotesPrimaryPl:{from:ig('"'),to:[null,"„",null,"”"]},quotesSecondaryPl:{from:ig("'"),to:[null,"‚",null,"’"]}},Ym={symbols:["copyright","registeredTrademark","trademark"],mathematical:["oneHalf","oneThird","twoThirds","oneForth","threeQuarters","lessThanOrEqual","greaterThanOrEqual","notEqual","arrowLeft","arrowRight"],typography:["horizontalEllipsis","enDash","emDash"],quotes:["quotesPrimary","quotesSecondary"]},Zm=["symbols","mathematical","typography","quotes"];function Xm(t){return"string"==typeof t?new RegExp(`(${Jm(t)})$`):t}function tg(t){return"string"==typeof t?()=>[t]:t instanceof Array?()=>t:t}function eg(t){return(t.textNode?t.textNode:t.nodeAfter).getAttributes()}function ig(t){return new RegExp(`(^|\\s)(${t})([^${t}]*)(${t})$`)}function ng(t,e,i,n){return n.createRange(sg(t,e,i,!0,n),sg(t,e,i,!1,n))}function sg(t,e,i,n,s){let o=t.textNode||(n?t.nodeBefore:t.nodeAfter),r=null;for(;o&&o.getAttribute(e)==i;)r=o,o=n?o.previousSibling:o.nextSibling;return r?s.createPositionAt(r,n?"before":"after"):t}function og(t,e,i,n){let s,o=null;"function"==typeof n?s=n:(o=t.commands.get(n),s=()=>{t.execute(n)}),t.model.document.on("change:data",((r,a)=>{if(o&&!o.isEnabled||!e.isEnabled)return;const l=ho(t.model.document.selection.getRanges());if(!l.isCollapsed)return;if(a.isUndo||!a.isLocal)return;const c=Array.from(t.model.document.differ.getChanges()),h=c[0];if(1!=c.length||"insert"!==h.type||"$text"!=h.name||1!=h.length)return;const d=h.position.parent;if(d.is("element","codeBlock"))return;if(d.is("element","listItem")&&"function"!=typeof n&&!["numberedList","bulletedList","todoList"].includes(n))return;if(o&&!0===o.value)return;const u=d.getChild(0),f=t.model.createRangeOn(u);if(!f.containsRange(l)&&!l.end.isEqual(f.end))return;const m=i.exec(u.data.substr(0,l.end.offset));m&&t.model.enqueueChange((e=>{const i=e.createPositionAt(d,0),n=e.createPositionAt(d,m[0].length),o=new Mh(i,n);if(!1!==s({match:m})){e.remove(o);const i=t.model.document.selection.getFirstRange(),n=e.createRangeIn(d);!d.isEmpty||n.isEqual(i)||n.containsRange(i,!0)||e.remove(d)}o.detach(),t.model.enqueueChange((()=>{t.plugins.get("Delete").requestUndoOnBackspace()}))}))}))}function rg(t,e,i,n){let s,o;i instanceof RegExp?s=i:o=i,o=o||(t=>{let e;const i=[],n=[];for(;null!==(e=s.exec(t))&&!(e&&e.length<4);){let{index:t,1:s,2:o,3:r}=e;const a=s+o+r;t+=e[0].length-a.length;const l=[t,t+s.length],c=[t+s.length+o.length,t+s.length+o.length+r.length];i.push(l),i.push(c),n.push([t+s.length,t+s.length+o.length])}return{remove:i,format:n}}),t.model.document.on("change:data",((i,s)=>{if(s.isUndo||!s.isLocal||!e.isEnabled)return;const r=t.model,a=r.document.selection;if(!a.isCollapsed)return;const l=Array.from(r.document.differ.getChanges()),c=l[0];if(1!=l.length||"insert"!==c.type||"$text"!=c.name||1!=c.length)return;const h=a.focus,d=h.parent,{text:u,range:f}=function(t,e){let i=t.start;const n=Array.from(t.getItems()).reduce(((t,n)=>!n.is("$text")&&!n.is("$textProxy")||n.getAttribute("code")?(i=e.createPositionAfter(n),""):t+n.data),"");return{text:n,range:e.createRange(i,t.end)}}(r.createRange(r.createPositionAt(d,0),h),r),m=o(u),g=ag(f.start,m.format,r),p=ag(f.start,m.remove,r);g.length&&p.length&&r.enqueueChange((e=>{if(!1!==n(e,g)){for(const t of p.reverse())e.remove(t);r.enqueueChange((()=>{t.plugins.get("Delete").requestUndoOnBackspace()}))}}))}))}function ag(t,e,i){return e.filter((t=>void 0!==t[0]&&void 0!==t[1])).map((e=>i.createRange(t.getShiftedBy(e[0]),t.getShiftedBy(e[1]))))}function lg(t,e){return(i,n)=>{if(!t.commands.get(e).isEnabled)return!1;const s=t.model.schema.getValidRanges(n,e);for(const t of s)i.setAttribute(e,!0,t);i.removeSelectionAttribute(e)}}function*cg(t,e){for(const i of e)i&&t.getAttributeProperties(i[0]).copyOnEnter&&(yield i)}class hg extends hr{execute(){this.editor.model.change((t=>{this.enterBlock(t),this.fire("afterExecute",{writer:t})}))}enterBlock(t){const e=this.editor.model,i=e.document.selection,n=e.schema,s=i.isCollapsed,o=i.getFirstRange(),r=o.start.parent,a=o.end.parent;if(n.isLimit(r)||n.isLimit(a))return s||r!=a||e.deleteContent(i),!1;if(s){const e=cg(t.model.schema,i.getAttributes());return dg(t,o.start),t.setSelectionAttribute(e),!0}{const n=!(o.start.isAtStart&&o.end.isAtEnd),s=r==a;if(e.deleteContent(i,{leaveUnmerged:n}),n){if(s)return dg(t,i.focus),!0;t.setSelection(a,0)}}return!1}}function dg(t,e){t.split(e),t.setSelection(e.parent.nextSibling,0)}const ug={insertParagraph:{isSoft:!1},insertLineBreak:{isSoft:!0}};class fg extends Ul{constructor(t){super(t);const e=this.document;e.on("beforeinput",((i,n)=>{if(!this.isEnabled)return;const s=n.domEvent,o=ug[n.inputType];if(!o)return;const r=new Ua(e,"enter",n.targetRanges[0]);e.fire(r,new Gl(t,s,{isSoft:o.isSoft})),r.stop.called&&i.stop()}))}observe(){}}class mg extends lr{static get pluginName(){return"Enter"}init(){const t=this.editor,e=t.editing.view,i=e.document;e.addObserver(fg),t.commands.add("enter",new hg(t)),this.listenTo(i,"enter",((n,s)=>{i.isComposing||s.preventDefault(),s.isSoft||(t.execute("enter"),e.scrollToTheSelection())}),{priority:"low"})}}class gg extends hr{execute(){const t=this.editor.model,e=t.document;t.change((i=>{!function(t,e,i){const n=i.isCollapsed,s=i.getFirstRange(),o=s.start.parent,r=s.end.parent,a=o==r;if(n){const n=cg(t.schema,i.getAttributes());pg(t,e,s.end),e.removeSelectionAttribute(i.getAttributeKeys()),e.setSelectionAttribute(n)}else{const n=!(s.start.isAtStart&&s.end.isAtEnd);t.deleteContent(i,{leaveUnmerged:n}),a?pg(t,e,i.focus):n&&e.setSelection(r,0)}}(t,i,e.selection),this.fire("afterExecute",{writer:i})}))}refresh(){const t=this.editor.model,e=t.document;this.isEnabled=function(t,e){if(e.rangeCount>1)return!1;const i=e.anchor;if(!i||!t.checkChild(i,"softBreak"))return!1;const n=e.getFirstRange(),s=n.start.parent,o=n.end.parent;if((wg(s,t)||wg(o,t))&&s!==o)return!1;return!0}(t.schema,e.selection)}}function pg(t,e,i){const n=e.createElement("softBreak");t.insertContent(n,i),e.setSelection(n,"after")}function wg(t,e){return!t.is("rootElement")&&(e.isLimit(t)||wg(t.parent,e))}class bg extends lr{static get pluginName(){return"ShiftEnter"}init(){const t=this.editor,e=t.model.schema,i=t.conversion,n=t.editing.view,s=n.document;e.register("softBreak",{allowWhere:"$text",isInline:!0}),i.for("upcast").elementToElement({model:"softBreak",view:"br"}),i.for("downcast").elementToElement({model:"softBreak",view:(t,{writer:e})=>e.createEmptyElement("br")}),n.addObserver(fg),t.commands.add("shiftEnter",new gg(t)),this.listenTo(s,"enter",((e,i)=>{s.isComposing||i.preventDefault(),i.isSoft&&(t.execute("shiftEnter"),n.scrollToTheSelection())}),{priority:"low"})}}class _g extends hr{refresh(){this.value=this._getValue(),this.isEnabled=this._checkEnabled()}execute(t={}){const e=this.editor.model,i=e.schema,n=e.document.selection,s=Array.from(n.getSelectedBlocks()),o=void 0===t.forceValue?!this.value:t.forceValue;e.change((t=>{if(o){const e=s.filter((t=>vg(t)||kg(i,t)));this._applyQuote(t,e)}else this._removeQuote(t,s.filter(vg))}))}_getValue(){const t=ho(this.editor.model.document.selection.getSelectedBlocks());return!(!t||!vg(t))}_checkEnabled(){if(this.value)return!0;const t=this.editor.model.document.selection,e=this.editor.model.schema,i=ho(t.getSelectedBlocks());return!!i&&kg(e,i)}_removeQuote(t,e){yg(t,e).reverse().forEach((e=>{if(e.start.isAtStart&&e.end.isAtEnd)return void t.unwrap(e.start.parent);if(e.start.isAtStart){const i=t.createPositionBefore(e.start.parent);return void t.move(e,i)}e.end.isAtEnd||t.split(e.end);const i=t.createPositionAfter(e.end.parent);t.move(e,i)}))}_applyQuote(t,e){const i=[];yg(t,e).reverse().forEach((e=>{let n=vg(e.start);n||(n=t.createElement("blockQuote"),t.wrap(e,n)),i.push(n)})),i.reverse().reduce(((e,i)=>e.nextSibling==i?(t.merge(t.createPositionAfter(e)),e):i))}}function vg(t){return"blockQuote"==t.parent.name?t.parent:null}function yg(t,e){let i,n=0;const s=[];for(;n{const n=t.model.document.differ.getChanges();for(const t of n)if("insert"==t.type){const n=t.position.nodeAfter;if(!n)continue;if(n.is("element","blockQuote")&&n.isEmpty)return i.remove(n),!0;if(n.is("element","blockQuote")&&!e.checkChild(t.position,n))return i.unwrap(n),!0;if(n.is("element")){const t=i.createRangeIn(n);for(const n of t.getItems())if(n.is("element","blockQuote")&&!e.checkChild(i.createPositionBefore(n),n))return i.unwrap(n),!0}}else if("remove"==t.type){const e=t.position.parent;if(e.is("element","blockQuote")&&e.isEmpty)return i.remove(e),!0}return!1}));const i=this.editor.editing.view.document,n=t.model.document.selection,s=t.commands.get("blockQuote");this.listenTo(i,"enter",((e,i)=>{if(!n.isCollapsed||!s.value)return;n.getLastPosition().parent.isEmpty&&(t.execute("blockQuote"),t.editing.view.scrollToTheSelection(),i.preventDefault(),e.stop())}),{context:"blockquote"}),this.listenTo(i,"delete",((e,i)=>{if("backward"!=i.direction||!n.isCollapsed||!s.value)return;const o=n.getLastPosition().parent;o.isEmpty&&!o.previousSibling&&(t.execute("blockQuote"),t.editing.view.scrollToTheSelection(),i.preventDefault(),e.stop())}),{context:"blockquote"})}}class xg extends lr{static get pluginName(){return"BlockQuoteUI"}init(){const t=this.editor,e=t.t;t.ui.componentFactory.add("blockQuote",(i=>{const n=t.commands.get("blockQuote"),s=new qo(i);return s.set({label:e("Block quote"),icon:yf.quote,tooltip:!0,isToggleable:!0}),s.bind("isOn","isEnabled").to(n,"value","isEnabled"),this.listenTo(s,"execute",(()=>{t.execute("blockQuote"),t.editing.view.focus()})),s}))}}class Cg extends hr{constructor(t,e){super(t),this.attributeKey=e}refresh(){const t=this.editor.model,e=t.document;this.value=this._getValueFromFirstAllowedNode(),this.isEnabled=t.schema.checkAttributeInSelection(e.selection,this.attributeKey)}execute(t={}){const e=this.editor.model,i=e.document.selection,n=void 0===t.forceValue?!this.value:t.forceValue;e.change((t=>{if(i.isCollapsed)n?t.setSelectionAttribute(this.attributeKey,!0):t.removeSelectionAttribute(this.attributeKey);else{const s=e.schema.getValidRanges(i.getRanges(),this.attributeKey);for(const e of s)n?t.setAttribute(this.attributeKey,n,e):t.removeAttribute(this.attributeKey,e)}}))}_getValueFromFirstAllowedNode(){const t=this.editor.model,e=t.schema,i=t.document.selection;if(i.isCollapsed)return i.hasAttribute(this.attributeKey);for(const t of i.getRanges())for(const i of t.getItems())if(e.checkAttribute(i,this.attributeKey))return i.hasAttribute(this.attributeKey);return!1}}const Pg="bold";class Tg extends lr{static get pluginName(){return"BoldEditing"}init(){const t=this.editor;t.model.schema.extend("$text",{allowAttributes:Pg}),t.model.schema.setAttributeProperties(Pg,{isFormatting:!0,copyOnEnter:!0}),t.conversion.attributeToElement({model:Pg,view:"strong",upcastAlso:["b",t=>{const e=t.getStyle("font-weight");return e&&("bold"==e||Number(e)>=600)?{name:!0,styles:["font-weight"]}:null}]}),t.commands.add(Pg,new Cg(t,Pg)),t.keystrokes.set("CTRL+B",Pg)}}const Eg="bold";class Sg extends lr{static get pluginName(){return"BoldUI"}init(){const t=this.editor,e=t.t;t.ui.componentFactory.add(Eg,(i=>{const n=t.commands.get(Eg),s=new qo(i);return s.set({label:e("Bold"),icon:yf.bold,keystroke:"CTRL+B",tooltip:!0,isToggleable:!0}),s.bind("isOn","isEnabled").to(n,"value","isEnabled"),this.listenTo(s,"execute",(()=>{t.execute(Eg),t.editing.view.focus()})),s}))}}class Rg extends Jl{constructor(t){super(t);const e=this.document;function i(t){return(i,n)=>{n.preventDefault();const s=n.dropRange?[n.dropRange]:null,o=new m(e,t);e.fire(o,{dataTransfer:n.dataTransfer,method:i.name,targetRanges:s,target:n.target}),o.stop.called&&n.stopPropagation()}}this.domEventType=["paste","copy","cut","drop","dragover","dragstart","dragend","dragenter","dragleave"],this.listenTo(e,"paste",i("clipboardInput"),{priority:"low"}),this.listenTo(e,"drop",i("clipboardInput"),{priority:"low"}),this.listenTo(e,"dragover",i("dragging"),{priority:"low"})}onDomEvent(t){const e={dataTransfer:new nh("clipboardData"in t?t.clipboardData:t.dataTransfer)};"drop"!=t.type&&"dragover"!=t.type||(e.dropRange=function(t,e){const i=e.target.ownerDocument,n=e.clientX,s=e.clientY;let o;i.caretRangeFromPoint&&i.caretRangeFromPoint(n,s)?o=i.caretRangeFromPoint(n,s):e.rangeParent&&(o=i.createRange(),o.setStart(e.rangeParent,e.rangeOffset),o.collapse(!0));if(o)return t.domConverter.domRangeToView(o);return null}(this.view,t)),this.fire(t.type,t,e)}}const Og=["figcaption","li"];function Ig(t){let e="";if(t.is("$text")||t.is("$textProxy"))e=t.data;else if(t.is("element","img")&&t.hasAttribute("alt"))e=t.getAttribute("alt");else if(t.is("element","br"))e="\n";else{let i=null;for(const n of t.getChildren()){const t=Ig(n);i&&(i.is("containerElement")||n.is("containerElement"))&&(Og.includes(i.name)||Og.includes(n.name)?e+="\n":e+="\n\n"),e+=t,i=n}}return e}class Vg extends lr{static get pluginName(){return"ClipboardPipeline"}init(){this.editor.editing.view.addObserver(Rg),this._setupPasteDrop(),this._setupCopyCut()}_setupPasteDrop(){const t=this.editor,e=t.model,i=t.editing.view,n=i.document;this.listenTo(n,"clipboardInput",(e=>{t.isReadOnly&&e.stop()}),{priority:"highest"}),this.listenTo(n,"clipboardInput",((t,e)=>{const n=e.dataTransfer;let s;if(e.content)s=e.content;else{let t="";n.getData("text/html")?t=function(t){return t.replace(/(\s+)<\/span>/g,((t,e)=>1==e.length?" ":e)).replace(//g,"")}(n.getData("text/html")):n.getData("text/plain")&&(((o=(o=n.getData("text/plain")).replace(//g,">").replace(/\r?\n\r?\n/g,"

").replace(/\r?\n/g,"
").replace(/\t/g,"    ").replace(/^\s/," ").replace(/\s$/," ").replace(/\s\s/g,"  ")).includes("

")||o.includes("
"))&&(o=`

${o}

`),t=o),s=this.editor.data.htmlProcessor.toView(t)}var o;const r=new m(this,"inputTransformation");this.fire(r,{content:s,dataTransfer:n,targetRanges:e.targetRanges,method:e.method}),r.stop.called&&t.stop(),i.scrollToTheSelection()}),{priority:"low"}),this.listenTo(this,"inputTransformation",((t,i)=>{if(i.content.isEmpty)return;const n=this.editor.data.toModel(i.content,"$clipboardHolder");0!=n.childCount&&(t.stop(),e.change((()=>{this.fire("contentInsertion",{content:n,method:i.method,dataTransfer:i.dataTransfer,targetRanges:i.targetRanges})})))}),{priority:"low"}),this.listenTo(this,"contentInsertion",((t,i)=>{i.resultRange=e.insertContent(i.content)}),{priority:"low"})}_setupCopyCut(){const t=this.editor,e=t.model.document,i=t.editing.view.document,n=(n,s)=>{const o=s.dataTransfer;s.preventDefault();const r=t.data.toView(t.model.getSelectedContent(e.selection));i.fire("clipboardOutput",{dataTransfer:o,content:r,method:n.name})};this.listenTo(i,"copy",n,{priority:"low"}),this.listenTo(i,"cut",((e,i)=>{t.isReadOnly?i.preventDefault():n(e,i)}),{priority:"low"}),this.listenTo(i,"clipboardOutput",((i,n)=>{n.content.isEmpty||(n.dataTransfer.setData("text/html",this.editor.data.htmlProcessor.toData(n.content)),n.dataTransfer.setData("text/plain",Ig(n.content))),"cut"==n.method&&t.model.deleteContent(e.selection)}),{priority:"low"})}}class Mg extends(R()){constructor(){super(),this._stack=[]}add(t,e){const i=this._stack,n=i[0];this._insertDescriptor(t);const s=i[0];n===s||Ng(n,s)||this.fire("change:top",{oldDescriptor:n,newDescriptor:s,writer:e})}remove(t,e){const i=this._stack,n=i[0];this._removeDescriptor(t);const s=i[0];n===s||Ng(n,s)||this.fire("change:top",{oldDescriptor:n,newDescriptor:s,writer:e})}_insertDescriptor(t){const e=this._stack,i=e.findIndex((e=>e.id===t.id));if(Ng(t,e[i]))return;i>-1&&e.splice(i,1);let n=0;for(;e[n]&&Bg(e[n],t);)n++;e.splice(n,0,t)}_removeDescriptor(t){const e=this._stack,i=e.findIndex((e=>e.id===t));i>-1&&e.splice(i,1)}}function Ng(t,e){return t&&e&&t.priority==e.priority&&Dg(t.classes)==Dg(e.classes)}function Bg(t,e){return t.priority>e.priority||!(t.priorityDg(e.classes)}function Dg(t){return Array.isArray(t)?t.sort().join(","):t}const Fg='',Lg="ck-widget",zg="ck-widget_selected";function Hg(t){return!!t.is("element")&&!!t.getCustomProperty("widget")}function jg(t,e,i={}){if(!t.is("containerElement"))throw new v("widget-to-widget-wrong-element-type",null,{element:t});return e.setAttribute("contenteditable","false",t),e.addClass(Lg,t),e.setCustomProperty("widget",!0,t),t.getFillerOffset=Ug,e.setCustomProperty("widgetLabel",[],t),i.label&&function(t,e){const i=t.getCustomProperty("widgetLabel");i.push(e)}(t,i.label),i.hasSelectionHandle&&function(t,e){const i=e.createUIElement("div",{class:"ck ck-widget__selection-handle"},(function(t){const e=this.toDomElement(t),i=new Wo;return i.set("content",Fg),i.render(),e.appendChild(i.element),e}));e.insert(e.createPositionAt(t,0),i),e.addClass(["ck-widget_with-selection-handle"],t)}(t,e),qg(t,e),t}function $g(t,e,i){if(e.classes&&i.addClass(so(e.classes),t),e.attributes)for(const n in e.attributes)i.setAttribute(n,e.attributes[n],t)}function Wg(t,e,i){if(e.classes&&i.removeClass(so(e.classes),t),e.attributes)for(const n in e.attributes)i.removeAttribute(n,t)}function qg(t,e,i=$g,n=Wg){const s=new Mg;s.on("change:top",((e,s)=>{s.oldDescriptor&&n(t,s.oldDescriptor,s.writer),s.newDescriptor&&i(t,s.newDescriptor,s.writer)}));e.setCustomProperty("addHighlight",((t,e,i)=>s.add(e,i)),t),e.setCustomProperty("removeHighlight",((t,e,i)=>s.remove(e,i)),t)}function Ug(){return null}const Kg="widget-type-around";function Gg(t,e,i){return!!t&&Hg(t)&&!i.isInline(e)}function Jg(t){return t.getAttribute(Kg)}const Qg=["before","after"],Yg=(new DOMParser).parseFromString('',"image/svg+xml").firstChild,Zg="ck-widget__type-around_disabled";class Xg extends lr{static get pluginName(){return"WidgetTypeAround"}static get requires(){return[mg,Fm]}constructor(t){super(t),this._currentFakeCaretModelElement=null}init(){const t=this.editor,e=t.editing.view;this.on("change:isEnabled",((i,n,s)=>{e.change((t=>{for(const i of e.document.roots)s?t.removeClass(Zg,i):t.addClass(Zg,i)})),s||t.model.change((t=>{t.removeSelectionAttribute(Kg)}))})),this._enableTypeAroundUIInjection(),this._enableInsertingParagraphsOnButtonClick(),this._enableInsertingParagraphsOnEnterKeypress(),this._enableInsertingParagraphsOnTypingKeystroke(),this._enableTypeAroundFakeCaretActivationUsingKeyboardArrows(),this._enableDeleteIntegration(),this._enableInsertContentIntegration(),this._enableInsertObjectIntegration(),this._enableDeleteContentIntegration()}destroy(){super.destroy(),this._currentFakeCaretModelElement=null}_insertParagraph(t,e){const i=this.editor,n=i.editing.view,s=i.model.schema.getAttributesWithProperty(t,"copyOnReplace",!0);i.execute("insertParagraph",{position:i.model.createPositionAt(t,e),attributes:s}),n.focus(),n.scrollToTheSelection()}_listenToIfEnabled(t,e,i,n){this.listenTo(t,e,((...t)=>{this.isEnabled&&i(...t)}),n)}_insertParagraphAccordingToFakeCaretPosition(){const t=this.editor.model.document.selection,e=Jg(t);if(!e)return!1;const i=t.getSelectedElement();return this._insertParagraph(i,e),!0}_enableTypeAroundUIInjection(){const t=this.editor,e=t.model.schema,i=t.locale.t,n={before:i("Insert paragraph before block"),after:i("Insert paragraph after block")};t.editing.downcastDispatcher.on("insert",((t,s,o)=>{const r=o.mapper.toViewElement(s.item);if(r&&Gg(r,s.item,e)){!function(t,e,i){const n=t.createUIElement("div",{class:"ck ck-reset_all ck-widget__type-around"},(function(t){const i=this.toDomElement(t);return function(t,e){for(const i of Qg){const n=new ko({tag:"div",attributes:{class:["ck","ck-widget__type-around__button",`ck-widget__type-around__button_${i}`],title:e[i],"aria-hidden":"true"},children:[t.ownerDocument.importNode(Yg,!0)]});t.appendChild(n.render())}}(i,e),function(t){const e=new ko({tag:"div",attributes:{class:["ck","ck-widget__type-around__fake-caret"]}});t.appendChild(e.render())}(i),i}));t.insert(t.createPositionAt(i,"end"),n)}(o.writer,n,r);r.getCustomProperty("widgetLabel").push((()=>this.isEnabled?i("Press Enter to type after or press Shift + Enter to type before the widget"):""))}}),{priority:"low"})}_enableTypeAroundFakeCaretActivationUsingKeyboardArrows(){const t=this.editor,e=t.model,i=e.document.selection,n=e.schema,s=t.editing.view;function o(t){return`ck-widget_type-around_show-fake-caret_${t}`}this._listenToIfEnabled(s.document,"arrowKey",((t,e)=>{this._handleArrowKeyPress(t,e)}),{context:[Hg,"$text"],priority:"high"}),this._listenToIfEnabled(i,"change:range",((e,i)=>{i.directChange&&t.model.change((t=>{t.removeSelectionAttribute(Kg)}))})),this._listenToIfEnabled(e.document,"change:data",(()=>{const e=i.getSelectedElement();if(e){if(Gg(t.editing.mapper.toViewElement(e),e,n))return}t.model.change((t=>{t.removeSelectionAttribute(Kg)}))})),this._listenToIfEnabled(t.editing.downcastDispatcher,"selection",((t,e,i)=>{const s=i.writer;if(this._currentFakeCaretModelElement){const t=i.mapper.toViewElement(this._currentFakeCaretModelElement);t&&(s.removeClass(Qg.map(o),t),this._currentFakeCaretModelElement=null)}const r=e.selection.getSelectedElement();if(!r)return;const a=i.mapper.toViewElement(r);if(!Gg(a,r,n))return;const l=Jg(e.selection);l&&(s.addClass(o(l),a),this._currentFakeCaretModelElement=r)})),this._listenToIfEnabled(t.ui.focusTracker,"change:isFocused",((e,i,n)=>{n||t.model.change((t=>{t.removeSelectionAttribute(Kg)}))}))}_handleArrowKeyPress(t,e){const i=this.editor,n=i.model,s=n.document.selection,o=n.schema,r=i.editing.view,a=function(t,e){const i=no(t,e);return"down"===i||"right"===i}(e.keyCode,i.locale.contentLanguageDirection),l=r.document.selection.getSelectedElement();let c;Gg(l,i.editing.mapper.toModelElement(l),o)?c=this._handleArrowKeyPressOnSelectedWidget(a):s.isCollapsed?c=this._handleArrowKeyPressWhenSelectionNextToAWidget(a):e.shiftKey||(c=this._handleArrowKeyPressWhenNonCollapsedSelection(a)),c&&(e.preventDefault(),t.stop())}_handleArrowKeyPressOnSelectedWidget(t){const e=this.editor.model,i=Jg(e.document.selection);return e.change((e=>{if(!i)return e.setSelectionAttribute(Kg,t?"after":"before"),!0;if(!(i===(t?"after":"before")))return e.removeSelectionAttribute(Kg),!0;return!1}))}_handleArrowKeyPressWhenSelectionNextToAWidget(t){const e=this.editor,i=e.model,n=i.schema,s=e.plugins.get("Widget"),o=s._getObjectElementNextToSelection(t);return!!Gg(e.editing.mapper.toViewElement(o),o,n)&&(i.change((e=>{s._setSelectionOverElement(o),e.setSelectionAttribute(Kg,t?"before":"after")})),!0)}_handleArrowKeyPressWhenNonCollapsedSelection(t){const e=this.editor,i=e.model,n=i.schema,s=e.editing.mapper,o=i.document.selection,r=t?o.getLastPosition().nodeBefore:o.getFirstPosition().nodeAfter;return!!Gg(s.toViewElement(r),r,n)&&(i.change((e=>{e.setSelection(r,"on"),e.setSelectionAttribute(Kg,t?"after":"before")})),!0)}_enableInsertingParagraphsOnButtonClick(){const t=this.editor,e=t.editing.view;this._listenToIfEnabled(e.document,"mousedown",((i,n)=>{const s=n.domTarget.closest(".ck-widget__type-around__button");if(!s)return;const o=function(t){return t.classList.contains("ck-widget__type-around__button_before")?"before":"after"}(s),r=function(t,e){const i=t.closest(".ck-widget");return e.mapDomToView(i)}(s,e.domConverter),a=t.editing.mapper.toModelElement(r);this._insertParagraph(a,o),n.preventDefault(),i.stop()}))}_enableInsertingParagraphsOnEnterKeypress(){const t=this.editor,e=t.model.document.selection,i=t.editing.view;this._listenToIfEnabled(i.document,"enter",((i,n)=>{if("atTarget"!=i.eventPhase)return;const s=e.getSelectedElement(),o=t.editing.mapper.toViewElement(s),r=t.model.schema;let a;this._insertParagraphAccordingToFakeCaretPosition()?a=!0:Gg(o,s,r)&&(this._insertParagraph(s,n.isSoft?"before":"after"),a=!0),a&&(n.preventDefault(),i.stop())}),{context:Hg})}_enableInsertingParagraphsOnTypingKeystroke(){const t=this.editor.editing.view.document;this._listenToIfEnabled(t,"insertText",((e,i)=>{this._insertParagraphAccordingToFakeCaretPosition()&&(i.selection=t.selection)}),{priority:"high"}),r.isAndroid?this._listenToIfEnabled(t,"keydown",((t,e)=>{229==e.keyCode&&this._insertParagraphAccordingToFakeCaretPosition()})):this._listenToIfEnabled(t,"compositionstart",(()=>{this._insertParagraphAccordingToFakeCaretPosition()}),{priority:"high"})}_enableDeleteIntegration(){const t=this.editor,e=t.editing.view,i=t.model,n=i.schema;this._listenToIfEnabled(e.document,"delete",((e,s)=>{if("atTarget"!=e.eventPhase)return;const o=Jg(i.document.selection);if(!o)return;const r=s.direction,a=i.document.selection.getSelectedElement(),l="forward"==r;if("before"===o===l)t.execute("delete",{selection:i.createSelection(a,"on")});else{const e=n.getNearestSelectionRange(i.createPositionAt(a,o),r);if(e)if(e.isCollapsed){const s=i.createSelection(e.start);if(i.modifySelection(s,{direction:r}),s.focus.isEqual(e.start)){const t=function(t,e){let i=e;for(const n of e.getAncestors({parentFirst:!0})){if(n.childCount>1||t.isLimit(n))break;i=n}return i}(n,e.start.parent);i.deleteContent(i.createSelection(t,"on"),{doNotAutoparagraph:!0})}else i.change((i=>{i.setSelection(e),t.execute(l?"deleteForward":"delete")}))}else i.change((i=>{i.setSelection(e),t.execute(l?"deleteForward":"delete")}))}s.preventDefault(),e.stop()}),{context:Hg})}_enableInsertContentIntegration(){const t=this.editor,e=this.editor.model,i=e.document.selection;this._listenToIfEnabled(t.model,"insertContent",((t,[n,s])=>{if(s&&!s.is("documentSelection"))return;const o=Jg(i);return o?(t.stop(),e.change((t=>{const s=i.getSelectedElement(),r=e.createPositionAt(s,o),a=t.createSelection(r),l=e.insertContent(n,a);return t.setSelection(a),l}))):void 0}),{priority:"high"})}_enableInsertObjectIntegration(){const t=this.editor,e=this.editor.model.document.selection;this._listenToIfEnabled(t.model,"insertObject",((t,i)=>{const[,n,,s={}]=i;if(n&&!n.is("documentSelection"))return;const o=Jg(e);o&&(s.findOptimalPosition=o,i[3]=s)}),{priority:"high"})}_enableDeleteContentIntegration(){const t=this.editor,e=this.editor.model.document.selection;this._listenToIfEnabled(t.model,"deleteContent",((t,[i])=>{if(i&&!i.is("documentSelection"))return;Jg(e)&&t.stop()}),{priority:"high"})}}function tp(t){const e=t.model;return(i,n)=>{const s=n.keyCode==Zs.arrowup,o=n.keyCode==Zs.arrowdown,r=n.shiftKey,a=e.document.selection;if(!s&&!o)return;const l=o;if(r&&function(t,e){return!t.isCollapsed&&t.isBackward==e}(a,l))return;const c=function(t,e,i){const n=t.model;if(i){const t=e.isCollapsed?e.focus:e.getLastPosition(),i=ep(n,t,"forward");if(!i)return null;const s=n.createRange(t,i),o=ip(n.schema,s,"backward");return o?n.createRange(t,o):null}{const t=e.isCollapsed?e.focus:e.getFirstPosition(),i=ep(n,t,"backward");if(!i)return null;const s=n.createRange(i,t),o=ip(n.schema,s,"forward");return o?n.createRange(o,t):null}}(t,a,l);if(c){if(c.isCollapsed){if(a.isCollapsed)return;if(r)return}(c.isCollapsed||function(t,e,i){const n=t.model,s=t.view.domConverter;if(i){const t=n.createSelection(e.start);n.modifySelection(t),t.focus.isAtEnd||e.start.isEqual(t.focus)||(e=n.createRange(t.focus,e.end))}const o=t.mapper.toViewRange(e),r=s.viewRangeToDom(o),a=Ps.getDomRangeRects(r);let l;for(const t of a)if(void 0!==l){if(Math.round(t.top)>=l)return!1;l=Math.max(l,Math.round(t.bottom))}else l=Math.round(t.bottom);return!0}(t,c,l))&&(e.change((t=>{const i=l?c.end:c.start;if(r){const n=e.createSelection(a.anchor);n.setFocus(i),t.setSelection(n)}else t.setSelection(i)})),i.stop(),n.preventDefault(),n.stopPropagation())}}}function ep(t,e,i){const n=t.schema,s=t.createRangeIn(e.root),o="forward"==i?"elementStart":"elementEnd";for(const{previousPosition:t,item:r,type:a}of s.getWalker({startPosition:e,direction:i})){if(n.isLimit(r)&&!n.isInline(r))return t;if(a==o&&n.isBlock(r))return null}return null}function ip(t,e,i){const n="backward"==i?e.end:e.start;if(t.checkChild(n,"$text"))return n;for(const{nextPosition:n}of e.getWalker({direction:i}))if(t.checkChild(n,"$text"))return n;return null}class np extends lr{static get pluginName(){return"Widget"}static get requires(){return[Xg,Fm]}init(){const t=this.editor,e=t.editing.view,i=e.document;this._previouslySelected=new Set,this.editor.editing.downcastDispatcher.on("selection",((e,i,n)=>{const s=n.writer,o=i.selection;if(o.isCollapsed)return;const r=o.getSelectedElement();if(!r)return;const a=t.editing.mapper.toViewElement(r);var l;Hg(a)&&(n.consumable.consume(o,"selection")&&s.setSelection(s.createRangeOn(a),{fake:!0,label:(l=a,l.getCustomProperty("widgetLabel").reduce(((t,e)=>"function"==typeof e?t?t+". "+e():e():t?t+". "+e:e),""))}))})),this.editor.editing.downcastDispatcher.on("selection",((t,e,i)=>{this._clearPreviouslySelectedWidgets(i.writer);const n=i.writer,s=n.document.selection;let o=null;for(const t of s.getRanges())for(const e of t){const t=e.item;Hg(t)&&!sp(t,o)&&(n.addClass(zg,t),this._previouslySelected.add(t),o=t)}}),{priority:"low"}),e.addObserver(lf),this.listenTo(i,"mousedown",((...t)=>this._onMousedown(...t))),this.listenTo(i,"arrowKey",((...t)=>{this._handleSelectionChangeOnArrowKeyPress(...t)}),{context:[Hg,"$text"]}),this.listenTo(i,"arrowKey",((...t)=>{this._preventDefaultOnArrowKeyPress(...t)}),{context:"$root"}),this.listenTo(i,"arrowKey",tp(this.editor.editing),{context:"$text"}),this.listenTo(i,"delete",((t,e)=>{this._handleDelete("forward"==e.direction)&&(e.preventDefault(),t.stop())}),{context:"$root"})}_onMousedown(t,e){const i=this.editor,n=i.editing.view,s=n.document;let o=e.target;if(function(t){let e=t;for(;e;){if(e.is("editableElement")&&!e.is("rootElement"))return!0;if(Hg(e))return!1;e=e.parent}return!1}(o)){if((r.isSafari||r.isGecko)&&e.domEvent.detail>=3){const t=i.editing.mapper,n=o.is("attributeElement")?o.findAncestor((t=>!t.is("attributeElement"))):o,s=t.toModelElement(n);e.preventDefault(),this.editor.model.change((t=>{t.setSelection(s,"in")}))}return}if(!Hg(o)&&(o=o.findAncestor(Hg),!o))return;r.isAndroid&&e.preventDefault(),s.isFocused||n.focus();const a=i.editing.mapper.toModelElement(o);this._setSelectionOverElement(a)}_handleSelectionChangeOnArrowKeyPress(t,e){const i=e.keyCode,n=this.editor.model,s=n.schema,o=n.document.selection,r=o.getSelectedElement(),a=no(i,this.editor.locale.contentLanguageDirection),l="down"==a||"right"==a,c="up"==a||"down"==a;if(r&&s.isObject(r)){const i=l?o.getLastPosition():o.getFirstPosition(),r=s.getNearestSelectionRange(i,l?"forward":"backward");return void(r&&(n.change((t=>{t.setSelection(r)})),e.preventDefault(),t.stop()))}if(!o.isCollapsed&&!e.shiftKey){const i=o.getFirstPosition(),r=o.getLastPosition(),a=i.nodeAfter,c=r.nodeBefore;return void((a&&s.isObject(a)||c&&s.isObject(c))&&(n.change((t=>{t.setSelection(l?r:i)})),e.preventDefault(),t.stop()))}if(!o.isCollapsed)return;const h=this._getObjectElementNextToSelection(l);if(h&&s.isObject(h)){if(s.isInline(h)&&c)return;this._setSelectionOverElement(h),e.preventDefault(),t.stop()}}_preventDefaultOnArrowKeyPress(t,e){const i=this.editor.model,n=i.schema,s=i.document.selection.getSelectedElement();s&&n.isObject(s)&&(e.preventDefault(),t.stop())}_handleDelete(t){if(this.editor.isReadOnly)return;const e=this.editor.model.document.selection;if(!e.isCollapsed)return;const i=this._getObjectElementNextToSelection(t);return i?(this.editor.model.change((t=>{let n=e.anchor.parent;for(;n.isEmpty;){const e=n;n=e.parent,t.remove(e)}this._setSelectionOverElement(i)})),!0):void 0}_setSelectionOverElement(t){this.editor.model.change((e=>{e.setSelection(e.createRangeOn(t))}))}_getObjectElementNextToSelection(t){const e=this.editor.model,i=e.schema,n=e.document.selection,s=e.createSelection(n);if(e.modifySelection(s,{direction:t?"forward":"backward"}),s.isEqual(n))return null;const o=t?s.focus.nodeBefore:s.focus.nodeAfter;return o&&i.isObject(o)?o:null}_clearPreviouslySelectedWidgets(t){for(const e of this._previouslySelected)t.removeClass(zg,e);this._previouslySelected.clear()}}function sp(t,e){return!!e&&Array.from(t.getAncestors()).includes(e)}class op extends(q()){constructor(t){super(),this.set("activeHandlePosition",null),this.set("proposedWidthPercents",null),this.set("proposedWidth",null),this.set("proposedHeight",null),this.set("proposedHandleHostWidth",null),this.set("proposedHandleHostHeight",null),this._options=t,this._referenceCoordinates=null}get originalWidth(){return this._originalWidth}get originalHeight(){return this._originalHeight}get originalWidthPercents(){return this._originalWidthPercents}get aspectRatio(){return this._aspectRatio}begin(t,e,i){const n=new Rect(e);this.activeHandlePosition=function(t){const e=["top-left","top-right","bottom-right","bottom-left"];for(const i of e)if(t.classList.contains(getResizerHandleClass(i)))return i}(t),this._referenceCoordinates=function(t,e){const i=new Rect(t),n=e.split("-"),s={x:"right"==n[1]?i.right:i.left,y:"bottom"==n[0]?i.bottom:i.top};return s.x+=t.ownerDocument.defaultView.scrollX,s.y+=t.ownerDocument.defaultView.scrollY,s}(e,function(t){const e=t.split("-"),i={top:"bottom",bottom:"top",left:"right",right:"left"};return`${i[e[0]]}-${i[e[1]]}`}(this.activeHandlePosition)),this._originalWidth=n.width,this._originalHeight=n.height,this._aspectRatio=n.width/n.height;const s=i.style.width;s&&s.match(/^\d+(\.\d*)?%$/)?this._originalWidthPercents=parseFloat(s):this._originalWidthPercents=function(t,e){const i=t.parentElement,n=parseFloat(i.ownerDocument.defaultView.getComputedStyle(i).width);return e.width/n*100}(i,n)}update(t){this.proposedWidth=t.width,this.proposedHeight=t.height,this.proposedWidthPercents=t.widthPercents,this.proposedHandleHostWidth=t.handleHostWidth,this.proposedHandleHostHeight=t.handleHostHeight}}class rp extends(q()){constructor(t){super(),this._options=t,this._viewResizerWrapper=null,this.set("isEnabled",!0),this.set("isSelected",!1),this.bind("isVisible").to(this,"isEnabled",this,"isSelected",((t,e)=>t&&e)),this.decorate("begin"),this.decorate("cancel"),this.decorate("commit"),this.decorate("updateSize"),this.on("commit",(t=>{this.state.proposedWidth||this.state.proposedWidthPercents||(this._cleanup(),t.stop())}),{priority:"high"})}get state(){return this._state}show(){this._options.editor.editing.view.change((t=>{t.removeClass("ck-hidden",this._viewResizerWrapper)}))}hide(){this._options.editor.editing.view.change((t=>{t.addClass("ck-hidden",this._viewResizerWrapper)}))}attach(){const t=this,e=this._options.viewElement;this._options.editor.editing.view.change((i=>{const n=i.createUIElement("div",{class:"ck ck-reset_all ck-widget__resizer"},(function(e){const i=this.toDomElement(e);return t._appendHandles(i),t._appendSizeUI(i),i}));i.insert(i.createPositionAt(e,"end"),n),i.addClass("ck-widget_with-resizer",e),this._viewResizerWrapper=n,this.isVisible||this.hide()})),this.on("change:isVisible",(()=>{this.isVisible?(this.show(),this.redraw()):this.hide()}))}begin(t){this._state=new ResizeState(this._options),this._sizeView._bindToState(this._options,this.state),this._initialViewWidth=this._options.viewElement.getStyle("width"),this.state.begin(t,this._getHandleHost(),this._getResizeHost())}updateSize(t){const e=this._proposeNewSize(t);this._options.editor.editing.view.change((t=>{const i=this._options.unit||"%",n=("%"===i?e.widthPercents:e.width)+i;t.setStyle("width",n,this._options.viewElement)}));const i=this._getHandleHost(),n=new Rect(i),s=Math.round(n.width),o=Math.round(n.height),r=new Rect(i);e.width=Math.round(r.width),e.height=Math.round(r.height),this.redraw(n),this.state.update({...e,handleHostWidth:s,handleHostHeight:o})}commit(){const t=this._options.unit||"%",e=("%"===t?this.state.proposedWidthPercents:this.state.proposedWidth)+t;this._options.editor.editing.view.change((()=>{this._cleanup(),this._options.onCommit(e)}))}cancel(){this._cleanup()}destroy(){this.cancel()}redraw(t){const e=this._domResizerWrapper;if(!(e&&i.ownerDocument&&i.ownerDocument.contains(i)))return;var i;const n=e.parentElement,s=this._getHandleHost(),o=this._viewResizerWrapper,r=[o.getStyle("width"),o.getStyle("height"),o.getStyle("left"),o.getStyle("top")];let a;if(n.isSameNode(s)){const e=t||new Rect(s);[e.width+"px",e.height+"px",void 0,void 0]}else[s.offsetWidth+"px",s.offsetHeight+"px",s.offsetLeft+"px",s.offsetTop+"px"];"same"!==compareArrays(r,a)&&this._options.editor.editing.view.change((t=>{t.setStyle({width:a[0],height:a[1],left:a[2],top:a[3]},o)}))}containsHandle(t){return this._domResizerWrapper.contains(t)}static isResizeHandle(t){return t.classList.contains("ck-widget__resizer__handle")}_cleanup(){this._sizeView._dismiss();this._options.editor.editing.view.change((t=>{t.setStyle("width",this._initialViewWidth,this._options.viewElement)}))}_proposeNewSize(t){const e=this.state,i={x:t.pageX,y:n.pageY};var n;const s=!this._options.isCentered||this._options.isCentered(this),o={x:e._referenceCoordinates.x-(i.x+e.originalWidth),y:i.y-e.originalHeight-e._referenceCoordinates.y};s&&e.activeHandlePosition.endsWith("-right")&&(o.x=i.x-(e._referenceCoordinates.x+e.originalWidth)),s&&(o.x*=2);let r=Math.abs(e.originalWidth+o.x),a=Math.abs(e.originalHeight+o.y);return"width"==(r/e.aspectRatio>a?"width":"height")?r/e.aspectRatio:a*e.aspectRatio,{width:Math.round(r),height:Math.round(a),widthPercents:Math.min(Math.round(e.originalWidthPercents/e.originalWidth*r*100)/100,100)}}_getResizeHost(){const t=this._domResizerWrapper.parentElement;return this._options.getResizeHost(t)}_getHandleHost(){const t=this._domResizerWrapper.parentElement;return this._options.getHandleHost(t)}get _domResizerWrapper(){return this._options.editor.editing.view.domConverter.mapViewToDom(this._viewResizerWrapper)}_appendHandles(t){const e=["top-left","top-right","bottom-right","bottom-left"];for(const n of e)t.appendChild(new Template({tag:"div",attributes:{class:"ck-widget__resizer__handle "+(n,`ck-widget__resizer__handle-${i}`)}}).render());var i}_appendSizeUI(t){this._sizeView=new SizeView,this._sizeView.render(),t.appendChild(this._sizeView.element)}}var ap="Expected a function";const lp=function(t,e,i){var n=!0,s=!0;if("function"!=typeof t)throw new TypeError(ap);return F(i)&&(n="leading"in i?!!i.leading:n,s="trailing"in i?!!i.trailing:s),dc(t,e,{leading:n,maxWait:e,trailing:s})};class cp extends lr{static get pluginName(){return"DragDrop"}static get requires(){return[Vg,np]}init(){const t=this.editor,e=t.editing.view;this._draggedRange=null,this._draggingUid="",this._draggableElement=null,this._updateDropMarkerThrottled=lp((t=>this._updateDropMarker(t)),40),this._removeDropMarkerDelayed=up((()=>this._removeDropMarker()),40),this._clearDraggableAttributesDelayed=up((()=>this._clearDraggableAttributes()),40),e.addObserver(Rg),e.addObserver(lf),this._setupDragging(),this._setupContentInsertionIntegration(),this._setupClipboardInputIntegration(),this._setupDropMarker(),this._setupDraggableAttributeHandling(),this.listenTo(t,"change:isReadOnly",((t,e,i)=>{i?this.forceDisabled("readOnlyMode"):this.clearForceDisabled("readOnlyMode")})),this.on("change:isEnabled",((t,e,i)=>{i||this._finalizeDragging(!1)})),r.isAndroid&&this.forceDisabled("noAndroidSupport")}destroy(){return this._draggedRange&&(this._draggedRange.detach(),this._draggedRange=null),this._updateDropMarkerThrottled.cancel(),this._removeDropMarkerDelayed.cancel(),this._clearDraggableAttributesDelayed.cancel(),super.destroy()}_setupDragging(){const t=this.editor,e=t.model,i=e.document,n=t.editing.view,s=n.document;this.listenTo(s,"dragstart",((n,o)=>{const r=i.selection;if(o.target&&o.target.is("editableElement"))return void o.preventDefault();const a=o.target?fp(o.target):null;if(a){const i=t.editing.mapper.toModelElement(a);this._draggedRange=Mh.fromRange(e.createRangeOn(i)),t.plugins.has("WidgetToolbarRepository")&&t.plugins.get("WidgetToolbarRepository").forceDisabled("dragDrop")}else if(!s.selection.isCollapsed){const t=s.selection.getSelectedElement();t&&Hg(t)||(this._draggedRange=Mh.fromRange(r.getFirstRange()))}if(!this._draggedRange)return void o.preventDefault();this._draggingUid=p(),o.dataTransfer.effectAllowed=this.isEnabled?"copyMove":"copy",o.dataTransfer.setData("application/ckeditor5-dragging-uid",this._draggingUid);const l=e.createSelection(this._draggedRange.toRange()),c=t.data.toView(e.getSelectedContent(l));s.fire("clipboardOutput",{dataTransfer:o.dataTransfer,content:c,method:"dragstart"}),this.isEnabled||(this._draggedRange.detach(),this._draggedRange=null,this._draggingUid="")}),{priority:"low"}),this.listenTo(s,"dragend",((t,e)=>{this._finalizeDragging(!e.dataTransfer.isCanceled&&"move"==e.dataTransfer.dropEffect)}),{priority:"low"}),this.listenTo(s,"dragenter",(()=>{this.isEnabled&&n.focus()})),this.listenTo(s,"dragleave",(()=>{this._removeDropMarkerDelayed()})),this.listenTo(s,"dragging",((e,i)=>{if(!this.isEnabled)return void(i.dataTransfer.dropEffect="none");this._removeDropMarkerDelayed.cancel();const n=hp(t,i.targetRanges,i.target);this._draggedRange||(i.dataTransfer.dropEffect="copy"),r.isGecko||("copy"==i.dataTransfer.effectAllowed?i.dataTransfer.dropEffect="copy":["all","copyMove"].includes(i.dataTransfer.effectAllowed)&&(i.dataTransfer.dropEffect="move")),n&&this._updateDropMarkerThrottled(n)}),{priority:"low"})}_setupClipboardInputIntegration(){const t=this.editor,e=t.editing.view.document;this.listenTo(e,"clipboardInput",((e,i)=>{if("drop"!=i.method)return;const n=hp(t,i.targetRanges,i.target);if(this._removeDropMarker(),!n)return this._finalizeDragging(!1),void e.stop();this._draggedRange&&this._draggingUid!=i.dataTransfer.getData("application/ckeditor5-dragging-uid")&&(this._draggedRange.detach(),this._draggedRange=null,this._draggingUid="");if("move"==dp(i.dataTransfer)&&this._draggedRange&&this._draggedRange.containsRange(n,!0))return this._finalizeDragging(!1),void e.stop();i.targetRanges=[t.editing.mapper.toViewRange(n)]}),{priority:"high"})}_setupContentInsertionIntegration(){const t=this.editor.plugins.get(Vg);t.on("contentInsertion",((t,e)=>{if(!this.isEnabled||"drop"!==e.method)return;const i=e.targetRanges.map((t=>this.editor.editing.mapper.toModelRange(t)));this.editor.model.change((t=>t.setSelection(i)))}),{priority:"high"}),t.on("contentInsertion",((t,e)=>{if(!this.isEnabled||"drop"!==e.method)return;const i="move"==dp(e.dataTransfer),n=!e.resultRange||!e.resultRange.isCollapsed;this._finalizeDragging(n&&i)}),{priority:"lowest"})}_setupDraggableAttributeHandling(){const t=this.editor,e=t.editing.view,i=e.document;this.listenTo(i,"mousedown",((n,s)=>{if(r.isAndroid||!s)return;this._clearDraggableAttributesDelayed.cancel();let o=fp(s.target);if(r.isBlink&&!t.isReadOnly&&!o&&!i.selection.isCollapsed){const t=i.selection.getSelectedElement();t&&Hg(t)||(o=i.selection.editableElement)}o&&(e.change((t=>{t.setAttribute("draggable","true",o)})),this._draggableElement=t.editing.mapper.toModelElement(o))})),this.listenTo(i,"mouseup",(()=>{r.isAndroid||this._clearDraggableAttributesDelayed()}))}_clearDraggableAttributes(){const t=this.editor.editing;t.view.change((e=>{this._draggableElement&&"$graveyard"!=this._draggableElement.root.rootName&&e.removeAttribute("draggable",t.mapper.toViewElement(this._draggableElement)),this._draggableElement=null}))}_setupDropMarker(){const t=this.editor;t.conversion.for("editingDowncast").markerToHighlight({model:"drop-target",view:{classes:["ck-clipboard-drop-target-range"]}}),t.conversion.for("editingDowncast").markerToElement({model:"drop-target",view:(e,{writer:i})=>{if(t.model.schema.checkChild(e.markerRange.start,"$text"))return i.createUIElement("span",{class:"ck ck-clipboard-drop-target-position"},(function(t){const e=this.toDomElement(t);return e.append("⁠",t.createElement("span"),"⁠"),e}))}})}_updateDropMarker(t){const e=this.editor,i=e.model.markers;e.model.change((e=>{i.has("drop-target")?i.get("drop-target").getRange().isEqual(t)||e.updateMarker("drop-target",{range:t}):e.addMarker("drop-target",{range:t,usingOperation:!1,affectsData:!1})}))}_removeDropMarker(){const t=this.editor.model;this._removeDropMarkerDelayed.cancel(),this._updateDropMarkerThrottled.cancel(),t.markers.has("drop-target")&&t.change((t=>{t.removeMarker("drop-target")}))}_finalizeDragging(t){const e=this.editor,i=e.model;this._removeDropMarker(),this._clearDraggableAttributes(),e.plugins.has("WidgetToolbarRepository")&&e.plugins.get("WidgetToolbarRepository").clearForceDisabled("dragDrop"),this._draggingUid="",this._draggedRange&&(t&&this.isEnabled&&i.deleteContent(i.createSelection(this._draggedRange),{doNotAutoparagraph:!0}),this._draggedRange.detach(),this._draggedRange=null)}}function hp(t,e,i){const n=t.model,s=t.editing.mapper;let o=null;const a=e?e[0].start:null;if(i.is("uiElement")&&(i=i.parent),o=function(t,e){const i=t.model,n=t.editing.mapper;if(Hg(e))return i.createRangeOn(n.toModelElement(e));if(!e.is("editableElement")){const t=e.findAncestor((t=>Hg(t)||t.is("editableElement")));if(Hg(t))return i.createRangeOn(n.toModelElement(t))}return null}(t,i),o)return o;const l=function(t,e){const i=t.editing.mapper,n=t.editing.view,s=i.toModelElement(e);if(s)return s;const o=n.createPositionBefore(e),r=i.findMappedViewAncestor(o);return i.toModelElement(r)}(t,i),c=a?s.toModelPosition(a):null;return c?(o=function(t,e,i){const n=t.model;if(!n.schema.checkChild(i,"$block"))return null;const s=n.createPositionAt(i,0),o=e.path.slice(0,s.path.length),r=n.createPositionFromPath(e.root,o),a=r.nodeAfter;if(a&&n.schema.isObject(a))return n.createRangeOn(a);return null}(t,c,l),o||(o=n.schema.getNearestSelectionRange(c,r.isGecko?"forward":"backward"),o||function(t,e){const i=t.model;let n=e;for(;n;){if(i.schema.isObject(n))return i.createRangeOn(n);n=n.parent}return null}(t,c.parent))):function(t,e){const i=t.model,n=i.schema,s=i.createPositionAt(e,0);return n.getNearestSelectionRange(s,"forward")}(t,l)}function dp(t){return r.isGecko?t.dropEffect:["all","copyMove"].includes(t.effectAllowed)?"move":"copy"}function up(t,e){let i;function n(...s){n.cancel(),i=setTimeout((()=>t(...s)),e)}return n.cancel=()=>{clearTimeout(i)},n}function fp(t){if(t.is("editableElement"))return null;if(t.hasClass("ck-widget__selection-handle"))return t.findAncestor(Hg);if(Hg(t))return t;const e=t.findAncestor((t=>Hg(t)||t.is("editableElement")));return Hg(e)?e:null}class mp extends lr{static get pluginName(){return"PastePlainText"}static get requires(){return[Vg]}init(){const t=this.editor,e=t.model,i=t.editing.view,n=i.document,s=e.document.selection;let o=!1;i.addObserver(Rg),this.listenTo(n,"keydown",((t,e)=>{o=e.shiftKey})),t.plugins.get(Vg).on("contentInsertion",((t,i)=>{(o||function(t,e){if(t.childCount>1)return!1;const i=t.getChild(0);if(e.isObject(i))return!1;return 0==Array.from(i.getAttributeKeys()).length}(i.content,e.schema))&&e.change((t=>{const n=Array.from(s.getAttributes()).filter((([t])=>e.schema.getAttributeProperties(t).isFormatting));s.isCollapsed||e.deleteContent(s,{doNotAutoparagraph:!0}),n.push(...s.getAttributes());const o=t.createRangeIn(i.content);for(const e of o.getItems())e.is("$textProxy")&&t.setAttributes(n,e)}))}))}}class gp extends lr{static get pluginName(){return"Clipboard"}static get requires(){return[Vg,cp,mp]}}class pp extends hr{constructor(t){super(t),this.affectsData=!1}execute(){const t=this.editor.model,e=t.document.selection;let i=t.schema.getLimitElement(e);if(e.containsEntireContent(i)||!wp(t.schema,i))do{if(i=i.parent,!i)return}while(!wp(t.schema,i));t.change((t=>{t.setSelection(i,"in")}))}}function wp(t,e){return t.isLimit(e)&&(t.checkChild(e,"$text")||t.checkChild(e,"paragraph"))}const bp=eo("Ctrl+A");class _p extends lr{static get pluginName(){return"SelectAllEditing"}init(){const t=this.editor,e=t.editing.view.document;t.commands.add("selectAll",new pp(t)),this.listenTo(e,"keydown",((e,i)=>{to(i)===bp&&(t.execute("selectAll"),i.preventDefault())}))}}class vp extends lr{static get pluginName(){return"SelectAllUI"}init(){const t=this.editor;t.ui.componentFactory.add("selectAll",(e=>{const i=t.commands.get("selectAll"),n=new qo(e),s=e.t;return n.set({label:s("Select all"),icon:'',keystroke:"Ctrl+A",tooltip:!0}),n.bind("isEnabled").to(i,"isEnabled"),this.listenTo(n,"execute",(()=>{t.execute("selectAll"),t.editing.view.focus()})),n}))}}class yp extends lr{static get requires(){return[_p,vp]}static get pluginName(){return"SelectAll"}}class kp extends hr{constructor(t){super(t),this._stack=[],this._createdBatches=new WeakSet,this.refresh(),this.listenTo(t.data,"set",((t,e)=>{e[1]={...e[1]};const i=e[1];i.batchType||(i.batchType={isUndoable:!1})}),{priority:"high"}),this.listenTo(t.data,"set",((t,e)=>{e[1].batchType.isUndoable||this.clearStack()}))}refresh(){this.isEnabled=this._stack.length>0}addBatch(t){const e=this.editor.model.document.selection,i={ranges:e.hasOwnRange?Array.from(e.getRanges()):[],isBackward:e.isBackward};this._stack.push({batch:t,selection:i}),this.refresh()}clearStack(){this._stack=[],this.refresh()}_restoreSelection(t,e,i){const n=this.editor.model,s=n.document,o=[],r=t.map((t=>t.getTransformedByOperations(i))),a=r.flat();for(const t of r){const e=t.filter((t=>t.root!=s.graveyard)).filter((t=>!xp(t,a)));e.length&&(Ap(e),o.push(e[0]))}o.length&&n.change((t=>{t.setSelection(o,{backward:e})}))}_undo(t,e){const i=this.editor.model,n=i.document;this._createdBatches.add(e);const s=t.operations.slice().filter((t=>t.isDocumentOperation));s.reverse();for(const t of s){const s=t.baseVersion+1,o=Array.from(n.history.getOperations(s)),r=hu([t.getReversed()],o,{useRelations:!0,document:this.editor.model.document,padWithNoOps:!1,forceWeakRemove:!0}).operationsA;for(const s of r)e.addOperation(s),i.applyOperation(s),n.history.setOperationAsUndone(t,s)}}}function Ap(t){t.sort(((t,e)=>t.start.isBefore(e.start)?-1:1));for(let e=1;ee!==t&&e.containsRange(t,!0)))}class Cp extends kp{execute(t=null){const e=t?this._stack.findIndex((e=>e.batch==t)):this._stack.length-1,i=this._stack.splice(e,1)[0],n=this.editor.model.createBatch({isUndo:!0});this.editor.model.enqueueChange(n,(()=>{this._undo(i.batch,n);const t=this.editor.model.document.history.getOperations(i.batch.baseVersion);this._restoreSelection(i.selection.ranges,i.selection.isBackward,t),this.fire("revert",i.batch,n)})),this.refresh()}}class Pp extends kp{execute(){const t=this._stack.pop(),e=this.editor.model.createBatch({isUndo:!0});this.editor.model.enqueueChange(e,(()=>{const i=t.batch.operations[t.batch.operations.length-1].baseVersion+1,n=this.editor.model.document.history.getOperations(i);this._restoreSelection(t.selection.ranges,t.selection.isBackward,n),this._undo(t.batch,e)})),this.refresh()}}class Tp extends lr{static get pluginName(){return"UndoEditing"}constructor(t){super(t),this._batchRegistry=new WeakSet}init(){const t=this.editor;this._undoCommand=new Cp(t),this._redoCommand=new Pp(t),t.commands.add("undo",this._undoCommand),t.commands.add("redo",this._redoCommand),this.listenTo(t.model,"applyOperation",((t,e)=>{const i=e[0];if(!i.isDocumentOperation)return;const n=i.batch,s=this._redoCommand._createdBatches.has(n),o=this._undoCommand._createdBatches.has(n);this._batchRegistry.has(n)||(this._batchRegistry.add(n),n.isUndoable&&(s?this._undoCommand.addBatch(n):o||(this._undoCommand.addBatch(n),this._redoCommand.clearStack())))}),{priority:"highest"}),this.listenTo(this._undoCommand,"revert",((t,e,i)=>{this._redoCommand.addBatch(i)})),t.keystrokes.set("CTRL+Z","undo"),t.keystrokes.set("CTRL+Y","redo"),t.keystrokes.set("CTRL+SHIFT+Z","redo")}}const Ep='',Sp='';class Rp extends lr{static get pluginName(){return"UndoUI"}init(){const t=this.editor,e=t.locale,i=t.t,n="ltr"==e.uiLanguageDirection?Ep:Sp,s="ltr"==e.uiLanguageDirection?Sp:Ep;this._addButton("undo",i("Undo"),"CTRL+Z",n),this._addButton("redo",i("Redo"),"CTRL+Y",s)}_addButton(t,e,i,n){const s=this.editor;s.ui.componentFactory.add(t,(o=>{const r=s.commands.get(t),a=new qo(o);return a.set({label:e,icon:n,keystroke:i,tooltip:!0}),a.bind("isEnabled").to(r,"isEnabled"),this.listenTo(a,"execute",(()=>{s.execute(t),s.editing.view.focus()})),a}))}}class Op extends lr{static get requires(){return[Tp,Rp]}static get pluginName(){return"Undo"}}class Ip extends hr{constructor(t,e){super(t),this.attributeKey=e}refresh(){const t=this.editor.model,e=t.document;this.value=e.selection.getAttribute(this.attributeKey),this.isEnabled=t.schema.checkAttributeInSelection(e.selection,this.attributeKey)}execute(t={}){const e=this.editor.model,i=e.document.selection,n=t.value;e.change((t=>{if(i.isCollapsed)n?t.setSelectionAttribute(this.attributeKey,n):t.removeSelectionAttribute(this.attributeKey);else{const s=e.schema.getValidRanges(i.getRanges(),this.attributeKey);for(const e of s)n?t.setAttribute(this.attributeKey,n,e):t.removeAttribute(this.attributeKey,e)}}))}}class Vp extends co{constructor(t){super(t),this.set("isEmpty",!0),this.on("change",(()=>{this.set("isEmpty",0===this.length)}))}add(t,e){this.find((e=>e.color===t.color))||super.add(t,e)}hasColor(t){return!!this.find((e=>e.color===t))}}u(Vp,q);class Mp extends yo{constructor(t,{colors:e,columns:i,removeButtonLabel:n,documentColorsLabel:s,documentColorsCount:o}){super(t),this.items=this.createCollection(),this.colorDefinitions=e,this.focusTracker=new uo,this.keystrokes=new fo,this.set("selectedColor"),this.removeButtonLabel=n,this.columns=i,this.documentColors=new Vp,this.documentColorsCount=o,this._focusables=new vo,this._focusCycler=new nr({focusables:this._focusables,focusTracker:this.focusTracker,keystrokeHandler:this.keystrokes,actions:{focusPrevious:"shift + tab",focusNext:"tab"}}),this._documentColorsLabel=s,this.setTemplate({tag:"div",attributes:{class:["ck","ck-color-table"]},children:this.items}),this.items.add(this._createRemoveColorButton())}updateDocumentColors(t,e){const i=t.document,n=this.documentColorsCount;this.documentColors.clear();for(const s of i.getRootNames()){const o=i.getRoot(s),r=t.createRangeIn(o);for(const t of r.getItems())if(t.is("$textProxy")&&t.hasAttribute(e)&&(this._addColorToDocumentColors(t.getAttribute(e)),this.documentColors.length>=n))return}}updateSelectedColors(){const t=this.documentColorsGrid,e=this.staticColorsGrid,i=this.selectedColor;e.selectedColor=i,t&&(t.selectedColor=i)}render(){super.render(),this.keystrokes.listenTo(this.element)}destroy(){super.destroy(),this.focusTracker.destroy(),this.keystrokes.destroy()}appendGrids(){if(!this.staticColorsGrid&&(this.staticColorsGrid=this._createStaticColorsGrid(),this.items.add(this.staticColorsGrid),this.focusTracker.add(this.staticColorsGrid.element),this._focusables.add(this.staticColorsGrid),this.documentColorsCount)){const t=ko.bind(this.documentColors,this.documentColors),e=new Gf(this.locale);e.text=this._documentColorsLabel,e.extendTemplate({attributes:{class:["ck","ck-color-grid__label",t.if("isEmpty","ck-hidden")]}}),this.items.add(e),this.documentColorsGrid=this._createDocumentColorsGrid(),this.items.add(this.documentColorsGrid),this.focusTracker.add(this.documentColorsGrid.element),this._focusables.add(this.documentColorsGrid)}}focus(){this._focusCycler.focusFirst()}focusLast(){this._focusCycler.focusLast()}_createRemoveColorButton(){const t=new qo;return t.set({withText:!0,icon:yf.eraser,label:this.removeButtonLabel}),t.class="ck-color-table__remove-color",t.on("execute",(()=>{this.fire("execute",{value:null})})),t.render(),this.focusTracker.add(t.element),this._focusables.add(t),t}_createStaticColorsGrid(){const t=new Jo(this.locale,{colorDefinitions:this.colorDefinitions,columns:this.columns});return t.delegate("execute").to(this),t}_createDocumentColorsGrid(){const t=ko.bind(this.documentColors,this.documentColors),e=new Jo(this.locale,{columns:this.columns});return e.delegate("execute").to(this),e.extendTemplate({attributes:{class:t.if("isEmpty","ck-hidden")}}),e.items.bindTo(this.documentColors).using((t=>{const e=new Go;return e.set({color:t.color,hasBorder:t.options&&t.options.hasBorder}),t.label&&e.set({label:t.label,tooltip:!0}),e.on("execute",(()=>{this.fire("execute",{value:t.color})})),e})),this.documentColors.on("change:isEmpty",((t,i,n)=>{n&&(e.selectedColor=null)})),e}_addColorToDocumentColors(t){const e=this.colorDefinitions.find((e=>e.color===t));e?this.documentColors.add(Object.assign({},e)):this.documentColors.add({color:t,label:t,options:{hasBorder:!1}})}}const Np="fontSize",Bp="fontFamily",Dp="fontColor";function Fp(t,e){const i={model:{key:t,values:[]},view:{},upcastAlso:{}};for(const t of e)i.model.values.push(t.model),i.view[t.model]=t.view,t.upcastAlso&&(i.upcastAlso[t.model]=t.upcastAlso);return i}function Lp(t){return(e,{writer:i})=>i.createAttributeElement("span",{style:`${t}:${e}`},{priority:7})}class zp extends Ip{constructor(t){super(t,Dp)}}class Hp extends lr{static get pluginName(){return"FontColorEditing"}constructor(t){var e;super(t),t.config.define(Dp,{colors:[{color:"hsl(0, 0%, 0%)",label:"Black"},{color:"hsl(0, 0%, 30%)",label:"Dim grey"},{color:"hsl(0, 0%, 60%)",label:"Grey"},{color:"hsl(0, 0%, 90%)",label:"Light grey"},{color:"hsl(0, 0%, 100%)",label:"White",hasBorder:!0},{color:"hsl(0, 75%, 60%)",label:"Red"},{color:"hsl(30, 75%, 60%)",label:"Orange"},{color:"hsl(60, 75%, 60%)",label:"Yellow"},{color:"hsl(90, 75%, 60%)",label:"Light green"},{color:"hsl(120, 75%, 60%)",label:"Green"},{color:"hsl(150, 75%, 60%)",label:"Aquamarine"},{color:"hsl(180, 75%, 60%)",label:"Turquoise"},{color:"hsl(210, 75%, 60%)",label:"Light blue"},{color:"hsl(240, 75%, 60%)",label:"Blue"},{color:"hsl(270, 75%, 60%)",label:"Purple"}],columns:5}),t.conversion.for("upcast").elementToAttribute({view:{name:"span",styles:{color:/[\s\S]+/}},model:{key:Dp,value:(e="color",t=>t.getStyle(e).replace(/\s/g,""))}}),t.conversion.for("upcast").elementToAttribute({view:{name:"font",attributes:{color:/^#?\w+$/}},model:{key:Dp,value:t=>t.getAttribute("color")}}),t.conversion.for("downcast").attributeToElement({model:Dp,view:Lp("color")}),t.commands.add(Dp,new zp(t)),t.model.schema.extend("$text",{allowAttributes:Dp}),t.model.schema.setAttributeProperties(Dp,{isFormatting:!0,copyOnEnter:!0})}}class jp extends lr{constructor(t,{commandName:e,icon:i,componentName:n,dropdownLabel:s}){super(t),this.commandName=e,this.componentName=n,this.icon=i,this.dropdownLabel=s,this.columns=t.config.get(`${this.componentName}.columns`),this.colorTableView=void 0}init(){const t=this.editor,e=t.locale,i=e.t,n=t.commands.get(this.commandName);const s=function(t,e){const i=t.t,n={Black:i("Black"),"Dim grey":i("Dim grey"),Grey:i("Grey"),"Light grey":i("Light grey"),White:i("White"),Red:i("Red"),Orange:i("Orange"),Yellow:i("Yellow"),"Light green":i("Light green"),Green:i("Green"),Aquamarine:i("Aquamarine"),Turquoise:i("Turquoise"),"Light blue":i("Light blue"),Blue:i("Blue"),Purple:i("Purple")};return e.map((t=>{const e=n[t.label];return e&&e!=t.label&&(t.label=e),t}))}(e,t.config.get(this.componentName).colors.map(Ko).filter((t=>!!t))),o=t.config.get(`${this.componentName}.documentColors`);t.ui.componentFactory.add(this.componentName,(e=>{const r=Of(e);return this.colorTableView=function({dropdownView:t,colors:e,columns:i,removeButtonLabel:n,documentColorsLabel:s,documentColorsCount:o}){const r=t.locale,a=new Mp(r,{colors:e,columns:i,removeButtonLabel:n,documentColorsLabel:s,documentColorsCount:o});return t.colorTableView=a,t.panelView.children.add(a),a.delegate("execute").to(t,"execute"),a}({dropdownView:r,colors:s.map((t=>({label:t.label,color:t.model,options:{hasBorder:t.hasBorder}}))),columns:this.columns,removeButtonLabel:i("Remove color"),documentColorsLabel:0!==o?i("Document colors"):void 0,documentColorsCount:void 0===o?this.columns:o}),this.colorTableView.bind("selectedColor").to(n,"value"),r.buttonView.set({label:this.dropdownLabel,icon:this.icon,tooltip:!0}),r.extendTemplate({attributes:{class:"ck-color-ui-dropdown"}}),r.bind("isEnabled").to(n),r.on("execute",((e,i)=>{t.execute(this.commandName,i),t.editing.view.focus()})),r.on("change:isOpen",((e,i,n)=>{r.colorTableView.appendGrids(),n&&(0!==o&&this.colorTableView.updateDocumentColors(t.model,this.componentName),this.colorTableView.updateSelectedColors())})),Bf(r,(()=>r.colorTableView.staticColorsGrid.items.find((t=>t.isOn)))),r}))}}class $p extends jp{constructor(t){const e=t.locale.t;super(t,{commandName:Dp,componentName:Dp,icon:'',dropdownLabel:e("Font Color")})}static get pluginName(){return"FontColorUI"}}class Wp extends Ip{constructor(t){super(t,Bp)}}function qp(t){return t.map(Up).filter((t=>!!t))}function Up(t){return"object"==typeof t?t:"default"===t?{title:"Default",model:void 0}:"string"==typeof t?function(t){const e=t.replace(/"|'/g,"").split(","),i=e[0],n=e.map(Kp).join(", ");return{title:i,model:n,view:{name:"span",styles:{"font-family":n},priority:7}}}(t):void 0}function Kp(t){return(t=t.trim()).indexOf(" ")>0&&(t=`'${t}'`),t}class Gp extends lr{static get pluginName(){return"FontFamilyEditing"}constructor(t){super(t),t.config.define(Bp,{options:["default","Arial, Helvetica, sans-serif","Courier New, Courier, monospace","Georgia, serif","Lucida Sans Unicode, Lucida Grande, sans-serif","Tahoma, Geneva, sans-serif","Times New Roman, Times, serif","Trebuchet MS, Helvetica, sans-serif","Verdana, Geneva, sans-serif"],supportAllValues:!1})}init(){const t=this.editor;t.model.schema.extend("$text",{allowAttributes:Bp}),t.model.schema.setAttributeProperties(Bp,{isFormatting:!0,copyOnEnter:!0});const e=qp(t.config.get("fontFamily.options")).filter((t=>t.model)),i=Fp(Bp,e);t.config.get("fontFamily.supportAllValues")?(this._prepareAnyValueConverters(),this._prepareCompatibilityConverter()):t.conversion.attributeToElement(i),t.commands.add(Bp,new Wp(t))}_prepareAnyValueConverters(){const t=this.editor;t.conversion.for("downcast").attributeToElement({model:Bp,view:(t,{writer:e})=>e.createAttributeElement("span",{style:"font-family:"+t},{priority:7})}),t.conversion.for("upcast").elementToAttribute({model:{key:Bp,value:t=>t.getStyle("font-family")},view:{name:"span",styles:{"font-family":/.*/}}})}_prepareCompatibilityConverter(){this.editor.conversion.for("upcast").elementToAttribute({view:{name:"font",attributes:{face:/.*/}},model:{key:Bp,value:t=>t.getAttribute("face")}})}}class Jp extends lr{static get pluginName(){return"FontFamilyUI"}init(){const t=this.editor,e=t.t,i=this._getLocalizedOptions(),n=t.commands.get(Bp);t.ui.componentFactory.add(Bp,(s=>{const o=Of(s);return Mf(o,(()=>function(t,e){const i=new co;for(const n of t){const t={type:"button",model:new sm({commandName:Bp,commandParam:n.model,label:n.title,withText:!0})};t.model.bind("isOn").to(e,"value",(t=>t===n.model||!(!t||!n.model)&&t.split(",")[0].replace(/'/g,"").toLowerCase()===n.model.toLowerCase())),n.view&&n.view.styles&&t.model.set("labelStyle",`font-family: ${n.view.styles["font-family"]}`),i.add(t)}return i}(i,n))),o.buttonView.set({label:e("Font Family"),icon:'',tooltip:!0}),o.extendTemplate({attributes:{class:"ck-font-family-dropdown"}}),o.bind("isEnabled").to(n),this.listenTo(o,"execute",(e=>{t.execute(e.source.commandName,{value:e.source.commandParam}),t.editing.view.focus()})),o}))}_getLocalizedOptions(){const t=this.editor,e=t.t;return qp(t.config.get(Bp).options).map((t=>("Default"===t.title&&(t.title=e("Default")),t)))}}class Qp extends Ip{constructor(t){super(t,Np)}}function Yp(t){return t.map((t=>function(t){if(e=t,"object"==typeof e&&e.title&&e.model&&e.view)return Xp(t);var e;const i=function(t){return Zp[t]||Zp[t.model]}(t);if(i)return Xp(i);if("default"===t)return{model:void 0,title:"Default"};if(function(t){let e;if("object"==typeof t){if(!t.model)throw new v("font-size-invalid-definition",null,t);e=parseFloat(t.model)}else e=parseFloat(t);return isNaN(e)}(t))return;return function(t){"number"!=typeof t&&"string"!=typeof t||(t={title:String(t),model:`${parseFloat(t)}px`});return t.view={name:"span",styles:{"font-size":t.model}},Xp(t)}(t)}(t))).filter((t=>!!t))}const Zp={get tiny(){return{title:"Tiny",model:"tiny",view:{name:"span",classes:"text-tiny",priority:7}}},get small(){return{title:"Small",model:"small",view:{name:"span",classes:"text-small",priority:7}}},get big(){return{title:"Big",model:"big",view:{name:"span",classes:"text-big",priority:7}}},get huge(){return{title:"Huge",model:"huge",view:{name:"span",classes:"text-huge",priority:7}}}};function Xp(t){return t.view.priority||(t.view.priority=7),t}const tw=["x-small","x-small","small","medium","large","x-large","xx-large","xxx-large"];class ew extends lr{static get pluginName(){return"FontSizeEditing"}constructor(t){super(t),t.config.define(Np,{options:["tiny","small","default","big","huge"],supportAllValues:!1})}init(){const t=this.editor;t.model.schema.extend("$text",{allowAttributes:Np}),t.model.schema.setAttributeProperties(Np,{isFormatting:!0,copyOnEnter:!0});const e=t.config.get("fontSize.supportAllValues"),i=Yp(this.editor.config.get("fontSize.options")).filter((t=>t.model)),n=Fp(Np,i);e?(this._prepareAnyValueConverters(n),this._prepareCompatibilityConverter()):t.conversion.attributeToElement(n),t.commands.add(Np,new Qp(t))}_prepareAnyValueConverters(t){const e=this.editor,i=t.model.values.filter((t=>{return!(e=String(t),hf.test(e)||function(t){return df.test(t)}(String(t)));var e}));if(i.length)throw new v("font-size-invalid-use-of-named-presets",null,{presets:i});e.conversion.for("downcast").attributeToElement({model:Np,view:(t,{writer:e})=>{if(t)return e.createAttributeElement("span",{style:"font-size:"+t},{priority:7})}}),e.conversion.for("upcast").elementToAttribute({model:{key:Np,value:t=>t.getStyle("font-size")},view:{name:"span",styles:{"font-size":/.*/}}})}_prepareCompatibilityConverter(){this.editor.conversion.for("upcast").elementToAttribute({view:{name:"font",attributes:{size:/^[+-]?\d{1,3}$/}},model:{key:Np,value:t=>{const e=t.getAttribute("size"),i="-"===e[0]||"+"===e[0];let n=parseInt(e,10);i&&(n=3+n);const s=tw.length-1,o=Math.min(Math.max(n,0),s);return tw[o]}}})}}class iw extends lr{static get pluginName(){return"FontSizeUI"}init(){const t=this.editor,e=t.t,i=this._getLocalizedOptions(),n=t.commands.get(Np);t.ui.componentFactory.add(Np,(s=>{const o=Of(s);return Mf(o,(()=>function(t,e){const i=new co;for(const n of t){const t={type:"button",model:new sm({commandName:Np,commandParam:n.model,label:n.title,class:"ck-fontsize-option",withText:!0})};n.view&&n.view.styles&&t.model.set("labelStyle",`font-size:${n.view.styles["font-size"]}`),n.view&&n.view.classes&&t.model.set("class",`${t.model.class} ${n.view.classes}`),t.model.bind("isOn").to(e,"value",(t=>t===n.model)),i.add(t)}return i}(i,n))),o.buttonView.set({label:e("Font Size"),icon:'',tooltip:!0}),o.extendTemplate({attributes:{class:["ck-font-size-dropdown"]}}),o.bind("isEnabled").to(n),this.listenTo(o,"execute",(e=>{t.execute(e.source.commandName,{value:e.source.commandParam}),t.editing.view.focus()})),o}))}_getLocalizedOptions(){const t=this.editor,e=t.t,i={Default:e("Default"),Tiny:e("Tiny"),Small:e("Small"),Big:e("Big"),Huge:e("Huge")};return Yp(t.config.get(Np).options).map((t=>{const e=i[t.title];return e&&e!=t.title&&(t=Object.assign({},t,{title:e})),t}))}}class nw extends hr{refresh(){const t=this.editor.model,e=ho(t.document.selection.getSelectedBlocks());this.value=!!e&&e.is("element","paragraph"),this.isEnabled=!!e&&sw(e,t.schema)}execute(t={}){const e=this.editor.model,i=e.document;e.change((n=>{const s=(t.selection||i.selection).getSelectedBlocks();for(const t of s)!t.is("element","paragraph")&&sw(t,e.schema)&&n.rename(t,"paragraph")}))}}function sw(t,e){return e.checkChild(t.parent,"paragraph")&&!e.isObject(t)}class ow extends hr{execute(t){const e=this.editor.model,i=t.attributes;let n=t.position;e.change((t=>{const s=t.createElement("paragraph");if(i&&e.schema.setAllowedAttributes(s,i,t),!e.schema.checkChild(n.parent,s)){const i=e.schema.findAllowedParent(n,s);if(!i)return;n=t.split(n,i).position}e.insertContent(s,n),t.setSelection(s,"in")}))}}class rw extends lr{static get pluginName(){return"Paragraph"}init(){const t=this.editor,e=t.model;t.commands.add("paragraph",new nw(t)),t.commands.add("insertParagraph",new ow(t)),e.schema.register("paragraph",{inheritAllFrom:"$block"}),t.conversion.elementToElement({model:"paragraph",view:"p"}),t.conversion.for("upcast").elementToElement({model:(t,{writer:e})=>rw.paragraphLikeElements.has(t.name)?t.isEmpty?null:e.createElement("paragraph"):null,view:/.+/,converterPriority:"low"})}}rw.paragraphLikeElements=new Set(["blockquote","dd","div","dt","h1","h2","h3","h4","h5","h6","li","p","td","th"]);class aw extends hr{constructor(t,e){super(t),this.modelElements=e}refresh(){const t=ho(this.editor.model.document.selection.getSelectedBlocks());this.value=!!t&&this.modelElements.includes(t.name)&&t.name,this.isEnabled=!!t&&this.modelElements.some((e=>lw(t,e,this.editor.model.schema)))}execute(t){const e=this.editor.model,i=e.document,n=t.value;e.change((t=>{const s=Array.from(i.selection.getSelectedBlocks()).filter((t=>lw(t,n,e.schema)));for(const e of s)e.is("element",n)||t.rename(e,n)}))}}function lw(t,e,i){return i.checkChild(t.parent,e)&&!i.isObject(t)}const cw="paragraph";class hw extends lr{static get pluginName(){return"HeadingEditing"}constructor(t){super(t),t.config.define("heading",{options:[{model:"paragraph",title:"Paragraph",class:"ck-heading_paragraph"},{model:"heading1",view:"h2",title:"Heading 1",class:"ck-heading_heading1"},{model:"heading2",view:"h3",title:"Heading 2",class:"ck-heading_heading2"},{model:"heading3",view:"h4",title:"Heading 3",class:"ck-heading_heading3"}]})}static get requires(){return[rw]}init(){const t=this.editor,e=t.config.get("heading.options"),i=[];for(const n of e)"paragraph"!==n.model&&(t.model.schema.register(n.model,{inheritAllFrom:"$block"}),t.conversion.elementToElement(n),i.push(n.model));this._addDefaultH1Conversion(t),t.commands.add("heading",new aw(t,i))}afterInit(){const t=this.editor,e=t.commands.get("enter"),i=t.config.get("heading.options");e&&this.listenTo(e,"afterExecute",((e,n)=>{const s=t.model.document.selection.getFirstPosition().parent;i.some((t=>s.is("element",t.model)))&&!s.is("element",cw)&&0===s.childCount&&n.writer.rename(s,cw)}))}_addDefaultH1Conversion(t){t.conversion.for("upcast").elementToElement({model:"heading1",view:"h1",converterPriority:w.get("low")+1})}}class dw extends lr{static get pluginName(){return"HeadingUI"}init(){const t=this.editor,e=t.t,i=function(t){const e=t.t,i={Paragraph:e("Paragraph"),"Heading 1":e("Heading 1"),"Heading 2":e("Heading 2"),"Heading 3":e("Heading 3"),"Heading 4":e("Heading 4"),"Heading 5":e("Heading 5"),"Heading 6":e("Heading 6")};return t.config.get("heading.options").map((t=>{const e=i[t.title];return e&&e!=t.title&&(t.title=e),t}))}(t),n=e("Choose heading"),s=e("Heading");t.ui.componentFactory.add("heading",(e=>{const o={},r=new co,a=t.commands.get("heading"),l=t.commands.get("paragraph"),c=[a];for(const t of i){const e={type:"button",model:new sm({label:t.title,class:t.class,withText:!0})};"paragraph"===t.model?(e.model.bind("isOn").to(l,"value"),e.model.set("commandName","paragraph"),c.push(l)):(e.model.bind("isOn").to(a,"value",(e=>e===t.model)),e.model.set({commandName:"heading",commandValue:t.model})),r.add(e),o[t.model]=t.title}const h=Of(e);return Mf(h,r),h.buttonView.set({isOn:!1,withText:!0,tooltip:s}),h.extendTemplate({attributes:{class:["ck-heading-dropdown"]}}),h.bind("isEnabled").toMany(c,"isEnabled",((...t)=>t.some((t=>t)))),h.buttonView.bind("label").to(a,"value",l,"value",((t,e)=>{const i=t||e&&"paragraph";return"boolean"==typeof i?n:o[i]?o[i]:n})),this.listenTo(h,"execute",(e=>{const{commandName:i,commandValue:n}=e.source;t.execute(i,n?{value:n}:void 0),t.editing.view.focus()})),h}))}}class uw extends hr{refresh(){const t=this.editor.model,e=t.schema,i=t.document.selection;this.isEnabled=function(t,e,i){const n=function(t,e){const i=function(t,e){const i=t.getSelectedElement();if(i){const n=Jg(t);if(n)return e.createRange(e.createPositionAt(i,n))}return Zu(t,e)}(t,e),n=i.start.parent;if(n.isEmpty&&!n.is("element","$root"))return n.parent;return n}(t,i);return e.checkChild(n,"horizontalLine")}(i,e,t)}execute(){const t=this.editor.model;t.change((e=>{const i=e.createElement("horizontalLine");t.insertObject(i,null,null,{setSelection:"after"})}))}}class fw extends lr{static get pluginName(){return"HorizontalLineEditing"}init(){const t=this.editor,e=t.model.schema,i=t.t,n=t.conversion;e.register("horizontalLine",{inheritAllFrom:"$blockObject"}),n.for("dataDowncast").elementToElement({model:"horizontalLine",view:(t,{writer:e})=>e.createEmptyElement("hr")}),n.for("editingDowncast").elementToStructure({model:"horizontalLine",view:(t,{writer:e})=>{const n=i("Horizontal line"),s=e.createContainerElement("div",null,e.createEmptyElement("hr"));return e.addClass("ck-horizontal-line",s),e.setCustomProperty("hr",!0,s),function(t,e,i){return e.setCustomProperty("horizontalLine",!0,t),jg(t,e,{label:i})}(s,e,n)}}),n.for("upcast").elementToElement({view:"hr",model:"horizontalLine"}),t.commands.add("horizontalLine",new uw(t))}}class mw extends lr{static get pluginName(){return"HorizontalLineUI"}init(){const t=this.editor,e=t.t;t.ui.componentFactory.add("horizontalLine",(i=>{const n=t.commands.get("horizontalLine"),s=new qo(i);return s.set({label:e("Horizontal line"),icon:'',tooltip:!0}),s.bind("isEnabled").to(n,"isEnabled"),this.listenTo(s,"execute",(()=>{t.execute("horizontalLine"),t.editing.view.focus()})),s}))}}class gw extends lr{static get pluginName(){return"IndentEditing"}init(){const t=this.editor;t.commands.add("indent",new ur(t)),t.commands.add("outdent",new ur(t))}}const pw='',ww='';class bw extends lr{static get pluginName(){return"IndentUI"}init(){const t=this.editor,e=t.locale,i=t.t,n="ltr"==e.uiLanguageDirection?pw:ww,s="ltr"==e.uiLanguageDirection?ww:pw;this._defineButton("indent",i("Increase indent"),n),this._defineButton("outdent",i("Decrease indent"),s)}_defineButton(t,e,i){const n=this.editor;n.ui.componentFactory.add(t,(s=>{const o=n.commands.get(t),r=new qo(s);return r.set({label:e,icon:i,tooltip:!0}),r.bind("isOn","isEnabled").to(o,"value","isEnabled"),this.listenTo(r,"execute",(()=>{n.execute(t),n.editing.view.focus()})),r}))}}class _w extends hr{constructor(t,e){super(t),this._indentBehavior=e}refresh(){const t=this.editor.model,e=ho(t.document.selection.getSelectedBlocks());e&&t.schema.checkAttribute(e,"blockIndent")?this.isEnabled=this._indentBehavior.checkEnabled(e.getAttribute("blockIndent")):this.isEnabled=!1}execute(){const t=this.editor.model,e=function(t){const e=t.document.selection,i=t.schema;return Array.from(e.getSelectedBlocks()).filter((t=>i.checkAttribute(t,"blockIndent")))}(t);t.change((t=>{for(const i of e){const e=i.getAttribute("blockIndent"),n=this._indentBehavior.getNextIndent(e);n?t.setAttribute("blockIndent",n,i):t.removeAttribute("blockIndent",i)}}))}}class vw{constructor(t){this.isForward="forward"===t.direction,this.offset=t.offset,this.unit=t.unit}checkEnabled(t){const e=parseFloat(t||0);return this.isForward||e>0}getNextIndent(t){const e=parseFloat(t||0);if(!(!t||t.endsWith(this.unit)))return this.isForward?this.offset+this.unit:void 0;const i=e+(this.isForward?this.offset:-this.offset);return i>0?i+this.unit:void 0}}class yw{constructor(t){this.isForward="forward"===t.direction,this.classes=t.classes}checkEnabled(t){const e=this.classes.indexOf(t);return this.isForward?e=0}getNextIndent(t){const e=this.classes.indexOf(t),i=this.isForward?1:-1;return this.classes[e+i]}}const kw=["paragraph","heading1","heading2","heading3","heading4","heading5","heading6"];const Aw="italic";class xw extends lr{static get pluginName(){return"ItalicEditing"}init(){const t=this.editor;t.model.schema.extend("$text",{allowAttributes:Aw}),t.model.schema.setAttributeProperties(Aw,{isFormatting:!0,copyOnEnter:!0}),t.conversion.attributeToElement({model:Aw,view:"i",upcastAlso:["em",{styles:{"font-style":"italic"}}]}),t.commands.add(Aw,new Cg(t,Aw)),t.keystrokes.set("CTRL+I",Aw)}}const Cw="italic";class Pw extends lr{static get pluginName(){return"ItalicUI"}init(){const t=this.editor,e=t.t;t.ui.componentFactory.add(Cw,(i=>{const n=t.commands.get(Cw),s=new qo(i);return s.set({label:e("Italic"),icon:'',keystroke:"CTRL+I",tooltip:!0,isToggleable:!0}),s.bind("isOn","isEnabled").to(n,"value","isEnabled"),this.listenTo(s,"execute",(()=>{t.execute(Cw),t.editing.view.focus()})),s}))}}class Tw{constructor(){this._definitions=new Set}get length(){return this._definitions.size}add(t){Array.isArray(t)?t.forEach((t=>this._definitions.add(t))):this._definitions.add(t)}getDispatcher(){return t=>{t.on("attribute:linkHref",((t,e,i)=>{if(!i.consumable.test(e.item,"attribute:linkHref"))return;if(!e.item.is("selection")&&!i.schema.isInline(e.item))return;const n=i.writer,s=n.document.selection;for(const t of this._definitions){const o=n.createAttributeElement("a",t.attributes,{priority:5});t.classes&&n.addClass(t.classes,o);for(const e in t.styles)n.setStyle(e,t.styles[e],o);n.setCustomProperty("link",!0,o),t.callback(e.attributeNewValue)?e.item.is("selection")?n.wrap(s.getFirstRange(),o):n.wrap(i.mapper.toViewRange(e.range),o):n.unwrap(i.mapper.toViewRange(e.range),o)}}),{priority:"high"})}}getDispatcherForLinkedImage(){return t=>{t.on("attribute:linkHref:imageBlock",((t,e,{writer:i,mapper:n})=>{const s=n.toViewElement(e.item),o=Array.from(s.getChildren()).find((t=>"a"===t.name));for(const t of this._definitions){const n=mo(t.attributes);if(t.callback(e.attributeNewValue)){for(const[t,e]of n)"class"===t?i.addClass(e,o):i.setAttribute(t,e,o);t.classes&&i.addClass(t.classes,o);for(const e in t.styles)i.setStyle(e,t.styles[e],o)}else{for(const[t,e]of n)"class"===t?i.removeClass(e,o):i.removeAttribute(t,o);t.classes&&i.removeClass(t.classes,o);for(const e in t.styles)i.removeStyle(e,o)}}}))}}}const Ew=function(t,e,i){var n=t.length;return i=void 0===i?n:i,!e&&i>=n?t:ta(t,e,i)};var Sw=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");const Rw=function(t){return Sw.test(t)};const Ow=function(t){return t.split("")};var Iw="\\ud800-\\udfff",Vw="["+Iw+"]",Mw="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",Nw="\\ud83c[\\udffb-\\udfff]",Bw="[^"+Iw+"]",Dw="(?:\\ud83c[\\udde6-\\uddff]){2}",Fw="[\\ud800-\\udbff][\\udc00-\\udfff]",Lw="(?:"+Mw+"|"+Nw+")"+"?",zw="[\\ufe0e\\ufe0f]?",Hw=zw+Lw+("(?:\\u200d(?:"+[Bw,Dw,Fw].join("|")+")"+zw+Lw+")*"),jw="(?:"+[Bw+Mw+"?",Mw,Dw,Fw,Vw].join("|")+")",$w=RegExp(Nw+"(?="+Nw+")|"+jw+Hw,"g");const Ww=function(t){return t.match($w)||[]};const qw=function(t){return Rw(t)?Ww(t):Ow(t)};const Uw=function(t){return function(e){e=Gr(e);var i=Rw(e)?qw(e):void 0,n=i?i[0]:e.charAt(0),s=i?Ew(i,1).join(""):e.slice(1);return n[t]()+s}}("toUpperCase"),Kw=/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205f\u3000]/g,Gw=/^(?:(?:https?|ftps?|mailto):|[^a-z]|[a-z+.-]+(?:[^a-z+.:-]|$))/i,Jw=/^[\S]+@((?![-_])(?:[-\w\u00a1-\uffff]{0,63}[^-_]\.))+(?:[a-z\u00a1-\uffff]{2,})$/i,Qw=/^((\w+:(\/{2,})?)|(\W))/i,Yw="Ctrl+K";function Zw(t,{writer:e}){const i=e.createAttributeElement("a",{href:t},{priority:5});return e.setCustomProperty("link",!0,i),i}function Xw(t){return function(t){const e=t.replace(Kw,"");return e.match(Gw)}(t=String(t))?t:"#"}function tb(t,e){return!!t&&e.checkAttribute(t.name,"linkHref")}function eb(t,e){const i=(n=t,Jw.test(n)?"mailto:":e);var n;const s=!!i&&!ib(t);return t&&s?i+t:t}function ib(t){return Qw.test(t)}function nb(t){window.open(t,"_blank","noopener")}class sb extends hr{constructor(t){super(t),this.manualDecorators=new co,this.automaticDecorators=new Tw}restoreManualDecoratorStates(){for(const t of this.manualDecorators)t.value=this._getDecoratorStateFromModel(t.id)}refresh(){const t=this.editor.model,e=t.document.selection,i=e.getSelectedElement()||ho(e.getSelectedBlocks());tb(i,t.schema)?(this.value=i.getAttribute("linkHref"),this.isEnabled=t.schema.checkAttribute(i,"linkHref")):(this.value=e.getAttribute("linkHref"),this.isEnabled=t.schema.checkAttributeInSelection(e,"linkHref"));for(const t of this.manualDecorators)t.value=this._getDecoratorStateFromModel(t.id)}execute(t,e={}){const i=this.editor.model,n=i.document.selection,s=[],o=[];for(const t in e)e[t]?s.push(t):o.push(t);i.change((e=>{if(n.isCollapsed){const r=n.getFirstPosition();if(n.hasAttribute("linkHref")){const a=ng(r,"linkHref",n.getAttribute("linkHref"),i);e.setAttribute("linkHref",t,a),s.forEach((t=>{e.setAttribute(t,!0,a)})),o.forEach((t=>{e.removeAttribute(t,a)})),e.setSelection(e.createPositionAfter(a.end.nodeBefore))}else if(""!==t){const o=mo(n.getAttributes());o.set("linkHref",t),s.forEach((t=>{o.set(t,!0)}));const{end:a}=i.insertContent(e.createText(t,o),r);e.setSelection(a)}["linkHref",...s,...o].forEach((t=>{e.removeSelectionAttribute(t)}))}else{const r=i.schema.getValidRanges(n.getRanges(),"linkHref"),a=[];for(const t of n.getSelectedBlocks())i.schema.checkAttribute(t,"linkHref")&&a.push(e.createRangeOn(t));const l=a.slice();for(const t of r)this._isRangeToUpdate(t,a)&&l.push(t);for(const i of l)e.setAttribute("linkHref",t,i),s.forEach((t=>{e.setAttribute(t,!0,i)})),o.forEach((t=>{e.removeAttribute(t,i)}))}}))}_getDecoratorStateFromModel(t){const e=this.editor.model,i=e.document.selection,n=i.getSelectedElement();return tb(n,e.schema)?n.getAttribute(t):i.getAttribute(t)}_isRangeToUpdate(t,e){for(const i of e)if(i.containsRange(t))return!1;return!0}}class ob extends hr{refresh(){const t=this.editor.model,e=t.document.selection,i=e.getSelectedElement();tb(i,t.schema)?this.isEnabled=t.schema.checkAttribute(i,"linkHref"):this.isEnabled=t.schema.checkAttributeInSelection(e,"linkHref")}execute(){const t=this.editor,e=this.editor.model,i=e.document.selection,n=t.commands.get("link");e.change((t=>{const s=i.isCollapsed?[ng(i.getFirstPosition(),"linkHref",i.getAttribute("linkHref"),e)]:e.schema.getValidRanges(i.getRanges(),"linkHref");for(const e of s)if(t.removeAttribute("linkHref",e),n)for(const i of n.manualDecorators)t.removeAttribute(i.id,e)}))}}class rb{constructor({id:t,label:e,attributes:i,classes:n,styles:s,defaultValue:o}){this.id=t,this.set("value"),this.defaultValue=o,this.label=e,this.attributes=i,this.classes=n,this.styles=s}_createPattern(){return{attributes:this.attributes,classes:this.classes,styles:this.styles}}}u(rb,q);const ab="automatic",lb=/^(https?:)?\/\//;class cb extends lr{static get pluginName(){return"LinkEditing"}static get requires(){return[jm,Sm,Vg]}constructor(t){super(t),t.config.define("link",{addTargetToExternalLinks:!1})}init(){const t=this.editor;t.model.schema.extend("$text",{allowAttributes:"linkHref"}),t.conversion.for("dataDowncast").attributeToElement({model:"linkHref",view:Zw}),t.conversion.for("editingDowncast").attributeToElement({model:"linkHref",view:(t,e)=>Zw(Xw(t),e)}),t.conversion.for("upcast").elementToAttribute({view:{name:"a",attributes:{href:!0}},model:{key:"linkHref",value:t=>t.getAttribute("href")}}),t.commands.add("link",new sb(t)),t.commands.add("unlink",new ob(t));const e=function(t,e){const i={"Open in a new tab":t("Open in a new tab"),Downloadable:t("Downloadable")};return e.forEach((t=>(t.label&&i[t.label]&&(t.label=i[t.label]),t))),e}(t.t,function(t){const e=[];if(t)for(const[i,n]of Object.entries(t)){const t=Object.assign({},n,{id:`link${Uw(i)}`});e.push(t)}return e}(t.config.get("link.decorators")));this._enableAutomaticDecorators(e.filter((t=>t.mode===ab))),this._enableManualDecorators(e.filter((t=>"manual"===t.mode)));t.plugins.get(jm).registerAttribute("linkHref"),function(t,e,i,n){const s=t.editing.view,o=new Set;s.document.registerPostFixer((s=>{const r=t.model.document.selection;let a=!1;if(r.hasAttribute(e)){const l=ng(r.getFirstPosition(),e,r.getAttribute(e),t.model),c=t.editing.mapper.toViewRange(l);for(const t of c.getItems())t.is("element",i)&&!t.hasClass(n)&&(s.addClass(n,t),o.add(t),a=!0)}return a})),t.conversion.for("editingDowncast").add((t=>{function e(){s.change((t=>{for(const e of o.values())t.removeClass(n,e),o.delete(e)}))}t.on("insert",e,{priority:"highest"}),t.on("remove",e,{priority:"highest"}),t.on("attribute",e,{priority:"highest"}),t.on("selection",e,{priority:"highest"})}))}(t,"linkHref","a","ck-link_selected"),this._enableLinkOpen(),this._enableInsertContentSelectionAttributesFixer(),this._enableClickingAfterLink(),this._enableTypingOverLink(),this._handleDeleteContentAfterLink(),this._enableClipboardIntegration()}_enableAutomaticDecorators(t){const e=this.editor,i=e.commands.get("link").automaticDecorators;e.config.get("link.addTargetToExternalLinks")&&i.add({id:"linkIsExternal",mode:ab,callback:t=>lb.test(t),attributes:{target:"_blank",rel:"noopener noreferrer"}}),i.add(t),i.length&&e.conversion.for("downcast").add(i.getDispatcher())}_enableManualDecorators(t){if(!t.length)return;const e=this.editor,i=e.commands.get("link").manualDecorators;t.forEach((t=>{e.model.schema.extend("$text",{allowAttributes:t.id}),t=new rb(t),i.add(t),e.conversion.for("downcast").attributeToElement({model:t.id,view:(e,{writer:i,schema:n},{item:s})=>{if((s.is("selection")||n.isInline(s))&&e){const e=i.createAttributeElement("a",t.attributes,{priority:5});t.classes&&i.addClass(t.classes,e);for(const n in t.styles)i.setStyle(n,t.styles[n],e);return i.setCustomProperty("link",!0,e),e}}}),e.conversion.for("upcast").elementToAttribute({view:{name:"a",...t._createPattern()},model:{key:t.id}})}))}_enableLinkOpen(){const t=this.editor,e=t.editing.view.document;this.listenTo(e,"click",((t,e)=>{if(!(r.isMac?e.domEvent.metaKey:e.domEvent.ctrlKey))return;let i=e.domTarget;if("a"!=i.tagName.toLowerCase()&&(i=i.closest("a")),!i)return;const n=i.getAttribute("href");n&&(t.stop(),e.preventDefault(),nb(n))}),{context:"$capture"}),this.listenTo(e,"keydown",((e,i)=>{const n=t.commands.get("link").value;n&&i.keyCode===Zs.enter&&i.altKey&&(e.stop(),nb(n))}))}_enableInsertContentSelectionAttributesFixer(){const t=this.editor.model,e=t.document.selection;this.listenTo(t,"insertContent",(()=>{const i=e.anchor.nodeBefore,n=e.anchor.nodeAfter;e.hasAttribute("linkHref")&&i&&i.hasAttribute("linkHref")&&(n&&n.hasAttribute("linkHref")||t.change((e=>{hb(e,ub(t.schema))})))}),{priority:"low"})}_enableClickingAfterLink(){const t=this.editor,e=t.model;t.editing.view.addObserver(lf);let i=!1;this.listenTo(t.editing.view.document,"mousedown",(()=>{i=!0})),this.listenTo(t.editing.view.document,"selectionChange",(()=>{if(!i)return;i=!1;const t=e.document.selection;if(!t.isCollapsed)return;if(!t.hasAttribute("linkHref"))return;const n=t.getFirstPosition(),s=ng(n,"linkHref",t.getAttribute("linkHref"),e);(n.isTouching(s.start)||n.isTouching(s.end))&&e.change((t=>{hb(t,ub(e.schema))}))}))}_enableTypingOverLink(){const t=this.editor,e=t.editing.view;let i,n;this.listenTo(e.document,"delete",(()=>{n=!0}),{priority:"high"}),this.listenTo(t.model,"deleteContent",(()=>{const e=t.model.document.selection;e.isCollapsed||(n?n=!1:db(t)&&function(t){const e=t.document.selection,i=e.getFirstPosition(),n=e.getLastPosition(),s=i.nodeAfter;if(!s)return!1;if(!s.is("$text"))return!1;if(!s.hasAttribute("linkHref"))return!1;const o=n.textNode||n.nodeBefore;if(s===o)return!0;return ng(i,"linkHref",s.getAttribute("linkHref"),t).containsRange(t.createRange(i,n),!0)}(t.model)&&(i=e.getAttributes()))}),{priority:"high"}),this.listenTo(t.model,"insertContent",((e,[s])=>{n=!1,db(t)&&i&&(t.model.change((t=>{for(const[e,n]of i)t.setAttribute(e,n,s)})),i=null)}),{priority:"high"})}_handleDeleteContentAfterLink(){const t=this.editor,e=t.model,i=e.document.selection,n=t.editing.view;let s=!1,o=!1;this.listenTo(n.document,"delete",((t,e)=>{o="backward"===e.direction}),{priority:"high"}),this.listenTo(e,"deleteContent",(()=>{s=!1;const t=i.getFirstPosition(),n=i.getAttribute("linkHref");if(!n)return;const o=ng(t,"linkHref",n,e);s=o.containsPosition(t)||o.end.isEqual(t)}),{priority:"high"}),this.listenTo(e,"deleteContent",(()=>{o&&(o=!1,s||t.model.enqueueChange((t=>{hb(t,ub(e.schema))})))}),{priority:"low"})}_enableClipboardIntegration(){const t=this.editor,e=t.model,i=this.editor.config.get("link.defaultProtocol");i&&this.listenTo(t.plugins.get("ClipboardPipeline"),"contentInsertion",((t,n)=>{e.change((t=>{const e=t.createRangeIn(n.content);for(const n of e.getItems())if(n.hasAttribute("linkHref")){const e=eb(n.getAttribute("linkHref"),i);t.setAttribute("linkHref",e,n)}}))}))}}function hb(t,e){t.removeSelectionAttribute("linkHref");for(const i of e)t.removeSelectionAttribute(i)}function db(t){return t.model.change((t=>t.batch)).isTyping}function ub(t){return t.getDefinition("$text").allowAttributes.filter((t=>t.startsWith("link")))}class fb extends yo{constructor(t,e){super(t);const i=t.t;this.focusTracker=new uo,this.keystrokes=new fo,this.urlInputView=this._createUrlInput(),this.saveButtonView=this._createButton(i("Save"),yf.check,"ck-button-save"),this.saveButtonView.type="submit",this.cancelButtonView=this._createButton(i("Cancel"),yf.cancel,"ck-button-cancel","cancel"),this._manualDecoratorSwitches=this._createManualDecoratorSwitches(e),this.children=this._createFormChildren(e.manualDecorators),this._focusables=new vo,this._focusCycler=new nr({focusables:this._focusables,focusTracker:this.focusTracker,keystrokeHandler:this.keystrokes,actions:{focusPrevious:"shift + tab",focusNext:"tab"}});const n=["ck","ck-link-form","ck-responsive-form"];e.manualDecorators.length&&n.push("ck-link-form_layout-vertical","ck-vertical-form"),this.setTemplate({tag:"form",attributes:{class:n,tabindex:"-1"},children:this.children}),function(t){const e=t;e.set("_isCssTransitionsDisabled",!1),e.disableCssTransitions=()=>{e._isCssTransitionsDisabled=!0},e.enableCssTransitions=()=>{e._isCssTransitionsDisabled=!1},e.extendTemplate({attributes:{class:[e.bindTemplate.if("_isCssTransitionsDisabled","ck-transitions-disabled")]}})}(this)}getDecoratorSwitchesState(){return Array.from(this._manualDecoratorSwitches).reduce(((t,e)=>(t[e.name]=e.isOn,t)),{})}render(){super.render(),function({view:t}){t.listenTo(t.element,"submit",((e,i)=>{i.preventDefault(),t.fire("submit")}),{useCapture:!0})}({view:this});[this.urlInputView,...this._manualDecoratorSwitches,this.saveButtonView,this.cancelButtonView].forEach((t=>{this._focusables.add(t),this.focusTracker.add(t.element)})),this.keystrokes.listenTo(this.element)}destroy(){super.destroy(),this.focusTracker.destroy(),this.keystrokes.destroy()}focus(){this._focusCycler.focusFirst()}_createUrlInput(){const t=this.locale.t,e=new em(this.locale,im);return e.label=t("Link URL"),e}_createButton(t,e,i,n){const s=new qo(this.locale);return s.set({label:t,icon:e,tooltip:!0}),s.extendTemplate({attributes:{class:i}}),n&&s.delegate("execute").to(this,n),s}_createManualDecoratorSwitches(t){const e=this.createCollection();for(const i of t.manualDecorators){const n=new Uo(this.locale);n.set({name:i.id,label:i.label,withText:!0}),n.bind("isOn").toMany([i,t],"value",((t,e)=>void 0===e&&void 0===t?i.defaultValue:t)),n.on("execute",(()=>{i.set("value",!n.isOn)})),e.add(n)}return e}_createFormChildren(t){const e=this.createCollection();if(e.add(this.urlInputView),t.length){const t=new yo;t.setTemplate({tag:"ul",children:this._manualDecoratorSwitches.map((t=>({tag:"li",children:[t],attributes:{class:["ck","ck-list__item"]}}))),attributes:{class:["ck","ck-reset","ck-list"]}}),e.add(t)}return e.add(this.saveButtonView),e.add(this.cancelButtonView),e}}class mb extends yo{constructor(t){super(t);const e=t.t;this.focusTracker=new uo,this.keystrokes=new fo,this.previewButtonView=this._createPreviewButton(),this.unlinkButtonView=this._createButton(e("Unlink"),'',"unlink"),this.editButtonView=this._createButton(e("Edit link"),yf.pencil,"edit"),this.set("href"),this._focusables=new vo,this._focusCycler=new nr({focusables:this._focusables,focusTracker:this.focusTracker,keystrokeHandler:this.keystrokes,actions:{focusPrevious:"shift + tab",focusNext:"tab"}}),this.setTemplate({tag:"div",attributes:{class:["ck","ck-link-actions","ck-responsive-form"],tabindex:"-1"},children:[this.previewButtonView,this.editButtonView,this.unlinkButtonView]})}render(){super.render();[this.previewButtonView,this.editButtonView,this.unlinkButtonView].forEach((t=>{this._focusables.add(t),this.focusTracker.add(t.element)})),this.keystrokes.listenTo(this.element)}destroy(){super.destroy(),this.focusTracker.destroy(),this.keystrokes.destroy()}focus(){this._focusCycler.focusFirst()}_createButton(t,e,i){const n=new qo(this.locale);return n.set({label:t,icon:e,tooltip:!0}),n.delegate("execute").to(this,i),n}_createPreviewButton(){const t=new qo(this.locale),e=this.bindTemplate,i=this.t;return t.set({withText:!0,tooltip:i("Open link in new tab")}),t.extendTemplate({attributes:{class:["ck","ck-link-actions__preview"],href:e.to("href",(t=>t&&Xw(t))),target:"_blank",rel:"noopener noreferrer"}}),t.bind("label").to(this,"href",(t=>t||i("This link has no URL"))),t.bind("isEnabled").to(this,"href",(t=>!!t)),t.template.tag="a",t.template.eventListeners={},t}}const gb="link-ui";class pb extends lr{static get requires(){return[rm]}static get pluginName(){return"LinkUI"}init(){const t=this.editor;t.editing.view.addObserver(af),this.actionsView=null,this.formView=null,this._balloon=t.plugins.get(rm),this._createToolbarLinkButton(),this._enableBalloonActivators(),t.conversion.for("editingDowncast").markerToHighlight({model:gb,view:{classes:["ck-fake-link-selection"]}}),t.conversion.for("editingDowncast").markerToElement({model:gb,view:{name:"span",classes:["ck-fake-link-selection","ck-fake-link-selection_collapsed"]}})}destroy(){super.destroy(),this.formView&&this.formView.destroy(),this.actionsView&&this.actionsView.destroy()}_createViews(){this.actionsView=this._createActionsView(),this.formView=this._createFormView(),this._enableUserBalloonInteractions()}_createActionsView(){const t=this.editor,e=new mb(t.locale),i=t.commands.get("link"),n=t.commands.get("unlink");return e.bind("href").to(i,"value"),e.editButtonView.bind("isEnabled").to(i),e.unlinkButtonView.bind("isEnabled").to(n),this.listenTo(e,"edit",(()=>{this._addFormView()})),this.listenTo(e,"unlink",(()=>{t.execute("unlink"),this._hideUI()})),e.keystrokes.set("Esc",((t,e)=>{this._hideUI(),e()})),e.keystrokes.set(Yw,((t,e)=>{this._addFormView(),e()})),e}_createFormView(){const t=this.editor,e=t.commands.get("link"),i=t.config.get("link.defaultProtocol"),n=new fb(t.locale,e);return n.urlInputView.fieldView.bind("value").to(e,"value"),n.urlInputView.bind("isReadOnly").to(e,"isEnabled",(t=>!t)),n.saveButtonView.bind("isEnabled").to(e),this.listenTo(n,"submit",(()=>{const{value:e}=n.urlInputView.fieldView.element,s=eb(e,i);t.execute("link",s,n.getDecoratorSwitchesState()),this._closeFormView()})),this.listenTo(n,"cancel",(()=>{this._closeFormView()})),n.keystrokes.set("Esc",((t,e)=>{this._closeFormView(),e()})),n}_createToolbarLinkButton(){const t=this.editor,e=t.commands.get("link"),i=t.t;t.ui.componentFactory.add("link",(t=>{const n=new qo(t);return n.isEnabled=!0,n.label=i("Link"),n.icon='',n.keystroke=Yw,n.tooltip=!0,n.isToggleable=!0,n.bind("isEnabled").to(e,"isEnabled"),n.bind("isOn").to(e,"value",(t=>!!t)),this.listenTo(n,"execute",(()=>this._showUI(!0))),n}))}_enableBalloonActivators(){const t=this.editor,e=t.editing.view.document;this.listenTo(e,"click",(()=>{this._getSelectedLinkElement()&&this._showUI()})),t.keystrokes.set(Yw,((e,i)=>{i(),t.commands.get("link").isEnabled&&this._showUI(!0)}))}_enableUserBalloonInteractions(){this.editor.keystrokes.set("Tab",((t,e)=>{this._areActionsVisible&&!this.actionsView.focusTracker.isFocused&&(this.actionsView.focus(),e())}),{priority:"high"}),this.editor.keystrokes.set("Esc",((t,e)=>{this._isUIVisible&&(this._hideUI(),e())})),i({emitter:this.formView,activator:()=>this._isUIInPanel,contextElements:()=>[this._balloon.view.element],callback:()=>this._hideUI()})}_addActionsView(){this.actionsView||this._createViews(),this._areActionsInPanel||this._balloon.add({view:this.actionsView,position:this._getBalloonPositionData()})}_addFormView(){if(this.formView||this._createViews(),this._isFormInPanel)return;const t=this.editor.commands.get("link");this.formView.disableCssTransitions(),this._balloon.add({view:this.formView,position:this._getBalloonPositionData()}),this._balloon.visibleView===this.formView&&this.formView.urlInputView.fieldView.select(),this.formView.enableCssTransitions(),this.formView.urlInputView.fieldView.element.value=t.value||""}_closeFormView(){const t=this.editor.commands.get("link");t.restoreManualDecoratorStates(),void 0!==t.value?this._removeFormView():this._hideUI()}_removeFormView(){this._isFormInPanel&&(this.formView.saveButtonView.focus(),this._balloon.remove(this.formView),this.editor.editing.view.focus(),this._hideFakeVisualSelection())}_showUI(t=!1){this.formView||this._createViews(),this._getSelectedLinkElement()?(this._areActionsVisible?this._addFormView():this._addActionsView(),t&&this._balloon.showStack("main")):(this._showFakeVisualSelection(),this._addActionsView(),t&&this._balloon.showStack("main"),this._addFormView()),this._startUpdatingUI()}_hideUI(){if(!this._isUIInPanel)return;const t=this.editor;this.stopListening(t.ui,"update"),this.stopListening(this._balloon,"change:visibleView"),t.editing.view.focus(),this._removeFormView(),this._balloon.remove(this.actionsView),this._hideFakeVisualSelection()}_startUpdatingUI(){const t=this.editor,e=t.editing.view.document;let i=this._getSelectedLinkElement(),n=o();const s=()=>{const t=this._getSelectedLinkElement(),e=o();i&&!t||!i&&e!==n?this._hideUI():this._isUIVisible&&this._balloon.updatePosition(this._getBalloonPositionData()),i=t,n=e};function o(){return e.selection.focus.getAncestors().reverse().find((t=>t.is("element")))}this.listenTo(t.ui,"update",s),this.listenTo(this._balloon,"change:visibleView",s)}get _isFormInPanel(){return this._balloon.hasView(this.formView)}get _areActionsInPanel(){return this._balloon.hasView(this.actionsView)}get _areActionsVisible(){return this._balloon.visibleView===this.actionsView}get _isUIInPanel(){return this._isFormInPanel||this._areActionsInPanel}get _isUIVisible(){return this._balloon.visibleView==this.formView||this._areActionsVisible}_getBalloonPositionData(){const t=this.editor.editing.view,e=this.editor.model,i=t.document;let n=null;if(e.markers.has(gb)){const e=Array.from(this.editor.editing.mapper.markerNameToElements(gb)),i=t.createRange(t.createPositionBefore(e[0]),t.createPositionAfter(e[e.length-1]));n=t.domConverter.viewRangeToDom(i)}else n=()=>{const e=this._getSelectedLinkElement();return e?t.domConverter.mapViewToDom(e):t.domConverter.viewRangeToDom(i.selection.getFirstRange())};return{target:n}}_getSelectedLinkElement(){const t=this.editor.editing.view,e=t.document.selection,i=e.getSelectedElement();if(e.isCollapsed||i&&Hg(i))return wb(e.getFirstPosition());{const i=e.getFirstRange().getTrimmed(),n=wb(i.start),s=wb(i.end);return n&&n==s&&t.createRangeIn(n).getTrimmed().isEqual(i)?n:null}}_showFakeVisualSelection(){const t=this.editor.model;t.change((e=>{const i=t.document.selection.getFirstRange();if(t.markers.has(gb))e.updateMarker(gb,{range:i});else if(i.start.isAtEnd){const n=i.start.getLastMatchingPosition((({item:e})=>!t.schema.isContent(e)),{boundaries:i});e.addMarker(gb,{usingOperation:!1,affectsData:!1,range:e.createRange(n,i.end)})}else e.addMarker(gb,{usingOperation:!1,affectsData:!1,range:i})}))}_hideFakeVisualSelection(){const t=this.editor.model;t.markers.has(gb)&&t.change((t=>{t.removeMarker(gb)}))}}function wb(t){return t.getAncestors().find((t=>{return(e=t).is("attributeElement")&&!!e.getCustomProperty("link");var e}))}const bb=4,_b=new RegExp("(^|\\s)(((?:(?:(?:https?|ftp):)?\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(((?!www\\.)|(www\\.))(?![-_])(?:[-_a-z0-9\\u00a1-\\uffff]{1,63}\\.)+(?:[a-z\\u00a1-\\uffff]{2,63})))(?::\\d{2,5})?(?:[/?#]\\S*)?)|((www.|(\\S+@))((?![-_])(?:[-_a-z0-9\\u00a1-\\uffff]{1,63}\\.))+(?:[a-z\\u00a1-\\uffff]{2,63})))$","i"),vb=2;class yb extends lr{static get requires(){return[Fm]}static get pluginName(){return"AutoLink"}init(){const t=this.editor.model.document.selection;t.on("change:range",(()=>{this.isEnabled=!t.anchor.parent.is("element","codeBlock")})),this._enableTypingHandling()}afterInit(){this._enableEnterHandling(),this._enableShiftEnterHandling()}_enableTypingHandling(){const t=this.editor,e=new Hm(t.model,(t=>{if(!function(t){return t.length>bb&&" "===t[t.length-1]&&" "!==t[t.length-2]}(t))return;const e=kb(t.substr(0,t.length-1));return e?{url:e}:void 0}));e.on("matched:data",((e,i)=>{const{batch:n,range:s,url:o}=i;if(!n.isTyping)return;const r=s.end.getShiftedBy(-1),a=r.getShiftedBy(-o.length),l=t.model.createRange(a,r);this._applyAutoLink(o,l)})),e.bind("isEnabled").to(this)}_enableEnterHandling(){const t=this.editor,e=t.model,i=t.commands.get("enter");i&&i.on("execute",(()=>{const t=e.document.selection.getFirstPosition();if(!t.parent.previousSibling)return;const i=e.createRangeIn(t.parent.previousSibling);this._checkAndApplyAutoLinkOnRange(i)}))}_enableShiftEnterHandling(){const t=this.editor,e=t.model,i=t.commands.get("shiftEnter");i&&i.on("execute",(()=>{const t=e.document.selection.getFirstPosition(),i=e.createRange(e.createPositionAt(t.parent,0),t.getShiftedBy(-1));this._checkAndApplyAutoLinkOnRange(i)}))}_checkAndApplyAutoLinkOnRange(t){const e=this.editor.model,{text:i,range:n}=zm(t,e),s=kb(i);if(s){const t=e.createRange(n.end.getShiftedBy(-s.length),n.end);this._applyAutoLink(s,t)}}_applyAutoLink(t,e){const i=this.editor.model,n=eb(t,this.editor.config.get("link.defaultProtocol"));this.isEnabled&&function(t,e){return e.schema.checkAttributeInSelection(e.createSelection(t),"linkHref")}(e,i)&&ib(n)&&!function(t){const e=t.start.nodeAfter;return e&&e.hasAttribute("linkHref")}(e)&&this._persistAutoLink(n,e)}_persistAutoLink(t,e){const i=this.editor.model,n=this.editor.plugins.get("Delete");i.enqueueChange((s=>{s.setAttribute("linkHref",t,e),i.enqueueChange((()=>{n.requestUndoOnBackspace()}))}))}}function kb(t){const e=_b.exec(t);return e?e[vb]:null}class Ab extends hr{constructor(t,e){super(t),this.type=e}refresh(){this.value=this._getValue(),this.isEnabled=this._checkEnabled()}execute(t={}){const e=this.editor.model,i=e.document,n=Array.from(i.selection.getSelectedBlocks()).filter((t=>Cb(t,e.schema))),s=void 0!==t.forceValue?!t.forceValue:this.value;e.change((t=>{if(s){let e=n[n.length-1].nextSibling,i=Number.POSITIVE_INFINITY,s=[];for(;e&&"listItem"==e.name&&0!==e.getAttribute("listIndent");){const t=e.getAttribute("listIndent");t=i;)o>s.getAttribute("listIndent")&&(o=s.getAttribute("listIndent")),s.getAttribute("listIndent")==o&&t[e?"unshift":"push"](s),s=s[e?"previousSibling":"nextSibling"]}}function Cb(t,e){return e.checkChild(t.parent,"listItem")&&!e.isObject(t)}class Pb extends hr{constructor(t,e){super(t),this._indentBy="forward"==e?1:-1}refresh(){this.isEnabled=this._checkEnabled()}execute(){const t=this.editor.model,e=t.document;let i=Array.from(e.selection.getSelectedBlocks());t.change((t=>{const e=i[i.length-1];let n=e.nextSibling;for(;n&&"listItem"==n.name&&n.getAttribute("listIndent")>e.getAttribute("listIndent");)i.push(n),n=n.nextSibling;this._indentBy<0&&(i=i.reverse());for(const e of i){const i=e.getAttribute("listIndent")+this._indentBy;i<0?t.rename(e,"paragraph"):t.setAttribute("listIndent",i,e)}this.fire("_executeCleanup",i)}))}_checkEnabled(){const t=ho(this.editor.model.document.selection.getSelectedBlocks());if(!t||!t.is("element","listItem"))return!1;if(this._indentBy>0){const e=t.getAttribute("listIndent"),i=t.getAttribute("listType");let n=t.previousSibling;for(;n&&n.is("element","listItem")&&n.getAttribute("listIndent")>=e;){if(n.getAttribute("listIndent")==e)return n.getAttribute("listType")==i;n=n.previousSibling}return!1}return!0}}function Tb(t,e){const i=e.mapper,n=e.writer,s="numbered"==t.getAttribute("listType")?"ol":"ul",o=function(t){const e=t.createContainerElement("li");return e.getFillerOffset=Fb,e}(n),r=n.createContainerElement(s,null);return n.insert(n.createPositionAt(r,0),o),i.bindElements(t,o),o}function Eb(t,e,i,n){const s=e.parent,o=i.mapper,r=i.writer;let a=o.toViewPosition(n.createPositionBefore(t));const l=Ob(t.previousSibling,{sameIndent:!0,smallerIndent:!0,listIndent:t.getAttribute("listIndent")}),c=t.previousSibling;if(l&&l.getAttribute("listIndent")==t.getAttribute("listIndent")){const t=o.toViewElement(l);a=r.breakContainer(r.createPositionAfter(t))}else if(c&&"listItem"==c.name){a=o.toViewPosition(n.createPositionAt(c,"end"));const t=o.findMappedViewAncestor(a),e=function(t){for(const e of t.getChildren())if("ul"==e.name||"ol"==e.name)return e;return null}(t);a=e?r.createPositionBefore(e):r.createPositionAt(t,"end")}else a=o.toViewPosition(n.createPositionBefore(t));if(a=Rb(a),r.insert(a,s),c&&"listItem"==c.name){const t=o.toViewElement(c),i=r.createRange(r.createPositionAt(t,0),a).getWalker({ignoreElementEnd:!0});for(const t of i)if(t.item.is("element","li")){const n=r.breakContainer(r.createPositionBefore(t.item)),s=t.item.parent,o=r.createPositionAt(e,"end");Sb(r,o.nodeBefore,o.nodeAfter),r.move(r.createRangeOn(s),o),i.position=n}}else{const i=s.nextSibling;if(i&&(i.is("element","ul")||i.is("element","ol"))){let n=null;for(const e of i.getChildren()){const i=o.toModelElement(e);if(!(i&&i.getAttribute("listIndent")>t.getAttribute("listIndent")))break;n=e}n&&(r.breakContainer(r.createPositionAfter(n)),r.move(r.createRangeOn(n.parent),r.createPositionAt(e,"end")))}}Sb(r,s,s.nextSibling),Sb(r,s.previousSibling,s)}function Sb(t,e,i){return!e||!i||"ul"!=e.name&&"ol"!=e.name||e.name!=i.name||e.getAttribute("class")!==i.getAttribute("class")?null:t.mergeContainers(t.createPositionAfter(e))}function Rb(t){return t.getLastMatchingPosition((t=>t.item.is("uiElement")))}function Ob(t,e){const i=!!e.sameIndent,n=!!e.smallerIndent,s=e.listIndent;let o=t;for(;o&&"listItem"==o.name;){const t=o.getAttribute("listIndent");if(i&&s==t||n&&s>t)return o;o="forward"===e.direction?o.nextSibling:o.previousSibling}return null}function Ib(t,e,i,n){t.ui.componentFactory.add(e,(s=>{const o=t.commands.get(e),r=new qo(s);return r.set({label:i,icon:n,tooltip:!0,isToggleable:!0}),r.bind("isOn","isEnabled").to(o,"value","isEnabled"),r.on("execute",(()=>{t.execute(e),t.editing.view.focus()})),r}))}function Vb(t,e){const i=[],n=t.parent,s={ignoreElementEnd:!1,startPosition:t,shallow:!0,direction:e},o=n.getAttribute("listIndent"),r=[...new mh(s)].filter((t=>t.item.is("element"))).map((t=>t.item));for(const t of r){if(!t.is("element","listItem"))break;if(t.getAttribute("listIndent")o)){if(t.getAttribute("listType")!==n.getAttribute("listType"))break;if(t.getAttribute("listStyle")!==n.getAttribute("listStyle"))break;if(t.getAttribute("listReversed")!==n.getAttribute("listReversed"))break;if(t.getAttribute("listStart")!==n.getAttribute("listStart"))break;"backward"===e?i.unshift(t):i.push(t)}}return i}function Mb(t){let e=[...t.document.selection.getSelectedBlocks()].filter((t=>t.is("element","listItem"))).map((e=>{const i=t.change((t=>t.createPositionAt(e,0)));return[...Vb(i,"backward"),...Vb(i,"forward")]})).flat();return e=[...new Set(e)],e}const Nb=["disc","circle","square"],Bb=["decimal","decimal-leading-zero","lower-roman","upper-roman","lower-latin","upper-latin"];function Db(t){return Nb.includes(t)?"bulleted":Bb.includes(t)?"numbered":null}function Fb(){const t=!this.isEmpty&&("ul"==this.getChild(0).name||"ol"==this.getChild(0).name);return this.isEmpty||t?0:Ba.call(this)}class Lb extends lr{static get pluginName(){return"ListUtils"}getListTypeFromListStyleType(t){return Db(t)}getSelectedListItems(t){return Mb(t)}getSiblingNodes(t,e){return Vb(t,e)}}function zb(t){return(e,i,n)=>{const s=n.consumable;if(!s.test(i.item,"insert")||!s.test(i.item,"attribute:listType")||!s.test(i.item,"attribute:listIndent"))return;s.consume(i.item,"insert"),s.consume(i.item,"attribute:listType"),s.consume(i.item,"attribute:listIndent");const o=i.item;Eb(o,Tb(o,n),n,t)}}const Hb=(t,e,i)=>{if(!i.consumable.test(e.item,t.name))return;const n=i.mapper.toViewElement(e.item),s=i.writer;s.breakContainer(s.createPositionBefore(n)),s.breakContainer(s.createPositionAfter(n));const o=n.parent,r="numbered"==e.attributeNewValue?"ol":"ul";s.rename(r,o)},jb=(t,e,i)=>{i.consumable.consume(e.item,t.name);const n=i.mapper.toViewElement(e.item).parent,s=i.writer;Sb(s,n,n.nextSibling),Sb(s,n.previousSibling,n)};const $b=(t,e,i)=>{if(i.consumable.test(e.item,t.name)&&"listItem"!=e.item.name){let t=i.mapper.toViewPosition(e.range.start);const n=i.writer,s=[];for(;("ul"==t.parent.name||"ol"==t.parent.name)&&(t=n.breakContainer(t),"li"==t.parent.name);){const e=t,i=n.createPositionAt(t.parent,"end");if(!e.isEqual(i)){const t=n.remove(n.createRange(e,i));s.push(t)}t=n.createPositionAfter(t.parent)}if(s.length>0){for(let e=0;e0){const e=Sb(n,i,i.nextSibling);e&&e.parent==i&&t.offset--}}Sb(n,t.nodeBefore,t.nodeAfter)}}},Wb=(t,e,i)=>{const n=i.mapper.toViewPosition(e.position),s=n.nodeBefore,o=n.nodeAfter;Sb(i.writer,s,o)},qb=(t,e,i)=>{if(i.consumable.consume(e.viewItem,{name:!0})){const t=i.writer,n=t.createElement("listItem"),s=function(t){let e=0,i=t.parent;for(;i;){if(i.is("element","li"))e++;else{const t=i.previousSibling;t&&t.is("element","li")&&e++}i=i.parent}return e}(e.viewItem);t.setAttribute("listIndent",s,n);const o=e.viewItem.parent&&"ol"==e.viewItem.parent.name?"numbered":"bulleted";if(t.setAttribute("listType",o,n),!i.safeInsert(n,e.modelCursor))return;const r=function(t,e,i){const{writer:n,schema:s}=i;let o=n.createPositionAfter(t);for(const r of e)if("ul"==r.name||"ol"==r.name)o=i.convertItem(r,o).modelCursor;else{const e=i.convertItem(r,n.createPositionAt(t,"end")),a=e.modelRange.start.nodeAfter;a&&a.is("element")&&!s.checkChild(t,a.name)&&(t=e.modelCursor.parent.is("element","listItem")?e.modelCursor.parent:Qb(e.modelCursor),o=n.createPositionAfter(t))}return o}(n,e.viewItem.getChildren(),i);e.modelRange=t.createRange(e.modelCursor,r),i.updateConversionResult(n,e)}},Ub=(t,e,i)=>{if(i.consumable.test(e.viewItem,{name:!0})){const t=Array.from(e.viewItem.getChildren());for(const e of t){!(e.is("element","li")||Zb(e))&&e._remove()}}},Kb=(t,e,i)=>{if(i.consumable.test(e.viewItem,{name:!0})){if(0===e.viewItem.childCount)return;const t=[...e.viewItem.getChildren()];let i=!1;for(const e of t)i&&!Zb(e)&&e._remove(),Zb(e)&&(i=!0)}};function Gb(t){return(e,i)=>{if(i.isPhantom)return;const n=i.modelPosition.nodeBefore;if(n&&n.is("element","listItem")){const e=i.mapper.toViewElement(n),s=e.getAncestors().find(Zb),o=t.createPositionAt(e,0).getWalker();for(const t of o){if("elementStart"==t.type&&t.item.is("element","li")){i.viewPosition=t.previousPosition;break}if("elementEnd"==t.type&&t.item==s){i.viewPosition=t.nextPosition;break}}}}}const Jb=function(t,[e,i,n]){const s=this;let o,r=e.is("documentFragment")?e.getChild(0):e;if(o=i?s.createSelection(i,n):s.document.selection,r&&r.is("element","listItem")){const t=o.getFirstPosition();let e=null;if(t.parent.is("element","listItem")?e=t.parent:t.nodeBefore&&t.nodeBefore.is("element","listItem")&&(e=t.nodeBefore),e){const t=e.getAttribute("listIndent");if(t>0)for(;r&&r.is("element","listItem");)r._setAttribute("listIndent",r.getAttribute("listIndent")+t),r=r.nextSibling}}};function Qb(t){const e=new mh({startPosition:t});let i;do{i=e.next()}while(!i.value.item.is("element","listItem"));return i.value.item}function Yb(t,e,i,n,s,o){const r=Ob(e.nodeBefore,{sameIndent:!0,smallerIndent:!0,listIndent:t}),a=s.mapper,l=s.writer,c=r?r.getAttribute("listIndent"):null;let h;if(r)if(c==t){const t=a.toViewElement(r).parent;h=l.createPositionAfter(t)}else{const t=o.createPositionAt(r,"end");h=a.toViewPosition(t)}else h=i;h=Rb(h);for(const t of[...n.getChildren()])Zb(t)&&(h=l.move(l.createRangeOn(t),h).end,Sb(l,t,t.nextSibling),Sb(l,t.previousSibling,t))}function Zb(t){return t.is("element","ol")||t.is("element","ul")}class Xb extends lr{static get pluginName(){return"ListEditing"}static get requires(){return[mg,Fm,Lb]}init(){const t=this.editor;t.model.schema.register("listItem",{inheritAllFrom:"$block",allowAttributes:["listType","listIndent"]});const e=t.data,i=t.editing;var n;t.model.document.registerPostFixer((e=>function(t,e){const i=t.document.differ.getChanges(),n=new Map;let s=!1;for(const n of i)if("insert"==n.type&&"listItem"==n.name)o(n.position);else if("insert"==n.type&&"listItem"!=n.name){if("$text"!=n.name){const i=n.position.nodeAfter;i.hasAttribute("listIndent")&&(e.removeAttribute("listIndent",i),s=!0),i.hasAttribute("listType")&&(e.removeAttribute("listType",i),s=!0),i.hasAttribute("listStyle")&&(e.removeAttribute("listStyle",i),s=!0),i.hasAttribute("listReversed")&&(e.removeAttribute("listReversed",i),s=!0),i.hasAttribute("listStart")&&(e.removeAttribute("listStart",i),s=!0);for(const e of Array.from(t.createRangeIn(i)).filter((t=>t.item.is("element","listItem"))))o(e.previousPosition)}o(n.position.getShiftedBy(n.length))}else"remove"==n.type&&"listItem"==n.name?o(n.position):("attribute"==n.type&&"listIndent"==n.attributeKey||"attribute"==n.type&&"listType"==n.attributeKey)&&o(n.range.start);for(const t of n.values())r(t),a(t);return s;function o(t){const e=t.nodeBefore;if(e&&e.is("element","listItem")){let t=e;if(n.has(t))return;for(let e=t.previousSibling;e&&e.is("element","listItem");e=t.previousSibling)if(t=e,n.has(t))return;n.set(e,t)}else{const e=t.nodeAfter;e&&e.is("element","listItem")&&n.set(e,e)}}function r(t){let i=0,n=null;for(;t&&t.is("element","listItem");){const o=t.getAttribute("listIndent");if(o>i){let r;null===n?(n=o-i,r=i):(n>o&&(n=o),r=o-n),e.setAttribute("listIndent",r,t),s=!0}else n=null,i=t.getAttribute("listIndent")+1;t=t.nextSibling}}function a(t){let i=[],n=null;for(;t&&t.is("element","listItem");){const o=t.getAttribute("listIndent");if(n&&n.getAttribute("listIndent")>o&&(i=i.slice(0,o+1)),0!=o)if(i[o]){const n=i[o];t.getAttribute("listType")!=n&&(e.setAttribute("listType",n,t),s=!0)}else i[o]=t.getAttribute("listType");n=t,t=t.nextSibling}}}(t.model,e))),i.mapper.registerViewToModelLength("li",t_),e.mapper.registerViewToModelLength("li",t_),i.mapper.on("modelToViewPosition",Gb(i.view)),i.mapper.on("viewToModelPosition",(n=t.model,(t,e)=>{const i=e.viewPosition,s=i.parent,o=e.mapper;if("ul"==s.name||"ol"==s.name){if(i.isAtEnd){const t=o.toModelElement(i.nodeBefore),s=o.getModelLength(i.nodeBefore);e.modelPosition=n.createPositionBefore(t).getShiftedBy(s)}else{const t=o.toModelElement(i.nodeAfter);e.modelPosition=n.createPositionBefore(t)}t.stop()}else if("li"==s.name&&i.nodeBefore&&("ul"==i.nodeBefore.name||"ol"==i.nodeBefore.name)){const r=o.toModelElement(s);let a=1,l=i.nodeBefore;for(;l&&Zb(l);)a+=o.getModelLength(l),l=l.previousSibling;e.modelPosition=n.createPositionBefore(r).getShiftedBy(a),t.stop()}})),e.mapper.on("modelToViewPosition",Gb(i.view)),t.conversion.for("editingDowncast").add((e=>{e.on("insert",$b,{priority:"high"}),e.on("insert:listItem",zb(t.model)),e.on("attribute:listType:listItem",Hb,{priority:"high"}),e.on("attribute:listType:listItem",jb,{priority:"low"}),e.on("attribute:listIndent:listItem",function(t){return(e,i,n)=>{if(!n.consumable.consume(i.item,"attribute:listIndent"))return;const s=n.mapper.toViewElement(i.item),o=n.writer;o.breakContainer(o.createPositionBefore(s)),o.breakContainer(o.createPositionAfter(s));const r=s.parent,a=r.previousSibling,l=o.createRangeOn(r);o.remove(l),a&&a.nextSibling&&Sb(o,a,a.nextSibling),Yb(i.attributeOldValue+1,i.range.start,l.start,s,n,t),Eb(i.item,s,n,t);for(const t of i.item.getChildren())n.consumable.consume(t,"insert")}}(t.model)),e.on("remove:listItem",function(t){return(e,i,n)=>{const s=n.mapper.toViewPosition(i.position).getLastMatchingPosition((t=>!t.item.is("element","li"))).nodeAfter,o=n.writer;o.breakContainer(o.createPositionBefore(s)),o.breakContainer(o.createPositionAfter(s));const r=s.parent,a=r.previousSibling,l=o.createRangeOn(r),c=o.remove(l);a&&a.nextSibling&&Sb(o,a,a.nextSibling),Yb(n.mapper.toModelElement(s).getAttribute("listIndent")+1,i.position,l.start,s,n,t);for(const t of o.createRangeIn(c).getItems())n.mapper.unbindViewElement(t);e.stop()}}(t.model)),e.on("remove",Wb,{priority:"low"})})),t.conversion.for("dataDowncast").add((e=>{e.on("insert",$b,{priority:"high"}),e.on("insert:listItem",zb(t.model))})),t.conversion.for("upcast").add((t=>{t.on("element:ul",Ub,{priority:"high"}),t.on("element:ol",Ub,{priority:"high"}),t.on("element:li",Kb,{priority:"high"}),t.on("element:li",qb)})),t.model.on("insertContent",Jb,{priority:"high"}),t.commands.add("numberedList",new Ab(t,"numbered")),t.commands.add("bulletedList",new Ab(t,"bulleted")),t.commands.add("indentList",new Pb(t,"forward")),t.commands.add("outdentList",new Pb(t,"backward"));const s=i.view.document;this.listenTo(s,"enter",((t,e)=>{const i=this.editor.model.document,n=i.selection.getLastPosition().parent;i.selection.isCollapsed&&"listItem"==n.name&&n.isEmpty&&(this.editor.execute("outdentList"),e.preventDefault(),t.stop())}),{context:"li"}),this.listenTo(s,"delete",((t,e)=>{if("backward"!==e.direction)return;const i=this.editor.model.document.selection;if(!i.isCollapsed)return;const n=i.getFirstPosition();if(!n.isAtStart)return;const s=n.parent;if("listItem"!==s.name)return;s.previousSibling&&"listItem"===s.previousSibling.name||(this.editor.execute("outdentList"),e.preventDefault(),t.stop())}),{context:"li"}),this.listenTo(t.editing.view.document,"tab",((e,i)=>{const n=i.shiftKey?"outdentList":"indentList";this.editor.commands.get(n).isEnabled&&(t.execute(n),i.stopPropagation(),i.preventDefault(),e.stop())}),{context:"li"})}afterInit(){const t=this.editor.commands,e=t.get("indent"),i=t.get("outdent");e&&e.registerChildCommand(t.get("indentList")),i&&i.registerChildCommand(t.get("outdentList"))}}function t_(t){let e=1;for(const i of t.getChildren())if("ul"==i.name||"ol"==i.name)for(const t of i.getChildren())e+=t_(t);return e}const e_='',i_='';class n_ extends lr{static get pluginName(){return"ListUI"}init(){const t=this.editor.t;Ib(this.editor,"numberedList",t("Numbered List"),e_),Ib(this.editor,"bulletedList",t("Bulleted List"),i_)}}class s_ extends hr{constructor(t,e){super(t),this.defaultType=e}refresh(){this.value=this._getValue(),this.isEnabled=this._checkEnabled()}execute(t={}){this._tryToConvertItemsToList(t);const e=this.editor.model,i=Mb(e);i.length&&e.change((e=>{for(const n of i)e.setAttribute("listStyle",t.type||this.defaultType,n)}))}_getValue(){const t=this.editor.model.document.selection.getFirstPosition().parent;return t&&t.is("element","listItem")?t.getAttribute("listStyle"):null}_checkEnabled(){const t=this.editor,e=t.commands.get("numberedList"),i=t.commands.get("bulletedList");return e.isEnabled||i.isEnabled}_tryToConvertItemsToList(t){if(!t.type)return;const e=Db(t.type);if(!e)return;const i=this.editor,n=`${e}List`;i.commands.get(n).value||i.execute(n)}}class o_ extends hr{refresh(){const t=this._getValue();this.value=t,this.isEnabled=null!=t}execute(t={}){const e=this.editor.model,i=Mb(e).filter((t=>"numbered"==t.getAttribute("listType")));e.change((e=>{for(const n of i)e.setAttribute("listReversed",!!t.reversed,n)}))}_getValue(){const t=this.editor.model.document.selection.getFirstPosition().parent;return t&&t.is("element","listItem")&&"numbered"==t.getAttribute("listType")?t.getAttribute("listReversed"):null}}class r_ extends hr{refresh(){const t=this._getValue();this.value=t,this.isEnabled=null!=t}execute({startIndex:t=1}={}){const e=this.editor.model,i=Mb(e).filter((t=>"numbered"==t.getAttribute("listType")));e.change((e=>{for(const n of i)e.setAttribute("listStart",t>=0?t:1,n)}))}_getValue(){const t=this.editor.model.document.selection.getFirstPosition().parent;return t&&t.is("element","listItem")&&"numbered"==t.getAttribute("listType")?t.getAttribute("listStart"):null}}const a_="default";class l_ extends lr{static get requires(){return[Xb]}static get pluginName(){return"ListPropertiesEditing"}constructor(t){super(t),t.config.define("list",{properties:{styles:!0,startIndex:!1,reversed:!1}})}init(){const t=this.editor,e=t.model,i=function(t){const e=[];t.styles&&e.push({attributeName:"listStyle",defaultValue:a_,addCommand(t){t.commands.add("listStyle",new s_(t,a_))},appliesToListItem:()=>!0,setAttributeOnDowncast(t,e,i){e&&e!==a_?t.setStyle("list-style-type",e,i):t.removeStyle("list-style-type",i)},getAttributeOnUpcast:t=>t.getStyle("list-style-type")||a_});t.reversed&&e.push({attributeName:"listReversed",defaultValue:!1,addCommand(t){t.commands.add("listReversed",new o_(t))},appliesToListItem:t=>"numbered"==t.getAttribute("listType"),setAttributeOnDowncast(t,e,i){e?t.setAttribute("reversed","reversed",i):t.removeAttribute("reversed",i)},getAttributeOnUpcast:t=>t.hasAttribute("reversed")});t.startIndex&&e.push({attributeName:"listStart",defaultValue:1,addCommand(t){t.commands.add("listStart",new r_(t))},appliesToListItem:t=>"numbered"==t.getAttribute("listType"),setAttributeOnDowncast(t,e,i){0==e||e>1?t.setAttribute("start",e,i):t.removeAttribute("start",i)},getAttributeOnUpcast(t){const e=t.getAttribute("start");return e>=0?e:1}});return e}(t.config.get("list.properties"));e.schema.extend("listItem",{allowAttributes:i.map((t=>t.attributeName))});for(const e of i)e.addCommand(t);var n;this.listenTo(t.commands.get("indentList"),"_executeCleanup",function(t,e){return(i,n)=>{const s=n[0],o=s.getAttribute("listIndent"),r=n.filter((t=>t.getAttribute("listIndent")===o));let a=null;s.previousSibling.getAttribute("listIndent")+1!==o&&(a=Ob(s.previousSibling,{sameIndent:!0,direction:"backward",listIndent:o})),t.model.change((t=>{for(const i of r)for(const n of e)if(n.appliesToListItem(i)){const e=null==a?n.defaultValue:a.getAttribute(n.attributeName);t.setAttribute(n.attributeName,e,i)}}))}}(t,i)),this.listenTo(t.commands.get("outdentList"),"_executeCleanup",function(t,e){return(i,n)=>{if(!(n=n.reverse().filter((t=>t.is("element","listItem")))).length)return;const s=n[0].getAttribute("listIndent"),o=n[0].getAttribute("listType");let r=n[0].previousSibling;if(r.is("element","listItem"))for(;r.getAttribute("listIndent")!==s;)r=r.previousSibling;else r=null;r||(r=n[n.length-1].nextSibling),r&&r.is("element","listItem")&&r.getAttribute("listType")===o&&t.model.change((t=>{const i=n.filter((t=>t.getAttribute("listIndent")===s));for(const n of i)for(const i of e)if(i.appliesToListItem(n)){const e=i.attributeName,s=r.getAttribute(e);t.setAttribute(e,s,n)}}))}}(t,i)),this.listenTo(t.commands.get("bulletedList"),"_executeCleanup",d_(t)),this.listenTo(t.commands.get("numberedList"),"_executeCleanup",d_(t)),e.document.registerPostFixer(function(t,e){return i=>{let n=!1;const s=u_(t.model.document.differ.getChanges()).filter((t=>"todo"!==t.getAttribute("listType")));if(!s.length)return n;let o=s[s.length-1].nextSibling;if((!o||!o.is("element","listItem"))&&(o=s[0].previousSibling,o)){const t=s[0].getAttribute("listIndent");for(;o.is("element","listItem")&&o.getAttribute("listIndent")!==t&&(o=o.previousSibling,o););}for(const t of e){const e=t.attributeName;for(const r of s)if(t.appliesToListItem(r))if(r.hasAttribute(e)){const s=r.previousSibling;h_(s,r,t.attributeName)&&(i.setAttribute(e,s.getAttribute(e),r),n=!0)}else c_(o,r,t)?i.setAttribute(e,o.getAttribute(e),r):i.setAttribute(e,t.defaultValue,r),n=!0;else i.removeAttribute(e,r)}return n}}(t,i)),t.conversion.for("upcast").add((n=i,t=>{t.on("element:li",((t,e,i)=>{const s=e.viewItem.parent,o=e.modelRange.start.nodeAfter||e.modelRange.end.nodeBefore;for(const t of n)if(t.appliesToListItem(o)){const e=t.getAttributeOnUpcast(s);i.writer.setAttribute(t.attributeName,e,o)}}),{priority:"low"})})),t.conversion.for("downcast").add(function(t){return i=>{for(const n of t)i.on(`attribute:${n.attributeName}:listItem`,((t,i,s)=>{const o=s.writer,r=i.item,a=Ob(r.previousSibling,{sameIndent:!0,listIndent:r.getAttribute("listIndent"),direction:"backward"}),l=s.mapper.toViewElement(r);e(r,a)||o.breakContainer(o.createPositionBefore(l)),n.setAttributeOnDowncast(o,i.attributeNewValue,l.parent)}),{priority:"low"})};function e(t,e){return e&&t.getAttribute("listType")===e.getAttribute("listType")&&t.getAttribute("listIndent")===e.getAttribute("listIndent")&&t.getAttribute("listStyle")===e.getAttribute("listStyle")&&t.getAttribute("listReversed")===e.getAttribute("listReversed")&&t.getAttribute("listStart")===e.getAttribute("listStart")}}(i)),this._mergeListAttributesWhileMergingLists(i)}afterInit(){const t=this.editor;t.commands.get("todoList")&&t.model.document.registerPostFixer(function(t){return e=>{const i=u_(t.model.document.differ.getChanges()).filter((t=>"todo"===t.getAttribute("listType")&&(t.hasAttribute("listStyle")||t.hasAttribute("listReversed")||t.hasAttribute("listStart"))));if(!i.length)return!1;for(const t of i)e.removeAttribute("listStyle",t),e.removeAttribute("listReversed",t),e.removeAttribute("listStart",t);return!0}}(t))}_mergeListAttributesWhileMergingLists(t){const e=this.editor.model;let i;this.listenTo(e,"deleteContent",((t,[e])=>{const n=e.getFirstPosition(),s=e.getLastPosition();if(n.parent===s.parent)return;if(!n.parent.is("element","listItem"))return;const o=s.parent.nextSibling;if(!o||!o.is("element","listItem"))return;const r=Ob(n.parent,{sameIndent:!0,listIndent:o.getAttribute("listIndent")});r&&r.getAttribute("listType")===o.getAttribute("listType")&&(i=r)}),{priority:"high"}),this.listenTo(e,"deleteContent",(()=>{i&&(e.change((e=>{const n=Ob(i.nextSibling,{sameIndent:!0,listIndent:i.getAttribute("listIndent"),direction:"forward"});if(!n)return void(i=null);const s=[n,...Vb(e.createPositionAt(n,0),"forward")];for(const n of s)for(const s of t)if(s.appliesToListItem(n)){const t=s.attributeName,o=i.getAttribute(t);e.setAttribute(t,o,n)}})),i=null)}),{priority:"low"})}}function c_(t,e,i){if(!t)return!1;const n=t.getAttribute(i.attributeName);return!!n&&(n!=i.defaultValue&&t.getAttribute("listType")===e.getAttribute("listType"))}function h_(t,e,i){if(!t||!t.is("element","listItem"))return!1;if(e.getAttribute("listType")!==t.getAttribute("listType"))return!1;const n=t.getAttribute("listIndent");if(n<1||n!==e.getAttribute("listIndent"))return!1;const s=t.getAttribute(i);return!(!s||s===e.getAttribute(i))}function d_(t){return(e,i)=>{i=i.filter((t=>t.is("element","listItem"))),t.model.change((t=>{for(const e of i)t.removeAttribute("listStyle",e)}))}}function u_(t){const e=[];for(const i of t){const t=f_(i);t&&t.is("element","listItem")&&e.push(t)}return e}function f_(t){return"attribute"===t.type?t.range.start.nodeAfter:"insert"===t.type?t.position.nodeAfter:null}class m_ extends yo{constructor(t,e){super(t);const i=this.bindTemplate;this.set("isCollapsed",!1),this.set("label",""),this.buttonView=this._createButtonView(),this.children=this.createCollection(),this.set("_collapsibleAriaLabelUid",void 0),e&&this.children.addMany(e),this.setTemplate({tag:"div",attributes:{class:["ck","ck-collapsible",i.if("isCollapsed","ck-collapsible_collapsed")]},children:[this.buttonView,{tag:"div",attributes:{class:["ck","ck-collapsible__children"],role:"region",hidden:i.if("isCollapsed","hidden"),"aria-labelledby":i.to("_collapsibleAriaLabelUid")},children:this.children}]})}render(){super.render(),this._collapsibleAriaLabelUid=this.buttonView.labelView.element.id}_createButtonView(){const t=new qo(this.locale),e=t.bindTemplate;return t.set({withText:!0,icon:Xo}),t.extendTemplate({attributes:{"aria-expanded":e.to("isOn",(t=>String(t)))}}),t.bind("label").to(this),t.bind("isOn").to(this,"isCollapsed",(t=>!t)),t.on("execute",(()=>{this.isCollapsed=!this.isCollapsed})),t}}class g_ extends yo{constructor(t,{enabledProperties:e,styleButtonViews:i,styleGridAriaLabel:n}){super(t),this.stylesView=null,this.additionalPropertiesCollapsibleView=null,this.startIndexFieldView=null,this.reversedSwitchButtonView=null,this.focusTracker=new uo,this.keystrokes=new fo,this.focusables=new vo;const s=["ck","ck-list-properties"];this.children=this.createCollection(),this.focusCycler=new nr({focusables:this.focusables,focusTracker:this.focusTracker,keystrokeHandler:this.keystrokes,actions:{focusPrevious:"shift + tab",focusNext:"tab"}}),e.styles?(this.stylesView=this._createStylesView(i,n),this.children.add(this.stylesView)):s.push("ck-list-properties_without-styles"),(e.startIndex||e.reversed)&&(this._addNumberedListPropertyViews(e),s.push("ck-list-properties_with-numbered-properties")),this.setTemplate({tag:"div",attributes:{class:s},children:this.children})}render(){if(super.render(),this.stylesView){this.focusables.add(this.stylesView),this.focusTracker.add(this.stylesView.element),(this.startIndexFieldView||this.reversedSwitchButtonView)&&(this.focusables.add(this.children.last.buttonView),this.focusTracker.add(this.children.last.buttonView.element));for(const t of this.stylesView.children)this.stylesView.focusTracker.add(t.element);n({keystrokeHandler:this.stylesView.keystrokes,focusTracker:this.stylesView.focusTracker,gridItems:this.stylesView.children,numberOfColumns:()=>vs.window.getComputedStyle(this.stylesView.element).getPropertyValue("grid-template-columns").split(" ").length,uiLanguageDirection:this.locale&&this.locale.uiLanguageDirection})}if(this.startIndexFieldView){this.focusables.add(this.startIndexFieldView),this.focusTracker.add(this.startIndexFieldView.element),this.listenTo(this.startIndexFieldView.element,"selectstart",((t,e)=>{e.stopPropagation()}),{priority:"high"});const t=t=>t.stopPropagation();this.keystrokes.set("arrowright",t),this.keystrokes.set("arrowleft",t),this.keystrokes.set("arrowup",t),this.keystrokes.set("arrowdown",t)}this.reversedSwitchButtonView&&(this.focusables.add(this.reversedSwitchButtonView),this.focusTracker.add(this.reversedSwitchButtonView.element)),this.keystrokes.listenTo(this.element)}focus(){this.focusCycler.focusFirst()}focusLast(){this.focusCycler.focusLast()}destroy(){super.destroy(),this.focusTracker.destroy(),this.keystrokes.destroy()}_createStylesView(t,e){const i=new yo(this.locale);return i.children=i.createCollection(),i.children.addMany(t),i.setTemplate({tag:"div",attributes:{"aria-label":e,class:["ck","ck-list-styles-list"]},children:i.children}),i.children.delegate("execute").to(this),i.focus=function(){this.children.first.focus()},i.focusTracker=new uo,i.keystrokes=new fo,i.render(),i.keystrokes.listenTo(i.element),i}_addNumberedListPropertyViews(t){const e=this.locale.t,i=[];t.startIndex&&(this.startIndexFieldView=this._createStartIndexField(),i.push(this.startIndexFieldView)),t.reversed&&(this.reversedSwitchButtonView=this._createReversedSwitchButton(),i.push(this.reversedSwitchButtonView)),t.styles?(this.additionalPropertiesCollapsibleView=new m_(this.locale,i),this.additionalPropertiesCollapsibleView.set({label:e("List properties"),isCollapsed:!0}),this.additionalPropertiesCollapsibleView.buttonView.bind("isEnabled").toMany(i,"isEnabled",((...t)=>t.some((t=>t)))),this.additionalPropertiesCollapsibleView.buttonView.on("change:isEnabled",((t,e,i)=>{i||(this.additionalPropertiesCollapsibleView.isCollapsed=!0)})),this.children.add(this.additionalPropertiesCollapsibleView)):this.children.addMany(i)}_createStartIndexField(){const t=this.locale.t,e=new em(this.locale,nm);return e.set({label:t("Start at"),class:"ck-numbered-list-properties__start-index"}),e.fieldView.set({min:0,step:1,value:1,inputMode:"numeric"}),e.fieldView.on("input",(()=>{const i=e.fieldView.element,n=i.valueAsNumber;Number.isNaN(n)||(i.checkValidity()?this.fire("listStart",{startIndex:n}):e.errorText=t("Start index must be greater than 0."))})),e}_createReversedSwitchButton(){const t=this.locale.t,e=new Uo(this.locale);return e.set({withText:!0,label:t("Reversed order"),class:"ck-numbered-list-properties__reversed-order"}),e.delegate("execute").to(this,"listReversed"),e}}class p_ extends lr{static get pluginName(){return"ListPropertiesUI"}init(){const t=this.editor,e=t.locale.t,i=t.config.get("list.properties");i.styles&&t.ui.componentFactory.add("bulletedList",w_({editor:t,parentCommandName:"bulletedList",buttonLabel:e("Bulleted List"),buttonIcon:i_,styleGridAriaLabel:e("Bulleted list styles toolbar"),styleDefinitions:[{label:e("Toggle the disc list style"),tooltip:e("Disc"),type:"disc",icon:''},{label:e("Toggle the circle list style"),tooltip:e("Circle"),type:"circle",icon:''},{label:e("Toggle the square list style"),tooltip:e("Square"),type:"square",icon:''}]})),(i.styles||i.startIndex||i.reversed)&&t.ui.componentFactory.add("numberedList",w_({editor:t,parentCommandName:"numberedList",buttonLabel:e("Numbered List"),buttonIcon:e_,styleGridAriaLabel:e("Numbered list styles toolbar"),styleDefinitions:[{label:e("Toggle the decimal list style"),tooltip:e("Decimal"),type:"decimal",icon:''},{label:e("Toggle the decimal with leading zero list style"),tooltip:e("Decimal with leading zero"),type:"decimal-leading-zero",icon:''},{label:e("Toggle the lower–roman list style"),tooltip:e("Lower–roman"),type:"lower-roman",icon:''},{label:e("Toggle the upper–roman list style"),tooltip:e("Upper-roman"),type:"upper-roman",icon:''},{label:e("Toggle the lower–latin list style"),tooltip:e("Lower-latin"),type:"lower-latin",icon:''},{label:e("Toggle the upper–latin list style"),tooltip:e("Upper-latin"),type:"upper-latin",icon:''}]}))}}function w_({editor:t,parentCommandName:e,buttonLabel:i,buttonIcon:n,styleGridAriaLabel:s,styleDefinitions:o}){const r=t.commands.get(e);return a=>{const l=Of(a,er),c=l.buttonView;return l.bind("isEnabled").to(r),l.class="ck-list-styles-dropdown",c.on("execute",(()=>{t.execute(e),t.editing.view.focus()})),c.set({label:i,icon:n,tooltip:!0,isToggleable:!0}),c.bind("isOn").to(r,"value",(t=>!!t)),l.once("change:isOpen",(()=>{const i=function({editor:t,dropdownView:e,parentCommandName:i,styleDefinitions:n,styleGridAriaLabel:s}){const o=t.locale,r=t.config.get("list.properties");let a=null;"numberedList"!=i&&(r.startIndex=!1,r.reversed=!1);if(r.styles){const e=t.commands.get("listStyle"),s=function({editor:t,listStyleCommand:e,parentCommandName:i}){const n=t.locale,s=t.commands.get(i);return({label:i,type:o,icon:r,tooltip:a})=>{const l=new qo(n);return l.set({label:i,icon:r,tooltip:a}),e.on("change:value",(()=>{l.isOn=e.value===o})),l.on("execute",(()=>{s.value?e.value!==o?t.execute("listStyle",{type:o}):t.execute("listStyle",{type:e.defaultType}):t.model.change((()=>{t.execute("listStyle",{type:o})}))})),l}}({editor:t,parentCommandName:i,listStyleCommand:e}),o="function"==typeof e.isStyleTypeSupported?t=>e.isStyleTypeSupported(t.type):()=>!0;a=n.filter(o).map(s)}const l=new g_(o,{styleGridAriaLabel:s,enabledProperties:r,styleButtonViews:a});r.styles&&Bf(e,(()=>l.stylesView.children.find((t=>t.isOn))));if(r.startIndex){const e=t.commands.get("listStart");l.startIndexFieldView.bind("isEnabled").to(e),l.startIndexFieldView.fieldView.bind("value").to(e),l.on("listStart",((e,i)=>t.execute("listStart",i)))}if(r.reversed){const e=t.commands.get("listReversed");l.reversedSwitchButtonView.bind("isEnabled").to(e),l.reversedSwitchButtonView.bind("isOn").to(e,"value",(t=>!!t)),l.on("listReversed",(()=>{const i=e.value;t.execute("listReversed",{reversed:!i})}))}return l.delegate("execute").to(e),l}({editor:t,dropdownView:l,parentCommandName:e,styleGridAriaLabel:s,styleDefinitions:o});l.panelView.children.add(i)})),l.on("execute",(()=>{t.editing.view.focus()})),l}}function b_(t,e,i,{blockElements:n,inlineObjectElements:s}){let o=i.createPositionAt(t,"forward"==e?"after":"before");return o=o.getLastMatchingPosition((({item:t})=>t.is("element")&&!n.includes(t.name)&&!s.includes(t.name)),{direction:e}),"forward"==e?o.nodeAfter:o.nodeBefore}function __(t,e){return!!t&&t.is("element")&&e.includes(t.name)}function v_(t,e){if(!t.childCount)return;const i=new cf(t.document),n=function(t,e){const i=e.createRangeIn(t),n=new Tr({name:/^p|h\d+$/,styles:{"mso-list":/.*/}}),s=[];for(const t of i)if("elementStart"===t.type&&n.match(t.item)){const e=A_(t.item);s.push({element:t.item,id:e.id,order:e.order,indent:e.indent})}return s}(t,i);if(!n.length)return;let s=null,o=1;n.forEach(((t,r)=>{const a=function(t,e){if(!t)return!0;if(t.id!==e.id)return e.indent-t.indent!=1;const i=e.element.previousSibling;if(!i)return!0;return n=i,!(n.is("element","ol")||n.is("element","ul"));var n}(n[r-1],t),l=a?null:n[r-1],c=(d=t,(h=l)?d.indent-h.indent:d.indent-1);var h,d;if(a&&(s=null,o=1),!s||0!==c){const n=function(t,e){const i=new RegExp(`@list l${t.id}:level${t.indent}\\s*({[^}]*)`,"gi"),n=/mso-level-number-format:([^;]{0,100});/gi,s=/mso-level-start-at:\s{0,100}([0-9]{0,10})\s{0,100};/gi,o=i.exec(e);let r="decimal",a="ol",l=null;if(o&&o[1]){const e=n.exec(o[1]);if(e&&e[1]&&(r=e[1].trim(),a="bullet"!==r&&"image"!==r?"ol":"ul"),"bullet"===r){const e=function(t){const e=function(t){if(t.getChild(0).is("$text"))return null;for(const e of t.getChildren()){if(!e.is("element","span"))continue;const t=e.getChild(0);return t.is("$text")?t:t.getChild(0)}return null}(t);if(!e)return null;const i=e._data;if("o"===i)return"circle";if("·"===i)return"disc";if("§"===i)return"square";return null}(t.element);e&&(r=e)}else{const t=s.exec(o[1]);t&&t[1]&&(l=parseInt(t[1]))}}return{type:a,startIndex:l,style:y_(r)}}(t,e);if(s){if(t.indent>o){const t=s.getChild(s.childCount-1),e=t.getChild(t.childCount-1);s=k_(n,e,i),o+=1}else if(t.indent1&&i.setAttribute("start",t.startIndex,s),s}function A_(t){const e={},i=t.getStyle("mso-list");if(i){const t=i.match(/(^|\s{1,100})l(\d+)/i),n=i.match(/\s{0,100}lfo(\d+)/i),s=i.match(/\s{0,100}level(\d+)/i);t&&n&&s&&(e.id=t[2],e.order=n[1],e.indent=parseInt(s[1]))}return e}const x_=/id=("|')docs-internal-guid-[-0-9a-f]+("|')/i;class C_{constructor(t){this.document=t}isActive(t){return x_.test(t)}execute(t){const e=new cf(this.document),{body:i}=t._parsedData;!function(t,e){for(const i of t.getChildren())if(i.is("element","b")&&"normal"===i.getStyle("font-weight")){const n=t.getChildIndex(i);e.remove(i),e.insertChild(n,i.getChildren(),t)}}(i,e),function(t,e){for(const i of e.createRangeIn(t)){const t=i.item;if(t.is("element","li")){const i=t.getChild(0);i&&i.is("element","p")&&e.unwrapElement(i)}}}(i,e),function(t,e){const i=new Xa(e.document.stylesProcessor),n=new jl(i,{renderingMode:"data"}),s=n.blockElements,o=n.inlineObjectElements,r=[];for(const i of e.createRangeIn(t)){const t=i.item;if(t.is("element","br")){const i=b_(t,"forward",e,{blockElements:s,inlineObjectElements:o}),n=b_(t,"backward",e,{blockElements:s,inlineObjectElements:o}),a=__(i,s);(__(n,s)||a)&&r.push(t)}}for(const t of r)t.hasClass("Apple-interchange-newline")?e.remove(t):e.replace(t,e.createElement("p"))}(i,e),t.content=i}}function P_(t,e){if(!t.childCount)return;const i=new cf(t.document),n=function(t,e){const i=e.createRangeIn(t),n=new Tr({name:/v:(.+)/}),s=[];for(const t of i){if("elementStart"!=t.type)continue;const e=t.item,i=e.previousSibling,o=i&&i.is("element")?i.name:null;n.match(e)&&e.getAttribute("o:gfxdata")&&"v:shapetype"!==o&&s.push(t.item.getAttribute("id"))}return s}(t,i);!function(t,e,i){const n=i.createRangeIn(e),s=new Tr({name:"img"}),o=[];for(const e of n)if(e.item.is("element")&&s.match(e.item)){const i=e.item,n=i.getAttribute("v:shapes")?i.getAttribute("v:shapes").split(" "):[];n.length&&n.every((e=>t.indexOf(e)>-1))?o.push(i):i.getAttribute("src")||o.push(i)}for(const t of o)i.remove(t)}(n,t,i),function(t,e,i){const n=i.createRangeIn(e),s=[];for(const e of n)if("elementStart"==e.type&&e.item.is("element","v:shape")){const i=e.item.getAttribute("id");if(t.includes(i))continue;o(e.item.parent.getChildren(),i)||s.push(e.item)}for(const t of s){const e={src:r(t)};t.hasAttribute("alt")&&(e.alt=t.getAttribute("alt"));const n=i.createElement("img",e);i.insertChild(t.index+1,n,t.parent)}function o(t,e){for(const i of t)if(i.is("element")){if("img"==i.name&&i.getAttribute("v:shapes")==e)return!0;if(o(i.getChildren(),e))return!0}return!1}function r(t){for(const e of t.getChildren())if(e.is("element")&&e.getAttribute("src"))return e.getAttribute("src")}}(n,t,i),function(t,e){const i=e.createRangeIn(t),n=new Tr({name:/v:(.+)/}),s=[];for(const t of i)"elementStart"==t.type&&n.match(t.item)&&s.push(t.item);for(const t of s)e.remove(t)}(t,i);const s=function(t,e){const i=e.createRangeIn(t),n=new Tr({name:"img"}),s=[];for(const t of i)t.item.is("element")&&n.match(t.item)&&t.item.getAttribute("src").startsWith("file://")&&s.push(t.item);return s}(t,i);s.length&&function(t,e,i){if(t.length===e.length)for(let n=0;nString.fromCharCode(parseInt(t,16)))).join(""))}const E_=//i,S_=/xmlns:o="urn:schemas-microsoft-com/i;class R_{constructor(t){this.document=t}isActive(t){return E_.test(t)||S_.test(t)}execute(t){const{body:e,stylesString:i}=t._parsedData;v_(e,i),P_(e,t.dataTransfer.getData("text/rtf")),t.content=e}}function O_(t){return t.replace(/(\s+)<\/span>/g,((t,e)=>1===e.length?" ":Array(e.length+1).join("  ").substr(0,e.length)))}function I_(t,e){const i=new DOMParser,n=function(t){return O_(O_(t)).replace(/([^\S\r\n]*?)[\r\n]+([^\S\r\n]*<\/span>)/g,"$1$2").replace(/<\/span>/g,"").replace(/ <\//g," <\/o:p>/g," ").replace(/( |\u00A0)<\/o:p>/g,"").replace(/>([^\S\r\n]*[\r\n]\s*)<")}(function(t){const e="",i="",n=t.indexOf(e);if(n<0)return t;const s=t.indexOf(i,n+e.length);return t.substring(0,n+e.length)+(s>=0?t.substring(s):"")}(t=t.replace(/

abc

+ // + if (isAttribute && this._wrapAttributeElement(wrapElement, child)) { + wrapPositions.push(new Position(parent, i)); + } + // + // Wrap the child if it is not an attribute element or if it is an attribute element that should be inside + // `wrapElement` (due to priority). + // + //

abc

-->

abc

+ //

abc

-->

abc

+ else if (isText || !isAttribute || shouldABeOutsideB(wrapElement, child)) { + // Clone attribute. + const newAttribute = wrapElement._clone(); + // Wrap current node with new attribute. + child._remove(); + newAttribute._appendChild(child); + parent._insertChild(i, newAttribute); + this._addToClonedElementsGroup(newAttribute); + wrapPositions.push(new Position(parent, i)); + } + // + // If other nested attribute is found and it wasn't wrapped (see above), continue wrapping inside it. + // + //

abc

-->

abc

+ // + else /* if ( isAttribute ) */ { + this._wrapChildren(child, 0, child.childCount, wrapElement); + } + i++; + } + // Merge at each wrap. + let offsetChange = 0; + for (const position of wrapPositions) { + position.offset -= offsetChange; + // Do not merge with elements outside selected children. + if (position.offset == startOffset) { + continue; + } + const newPosition = this.mergeAttributes(position); + // If nodes were merged - other merge offsets will change. + if (!newPosition.isEqual(position)) { + offsetChange++; + endOffset--; + } + } + return Range._createFromParentsAndOffsets(parent, startOffset, parent, endOffset); + } + /** + * Unwraps children from provided `unwrapElement`. Only children contained in `parent` element between + * `startOffset` and `endOffset` will be unwrapped. + */ + _unwrapChildren(parent, startOffset, endOffset, unwrapElement) { + let i = startOffset; + const unwrapPositions = []; + // Iterate over each element between provided offsets inside parent. + // We don't use tree walker or range iterator because we will be removing and merging potentially multiple nodes, + // so it could get messy. It is safer to it manually in this case. + while (i < endOffset) { + const child = parent.getChild(i); + // Skip all text nodes. There should be no container element's here either. + if (!child.is('attributeElement')) { + i++; + continue; + } + // + // (In all examples, assume that `unwrapElement` is `` element.) + // + // If the child is similar to the given attribute element, unwrap it - it will be completely removed. + // + //

abcxyz

-->

abcxyz

+ // + if (child.isSimilar(unwrapElement)) { + const unwrapped = child.getChildren(); + const count = child.childCount; + // Replace wrapper element with its children + child._remove(); + parent._insertChild(i, unwrapped); + this._removeFromClonedElementsGroup(child); + // Save start and end position of moved items. + unwrapPositions.push(new Position(parent, i), new Position(parent, i + count)); + // Skip elements that were unwrapped. Assuming there won't be another element to unwrap in child elements. + i += count; + endOffset += count - 1; + continue; + } + // + // If the child is not similar but is an attribute element, try partial unwrapping - remove the same attributes/styles/classes. + // Partial unwrapping will happen only if the elements have the same name. + // + //

abcxyz

-->

abcxyz

+ //

abcxyz

-->

abcxyz

+ // + if (this._unwrapAttributeElement(unwrapElement, child)) { + unwrapPositions.push(new Position(parent, i), new Position(parent, i + 1)); + i++; + continue; + } + // + // If other nested attribute is found, look through it's children for elements to unwrap. + // + //

abc

-->

abc

+ // + this._unwrapChildren(child, 0, child.childCount, unwrapElement); + i++; + } + // Merge at each unwrap. + let offsetChange = 0; + for (const position of unwrapPositions) { + position.offset -= offsetChange; + // Do not merge with elements outside selected children. + if (position.offset == startOffset || position.offset == endOffset) { + continue; + } + const newPosition = this.mergeAttributes(position); + // If nodes were merged - other merge offsets will change. + if (!newPosition.isEqual(position)) { + offsetChange++; + endOffset--; + } + } + return Range._createFromParentsAndOffsets(parent, startOffset, parent, endOffset); + } + /** + * Helper function for `view.writer.wrap`. Wraps range with provided attribute element. + * This method will also merge newly added attribute element with its siblings whenever possible. + * + * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not + * an instance of {@link module:engine/view/attributeelement~AttributeElement AttributeElement}. + * + * @returns New range after wrapping, spanning over wrapping attribute element. + */ + _wrapRange(range, attribute) { + // Break attributes at range start and end. + const { start: breakStart, end: breakEnd } = this._breakAttributesRange(range, true); + const parentContainer = breakStart.parent; + // Wrap all children with attribute. + const newRange = this._wrapChildren(parentContainer, breakStart.offset, breakEnd.offset, attribute); + // Merge attributes at the both ends and return a new range. + const start = this.mergeAttributes(newRange.start); + // If start position was merged - move end position back. + if (!start.isEqual(newRange.start)) { + newRange.end.offset--; + } + const end = this.mergeAttributes(newRange.end); + return new Range(start, end); + } + /** + * Helper function for {@link #wrap}. Wraps position with provided attribute element. + * This method will also merge newly added attribute element with its siblings whenever possible. + * + * Throws {@link module:utils/ckeditorerror~CKEditorError} `view-writer-wrap-invalid-attribute` when passed attribute element is not + * an instance of {@link module:engine/view/attributeelement~AttributeElement AttributeElement}. + * + * @returns New position after wrapping. + */ + _wrapPosition(position, attribute) { + // Return same position when trying to wrap with attribute similar to position parent. + if (attribute.isSimilar(position.parent)) { + return movePositionToTextNode(position.clone()); + } + // When position is inside text node - break it and place new position between two text nodes. + if (position.parent.is('$text')) { + position = breakTextNode(position); + } + // Create fake element that will represent position, and will not be merged with other attributes. + const fakeElement = this.createAttributeElement('_wrapPosition-fake-element'); + fakeElement._priority = Number.POSITIVE_INFINITY; + fakeElement.isSimilar = () => false; + // Insert fake element in position location. + position.parent._insertChild(position.offset, fakeElement); + // Range around inserted fake attribute element. + const wrapRange = new Range(position, position.getShiftedBy(1)); + // Wrap fake element with attribute (it will also merge if possible). + this.wrap(wrapRange, attribute); + // Remove fake element and place new position there. + const newPosition = new Position(fakeElement.parent, fakeElement.index); + fakeElement._remove(); + // If position is placed between text nodes - merge them and return position inside. + const nodeBefore = newPosition.nodeBefore; + const nodeAfter = newPosition.nodeAfter; + if (nodeBefore instanceof text_Text && nodeAfter instanceof text_Text) { + return mergeTextNodes(nodeBefore, nodeAfter); + } + // If position is next to text node - move position inside. + return movePositionToTextNode(newPosition); + } + /** + * Wraps one {@link module:engine/view/attributeelement~AttributeElement AttributeElement} into another by + * merging them if possible. When merging is possible - all attributes, styles and classes are moved from wrapper + * element to element being wrapped. + * + * @param wrapper Wrapper AttributeElement. + * @param toWrap AttributeElement to wrap using wrapper element. + * @returns Returns `true` if elements are merged. + */ + _wrapAttributeElement(wrapper, toWrap) { + if (!canBeJoined(wrapper, toWrap)) { + return false; + } + // Can't merge if name or priority differs. + if (wrapper.name !== toWrap.name || wrapper.priority !== toWrap.priority) { + return false; + } + // Check if attributes can be merged. + for (const key of wrapper.getAttributeKeys()) { + // Classes and styles should be checked separately. + if (key === 'class' || key === 'style') { + continue; + } + // If some attributes are different we cannot wrap. + if (toWrap.hasAttribute(key) && toWrap.getAttribute(key) !== wrapper.getAttribute(key)) { + return false; + } + } + // Check if styles can be merged. + for (const key of wrapper.getStyleNames()) { + if (toWrap.hasStyle(key) && toWrap.getStyle(key) !== wrapper.getStyle(key)) { + return false; + } + } + // Move all attributes/classes/styles from wrapper to wrapped AttributeElement. + for (const key of wrapper.getAttributeKeys()) { + // Classes and styles should be checked separately. + if (key === 'class' || key === 'style') { + continue; + } + // Move only these attributes that are not present - other are similar. + if (!toWrap.hasAttribute(key)) { + this.setAttribute(key, wrapper.getAttribute(key), toWrap); + } + } + for (const key of wrapper.getStyleNames()) { + if (!toWrap.hasStyle(key)) { + this.setStyle(key, wrapper.getStyle(key), toWrap); + } + } + for (const key of wrapper.getClassNames()) { + if (!toWrap.hasClass(key)) { + this.addClass(key, toWrap); + } + } + return true; + } + /** + * Unwraps {@link module:engine/view/attributeelement~AttributeElement AttributeElement} from another by removing + * corresponding attributes, classes and styles. All attributes, classes and styles from wrapper should be present + * inside element being unwrapped. + * + * @param wrapper Wrapper AttributeElement. + * @param toUnwrap AttributeElement to unwrap using wrapper element. + * @returns Returns `true` if elements are unwrapped. + **/ + _unwrapAttributeElement(wrapper, toUnwrap) { + if (!canBeJoined(wrapper, toUnwrap)) { + return false; + } + // Can't unwrap if name or priority differs. + if (wrapper.name !== toUnwrap.name || wrapper.priority !== toUnwrap.priority) { + return false; + } + // Check if AttributeElement has all wrapper attributes. + for (const key of wrapper.getAttributeKeys()) { + // Classes and styles should be checked separately. + if (key === 'class' || key === 'style') { + continue; + } + // If some attributes are missing or different we cannot unwrap. + if (!toUnwrap.hasAttribute(key) || toUnwrap.getAttribute(key) !== wrapper.getAttribute(key)) { + return false; + } + } + // Check if AttributeElement has all wrapper classes. + if (!toUnwrap.hasClass(...wrapper.getClassNames())) { + return false; + } + // Check if AttributeElement has all wrapper styles. + for (const key of wrapper.getStyleNames()) { + // If some styles are missing or different we cannot unwrap. + if (!toUnwrap.hasStyle(key) || toUnwrap.getStyle(key) !== wrapper.getStyle(key)) { + return false; + } + } + // Remove all wrapper's attributes from unwrapped element. + for (const key of wrapper.getAttributeKeys()) { + // Classes and styles should be checked separately. + if (key === 'class' || key === 'style') { + continue; + } + this.removeAttribute(key, toUnwrap); + } + // Remove all wrapper's classes from unwrapped element. + this.removeClass(Array.from(wrapper.getClassNames()), toUnwrap); + // Remove all wrapper's styles from unwrapped element. + this.removeStyle(Array.from(wrapper.getStyleNames()), toUnwrap); + return true; + } + /** + * Helper function used by other `DowncastWriter` methods. Breaks attribute elements at the boundaries of given range. + * + * @param range Range which `start` and `end` positions will be used to break attributes. + * @param forceSplitText If set to `true`, will break text nodes even if they are directly in container element. + * This behavior will result in incorrect view state, but is needed by other view writing methods which then fixes view state. + * @returns New range with located at break positions. + */ + _breakAttributesRange(range, forceSplitText = false) { + const rangeStart = range.start; + const rangeEnd = range.end; + validateRangeContainer(range, this.document); + // Break at the collapsed position. Return new collapsed range. + if (range.isCollapsed) { + const position = this._breakAttributes(range.start, forceSplitText); + return new Range(position, position); + } + const breakEnd = this._breakAttributes(rangeEnd, forceSplitText); + const count = breakEnd.parent.childCount; + const breakStart = this._breakAttributes(rangeStart, forceSplitText); + // Calculate new break end offset. + breakEnd.offset += breakEnd.parent.childCount - count; + return new Range(breakStart, breakEnd); + } + /** + * Helper function used by other `DowncastWriter` methods. Breaks attribute elements at given position. + * + * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-empty-element` when break position + * is placed inside {@link module:engine/view/emptyelement~EmptyElement EmptyElement}. + * + * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-cannot-break-ui-element` when break position + * is placed inside {@link module:engine/view/uielement~UIElement UIElement}. + * + * @param position Position where to break attributes. + * @param forceSplitText If set to `true`, will break text nodes even if they are directly in container element. + * This behavior will result in incorrect view state, but is needed by other view writing methods which then fixes view state. + * @returns New position after breaking the attributes. + */ + _breakAttributes(position, forceSplitText = false) { + const positionOffset = position.offset; + const positionParent = position.parent; + // If position is placed inside EmptyElement - throw an exception as we cannot break inside. + if (position.parent.is('emptyElement')) { + /** + * Cannot break an `EmptyElement` instance. + * + * This error is thrown if + * {@link module:engine/view/downcastwriter~DowncastWriter#breakAttributes `DowncastWriter#breakAttributes()`} + * was executed in an incorrect position. + * + * @error view-writer-cannot-break-empty-element + */ + throw new ckeditorerror_CKEditorError('view-writer-cannot-break-empty-element', this.document); + } + // If position is placed inside UIElement - throw an exception as we cannot break inside. + if (position.parent.is('uiElement')) { + /** + * Cannot break a `UIElement` instance. + * + * This error is thrown if + * {@link module:engine/view/downcastwriter~DowncastWriter#breakAttributes `DowncastWriter#breakAttributes()`} + * was executed in an incorrect position. + * + * @error view-writer-cannot-break-ui-element + */ + throw new ckeditorerror_CKEditorError('view-writer-cannot-break-ui-element', this.document); + } + // If position is placed inside RawElement - throw an exception as we cannot break inside. + if (position.parent.is('rawElement')) { + /** + * Cannot break a `RawElement` instance. + * + * This error is thrown if + * {@link module:engine/view/downcastwriter~DowncastWriter#breakAttributes `DowncastWriter#breakAttributes()`} + * was executed in an incorrect position. + * + * @error view-writer-cannot-break-raw-element + */ + throw new ckeditorerror_CKEditorError('view-writer-cannot-break-raw-element', this.document); + } + // There are no attributes to break and text nodes breaking is not forced. + if (!forceSplitText && positionParent.is('$text') && isContainerOrFragment(positionParent.parent)) { + return position.clone(); + } + // Position's parent is container, so no attributes to break. + if (isContainerOrFragment(positionParent)) { + return position.clone(); + } + // Break text and start again in new position. + if (positionParent.is('$text')) { + return this._breakAttributes(breakTextNode(position), forceSplitText); + } + const length = positionParent.childCount; + //

foobar{}

+ //

foobar[]

+ //

foobar[]

+ if (positionOffset == length) { + const newPosition = new Position(positionParent.parent, positionParent.index + 1); + return this._breakAttributes(newPosition, forceSplitText); + } + else { + //

foo{}bar

+ //

foo[]bar

+ //

foo{}bar

+ if (positionOffset === 0) { + const newPosition = new Position(positionParent.parent, positionParent.index); + return this._breakAttributes(newPosition, forceSplitText); + } + //

foob{}ar

+ //

foob[]ar

+ //

foob[]ar

+ //

foob[]ar

+ else { + const offsetAfter = positionParent.index + 1; + // Break element. + const clonedNode = positionParent._clone(); + // Insert cloned node to position's parent node. + positionParent.parent._insertChild(offsetAfter, clonedNode); + this._addToClonedElementsGroup(clonedNode); + // Get nodes to move. + const count = positionParent.childCount - positionOffset; + const nodesToMove = positionParent._removeChildren(positionOffset, count); + // Move nodes to cloned node. + clonedNode._appendChild(nodesToMove); + // Create new position to work on. + const newPosition = new Position(positionParent.parent, offsetAfter); + return this._breakAttributes(newPosition, forceSplitText); + } + } + } + /** + * Stores the information that an {@link module:engine/view/attributeelement~AttributeElement attribute element} was + * added to the tree. Saves the reference to the group in the given element and updates the group, so other elements + * from the group now keep a reference to the given attribute element. + * + * The clones group can be obtained using {@link module:engine/view/attributeelement~AttributeElement#getElementsWithSameId}. + * + * Does nothing if added element has no {@link module:engine/view/attributeelement~AttributeElement#id id}. + * + * @param element Attribute element to save. + */ + _addToClonedElementsGroup(element) { + // Add only if the element is in document tree. + if (!element.root.is('rootElement')) { + return; + } + // Traverse the element's children recursively to find other attribute elements that also might got inserted. + // The loop is at the beginning so we can make fast returns later in the code. + if (element.is('element')) { + for (const child of element.getChildren()) { + this._addToClonedElementsGroup(child); + } + } + const id = element.id; + if (!id) { + return; + } + let group = this._cloneGroups.get(id); + if (!group) { + group = new Set(); + this._cloneGroups.set(id, group); + } + group.add(element); + element._clonesGroup = group; + } + /** + * Removes all the information about the given {@link module:engine/view/attributeelement~AttributeElement attribute element} + * from its clones group. + * + * Keep in mind, that the element will still keep a reference to the group (but the group will not keep a reference to it). + * This allows to reference the whole group even if the element was already removed from the tree. + * + * Does nothing if the element has no {@link module:engine/view/attributeelement~AttributeElement#id id}. + * + * @param element Attribute element to remove. + */ + _removeFromClonedElementsGroup(element) { + // Traverse the element's children recursively to find other attribute elements that also got removed. + // The loop is at the beginning so we can make fast returns later in the code. + if (element.is('element')) { + for (const child of element.getChildren()) { + this._removeFromClonedElementsGroup(child); + } + } + const id = element.id; + if (!id) { + return; + } + const group = this._cloneGroups.get(id); + if (!group) { + return; + } + group.delete(element); + // Not removing group from element on purpose! + // If other parts of code have reference to this element, they will be able to get references to other elements from the group. + } +} +// Helper function for `view.writer.wrap`. Checks if given element has any children that are not ui elements. +function _hasNonUiChildren(parent) { + return Array.from(parent.getChildren()).some(child => !child.is('uiElement')); +} +/** + * The `attribute` passed to {@link module:engine/view/downcastwriter~DowncastWriter#wrap `DowncastWriter#wrap()`} + * must be an instance of {@link module:engine/view/attributeelement~AttributeElement `AttributeElement`}. + * + * @error view-writer-wrap-invalid-attribute + */ +/** + * Returns first parent container of specified {@link module:engine/view/position~Position Position}. + * Position's parent node is checked as first, then next parents are checked. + * Note that {@link module:engine/view/documentfragment~DocumentFragment DocumentFragment} is treated like a container. + * + * @param position Position used as a start point to locate parent container. + * @returns Parent container element or `undefined` if container is not found. + */ +function getParentContainer(position) { + let parent = position.parent; + while (!isContainerOrFragment(parent)) { + if (!parent) { + return undefined; + } + parent = parent.parent; + } + return parent; +} +/** + * Checks if first {@link module:engine/view/attributeelement~AttributeElement AttributeElement} provided to the function + * can be wrapped outside second element. It is done by comparing elements' + * {@link module:engine/view/attributeelement~AttributeElement#priority priorities}, if both have same priority + * {@link module:engine/view/element~Element#getIdentity identities} are compared. + */ +function shouldABeOutsideB(a, b) { + if (a.priority < b.priority) { + return true; + } + else if (a.priority > b.priority) { + return false; + } + // When priorities are equal and names are different - use identities. + return a.getIdentity() < b.getIdentity(); +} +/** + * Returns new position that is moved to near text node. Returns same position if there is no text node before of after + * specified position. + * + * ```html + *

foo[]

->

foo{}

+ *

[]foo

->

{}foo

+ * ``` + * + * @returns Position located inside text node or same position if there is no text nodes + * before or after position location. + */ +function movePositionToTextNode(position) { + const nodeBefore = position.nodeBefore; + if (nodeBefore && nodeBefore.is('$text')) { + return new Position(nodeBefore, nodeBefore.data.length); + } + const nodeAfter = position.nodeAfter; + if (nodeAfter && nodeAfter.is('$text')) { + return new Position(nodeAfter, 0); + } + return position; +} +/** + * Breaks text node into two text nodes when possible. + * + * ```html + *

foo{}bar

->

foo[]bar

+ *

{}foobar

->

[]foobar

+ *

foobar{}

->

foobar[]

+ * ``` + * + * @param position Position that need to be placed inside text node. + * @returns New position after breaking text node. + */ +function breakTextNode(position) { + if (position.offset == position.parent.data.length) { + return new Position(position.parent.parent, position.parent.index + 1); + } + if (position.offset === 0) { + return new Position(position.parent.parent, position.parent.index); + } + // Get part of the text that need to be moved. + const textToMove = position.parent.data.slice(position.offset); + // Leave rest of the text in position's parent. + position.parent._data = position.parent.data.slice(0, position.offset); + // Insert new text node after position's parent text node. + position.parent.parent._insertChild(position.parent.index + 1, new text_Text(position.root.document, textToMove)); + // Return new position between two newly created text nodes. + return new Position(position.parent.parent, position.parent.index + 1); +} +/** + * Merges two text nodes into first node. Removes second node and returns merge position. + * + * @param t1 First text node to merge. Data from second text node will be moved at the end of this text node. + * @param t2 Second text node to merge. This node will be removed after merging. + * @returns Position after merging text nodes. + */ +function mergeTextNodes(t1, t2) { + // Merge text data into first text node and remove second one. + const nodeBeforeLength = t1.data.length; + t1._data += t2.data; + t2._remove(); + return new Position(t1, nodeBeforeLength); +} +const validNodesToInsert = [text_Text, AttributeElement, ContainerElement, EmptyElement, RawElement, UIElement]; +/** + * Checks if provided nodes are valid to insert. + * + * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-insert-invalid-node` when nodes to insert + * contains instances that are not supported ones (see error description for valid ones. + */ +function validateNodesToInsert(nodes, errorContext) { + for (const node of nodes) { + if (!validNodesToInsert.some((validNode => node instanceof validNode))) { // eslint-disable-line no-use-before-define + /** + * One of the nodes to be inserted is of an invalid type. + * + * Nodes to be inserted with {@link module:engine/view/downcastwriter~DowncastWriter#insert `DowncastWriter#insert()`} should be + * of the following types: + * + * * {@link module:engine/view/attributeelement~AttributeElement AttributeElement}, + * * {@link module:engine/view/containerelement~ContainerElement ContainerElement}, + * * {@link module:engine/view/emptyelement~EmptyElement EmptyElement}, + * * {@link module:engine/view/uielement~UIElement UIElement}, + * * {@link module:engine/view/rawelement~RawElement RawElement}, + * * {@link module:engine/view/text~Text Text}. + * + * @error view-writer-insert-invalid-node-type + */ + throw new ckeditorerror_CKEditorError('view-writer-insert-invalid-node-type', errorContext); + } + if (!node.is('$text')) { + validateNodesToInsert(node.getChildren(), errorContext); + } + } +} +/** + * Checks if node is ContainerElement or DocumentFragment, because in most cases they should be treated the same way. + * + * @returns Returns `true` if node is instance of ContainerElement or DocumentFragment. + */ +function isContainerOrFragment(node) { + return node && (node.is('containerElement') || node.is('documentFragment')); +} +/** + * Checks if {@link module:engine/view/range~Range#start range start} and {@link module:engine/view/range~Range#end range end} are placed + * inside same {@link module:engine/view/containerelement~ContainerElement container element}. + * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `view-writer-invalid-range-container` when validation fails. + */ +function validateRangeContainer(range, errorContext) { + const startContainer = getParentContainer(range.start); + const endContainer = getParentContainer(range.end); + if (!startContainer || !endContainer || startContainer !== endContainer) { + /** + * The container of the given range is invalid. + * + * This may happen if {@link module:engine/view/range~Range#start range start} and + * {@link module:engine/view/range~Range#end range end} positions are not placed inside the same container element or + * a parent container for these positions cannot be found. + * + * Methods like {@link module:engine/view/downcastwriter~DowncastWriter#wrap `DowncastWriter#remove()`}, + * {@link module:engine/view/downcastwriter~DowncastWriter#wrap `DowncastWriter#clean()`}, + * {@link module:engine/view/downcastwriter~DowncastWriter#wrap `DowncastWriter#wrap()`}, + * {@link module:engine/view/downcastwriter~DowncastWriter#wrap `DowncastWriter#unwrap()`} need to be called + * on a range that has its start and end positions located in the same container element. Both positions can be + * nested within other elements (e.g. an attribute element) but the closest container ancestor must be the same. + * + * @error view-writer-invalid-range-container + */ + throw new ckeditorerror_CKEditorError('view-writer-invalid-range-container', errorContext); + } +} +/** + * Checks if two attribute elements can be joined together. Elements can be joined together if, and only if + * they do not have ids specified. + */ +function canBeJoined(a, b) { + return a.id === null && b.id === null; +} + +;// CONCATENATED MODULE: ./node_modules/@ckeditor/ckeditor5-engine/src/view/filler.js +/** + * @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved. + * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license + */ + +/** + * Set of utilities related to handling block and inline fillers. + * + * Browsers do not allow to put caret in elements which does not have height. Because of it, we need to fill all + * empty elements which should be selectable with elements or characters called "fillers". Unfortunately there is no one + * universal filler, this is why two types are uses: + * + * * Block filler is an element which fill block elements, like `

`. CKEditor uses `
` as a block filler during the editing, + * as browsers do natively. So instead of an empty `

` there will be `


`. The advantage of block filler is that + * it is transparent for the selection, so when the caret is before the `
` and user presses right arrow he will be + * moved to the next paragraph, not after the `
`. The disadvantage is that it breaks a block, so it can not be used + * in the middle of a line of text. The {@link module:engine/view/filler~BR_FILLER `
` filler} can be replaced with any other + * character in the data output, for instance {@link module:engine/view/filler~NBSP_FILLER non-breaking space} or + * {@link module:engine/view/filler~MARKED_NBSP_FILLER marked non-breaking space}. + * + * * Inline filler is a filler which does not break a line of text, so it can be used inside the text, for instance in the empty + * `` surrendered by text: `foobar`, if we want to put the caret there. CKEditor uses a sequence of the zero-width + * spaces as an {@link module:engine/view/filler~INLINE_FILLER inline filler} having the predetermined + * {@link module:engine/view/filler~INLINE_FILLER_LENGTH length}. A sequence is used, instead of a single character to + * avoid treating random zero-width spaces as the inline filler. Disadvantage of the inline filler is that it is not + * transparent for the selection. The arrow key moves the caret between zero-width spaces characters, so the additional + * code is needed to handle the caret. + * + * Both inline and block fillers are handled by the {@link module:engine/view/renderer~Renderer renderer} and are not present in the + * view. + * + * @module engine/view/filler + */ +/** + * Non-breaking space filler creator. This function creates the ` ` text node. + * It defines how the filler is created. + * + * @see module:engine/view/filler~MARKED_NBSP_FILLER + * @see module:engine/view/filler~BR_FILLER + */ +const NBSP_FILLER = (domDocument) => domDocument.createTextNode('\u00A0'); +/** + * Marked non-breaking space filler creator. This function creates the ` ` element. + * It defines how the filler is created. + * + * @see module:engine/view/filler~NBSP_FILLER + * @see module:engine/view/filler~BR_FILLER + */ +const MARKED_NBSP_FILLER = (domDocument) => { + const span = domDocument.createElement('span'); + span.dataset.ckeFiller = 'true'; + span.innerText = '\u00A0'; + return span; +}; +/** + * `
` filler creator. This function creates the `
` element. + * It defines how the filler is created. + * + * @see module:engine/view/filler~NBSP_FILLER + * @see module:engine/view/filler~MARKED_NBSP_FILLER + */ +const BR_FILLER = (domDocument) => { + const fillerBr = domDocument.createElement('br'); + fillerBr.dataset.ckeFiller = 'true'; + return fillerBr; +}; +/** + * Length of the {@link module:engine/view/filler~INLINE_FILLER INLINE_FILLER}. + */ +const INLINE_FILLER_LENGTH = 7; +/** + * Inline filler which is a sequence of the word joiners. + */ +const INLINE_FILLER = '\u2060'.repeat(INLINE_FILLER_LENGTH); +/** + * Checks if the node is a text node which starts with the {@link module:engine/view/filler~INLINE_FILLER inline filler}. + * + * ```ts + * startsWithFiller( document.createTextNode( INLINE_FILLER ) ); // true + * startsWithFiller( document.createTextNode( INLINE_FILLER + 'foo' ) ); // true + * startsWithFiller( document.createTextNode( 'foo' ) ); // false + * startsWithFiller( document.createElement( 'p' ) ); // false + * ``` + * + * @param domNode DOM node. + * @returns True if the text node starts with the {@link module:engine/view/filler~INLINE_FILLER inline filler}. + */ +function startsWithFiller(domNode) { + return isText(domNode) && (domNode.data.substr(0, INLINE_FILLER_LENGTH) === INLINE_FILLER); +} +/** + * Checks if the text node contains only the {@link module:engine/view/filler~INLINE_FILLER inline filler}. + * + * ```ts + * isInlineFiller( document.createTextNode( INLINE_FILLER ) ); // true + * isInlineFiller( document.createTextNode( INLINE_FILLER + 'foo' ) ); // false + * ``` + * + * @param domText DOM text node. + * @returns True if the text node contains only the {@link module:engine/view/filler~INLINE_FILLER inline filler}. + */ +function isInlineFiller(domText) { + return domText.data.length == INLINE_FILLER_LENGTH && startsWithFiller(domText); +} +/** + * Get string data from the text node, removing an {@link module:engine/view/filler~INLINE_FILLER inline filler} from it, + * if text node contains it. + * + * ```ts + * getDataWithoutFiller( document.createTextNode( INLINE_FILLER + 'foo' ) ) == 'foo' // true + * getDataWithoutFiller( document.createTextNode( 'foo' ) ) == 'foo' // true + * ``` + * + * @param domText DOM text node, possible with inline filler. + * @returns Data without filler. + */ +function getDataWithoutFiller(domText) { + if (startsWithFiller(domText)) { + return domText.data.slice(INLINE_FILLER_LENGTH); + } + else { + return domText.data; + } +} +/** + * Assign key observer which move cursor from the end of the inline filler to the beginning of it when + * the left arrow is pressed, so the filler does not break navigation. + * + * @param view View controller instance we should inject quirks handling on. + */ +function injectQuirksHandling(view) { + view.document.on('arrowKey', jumpOverInlineFiller, { priority: 'low' }); +} +/** + * Move cursor from the end of the inline filler to the beginning of it when, so the filler does not break navigation. + */ +function jumpOverInlineFiller(evt, data) { + if (data.keyCode == keyCodes.arrowleft) { + const domSelection = data.domTarget.ownerDocument.defaultView.getSelection(); + if (domSelection.rangeCount == 1 && domSelection.getRangeAt(0).collapsed) { + const domParent = domSelection.getRangeAt(0).startContainer; + const domOffset = domSelection.getRangeAt(0).startOffset; + if (startsWithFiller(domParent) && domOffset <= INLINE_FILLER_LENGTH) { + domSelection.collapse(domParent, 0); + } + } + } +} + +;// CONCATENATED MODULE: ./node_modules/@ckeditor/ckeditor5-engine/src/view/renderer.js +/** + * @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved. + * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license + */ +/** + * @module engine/view/renderer + */ + + + + + +/** + * Renderer is responsible for updating the DOM structure and the DOM selection based on + * the {@link module:engine/view/renderer~Renderer#markToSync information about updated view nodes}. + * In other words, it renders the view to the DOM. + * + * Its main responsibility is to make only the necessary, minimal changes to the DOM. However, unlike in many + * virtual DOM implementations, the primary reason for doing minimal changes is not the performance but ensuring + * that native editing features such as text composition, autocompletion, spell checking, selection's x-index are + * affected as little as possible. + * + * Renderer uses {@link module:engine/view/domconverter~DomConverter} to transform view nodes and positions + * to and from the DOM. + */ +class Renderer extends ObservableMixin() { + /** + * Creates a renderer instance. + * + * @param domConverter Converter instance. + * @param selection View selection. + */ + constructor(domConverter, selection) { + super(); + /** + * Set of DOM Documents instances. + */ + this.domDocuments = new Set(); + /** + * Set of nodes which attributes changed and may need to be rendered. + */ + this.markedAttributes = new Set(); + /** + * Set of elements which child lists changed and may need to be rendered. + */ + this.markedChildren = new Set(); + /** + * Set of text nodes which text data changed and may need to be rendered. + */ + this.markedTexts = new Set(); + /** + * The text node in which the inline filler was rendered. + */ + this._inlineFiller = null; + /** + * DOM element containing fake selection. + */ + this._fakeSelectionContainer = null; + this.domConverter = domConverter; + this.selection = selection; + this.set('isFocused', false); + this.set('isSelecting', false); + // Rendering the selection and inline filler manipulation should be postponed in (non-Android) Blink until the user finishes + // creating the selection in DOM to avoid accidental selection collapsing + // (https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723). + // When the user stops selecting, all pending changes should be rendered ASAP, though. + if (src_env.isBlink && !src_env.isAndroid) { + this.on('change:isSelecting', () => { + if (!this.isSelecting) { + this.render(); + } + }); + } + this.set('isComposing', false); + this.on('change:isComposing', () => { + if (!this.isComposing) { + this.render(); + } + }); + } + /** + * Marks a view node to be updated in the DOM by {@link #render `render()`}. + * + * Note that only view nodes whose parents have corresponding DOM elements need to be marked to be synchronized. + * + * @see #markedAttributes + * @see #markedChildren + * @see #markedTexts + * + * @param type Type of the change. + * @param node ViewNode to be marked. + */ + markToSync(type, node) { + if (type === 'text') { + if (this.domConverter.mapViewToDom(node.parent)) { + this.markedTexts.add(node); + } + } + else { + // If the node has no DOM element it is not rendered yet, + // its children/attributes do not need to be marked to be sync. + if (!this.domConverter.mapViewToDom(node)) { + return; + } + if (type === 'attributes') { + this.markedAttributes.add(node); + } + else if (type === 'children') { + this.markedChildren.add(node); + } + else { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const unreachable = type; + /** + * Unknown type passed to Renderer.markToSync. + * + * @error view-renderer-unknown-type + */ + throw new ckeditorerror_CKEditorError('view-renderer-unknown-type', this); + } + } + } + /** + * Renders all buffered changes ({@link #markedAttributes}, {@link #markedChildren} and {@link #markedTexts}) and + * the current view selection (if needed) to the DOM by applying a minimal set of changes to it. + * + * Renderer tries not to break the text composition (e.g. IME) and x-index of the selection, + * so it does as little as it is needed to update the DOM. + * + * Renderer also handles {@link module:engine/view/filler fillers}. Especially, it checks if the inline filler is needed + * at the selection position and adds or removes it. To prevent breaking text composition inline filler will not be + * removed as long as the selection is in the text node which needed it at first. + */ + render() { + // Ignore rendering while in the composition mode. Composition events are not cancellable and browser will modify the DOM tree. + // All marked elements, attributes, etc. will wait until next render after the composition ends. + // On Android composition events are immediately applied to the model, so we don't need to skip rendering, + // and we should not do it because the difference between view and DOM could lead to position mapping problems. + if (this.isComposing && !src_env.isAndroid) { + // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) { + // @if CK_DEBUG_TYPING // console.info( '%c[Renderer]%c Rendering aborted while isComposing', + // @if CK_DEBUG_TYPING // 'color: green;font-weight: bold', '' + // @if CK_DEBUG_TYPING // ); + // @if CK_DEBUG_TYPING // } + return; + } + // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) { + // @if CK_DEBUG_TYPING // console.group( '%c[Renderer]%c Rendering', + // @if CK_DEBUG_TYPING // 'color: green;font-weight: bold', '' + // @if CK_DEBUG_TYPING // ); + // @if CK_DEBUG_TYPING // } + let inlineFillerPosition = null; + const isInlineFillerRenderingPossible = src_env.isBlink && !src_env.isAndroid ? !this.isSelecting : true; + // Refresh mappings. + for (const element of this.markedChildren) { + this._updateChildrenMappings(element); + } + // Don't manipulate inline fillers while the selection is being made in (non-Android) Blink to prevent accidental + // DOM selection collapsing + // (https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723). + if (isInlineFillerRenderingPossible) { + // There was inline filler rendered in the DOM but it's not + // at the selection position any more, so we can remove it + // (cause even if it's needed, it must be placed in another location). + if (this._inlineFiller && !this._isSelectionInInlineFiller()) { + this._removeInlineFiller(); + } + // If we've got the filler, let's try to guess its position in the view. + if (this._inlineFiller) { + inlineFillerPosition = this._getInlineFillerPosition(); + } + // Otherwise, if it's needed, create it at the selection position. + else if (this._needsInlineFillerAtSelection()) { + inlineFillerPosition = this.selection.getFirstPosition(); + // Do not use `markToSync` so it will be added even if the parent is already added. + this.markedChildren.add(inlineFillerPosition.parent); + } + } + // Make sure the inline filler has any parent, so it can be mapped to view position by DomConverter. + else if (this._inlineFiller && this._inlineFiller.parentNode) { + // While the user is making selection, preserve the inline filler at its original position. + inlineFillerPosition = this.domConverter.domPositionToView(this._inlineFiller); + // While down-casting the document selection attributes, all existing empty + // attribute elements (for selection position) are removed from the view and DOM, + // so make sure that we were able to map filler position. + // https://github.com/ckeditor/ckeditor5/issues/12026 + if (inlineFillerPosition && inlineFillerPosition.parent.is('$text')) { + // The inline filler position is expected to be before the text node. + inlineFillerPosition = Position._createBefore(inlineFillerPosition.parent); + } + } + for (const element of this.markedAttributes) { + this._updateAttrs(element); + } + for (const element of this.markedChildren) { + this._updateChildren(element, { inlineFillerPosition }); + } + for (const node of this.markedTexts) { + if (!this.markedChildren.has(node.parent) && this.domConverter.mapViewToDom(node.parent)) { + this._updateText(node, { inlineFillerPosition }); + } + } + // * Check whether the inline filler is required and where it really is in the DOM. + // At this point in most cases it will be in the DOM, but there are exceptions. + // For example, if the inline filler was deep in the created DOM structure, it will not be created. + // Similarly, if it was removed at the beginning of this function and then neither text nor children were updated, + // it will not be present. Fix those and similar scenarios. + // * Don't manipulate inline fillers while the selection is being made in (non-Android) Blink to prevent accidental + // DOM selection collapsing + // (https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723). + if (isInlineFillerRenderingPossible) { + if (inlineFillerPosition) { + const fillerDomPosition = this.domConverter.viewPositionToDom(inlineFillerPosition); + const domDocument = fillerDomPosition.parent.ownerDocument; + if (!startsWithFiller(fillerDomPosition.parent)) { + // Filler has not been created at filler position. Create it now. + this._inlineFiller = addInlineFiller(domDocument, fillerDomPosition.parent, fillerDomPosition.offset); + } + else { + // Filler has been found, save it. + this._inlineFiller = fillerDomPosition.parent; + } + } + else { + // There is no filler needed. + this._inlineFiller = null; + } + } + // First focus the new editing host, then update the selection. + // Otherwise, FF may throw an error (https://github.com/ckeditor/ckeditor5/issues/721). + this._updateFocus(); + this._updateSelection(); + this.markedTexts.clear(); + this.markedAttributes.clear(); + this.markedChildren.clear(); + // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) { + // @if CK_DEBUG_TYPING // console.groupEnd(); + // @if CK_DEBUG_TYPING // } + } + /** + * Updates mappings of view element's children. + * + * Children that were replaced in the view structure by similar elements (same tag name) are treated as 'replaced'. + * This means that their mappings can be updated so the new view elements are mapped to the existing DOM elements. + * Thanks to that these elements do not need to be re-rendered completely. + * + * @param viewElement The view element whose children mappings will be updated. + */ + _updateChildrenMappings(viewElement) { + const domElement = this.domConverter.mapViewToDom(viewElement); + if (!domElement) { + // If there is no `domElement` it means that it was already removed from DOM and there is no need to process it. + return; + } + // Removing nodes from the DOM as we iterate can cause `actualDomChildren` + // (which is a live-updating `NodeList`) to get out of sync with the + // indices that we compute as we iterate over `actions`. + // This would produce incorrect element mappings. + // + // Converting live list to an array to make the list static. + const actualDomChildren = Array.from(this.domConverter.mapViewToDom(viewElement).childNodes); + const expectedDomChildren = Array.from(this.domConverter.viewChildrenToDom(viewElement, { withChildren: false })); + const diff = this._diffNodeLists(actualDomChildren, expectedDomChildren); + const actions = this._findUpdateActions(diff, actualDomChildren, expectedDomChildren, areSimilarElements); + if (actions.indexOf('update') !== -1) { + const counter = { equal: 0, insert: 0, delete: 0 }; + for (const action of actions) { + if (action === 'update') { + const insertIndex = counter.equal + counter.insert; + const deleteIndex = counter.equal + counter.delete; + const viewChild = viewElement.getChild(insertIndex); + // UIElement and RawElement are special cases. Their children are not stored in a view (#799) + // so we cannot use them with replacing flow (since they use view children during rendering + // which will always result in rendering empty elements). + if (viewChild && !(viewChild.is('uiElement') || viewChild.is('rawElement'))) { + this._updateElementMappings(viewChild, actualDomChildren[deleteIndex]); + } + remove(expectedDomChildren[insertIndex]); + counter.equal++; + } + else { + counter[action]++; + } + } + } + } + /** + * Updates mappings of a given view element. + * + * @param viewElement The view element whose mappings will be updated. + * @param domElement The DOM element representing the given view element. + */ + _updateElementMappings(viewElement, domElement) { + // Remap 'DomConverter' bindings. + this.domConverter.unbindDomElement(domElement); + this.domConverter.bindElements(domElement, viewElement); + // View element may have children which needs to be updated, but are not marked, mark them to update. + this.markedChildren.add(viewElement); + // Because we replace new view element mapping with the existing one, the corresponding DOM element + // will not be rerendered. The new view element may have different attributes than the previous one. + // Since its corresponding DOM element will not be rerendered, new attributes will not be added + // to the DOM, so we need to mark it here to make sure its attributes gets updated. See #1427 for more + // detailed case study. + // Also there are cases where replaced element is removed from the view structure and then has + // its attributes changed or removed. In such cases the element will not be present in `markedAttributes` + // and also may be the same (`element.isSimilar()`) as the reused element not having its attributes updated. + // To prevent such situations we always mark reused element to have its attributes rerenderd (#1560). + this.markedAttributes.add(viewElement); + } + /** + * Gets the position of the inline filler based on the current selection. + * Here, we assume that we know that the filler is needed and + * {@link #_isSelectionInInlineFiller is at the selection position}, and, since it is needed, + * it is somewhere at the selection position. + * + * Note: The filler position cannot be restored based on the filler's DOM text node, because + * when this method is called (before rendering), the bindings will often be broken. View-to-DOM + * bindings are only dependable after rendering. + */ + _getInlineFillerPosition() { + const firstPos = this.selection.getFirstPosition(); + if (firstPos.parent.is('$text')) { + return Position._createBefore(firstPos.parent); + } + else { + return firstPos; + } + } + /** + * Returns `true` if the selection has not left the inline filler's text node. + * If it is `true`, it means that the filler had been added for a reason and the selection did not + * leave the filler's text node. For example, the user can be in the middle of a composition so it should not be touched. + * + * @returns `true` if the inline filler and selection are in the same place. + */ + _isSelectionInInlineFiller() { + if (this.selection.rangeCount != 1 || !this.selection.isCollapsed) { + return false; + } + // Note, we can't check if selection's position equals position of the + // this._inlineFiller node, because of #663. We may not be able to calculate + // the filler's position in the view at this stage. + // Instead, we check it the other way – whether selection is anchored in + // that text node or next to it. + // Possible options are: + // "FILLER{}" + // "FILLERadded-text{}" + const selectionPosition = this.selection.getFirstPosition(); + const position = this.domConverter.viewPositionToDom(selectionPosition); + if (position && isText(position.parent) && startsWithFiller(position.parent)) { + return true; + } + return false; + } + /** + * Removes the inline filler. + */ + _removeInlineFiller() { + const domFillerNode = this._inlineFiller; + // Something weird happened and the stored node doesn't contain the filler's text. + if (!startsWithFiller(domFillerNode)) { + /** + * The inline filler node was lost. Most likely, something overwrote the filler text node + * in the DOM. + * + * @error view-renderer-filler-was-lost + */ + throw new ckeditorerror_CKEditorError('view-renderer-filler-was-lost', this); + } + if (isInlineFiller(domFillerNode)) { + domFillerNode.remove(); + } + else { + domFillerNode.data = domFillerNode.data.substr(INLINE_FILLER_LENGTH); + } + this._inlineFiller = null; + } + /** + * Checks if the inline {@link module:engine/view/filler filler} should be added. + * + * @returns `true` if the inline filler should be added. + */ + _needsInlineFillerAtSelection() { + if (this.selection.rangeCount != 1 || !this.selection.isCollapsed) { + return false; + } + const selectionPosition = this.selection.getFirstPosition(); + const selectionParent = selectionPosition.parent; + const selectionOffset = selectionPosition.offset; + // If there is no DOM root we do not care about fillers. + if (!this.domConverter.mapViewToDom(selectionParent.root)) { + return false; + } + if (!(selectionParent.is('element'))) { + return false; + } + // Prevent adding inline filler inside elements with contenteditable=false. + // https://github.com/ckeditor/ckeditor5-engine/issues/1170 + if (!isEditable(selectionParent)) { + return false; + } + // We have block filler, we do not need inline one. + if (selectionOffset === selectionParent.getFillerOffset()) { + return false; + } + const nodeBefore = selectionPosition.nodeBefore; + const nodeAfter = selectionPosition.nodeAfter; + if (nodeBefore instanceof text_Text || nodeAfter instanceof text_Text) { + return false; + } + // Do not use inline filler while typing outside inline elements on Android. + // The deleteContentBackward would remove part of the inline filler instead of removing last letter in a link. + if (src_env.isAndroid && (nodeBefore || nodeAfter)) { + return false; + } + return true; + } + /** + * Checks if text needs to be updated and possibly updates it. + * + * @param viewText View text to update. + * @param options.inlineFillerPosition The position where the inline filler should be rendered. + */ + _updateText(viewText, options) { + const domText = this.domConverter.findCorrespondingDomText(viewText); + const newDomText = this.domConverter.viewToDom(viewText); + let expectedText = newDomText.data; + const filler = options.inlineFillerPosition; + if (filler && filler.parent == viewText.parent && filler.offset == viewText.index) { + expectedText = INLINE_FILLER + expectedText; + } + // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) { + // @if CK_DEBUG_TYPING // console.group( '%c[Renderer]%c Update text', + // @if CK_DEBUG_TYPING // 'color: green;font-weight: bold', '' + // @if CK_DEBUG_TYPING // ); + // @if CK_DEBUG_TYPING // } + updateTextNode(domText, expectedText); + // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) { + // @if CK_DEBUG_TYPING // console.groupEnd(); + // @if CK_DEBUG_TYPING // } + } + /** + * Checks if attribute list needs to be updated and possibly updates it. + * + * @param viewElement The view element to update. + */ + _updateAttrs(viewElement) { + const domElement = this.domConverter.mapViewToDom(viewElement); + if (!domElement) { + // If there is no `domElement` it means that 'viewElement' is outdated as its mapping was updated + // in 'this._updateChildrenMappings()'. There is no need to process it as new view element which + // replaced old 'viewElement' mapping was also added to 'this.markedAttributes' + // in 'this._updateChildrenMappings()' so it will be processed separately. + return; + } + const domAttrKeys = Array.from(domElement.attributes).map(attr => attr.name); + const viewAttrKeys = viewElement.getAttributeKeys(); + // Add or overwrite attributes. + for (const key of viewAttrKeys) { + this.domConverter.setDomElementAttribute(domElement, key, viewElement.getAttribute(key), viewElement); + } + // Remove from DOM attributes which do not exists in the view. + for (const key of domAttrKeys) { + // All other attributes not present in the DOM should be removed. + if (!viewElement.hasAttribute(key)) { + this.domConverter.removeDomElementAttribute(domElement, key); + } + } + } + /** + * Checks if elements child list needs to be updated and possibly updates it. + * + * Note that on Android, to reduce the risk of composition breaks, it tries to update data of an existing + * child text nodes instead of replacing them completely. + * + * @param viewElement View element to update. + * @param options.inlineFillerPosition The position where the inline filler should be rendered. + */ + _updateChildren(viewElement, options) { + const domElement = this.domConverter.mapViewToDom(viewElement); + if (!domElement) { + // If there is no `domElement` it means that it was already removed from DOM. + // There is no need to process it. It will be processed when re-inserted. + return; + } + // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) { + // @if CK_DEBUG_TYPING // console.group( '%c[Renderer]%c Update children', + // @if CK_DEBUG_TYPING // 'color: green;font-weight: bold', '' + // @if CK_DEBUG_TYPING // ); + // @if CK_DEBUG_TYPING // } + // IME on Android inserts a new text node while typing after a link + // instead of updating an existing text node that follows the link. + // We must normalize those text nodes so the diff won't get confused. + // https://github.com/ckeditor/ckeditor5/issues/12574. + if (src_env.isAndroid) { + let previousDomNode = null; + for (const domNode of Array.from(domElement.childNodes)) { + if (previousDomNode && isText(previousDomNode) && isText(domNode)) { + domElement.normalize(); + break; + } + previousDomNode = domNode; + } + } + const inlineFillerPosition = options.inlineFillerPosition; + const actualDomChildren = domElement.childNodes; + const expectedDomChildren = Array.from(this.domConverter.viewChildrenToDom(viewElement, { bind: true })); + // Inline filler element has to be created as it is present in the DOM, but not in the view. It is required + // during diffing so text nodes could be compared correctly and also during rendering to maintain + // proper order and indexes while updating the DOM. + if (inlineFillerPosition && inlineFillerPosition.parent === viewElement) { + addInlineFiller(domElement.ownerDocument, expectedDomChildren, inlineFillerPosition.offset); + } + const diff = this._diffNodeLists(actualDomChildren, expectedDomChildren); + // We need to make sure that we update the existing text node and not replace it with another one. + // The composition and different "language" browser extensions are fragile to text node being completely replaced. + const actions = this._findUpdateActions(diff, actualDomChildren, expectedDomChildren, areTextNodes); + let i = 0; + const nodesToUnbind = new Set(); + // Handle deletions first. + // This is to prevent a situation where an element that already exists in `actualDomChildren` is inserted at a different + // index in `actualDomChildren`. Since `actualDomChildren` is a `NodeList`, this works like move, not like an insert, + // and it disrupts the whole algorithm. See https://github.com/ckeditor/ckeditor5/issues/6367. + // + // It doesn't matter in what order we remove or add nodes, as long as we remove and add correct nodes at correct indexes. + for (const action of actions) { + if (action === 'delete') { + // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) { + // @if CK_DEBUG_TYPING // console.info( '%c[Renderer]%c Remove node', + // @if CK_DEBUG_TYPING // 'color: green;font-weight: bold', '', actualDomChildren[ i ] + // @if CK_DEBUG_TYPING // ); + // @if CK_DEBUG_TYPING // } + nodesToUnbind.add(actualDomChildren[i]); + remove(actualDomChildren[i]); + } + else if (action === 'equal' || action === 'update') { + i++; + } + } + i = 0; + for (const action of actions) { + if (action === 'insert') { + // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) { + // @if CK_DEBUG_TYPING // console.info( '%c[Renderer]%c Insert node', + // @if CK_DEBUG_TYPING // 'color: green;font-weight: bold', '', expectedDomChildren[ i ] + // @if CK_DEBUG_TYPING // ); + // @if CK_DEBUG_TYPING // } + insertAt(domElement, i, expectedDomChildren[i]); + i++; + } + // Update the existing text node data. Note that replace action is generated only for Android for now. + else if (action === 'update') { + // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) { + // @if CK_DEBUG_TYPING // console.group( '%c[Renderer]%c Update text node', + // @if CK_DEBUG_TYPING // 'color: green;font-weight: bold', '' + // @if CK_DEBUG_TYPING // ); + // @if CK_DEBUG_TYPING // } + updateTextNode(actualDomChildren[i], expectedDomChildren[i].data); + i++; + // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) { + // @if CK_DEBUG_TYPING // console.groupEnd(); + // @if CK_DEBUG_TYPING // } + } + else if (action === 'equal') { + // Force updating text nodes inside elements which did not change and do not need to be re-rendered (#1125). + // Do it here (not in the loop above) because only after insertions the `i` index is correct. + this._markDescendantTextToSync(this.domConverter.domToView(expectedDomChildren[i])); + i++; + } + } + // Unbind removed nodes. When node does not have a parent it means that it was removed from DOM tree during + // comparison with the expected DOM. We don't need to check child nodes, because if child node was reinserted, + // it was moved to DOM tree out of the removed node. + for (const node of nodesToUnbind) { + if (!node.parentNode) { + this.domConverter.unbindDomElement(node); + } + } + // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) { + // @if CK_DEBUG_TYPING // console.groupEnd(); + // @if CK_DEBUG_TYPING // } + } + /** + * Shorthand for diffing two arrays or node lists of DOM nodes. + * + * @param actualDomChildren Actual DOM children + * @param expectedDomChildren Expected DOM children. + * @returns The list of actions based on the {@link module:utils/diff~diff} function. + */ + _diffNodeLists(actualDomChildren, expectedDomChildren) { + actualDomChildren = filterOutFakeSelectionContainer(actualDomChildren, this._fakeSelectionContainer); + return diff(actualDomChildren, expectedDomChildren, sameNodes.bind(null, this.domConverter)); + } + /** + * Finds DOM nodes that were replaced with the similar nodes (same tag name) in the view. All nodes are compared + * within one `insert`/`delete` action group, for example: + * + * ``` + * Actual DOM:

FooBarBazBax

+ * Expected DOM:

Bar123Baz456

+ * Input actions: [ insert, insert, delete, delete, equal, insert, delete ] + * Output actions: [ insert, replace, delete, equal, replace ] + * ``` + * + * @param actions Actions array which is a result of the {@link module:utils/diff~diff} function. + * @param actualDom Actual DOM children + * @param expectedDom Expected DOM children. + * @param comparator A comparator function that should return `true` if the given node should be reused + * (either by the update of a text node data or an element children list for similar elements). + * @returns Actions array modified with the `update` actions. + */ + _findUpdateActions(actions, actualDom, expectedDom, comparator) { + // If there is no both 'insert' and 'delete' actions, no need to check for replaced elements. + if (actions.indexOf('insert') === -1 || actions.indexOf('delete') === -1) { + return actions; + } + let newActions = []; + let actualSlice = []; + let expectedSlice = []; + const counter = { equal: 0, insert: 0, delete: 0 }; + for (const action of actions) { + if (action === 'insert') { + expectedSlice.push(expectedDom[counter.equal + counter.insert]); + } + else if (action === 'delete') { + actualSlice.push(actualDom[counter.equal + counter.delete]); + } + else { // equal + newActions = newActions.concat(diff(actualSlice, expectedSlice, comparator) + .map(action => action === 'equal' ? 'update' : action)); + newActions.push('equal'); + // Reset stored elements on 'equal'. + actualSlice = []; + expectedSlice = []; + } + counter[action]++; + } + return newActions.concat(diff(actualSlice, expectedSlice, comparator) + .map(action => action === 'equal' ? 'update' : action)); + } + /** + * Marks text nodes to be synchronized. + * + * If a text node is passed, it will be marked. If an element is passed, all descendant text nodes inside it will be marked. + * + * @param viewNode View node to sync. + */ + _markDescendantTextToSync(viewNode) { + if (!viewNode) { + return; + } + if (viewNode.is('$text')) { + this.markedTexts.add(viewNode); + } + else if (viewNode.is('element')) { + for (const child of viewNode.getChildren()) { + this._markDescendantTextToSync(child); + } + } + } + /** + * Checks if the selection needs to be updated and possibly updates it. + */ + _updateSelection() { + // Block updating DOM selection in (non-Android) Blink while the user is selecting to prevent accidental selection collapsing. + // Note: Structural changes in DOM must trigger selection rendering, though. Nodes the selection was anchored + // to, may disappear in DOM which would break the selection (e.g. in real-time collaboration scenarios). + // https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723 + if (src_env.isBlink && !src_env.isAndroid && this.isSelecting && !this.markedChildren.size) { + return; + } + // If there is no selection - remove DOM and fake selections. + if (this.selection.rangeCount === 0) { + this._removeDomSelection(); + this._removeFakeSelection(); + return; + } + const domRoot = this.domConverter.mapViewToDom(this.selection.editableElement); + // Do nothing if there is no focus, or there is no DOM element corresponding to selection's editable element. + if (!this.isFocused || !domRoot) { + return; + } + // Render fake selection - create the fake selection container (if needed) and move DOM selection to it. + if (this.selection.isFake) { + this._updateFakeSelection(domRoot); + } + // There was a fake selection so remove it and update the DOM selection. + // This is especially important on Android because otherwise IME will try to compose over the fake selection container. + else if (this._fakeSelectionContainer && this._fakeSelectionContainer.isConnected) { + this._removeFakeSelection(); + this._updateDomSelection(domRoot); + } + // Update the DOM selection in case of a plain selection change (no fake selection is involved). + // On non-Android the whole rendering is disabled in composition mode (including DOM selection update), + // but updating DOM selection should be also disabled on Android if in the middle of the composition + // (to not interrupt it). + else if (!(this.isComposing && src_env.isAndroid)) { + this._updateDomSelection(domRoot); + } + } + /** + * Updates the fake selection. + * + * @param domRoot A valid DOM root where the fake selection container should be added. + */ + _updateFakeSelection(domRoot) { + const domDocument = domRoot.ownerDocument; + if (!this._fakeSelectionContainer) { + this._fakeSelectionContainer = createFakeSelectionContainer(domDocument); + } + const container = this._fakeSelectionContainer; + // Bind fake selection container with the current selection *position*. + this.domConverter.bindFakeSelection(container, this.selection); + if (!this._fakeSelectionNeedsUpdate(domRoot)) { + return; + } + if (!container.parentElement || container.parentElement != domRoot) { + domRoot.appendChild(container); + } + container.textContent = this.selection.fakeSelectionLabel || '\u00A0'; + const domSelection = domDocument.getSelection(); + const domRange = domDocument.createRange(); + domSelection.removeAllRanges(); + domRange.selectNodeContents(container); + domSelection.addRange(domRange); + } + /** + * Updates the DOM selection. + * + * @param domRoot A valid DOM root where the DOM selection should be rendered. + */ + _updateDomSelection(domRoot) { + const domSelection = domRoot.ownerDocument.defaultView.getSelection(); + // Let's check whether DOM selection needs updating at all. + if (!this._domSelectionNeedsUpdate(domSelection)) { + return; + } + // Multi-range selection is not available in most browsers, and, at least in Chrome, trying to + // set such selection, that is not continuous, throws an error. Because of that, we will just use anchor + // and focus of view selection. + // Since we are not supporting multi-range selection, we also do not need to check if proper editable is + // selected. If there is any editable selected, it is okay (editable is taken from selection anchor). + const anchor = this.domConverter.viewPositionToDom(this.selection.anchor); + const focus = this.domConverter.viewPositionToDom(this.selection.focus); + // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) { + // @if CK_DEBUG_TYPING // console.info( '%c[Renderer]%c Update DOM selection:', + // @if CK_DEBUG_TYPING // 'color: green;font-weight: bold', '', anchor, focus + // @if CK_DEBUG_TYPING // ); + // @if CK_DEBUG_TYPING // } + domSelection.collapse(anchor.parent, anchor.offset); + domSelection.extend(focus.parent, focus.offset); + // Firefox–specific hack (https://github.com/ckeditor/ckeditor5-engine/issues/1439). + if (src_env.isGecko) { + fixGeckoSelectionAfterBr(focus, domSelection); + } + } + /** + * Checks whether a given DOM selection needs to be updated. + * + * @param domSelection The DOM selection to check. + */ + _domSelectionNeedsUpdate(domSelection) { + if (!this.domConverter.isDomSelectionCorrect(domSelection)) { + // Current DOM selection is in incorrect position. We need to update it. + return true; + } + const oldViewSelection = domSelection && this.domConverter.domSelectionToView(domSelection); + if (oldViewSelection && this.selection.isEqual(oldViewSelection)) { + return false; + } + // If selection is not collapsed, it does not need to be updated if it is similar. + if (!this.selection.isCollapsed && this.selection.isSimilar(oldViewSelection)) { + // Selection did not changed and is correct, do not update. + return false; + } + // Selections are not similar. + return true; + } + /** + * Checks whether the fake selection needs to be updated. + * + * @param domRoot A valid DOM root where a new fake selection container should be added. + */ + _fakeSelectionNeedsUpdate(domRoot) { + const container = this._fakeSelectionContainer; + const domSelection = domRoot.ownerDocument.getSelection(); + // Fake selection needs to be updated if there's no fake selection container, or the container currently sits + // in a different root. + if (!container || container.parentElement !== domRoot) { + return true; + } + // Make sure that the selection actually is within the fake selection. + if (domSelection.anchorNode !== container && !container.contains(domSelection.anchorNode)) { + return true; + } + return container.textContent !== this.selection.fakeSelectionLabel; + } + /** + * Removes the DOM selection. + */ + _removeDomSelection() { + for (const doc of this.domDocuments) { + const domSelection = doc.getSelection(); + if (domSelection.rangeCount) { + const activeDomElement = doc.activeElement; + const viewElement = this.domConverter.mapDomToView(activeDomElement); + if (activeDomElement && viewElement) { + domSelection.removeAllRanges(); + } + } + } + } + /** + * Removes the fake selection. + */ + _removeFakeSelection() { + const container = this._fakeSelectionContainer; + if (container) { + container.remove(); + } + } + /** + * Checks if focus needs to be updated and possibly updates it. + */ + _updateFocus() { + if (this.isFocused) { + const editable = this.selection.editableElement; + if (editable) { + this.domConverter.focus(editable); + } + } + } +} +/** + * Checks if provided element is editable. + */ +function isEditable(element) { + if (element.getAttribute('contenteditable') == 'false') { + return false; + } + const parent = element.findAncestor(element => element.hasAttribute('contenteditable')); + return !parent || parent.getAttribute('contenteditable') == 'true'; +} +/** + * Adds inline filler at a given position. + * + * The position can be given as an array of DOM nodes and an offset in that array, + * or a DOM parent element and an offset in that element. + * + * @returns The DOM text node that contains an inline filler. + */ +function addInlineFiller(domDocument, domParentOrArray, offset) { + const childNodes = domParentOrArray instanceof Array ? domParentOrArray : domParentOrArray.childNodes; + const nodeAfterFiller = childNodes[offset]; + if (isText(nodeAfterFiller)) { + nodeAfterFiller.data = INLINE_FILLER + nodeAfterFiller.data; + return nodeAfterFiller; + } + else { + const fillerNode = domDocument.createTextNode(INLINE_FILLER); + if (Array.isArray(domParentOrArray)) { + childNodes.splice(offset, 0, fillerNode); + } + else { + insertAt(domParentOrArray, offset, fillerNode); + } + return fillerNode; + } +} +/** + * Whether two DOM nodes should be considered as similar. + * Nodes are considered similar if they have the same tag name. + */ +function areSimilarElements(node1, node2) { + return isNode(node1) && isNode(node2) && + !isText(node1) && !isText(node2) && + !isComment(node1) && !isComment(node2) && + node1.tagName.toLowerCase() === node2.tagName.toLowerCase(); +} +/** + * Whether two DOM nodes are text nodes. + */ +function areTextNodes(node1, node2) { + return isNode(node1) && isNode(node2) && + isText(node1) && isText(node2); +} +/** + * Whether two dom nodes should be considered as the same. + * Two nodes which are considered the same are: + * + * * Text nodes with the same text. + * * Element nodes represented by the same object. + * * Two block filler elements. + * + * @param blockFillerMode Block filler mode, see {@link module:engine/view/domconverter~DomConverter#blockFillerMode}. + */ +function sameNodes(domConverter, actualDomChild, expectedDomChild) { + // Elements. + if (actualDomChild === expectedDomChild) { + return true; + } + // Texts. + else if (isText(actualDomChild) && isText(expectedDomChild)) { + return actualDomChild.data === expectedDomChild.data; + } + // Block fillers. + else if (domConverter.isBlockFiller(actualDomChild) && + domConverter.isBlockFiller(expectedDomChild)) { + return true; + } + // Not matching types. + return false; +} +/** + * The following is a Firefox–specific hack (https://github.com/ckeditor/ckeditor5-engine/issues/1439). + * When the native DOM selection is at the end of the block and preceded by
e.g. + * + * ```html + *

foo
[]

+ * ``` + * + * which happens a lot when using the soft line break, the browser fails to (visually) move the + * caret to the new line. A quick fix is as simple as force–refreshing the selection with the same range. + */ +function fixGeckoSelectionAfterBr(focus, domSelection) { + const parent = focus.parent; + // This fix works only when the focus point is at the very end of an element. + // There is no point in running it in cases unrelated to the browser bug. + if (parent.nodeType != Node.ELEMENT_NODE || focus.offset != parent.childNodes.length - 1) { + return; + } + const childAtOffset = parent.childNodes[focus.offset]; + // To stay on the safe side, the fix being as specific as possible, it targets only the + // selection which is at the very end of the element and preceded by
. + if (childAtOffset && childAtOffset.tagName == 'BR') { + domSelection.addRange(domSelection.getRangeAt(0)); + } +} +function filterOutFakeSelectionContainer(domChildList, fakeSelectionContainer) { + const childList = Array.from(domChildList); + if (childList.length == 0 || !fakeSelectionContainer) { + return childList; + } + const last = childList[childList.length - 1]; + if (last == fakeSelectionContainer) { + childList.pop(); + } + return childList; +} +/** + * Creates a fake selection container for a given document. + */ +function createFakeSelectionContainer(domDocument) { + const container = domDocument.createElement('div'); + container.className = 'ck-fake-selection-container'; + Object.assign(container.style, { + position: 'fixed', + top: 0, + left: '-9999px', + // See https://github.com/ckeditor/ckeditor5/issues/752. + width: '42px' + }); + // Fill it with a text node so we can update it later. + container.textContent = '\u00A0'; + return container; +} +/** + * Checks if text needs to be updated and possibly updates it by removing and inserting only parts + * of the data from the existing text node to reduce impact on the IME composition. + * + * @param domText DOM text node to update. + * @param expectedText The expected data of a text node. + */ +function updateTextNode(domText, expectedText) { + const actualText = domText.data; + if (actualText == expectedText) { + // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) { + // @if CK_DEBUG_TYPING // console.info( '%c[Renderer]%c Text node does not need update:', + // @if CK_DEBUG_TYPING // 'color: green;font-weight: bold', '', + // @if CK_DEBUG_TYPING // `"${ domText.data }" (${ domText.data.length })` + // @if CK_DEBUG_TYPING // ); + // @if CK_DEBUG_TYPING // } + return; + } + // @if CK_DEBUG_TYPING // if ( ( window as any ).logCKETyping ) { + // @if CK_DEBUG_TYPING // console.info( '%c[Renderer]%c Update text node:', + // @if CK_DEBUG_TYPING // 'color: green;font-weight: bold', '', + // @if CK_DEBUG_TYPING // `"${ domText.data }" (${ domText.data.length }) -> "${ expectedText }" (${ expectedText.length })` + // @if CK_DEBUG_TYPING // ); + // @if CK_DEBUG_TYPING // } + const actions = fastDiff(actualText, expectedText); + for (const action of actions) { + if (action.type === 'insert') { + domText.insertData(action.index, action.values.join('')); + } + else { // 'delete' + domText.deleteData(action.index, action.howMany); + } + } +} + +;// CONCATENATED MODULE: ./node_modules/@ckeditor/ckeditor5-engine/src/view/domconverter.js +/** + * @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved. + * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license + */ +/** + * @module engine/view/domconverter + */ +/* globals Node, NodeFilter, DOMParser, Text */ + + + + + + + + + + + +const BR_FILLER_REF = BR_FILLER(dom_global.document); // eslint-disable-line new-cap +const NBSP_FILLER_REF = NBSP_FILLER(dom_global.document); // eslint-disable-line new-cap +const MARKED_NBSP_FILLER_REF = MARKED_NBSP_FILLER(dom_global.document); // eslint-disable-line new-cap +const UNSAFE_ATTRIBUTE_NAME_PREFIX = 'data-ck-unsafe-attribute-'; +const UNSAFE_ELEMENT_REPLACEMENT_ATTRIBUTE = 'data-ck-unsafe-element'; +/** + * `DomConverter` is a set of tools to do transformations between DOM nodes and view nodes. It also handles + * {@link module:engine/view/domconverter~DomConverter#bindElements bindings} between these nodes. + * + * An instance of the DOM converter is available under + * {@link module:engine/view/view~View#domConverter `editor.editing.view.domConverter`}. + * + * The DOM converter does not check which nodes should be rendered (use {@link module:engine/view/renderer~Renderer}), does not keep the + * state of a tree nor keeps the synchronization between the tree view and the DOM tree (use {@link module:engine/view/document~Document}). + * + * The DOM converter keeps DOM elements to view element bindings, so when the converter gets destroyed, the bindings are lost. + * Two converters will keep separate binding maps, so one tree view can be bound with two DOM trees. + */ +class DomConverter { + /** + * Creates a DOM converter. + * + * @param document The view document instance. + * @param options An object with configuration options. + * @param options.blockFillerMode The type of the block filler to use. + * Default value depends on the options.renderingMode: + * 'nbsp' when options.renderingMode == 'data', + * 'br' when options.renderingMode == 'editing'. + * @param options.renderingMode Whether to leave the View-to-DOM conversion result unchanged + * or improve editing experience by filtering out interactive data. + */ + constructor(document, { blockFillerMode, renderingMode = 'editing' } = {}) { + /** + * The DOM-to-view mapping. + */ + this._domToViewMapping = new WeakMap(); + /** + * The view-to-DOM mapping. + */ + this._viewToDomMapping = new WeakMap(); + /** + * Holds the mapping between fake selection containers and corresponding view selections. + */ + this._fakeSelectionMapping = new WeakMap(); + /** + * Matcher for view elements whose content should be treated as raw data + * and not processed during the conversion from DOM nodes to view elements. + */ + this._rawContentElementMatcher = new Matcher(); + /** + * A set of encountered raw content DOM nodes. It is used for preventing left trimming of the following text node. + */ + this._encounteredRawContentDomNodes = new WeakSet(); + this.document = document; + this.renderingMode = renderingMode; + this.blockFillerMode = blockFillerMode || (renderingMode === 'editing' ? 'br' : 'nbsp'); + this.preElements = ['pre']; + this.blockElements = [ + 'address', 'article', 'aside', 'blockquote', 'caption', 'center', 'dd', 'details', 'dir', 'div', + 'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', + 'hgroup', 'legend', 'li', 'main', 'menu', 'nav', 'ol', 'p', 'pre', 'section', 'summary', 'table', 'tbody', + 'td', 'tfoot', 'th', 'thead', 'tr', 'ul' + ]; + this.inlineObjectElements = [ + 'object', 'iframe', 'input', 'button', 'textarea', 'select', 'option', 'video', 'embed', 'audio', 'img', 'canvas' + ]; + this.unsafeElements = ['script', 'style']; + this._domDocument = this.renderingMode === 'editing' ? dom_global.document : dom_global.document.implementation.createHTMLDocument(''); + } + /** + * Binds a given DOM element that represents fake selection to a **position** of a + * {@link module:engine/view/documentselection~DocumentSelection document selection}. + * Document selection copy is stored and can be retrieved by the + * {@link module:engine/view/domconverter~DomConverter#fakeSelectionToView} method. + */ + bindFakeSelection(domElement, viewDocumentSelection) { + this._fakeSelectionMapping.set(domElement, new Selection(viewDocumentSelection)); + } + /** + * Returns a {@link module:engine/view/selection~Selection view selection} instance corresponding to a given + * DOM element that represents fake selection. Returns `undefined` if binding to the given DOM element does not exist. + */ + fakeSelectionToView(domElement) { + return this._fakeSelectionMapping.get(domElement); + } + /** + * Binds DOM and view elements, so it will be possible to get corresponding elements using + * {@link module:engine/view/domconverter~DomConverter#mapDomToView} and + * {@link module:engine/view/domconverter~DomConverter#mapViewToDom}. + * + * @param domElement The DOM element to bind. + * @param viewElement The view element to bind. + */ + bindElements(domElement, viewElement) { + this._domToViewMapping.set(domElement, viewElement); + this._viewToDomMapping.set(viewElement, domElement); + } + /** + * Unbinds a given DOM element from the view element it was bound to. Unbinding is deep, meaning that all children of + * the DOM element will be unbound too. + * + * @param domElement The DOM element to unbind. + */ + unbindDomElement(domElement) { + const viewElement = this._domToViewMapping.get(domElement); + if (viewElement) { + this._domToViewMapping.delete(domElement); + this._viewToDomMapping.delete(viewElement); + for (const child of Array.from(domElement.children)) { + this.unbindDomElement(child); + } + } + } + /** + * Binds DOM and view document fragments, so it will be possible to get corresponding document fragments using + * {@link module:engine/view/domconverter~DomConverter#mapDomToView} and + * {@link module:engine/view/domconverter~DomConverter#mapViewToDom}. + * + * @param domFragment The DOM document fragment to bind. + * @param viewFragment The view document fragment to bind. + */ + bindDocumentFragments(domFragment, viewFragment) { + this._domToViewMapping.set(domFragment, viewFragment); + this._viewToDomMapping.set(viewFragment, domFragment); + } + /** + * Decides whether a given pair of attribute key and value should be passed further down the pipeline. + * + * @param elementName Element name in lower case. + */ + shouldRenderAttribute(attributeKey, attributeValue, elementName) { + if (this.renderingMode === 'data') { + return true; + } + attributeKey = attributeKey.toLowerCase(); + if (attributeKey.startsWith('on')) { + return false; + } + if (attributeKey === 'srcdoc' && + attributeValue.match(/\bon\S+\s*=|javascript:|<\s*\/*script/i)) { + return false; + } + if (elementName === 'img' && + (attributeKey === 'src' || attributeKey === 'srcset')) { + return true; + } + if (elementName === 'source' && attributeKey === 'srcset') { + return true; + } + if (attributeValue.match(/^\s*(javascript:|data:(image\/svg|text\/x?html))/i)) { + return false; + } + return true; + } + /** + * Set `domElement`'s content using provided `html` argument. Apply necessary filtering for the editing pipeline. + * + * @param domElement DOM element that should have `html` set as its content. + * @param html Textual representation of the HTML that will be set on `domElement`. + */ + setContentOf(domElement, html) { + // For data pipeline we pass the HTML as-is. + if (this.renderingMode === 'data') { + domElement.innerHTML = html; + return; + } + const document = new DOMParser().parseFromString(html, 'text/html'); + const fragment = document.createDocumentFragment(); + const bodyChildNodes = document.body.childNodes; + while (bodyChildNodes.length > 0) { + fragment.appendChild(bodyChildNodes[0]); + } + const treeWalker = document.createTreeWalker(fragment, NodeFilter.SHOW_ELEMENT); + const nodes = []; + let currentNode; + // eslint-disable-next-line no-cond-assign + while (currentNode = treeWalker.nextNode()) { + nodes.push(currentNode); + } + for (const currentNode of nodes) { + // Go through nodes to remove those that are prohibited in editing pipeline. + for (const attributeName of currentNode.getAttributeNames()) { + this.setDomElementAttribute(currentNode, attributeName, currentNode.getAttribute(attributeName)); + } + const elementName = currentNode.tagName.toLowerCase(); + // There are certain nodes, that should be renamed to in editing pipeline. + if (this._shouldRenameElement(elementName)) { + _logUnsafeElement(elementName); + currentNode.replaceWith(this._createReplacementDomElement(elementName, currentNode)); + } + } + // Empty the target element. + while (domElement.firstChild) { + domElement.firstChild.remove(); + } + domElement.append(fragment); + } + /** + * Converts the view to the DOM. For all text nodes, not bound elements and document fragments new items will + * be created. For bound elements and document fragments the method will return corresponding items. + * + * @param viewNode View node or document fragment to transform. + * @param options Conversion options. + * @param options.bind Determines whether new elements will be bound. + * @param options.withChildren If `false`, node's and document fragment's children will not be converted. + * @returns Converted node or DocumentFragment. + */ + viewToDom(viewNode, options = {}) { + if (viewNode.is('$text')) { + const textData = this._processDataFromViewText(viewNode); + return this._domDocument.createTextNode(textData); + } + else { + if (this.mapViewToDom(viewNode)) { + return this.mapViewToDom(viewNode); + } + let domElement; + if (viewNode.is('documentFragment')) { + // Create DOM document fragment. + domElement = this._domDocument.createDocumentFragment(); + if (options.bind) { + this.bindDocumentFragments(domElement, viewNode); + } + } + else if (viewNode.is('uiElement')) { + if (viewNode.name === '$comment') { + domElement = this._domDocument.createComment(viewNode.getCustomProperty('$rawContent')); + } + else { + // UIElement has its own render() method (see #799). + domElement = viewNode.render(this._domDocument, this); + } + if (options.bind) { + this.bindElements(domElement, viewNode); + } + return domElement; + } + else { + // Create DOM element. + if (this._shouldRenameElement(viewNode.name)) { + _logUnsafeElement(viewNode.name); + domElement = this._createReplacementDomElement(viewNode.name); + } + else if (viewNode.hasAttribute('xmlns')) { + domElement = this._domDocument.createElementNS(viewNode.getAttribute('xmlns'), viewNode.name); + } + else { + domElement = this._domDocument.createElement(viewNode.name); + } + // RawElement take care of their children in RawElement#render() method which can be customized + // (see https://github.com/ckeditor/ckeditor5/issues/4469). + if (viewNode.is('rawElement')) { + viewNode.render(domElement, this); + } + if (options.bind) { + this.bindElements(domElement, viewNode); + } + // Copy element's attributes. + for (const key of viewNode.getAttributeKeys()) { + this.setDomElementAttribute(domElement, key, viewNode.getAttribute(key), viewNode); + } + } + if (options.withChildren !== false) { + for (const child of this.viewChildrenToDom(viewNode, options)) { + domElement.appendChild(child); + } + } + return domElement; + } + } + /** + * Sets the attribute on a DOM element. + * + * **Note**: To remove the attribute, use {@link #removeDomElementAttribute}. + * + * @param domElement The DOM element the attribute should be set on. + * @param key The name of the attribute. + * @param value The value of the attribute. + * @param relatedViewElement The view element related to the `domElement` (if there is any). + * It helps decide whether the attribute set is unsafe. For instance, view elements created via the + * {@link module:engine/view/downcastwriter~DowncastWriter} methods can allow certain attributes that would normally be filtered out. + */ + setDomElementAttribute(domElement, key, value, relatedViewElement) { + const shouldRenderAttribute = this.shouldRenderAttribute(key, value, domElement.tagName.toLowerCase()) || + relatedViewElement && relatedViewElement.shouldRenderUnsafeAttribute(key); + if (!shouldRenderAttribute) { + ckeditorerror_logWarning('domconverter-unsafe-attribute-detected', { domElement, key, value }); + } + if (!isValidAttributeName(key)) { + /** + * Invalid attribute name was ignored during rendering. + * + * @error domconverter-invalid-attribute-detected + */ + ckeditorerror_logWarning('domconverter-invalid-attribute-detected', { domElement, key, value }); + return; + } + // The old value was safe but the new value is unsafe. + if (domElement.hasAttribute(key) && !shouldRenderAttribute) { + domElement.removeAttribute(key); + } + // The old value was unsafe (but prefixed) but the new value will be safe (will be unprefixed). + else if (domElement.hasAttribute(UNSAFE_ATTRIBUTE_NAME_PREFIX + key) && shouldRenderAttribute) { + domElement.removeAttribute(UNSAFE_ATTRIBUTE_NAME_PREFIX + key); + } + // If the attribute should not be rendered, rename it (instead of removing) to give developers some idea of what + // is going on (https://github.com/ckeditor/ckeditor5/issues/10801). + domElement.setAttribute(shouldRenderAttribute ? key : UNSAFE_ATTRIBUTE_NAME_PREFIX + key, value); + } + /** + * Removes an attribute from a DOM element. + * + * **Note**: To set the attribute, use {@link #setDomElementAttribute}. + * + * @param domElement The DOM element the attribute should be removed from. + * @param key The name of the attribute. + */ + removeDomElementAttribute(domElement, key) { + // See #_createReplacementDomElement() to learn what this is. + if (key == UNSAFE_ELEMENT_REPLACEMENT_ATTRIBUTE) { + return; + } + domElement.removeAttribute(key); + // See setDomElementAttribute() to learn what this is. + domElement.removeAttribute(UNSAFE_ATTRIBUTE_NAME_PREFIX + key); + } + /** + * Converts children of the view element to DOM using the + * {@link module:engine/view/domconverter~DomConverter#viewToDom} method. + * Additionally, this method adds block {@link module:engine/view/filler filler} to the list of children, if needed. + * + * @param viewElement Parent view element. + * @param options See {@link module:engine/view/domconverter~DomConverter#viewToDom} options parameter. + * @returns DOM nodes. + */ + *viewChildrenToDom(viewElement, options = {}) { + const fillerPositionOffset = viewElement.getFillerOffset && viewElement.getFillerOffset(); + let offset = 0; + for (const childView of viewElement.getChildren()) { + if (fillerPositionOffset === offset) { + yield this._getBlockFiller(); + } + const transparentRendering = childView.is('element') && + !!childView.getCustomProperty('dataPipeline:transparentRendering') && + !first(childView.getAttributes()); + if (transparentRendering && this.renderingMode == 'data') { + yield* this.viewChildrenToDom(childView, options); + } + else { + if (transparentRendering) { + /** + * The `dataPipeline:transparentRendering` flag is supported only in the data pipeline. + * + * @error domconverter-transparent-rendering-unsupported-in-editing-pipeline + */ + ckeditorerror_logWarning('domconverter-transparent-rendering-unsupported-in-editing-pipeline', { viewElement: childView }); + } + yield this.viewToDom(childView, options); + } + offset++; + } + if (fillerPositionOffset === offset) { + yield this._getBlockFiller(); + } + } + /** + * Converts view {@link module:engine/view/range~Range} to DOM range. + * Inline and block {@link module:engine/view/filler fillers} are handled during the conversion. + * + * @param viewRange View range. + * @returns DOM range. + */ + viewRangeToDom(viewRange) { + const domStart = this.viewPositionToDom(viewRange.start); + const domEnd = this.viewPositionToDom(viewRange.end); + const domRange = this._domDocument.createRange(); + domRange.setStart(domStart.parent, domStart.offset); + domRange.setEnd(domEnd.parent, domEnd.offset); + return domRange; + } + /** + * Converts view {@link module:engine/view/position~Position} to DOM parent and offset. + * + * Inline and block {@link module:engine/view/filler fillers} are handled during the conversion. + * If the converted position is directly before inline filler it is moved inside the filler. + * + * @param viewPosition View position. + * @returns DOM position or `null` if view position could not be converted to DOM. + * DOM position has two properties: + * * `parent` - DOM position parent. + * * `offset` - DOM position offset. + */ + viewPositionToDom(viewPosition) { + const viewParent = viewPosition.parent; + if (viewParent.is('$text')) { + const domParent = this.findCorrespondingDomText(viewParent); + if (!domParent) { + // Position is in a view text node that has not been rendered to DOM yet. + return null; + } + let offset = viewPosition.offset; + if (startsWithFiller(domParent)) { + offset += INLINE_FILLER_LENGTH; + } + return { parent: domParent, offset }; + } + else { + // viewParent is instance of ViewElement. + let domParent, domBefore, domAfter; + if (viewPosition.offset === 0) { + domParent = this.mapViewToDom(viewParent); + if (!domParent) { + // Position is in a view element that has not been rendered to DOM yet. + return null; + } + domAfter = domParent.childNodes[0]; + } + else { + const nodeBefore = viewPosition.nodeBefore; + domBefore = nodeBefore.is('$text') ? + this.findCorrespondingDomText(nodeBefore) : + this.mapViewToDom(nodeBefore); + if (!domBefore) { + // Position is after a view element that has not been rendered to DOM yet. + return null; + } + domParent = domBefore.parentNode; + domAfter = domBefore.nextSibling; + } + // If there is an inline filler at position return position inside the filler. We should never return + // the position before the inline filler. + if (isText(domAfter) && startsWithFiller(domAfter)) { + return { parent: domAfter, offset: INLINE_FILLER_LENGTH }; + } + const offset = domBefore ? indexOf(domBefore) + 1 : 0; + return { parent: domParent, offset }; + } + } + /** + * Converts DOM to view. For all text nodes, not bound elements and document fragments new items will + * be created. For bound elements and document fragments function will return corresponding items. For + * {@link module:engine/view/filler fillers} `null` will be returned. + * For all DOM elements rendered by {@link module:engine/view/uielement~UIElement} that UIElement will be returned. + * + * @param domNode DOM node or document fragment to transform. + * @param options Conversion options. + * @param options.bind Determines whether new elements will be bound. False by default. + * @param options.withChildren If `true`, node's and document fragment's children will be converted too. True by default. + * @param options.keepOriginalCase If `false`, node's tag name will be converted to lower case. False by default. + * @param options.skipComments If `false`, comment nodes will be converted to `$comment` + * {@link module:engine/view/uielement~UIElement view UI elements}. False by default. + * @returns Converted node or document fragment or `null` if DOM node is a {@link module:engine/view/filler filler} + * or the given node is an empty text node. + */ + domToView(domNode, options = {}) { + if (this.isBlockFiller(domNode)) { + return null; + } + // When node is inside a UIElement or a RawElement return that parent as it's view representation. + const hostElement = this.getHostViewElement(domNode); + if (hostElement) { + return hostElement; + } + if (isComment(domNode) && options.skipComments) { + return null; + } + if (isText(domNode)) { + if (isInlineFiller(domNode)) { + return null; + } + else { + const textData = this._processDataFromDomText(domNode); + return textData === '' ? null : new text_Text(this.document, textData); + } + } + else { + if (this.mapDomToView(domNode)) { + return this.mapDomToView(domNode); + } + let viewElement; + if (this.isDocumentFragment(domNode)) { + // Create view document fragment. + viewElement = new DocumentFragment(this.document); + if (options.bind) { + this.bindDocumentFragments(domNode, viewElement); + } + } + else { + // Create view element. + viewElement = this._createViewElement(domNode, options); + if (options.bind) { + this.bindElements(domNode, viewElement); + } + // Copy element's attributes. + const attrs = domNode.attributes; + if (attrs) { + for (let l = attrs.length, i = 0; i < l; i++) { + viewElement._setAttribute(attrs[i].name, attrs[i].value); + } + } + // Treat this element's content as a raw data if it was registered as such. + // Comment node is also treated as an element with raw data. + if (this._isViewElementWithRawContent(viewElement, options) || isComment(domNode)) { + const rawContent = isComment(domNode) ? domNode.data : domNode.innerHTML; + viewElement._setCustomProperty('$rawContent', rawContent); + // Store a DOM node to prevent left trimming of the following text node. + this._encounteredRawContentDomNodes.add(domNode); + return viewElement; + } + } + if (options.withChildren !== false) { + for (const child of this.domChildrenToView(domNode, options)) { + viewElement._appendChild(child); + } + } + return viewElement; + } + } + /** + * Converts children of the DOM element to view nodes using + * the {@link module:engine/view/domconverter~DomConverter#domToView} method. + * Additionally this method omits block {@link module:engine/view/filler filler}, if it exists in the DOM parent. + * + * @param domElement Parent DOM element. + * @param options See {@link module:engine/view/domconverter~DomConverter#domToView} options parameter. + * @returns View nodes. + */ + *domChildrenToView(domElement, options) { + for (let i = 0; i < domElement.childNodes.length; i++) { + const domChild = domElement.childNodes[i]; + const viewChild = this.domToView(domChild, options); + if (viewChild !== null) { + yield viewChild; + } + } + } + /** + * Converts DOM selection to view {@link module:engine/view/selection~Selection}. + * Ranges which cannot be converted will be omitted. + * + * @param domSelection DOM selection. + * @returns View selection. + */ + domSelectionToView(domSelection) { + // DOM selection might be placed in fake selection container. + // If container contains fake selection - return corresponding view selection. + if (domSelection.rangeCount === 1) { + let container = domSelection.getRangeAt(0).startContainer; + // The DOM selection might be moved to the text node inside the fake selection container. + if (isText(container)) { + container = container.parentNode; + } + const viewSelection = this.fakeSelectionToView(container); + if (viewSelection) { + return viewSelection; + } + } + const isBackward = this.isDomSelectionBackward(domSelection); + const viewRanges = []; + for (let i = 0; i < domSelection.rangeCount; i++) { + // DOM Range have correct start and end, no matter what is the DOM Selection direction. So we don't have to fix anything. + const domRange = domSelection.getRangeAt(i); + const viewRange = this.domRangeToView(domRange); + if (viewRange) { + viewRanges.push(viewRange); + } + } + return new Selection(viewRanges, { backward: isBackward }); + } + /** + * Converts DOM Range to view {@link module:engine/view/range~Range}. + * If the start or end position can not be converted `null` is returned. + * + * @param domRange DOM range. + * @returns View range. + */ + domRangeToView(domRange) { + const viewStart = this.domPositionToView(domRange.startContainer, domRange.startOffset); + const viewEnd = this.domPositionToView(domRange.endContainer, domRange.endOffset); + if (viewStart && viewEnd) { + return new Range(viewStart, viewEnd); + } + return null; + } + /** + * Converts DOM parent and offset to view {@link module:engine/view/position~Position}. + * + * If the position is inside a {@link module:engine/view/filler filler} which has no corresponding view node, + * position of the filler will be converted and returned. + * + * If the position is inside DOM element rendered by {@link module:engine/view/uielement~UIElement} + * that position will be converted to view position before that UIElement. + * + * If structures are too different and it is not possible to find corresponding position then `null` will be returned. + * + * @param domParent DOM position parent. + * @param domOffset DOM position offset. You can skip it when converting the inline filler node. + * @returns View position. + */ + domPositionToView(domParent, domOffset = 0) { + if (this.isBlockFiller(domParent)) { + return this.domPositionToView(domParent.parentNode, indexOf(domParent)); + } + // If position is somewhere inside UIElement or a RawElement - return position before that element. + const viewElement = this.mapDomToView(domParent); + if (viewElement && (viewElement.is('uiElement') || viewElement.is('rawElement'))) { + return Position._createBefore(viewElement); + } + if (isText(domParent)) { + if (isInlineFiller(domParent)) { + return this.domPositionToView(domParent.parentNode, indexOf(domParent)); + } + const viewParent = this.findCorrespondingViewText(domParent); + let offset = domOffset; + if (!viewParent) { + return null; + } + if (startsWithFiller(domParent)) { + offset -= INLINE_FILLER_LENGTH; + offset = offset < 0 ? 0 : offset; + } + return new Position(viewParent, offset); + } + // domParent instanceof HTMLElement. + else { + if (domOffset === 0) { + const viewParent = this.mapDomToView(domParent); + if (viewParent) { + return new Position(viewParent, 0); + } + } + else { + const domBefore = domParent.childNodes[domOffset - 1]; + // Jump over an inline filler (and also on Firefox jump over a block filler while pressing backspace in an empty paragraph). + if (isText(domBefore) && isInlineFiller(domBefore) || domBefore && this.isBlockFiller(domBefore)) { + return this.domPositionToView(domBefore.parentNode, indexOf(domBefore)); + } + const viewBefore = isText(domBefore) ? + this.findCorrespondingViewText(domBefore) : + this.mapDomToView(domBefore); + // TODO #663 + if (viewBefore && viewBefore.parent) { + return new Position(viewBefore.parent, viewBefore.index + 1); + } + } + return null; + } + } + /** + * Returns corresponding view {@link module:engine/view/element~Element Element} or + * {@link module:engine/view/documentfragment~DocumentFragment} for provided DOM element or + * document fragment. If there is no view item {@link module:engine/view/domconverter~DomConverter#bindElements bound} + * to the given DOM - `undefined` is returned. + * + * For all DOM elements rendered by a {@link module:engine/view/uielement~UIElement} or + * a {@link module:engine/view/rawelement~RawElement}, the parent `UIElement` or `RawElement` will be returned. + * + * @param domElementOrDocumentFragment DOM element or document fragment. + * @returns Corresponding view element, document fragment or `undefined` if no element was bound. + */ + mapDomToView(domElementOrDocumentFragment) { + const hostElement = this.getHostViewElement(domElementOrDocumentFragment); + return hostElement || this._domToViewMapping.get(domElementOrDocumentFragment); + } + /** + * Finds corresponding text node. Text nodes are not {@link module:engine/view/domconverter~DomConverter#bindElements bound}, + * corresponding text node is returned based on the sibling or parent. + * + * If the directly previous sibling is a {@link module:engine/view/domconverter~DomConverter#bindElements bound} element, it is used + * to find the corresponding text node. + * + * If this is a first child in the parent and the parent is a {@link module:engine/view/domconverter~DomConverter#bindElements bound} + * element, it is used to find the corresponding text node. + * + * For all text nodes rendered by a {@link module:engine/view/uielement~UIElement} or + * a {@link module:engine/view/rawelement~RawElement}, the parent `UIElement` or `RawElement` will be returned. + * + * Otherwise `null` is returned. + * + * Note that for the block or inline {@link module:engine/view/filler filler} this method returns `null`. + * + * @param domText DOM text node. + * @returns Corresponding view text node or `null`, if it was not possible to find a corresponding node. + */ + findCorrespondingViewText(domText) { + if (isInlineFiller(domText)) { + return null; + } + // If DOM text was rendered by a UIElement or a RawElement - return this parent element. + const hostElement = this.getHostViewElement(domText); + if (hostElement) { + return hostElement; + } + const previousSibling = domText.previousSibling; + // Try to use previous sibling to find the corresponding text node. + if (previousSibling) { + if (!(this.isElement(previousSibling))) { + // The previous is text or comment. + return null; + } + const viewElement = this.mapDomToView(previousSibling); + if (viewElement) { + const nextSibling = viewElement.nextSibling; + // It might be filler which has no corresponding view node. + if (nextSibling instanceof text_Text) { + return nextSibling; + } + else { + return null; + } + } + } + // Try to use parent to find the corresponding text node. + else { + const viewElement = this.mapDomToView(domText.parentNode); + if (viewElement) { + const firstChild = viewElement.getChild(0); + // It might be filler which has no corresponding view node. + if (firstChild instanceof text_Text) { + return firstChild; + } + else { + return null; + } + } + } + return null; + } + mapViewToDom(documentFragmentOrElement) { + return this._viewToDomMapping.get(documentFragmentOrElement); + } + /** + * Finds corresponding text node. Text nodes are not {@link module:engine/view/domconverter~DomConverter#bindElements bound}, + * corresponding text node is returned based on the sibling or parent. + * + * If the directly previous sibling is a {@link module:engine/view/domconverter~DomConverter#bindElements bound} element, it is used + * to find the corresponding text node. + * + * If this is a first child in the parent and the parent is a {@link module:engine/view/domconverter~DomConverter#bindElements bound} + * element, it is used to find the corresponding text node. + * + * Otherwise `null` is returned. + * + * @param viewText View text node. + * @returns Corresponding DOM text node or `null`, if it was not possible to find a corresponding node. + */ + findCorrespondingDomText(viewText) { + const previousSibling = viewText.previousSibling; + // Try to use previous sibling to find the corresponding text node. + if (previousSibling && this.mapViewToDom(previousSibling)) { + return this.mapViewToDom(previousSibling).nextSibling; + } + // If this is a first node, try to use parent to find the corresponding text node. + if (!previousSibling && viewText.parent && this.mapViewToDom(viewText.parent)) { + return this.mapViewToDom(viewText.parent).childNodes[0]; + } + return null; + } + /** + * Focuses DOM editable that is corresponding to provided {@link module:engine/view/editableelement~EditableElement}. + */ + focus(viewEditable) { + const domEditable = this.mapViewToDom(viewEditable); + if (domEditable && domEditable.ownerDocument.activeElement !== domEditable) { + // Save the scrollX and scrollY positions before the focus. + const { scrollX, scrollY } = dom_global.window; + const scrollPositions = []; + // Save all scrollLeft and scrollTop values starting from domEditable up to + // document#documentElement. + forEachDomElementAncestor(domEditable, node => { + const { scrollLeft, scrollTop } = node; + scrollPositions.push([scrollLeft, scrollTop]); + }); + domEditable.focus(); + // Restore scrollLeft and scrollTop values starting from domEditable up to + // document#documentElement. + // https://github.com/ckeditor/ckeditor5-engine/issues/951 + // https://github.com/ckeditor/ckeditor5-engine/issues/957 + forEachDomElementAncestor(domEditable, node => { + const [scrollLeft, scrollTop] = scrollPositions.shift(); + node.scrollLeft = scrollLeft; + node.scrollTop = scrollTop; + }); + // Restore the scrollX and scrollY positions after the focus. + // https://github.com/ckeditor/ckeditor5-engine/issues/951 + dom_global.window.scrollTo(scrollX, scrollY); + } + } + /** + * Returns `true` when `node.nodeType` equals `Node.ELEMENT_NODE`. + * + * @param node Node to check. + */ + isElement(node) { + return node && node.nodeType == Node.ELEMENT_NODE; + } + /** + * Returns `true` when `node.nodeType` equals `Node.DOCUMENT_FRAGMENT_NODE`. + * + * @param node Node to check. + */ + isDocumentFragment(node) { + return node && node.nodeType == Node.DOCUMENT_FRAGMENT_NODE; + } + /** + * Checks if the node is an instance of the block filler for this DOM converter. + * + * ```ts + * const converter = new DomConverter( viewDocument, { blockFillerMode: 'br' } ); + * + * converter.isBlockFiller( BR_FILLER( document ) ); // true + * converter.isBlockFiller( NBSP_FILLER( document ) ); // false + * ``` + * + * **Note:**: For the `'nbsp'` mode the method also checks context of a node so it cannot be a detached node. + * + * **Note:** A special case in the `'nbsp'` mode exists where the `
` in `


` is treated as a block filler. + * + * @param domNode DOM node to check. + * @returns True if a node is considered a block filler for given mode. + */ + isBlockFiller(domNode) { + if (this.blockFillerMode == 'br') { + return domNode.isEqualNode(BR_FILLER_REF); + } + // Special case for


in which
should be treated as filler even when we are not in the 'br' mode. See ckeditor5#5564. + if (domNode.tagName === 'BR' && + hasBlockParent(domNode, this.blockElements) && + domNode.parentNode.childNodes.length === 1) { + return true; + } + // If not in 'br' mode, try recognizing both marked and regular nbsp block fillers. + return domNode.isEqualNode(MARKED_NBSP_FILLER_REF) || isNbspBlockFiller(domNode, this.blockElements); + } + /** + * Returns `true` if given selection is a backward selection, that is, if it's `focus` is before `anchor`. + * + * @param DOM Selection instance to check. + */ + isDomSelectionBackward(selection) { + if (selection.isCollapsed) { + return false; + } + // Since it takes multiple lines of code to check whether a "DOM Position" is before/after another "DOM Position", + // we will use the fact that range will collapse if it's end is before it's start. + const range = this._domDocument.createRange(); + try { + range.setStart(selection.anchorNode, selection.anchorOffset); + range.setEnd(selection.focusNode, selection.focusOffset); + } + catch (e) { + // Safari sometimes gives us a selection that makes Range.set{Start,End} throw. + // See https://github.com/ckeditor/ckeditor5/issues/12375. + return false; + } + const backward = range.collapsed; + range.detach(); + return backward; + } + /** + * Returns a parent {@link module:engine/view/uielement~UIElement} or {@link module:engine/view/rawelement~RawElement} + * that hosts the provided DOM node. Returns `null` if there is no such parent. + */ + getHostViewElement(domNode) { + const ancestors = getAncestors(domNode); + // Remove domNode from the list. + ancestors.pop(); + while (ancestors.length) { + const domNode = ancestors.pop(); + const viewNode = this._domToViewMapping.get(domNode); + if (viewNode && (viewNode.is('uiElement') || viewNode.is('rawElement'))) { + return viewNode; + } + } + return null; + } + /** + * Checks if the given selection's boundaries are at correct places. + * + * The following places are considered as incorrect for selection boundaries: + * + * * before or in the middle of an inline filler sequence, + * * inside a DOM element which represents {@link module:engine/view/uielement~UIElement a view UI element}, + * * inside a DOM element which represents {@link module:engine/view/rawelement~RawElement a view raw element}. + * + * @param domSelection The DOM selection object to be checked. + * @returns `true` if the given selection is at a correct place, `false` otherwise. + */ + isDomSelectionCorrect(domSelection) { + return this._isDomSelectionPositionCorrect(domSelection.anchorNode, domSelection.anchorOffset) && + this._isDomSelectionPositionCorrect(domSelection.focusNode, domSelection.focusOffset); + } + /** + * Registers a {@link module:engine/view/matcher~MatcherPattern} for view elements whose content should be treated as raw data + * and not processed during the conversion from DOM nodes to view elements. + * + * This is affecting how {@link module:engine/view/domconverter~DomConverter#domToView} and + * {@link module:engine/view/domconverter~DomConverter#domChildrenToView} process DOM nodes. + * + * The raw data can be later accessed by a + * {@link module:engine/view/element~Element#getCustomProperty custom property of a view element} called `"$rawContent"`. + * + * @param pattern Pattern matching a view element whose content should + * be treated as raw data. + */ + registerRawContentMatcher(pattern) { + this._rawContentElementMatcher.add(pattern); + } + /** + * Returns the block {@link module:engine/view/filler filler} node based on the current {@link #blockFillerMode} setting. + */ + _getBlockFiller() { + switch (this.blockFillerMode) { + case 'nbsp': + return NBSP_FILLER(this._domDocument); // eslint-disable-line new-cap + case 'markedNbsp': + return MARKED_NBSP_FILLER(this._domDocument); // eslint-disable-line new-cap + case 'br': + return BR_FILLER(this._domDocument); // eslint-disable-line new-cap + } + } + /** + * Checks if the given DOM position is a correct place for selection boundary. See {@link #isDomSelectionCorrect}. + * + * @param domParent Position parent. + * @param offset Position offset. + * @returns `true` if given position is at a correct place for selection boundary, `false` otherwise. + */ + _isDomSelectionPositionCorrect(domParent, offset) { + // If selection is before or in the middle of inline filler string, it is incorrect. + if (isText(domParent) && startsWithFiller(domParent) && offset < INLINE_FILLER_LENGTH) { + // Selection in a text node, at wrong position (before or in the middle of filler). + return false; + } + if (this.isElement(domParent) && startsWithFiller(domParent.childNodes[offset])) { + // Selection in an element node, before filler text node. + return false; + } + const viewParent = this.mapDomToView(domParent); + // The position is incorrect when anchored inside a UIElement or a RawElement. + // Note: In case of UIElement and RawElement, mapDomToView() returns a parent element for any DOM child + // so there's no need to perform any additional checks. + if (viewParent && (viewParent.is('uiElement') || viewParent.is('rawElement'))) { + return false; + } + return true; + } + /** + * Takes text data from a given {@link module:engine/view/text~Text#data} and processes it so + * it is correctly displayed in the DOM. + * + * Following changes are done: + * + * * a space at the beginning is changed to ` ` if this is the first text node in its container + * element or if a previous text node ends with a space character, + * * space at the end of the text node is changed to ` ` if there are two spaces at the end of a node or if next node + * starts with a space or if it is the last text node in its container, + * * remaining spaces are replaced to a chain of spaces and ` ` (e.g. `'x x'` becomes `'x   x'`). + * + * Content of {@link #preElements} is not processed. + * + * @param node View text node to process. + * @returns Processed text data. + */ + _processDataFromViewText(node) { + let data = node.data; + // If any of node ancestors has a name which is in `preElements` array, then currently processed + // view text node is (will be) in preformatted element. We should not change whitespaces then. + if (node.getAncestors().some(parent => this.preElements.includes(parent.name))) { + return data; + } + // 1. Replace the first space with a nbsp if the previous node ends with a space or there is no previous node + // (container element boundary). + if (data.charAt(0) == ' ') { + const prevNode = this._getTouchingInlineViewNode(node, false); + const prevEndsWithSpace = prevNode && prevNode.is('$textProxy') && this._nodeEndsWithSpace(prevNode); + if (prevEndsWithSpace || !prevNode) { + data = '\u00A0' + data.substr(1); + } + } + // 2. Replace the last space with nbsp if there are two spaces at the end or if the next node starts with space or there is no + // next node (container element boundary). + // + // Keep in mind that Firefox prefers $nbsp; before tag, not inside it: + // + // Foo  bar <-- bad. + // Foo  bar <-- good. + // + // More here: https://github.com/ckeditor/ckeditor5-engine/issues/1747. + if (data.charAt(data.length - 1) == ' ') { + const nextNode = this._getTouchingInlineViewNode(node, true); + const nextStartsWithSpace = nextNode && nextNode.is('$textProxy') && nextNode.data.charAt(0) == ' '; + if (data.charAt(data.length - 2) == ' ' || !nextNode || nextStartsWithSpace) { + data = data.substr(0, data.length - 1) + '\u00A0'; + } + } + // 3. Create space+nbsp pairs. + return data.replace(/ {2}/g, ' \u00A0'); + } + /** + * Checks whether given node ends with a space character after changing appropriate space characters to ` `s. + * + * @param node Node to check. + * @returns `true` if given `node` ends with space, `false` otherwise. + */ + _nodeEndsWithSpace(node) { + if (node.getAncestors().some(parent => this.preElements.includes(parent.name))) { + return false; + } + const data = this._processDataFromViewText(node); + return data.charAt(data.length - 1) == ' '; + } + /** + * Takes text data from native `Text` node and processes it to a correct {@link module:engine/view/text~Text view text node} data. + * + * Following changes are done: + * + * * multiple whitespaces are replaced to a single space, + * * space at the beginning of a text node is removed if it is the first text node in its container + * element or if the previous text node ends with a space character, + * * space at the end of the text node is removed if there are two spaces at the end of a node or if next node + * starts with a space or if it is the last text node in its container + * * nbsps are converted to spaces. + * + * @param node DOM text node to process. + * @returns Processed data. + */ + _processDataFromDomText(node) { + let data = node.data; + if (_hasDomParentOfType(node, this.preElements)) { + return getDataWithoutFiller(node); + } + // Change all consecutive whitespace characters (from the [ \n\t\r] set – + // see https://github.com/ckeditor/ckeditor5-engine/issues/822#issuecomment-311670249) to a single space character. + // That's how multiple whitespaces are treated when rendered, so we normalize those whitespaces. + // We're replacing 1+ (and not 2+) to also normalize singular \n\t\r characters (#822). + data = data.replace(/[ \n\t\r]{1,}/g, ' '); + const prevNode = this._getTouchingInlineDomNode(node, false); + const nextNode = this._getTouchingInlineDomNode(node, true); + const shouldLeftTrim = this._checkShouldLeftTrimDomText(node, prevNode); + const shouldRightTrim = this._checkShouldRightTrimDomText(node, nextNode); + // If the previous dom text node does not exist or it ends by whitespace character, remove space character from the beginning + // of this text node. Such space character is treated as a whitespace. + if (shouldLeftTrim) { + data = data.replace(/^ /, ''); + } + // If the next text node does not exist remove space character from the end of this text node. + if (shouldRightTrim) { + data = data.replace(/ $/, ''); + } + // At the beginning and end of a block element, Firefox inserts normal space +
instead of non-breaking space. + // This means that the text node starts/end with normal space instead of non-breaking space. + // This causes a problem because the normal space would be removed in `.replace` calls above. To prevent that, + // the inline filler is removed only after the data is initially processed (by the `.replace` above). See ckeditor5#692. + data = getDataWithoutFiller(new Text(data)); + // At this point we should have removed all whitespaces from DOM text data. + // + // Now, We will reverse the process that happens in `_processDataFromViewText`. + // + // We have to change   chars, that were in DOM text data because of rendering reasons, to spaces. + // First, change all ` \u00A0` pairs (space +  ) to two spaces. DOM converter changes two spaces from model/view to + // ` \u00A0` to ensure proper rendering. Since here we convert back, we recognize those pairs and change them back to ` `. + data = data.replace(/ \u00A0/g, ' '); + const isNextNodeInlineObjectElement = nextNode && this.isElement(nextNode) && nextNode.tagName != 'BR'; + const isNextNodeStartingWithSpace = nextNode && isText(nextNode) && nextNode.data.charAt(0) == ' '; + // Then, let's change the last nbsp to a space. + if (/( |\u00A0)\u00A0$/.test(data) || !nextNode || isNextNodeInlineObjectElement || isNextNodeStartingWithSpace) { + data = data.replace(/\u00A0$/, ' '); + } + // Then, change   character that is at the beginning of the text node to space character. + // We do that replacement only if this is the first node or the previous node ends on whitespace character. + if (shouldLeftTrim || prevNode && this.isElement(prevNode) && prevNode.tagName != 'BR') { + data = data.replace(/^\u00A0/, ' '); + } + // At this point, all whitespaces should be removed and all   created for rendering reasons should be + // changed to normal space. All left   are   inserted intentionally. + return data; + } + /** + * Helper function which checks if a DOM text node, preceded by the given `prevNode` should + * be trimmed from the left side. + * + * @param prevNode Either DOM text or `
` or one of `#inlineObjectElements`. + */ + _checkShouldLeftTrimDomText(node, prevNode) { + if (!prevNode) { + return true; + } + if (this.isElement(prevNode)) { + return prevNode.tagName === 'BR'; + } + // Shouldn't left trim if previous node is a node that was encountered as a raw content node. + if (this._encounteredRawContentDomNodes.has(node.previousSibling)) { + return false; + } + return /[^\S\u00A0]/.test(prevNode.data.charAt(prevNode.data.length - 1)); + } + /** + * Helper function which checks if a DOM text node, succeeded by the given `nextNode` should + * be trimmed from the right side. + * + * @param nextNode Either DOM text or `
` or one of `#inlineObjectElements`. + */ + _checkShouldRightTrimDomText(node, nextNode) { + if (nextNode) { + return false; + } + return !startsWithFiller(node); + } + /** + * Helper function. For given {@link module:engine/view/text~Text view text node}, it finds previous or next sibling + * that is contained in the same container element. If there is no such sibling, `null` is returned. + * + * @param node Reference node. + * @returns Touching text node, an inline object + * or `null` if there is no next or previous touching text node. + */ + _getTouchingInlineViewNode(node, getNext) { + const treeWalker = new TreeWalker({ + startPosition: getNext ? Position._createAfter(node) : Position._createBefore(node), + direction: getNext ? 'forward' : 'backward' + }); + for (const value of treeWalker) { + // Found an inline object (for example an image). + if (value.item.is('element') && this.inlineObjectElements.includes(value.item.name)) { + return value.item; + } + // ViewContainerElement is found on a way to next ViewText node, so given `node` was first/last + // text node in its container element. + else if (value.item.is('containerElement')) { + return null; + } + //
found – it works like a block boundary, so do not scan further. + else if (value.item.is('element', 'br')) { + return null; + } + // Found a text node in the same container element. + else if (value.item.is('$textProxy')) { + return value.item; + } + } + return null; + } + /** + * Helper function. For the given text node, it finds the closest touching node which is either + * a text, `
` or an {@link #inlineObjectElements inline object}. + * + * If no such node is found, `null` is returned. + * + * For instance, in the following DOM structure: + * + * ```html + *

foobar
bom

+ * ``` + * + * * `foo` doesn't have its previous touching inline node (`null` is returned), + * * `foo`'s next touching inline node is `bar` + * * `bar`'s next touching inline node is `
` + * + * This method returns text nodes and `
` elements because these types of nodes affect how + * spaces in the given text node need to be converted. + */ + _getTouchingInlineDomNode(node, getNext) { + if (!node.parentNode) { + return null; + } + const stepInto = getNext ? 'firstChild' : 'lastChild'; + const stepOver = getNext ? 'nextSibling' : 'previousSibling'; + let skipChildren = true; + let returnNode = node; + do { + if (!skipChildren && returnNode[stepInto]) { + returnNode = returnNode[stepInto]; + } + else if (returnNode[stepOver]) { + returnNode = returnNode[stepOver]; + skipChildren = false; + } + else { + returnNode = returnNode.parentNode; + skipChildren = true; + } + if (!returnNode || this._isBlockElement(returnNode)) { + return null; + } + } while (!(isText(returnNode) || returnNode.tagName == 'BR' || this._isInlineObjectElement(returnNode))); + return returnNode; + } + /** + * Returns `true` if a DOM node belongs to {@link #blockElements}. `false` otherwise. + */ + _isBlockElement(node) { + return this.isElement(node) && this.blockElements.includes(node.tagName.toLowerCase()); + } + /** + * Returns `true` if a DOM node belongs to {@link #inlineObjectElements}. `false` otherwise. + */ + _isInlineObjectElement(node) { + return this.isElement(node) && this.inlineObjectElements.includes(node.tagName.toLowerCase()); + } + /** + * Creates view element basing on the node type. + * + * @param node DOM node to check. + * @param options Conversion options. See {@link module:engine/view/domconverter~DomConverter#domToView} options parameter. + */ + _createViewElement(node, options) { + if (isComment(node)) { + return new UIElement(this.document, '$comment'); + } + const viewName = options.keepOriginalCase ? node.tagName : node.tagName.toLowerCase(); + return new Element(this.document, viewName); + } + /** + * Checks if view element's content should be treated as a raw data. + * + * @param viewElement View element to check. + * @param options Conversion options. See {@link module:engine/view/domconverter~DomConverter#domToView} options parameter. + */ + _isViewElementWithRawContent(viewElement, options) { + return options.withChildren !== false && !!this._rawContentElementMatcher.match(viewElement); + } + /** + * Checks whether a given element name should be renamed in a current rendering mode. + * + * @param elementName The name of view element. + */ + _shouldRenameElement(elementName) { + const name = elementName.toLowerCase(); + return this.renderingMode === 'editing' && this.unsafeElements.includes(name); + } + /** + * Return a element with a special attribute holding the name of the original element. + * Optionally, copy all the attributes of the original element if that element is provided. + * + * @param elementName The name of view element. + * @param originalDomElement The original DOM element to copy attributes and content from. + */ + _createReplacementDomElement(elementName, originalDomElement) { + const newDomElement = this._domDocument.createElement('span'); + // Mark the span replacing a script as hidden. + newDomElement.setAttribute(UNSAFE_ELEMENT_REPLACEMENT_ATTRIBUTE, elementName); + if (originalDomElement) { + while (originalDomElement.firstChild) { + newDomElement.appendChild(originalDomElement.firstChild); + } + for (const attributeName of originalDomElement.getAttributeNames()) { + newDomElement.setAttribute(attributeName, originalDomElement.getAttribute(attributeName)); + } + } + return newDomElement; + } +} +/** + * Helper function. + * Used to check if given native `Element` or `Text` node has parent with tag name from `types` array. + * + * @returns`true` if such parent exists or `false` if it does not. + */ +function _hasDomParentOfType(node, types) { + const parents = getAncestors(node); + return parents.some(parent => parent.tagName && types.includes(parent.tagName.toLowerCase())); +} +/** + * A helper that executes given callback for each DOM node's ancestor, starting from the given node + * and ending in document#documentElement. + * + * @param callback A callback to be executed for each ancestor. + */ +function forEachDomElementAncestor(element, callback) { + let node = element; + while (node) { + callback(node); + node = node.parentElement; + } +} +/** + * Checks if given node is a nbsp block filler. + * + * A   is a block filler only if it is a single child of a block element. + * + * @param domNode DOM node. + */ +function isNbspBlockFiller(domNode, blockElements) { + const isNBSP = domNode.isEqualNode(NBSP_FILLER_REF); + return isNBSP && hasBlockParent(domNode, blockElements) && domNode.parentNode.childNodes.length === 1; +} +/** + * Checks if domNode has block parent. + * + * @param domNode DOM node. + */ +function hasBlockParent(domNode, blockElements) { + const parent = domNode.parentNode; + return !!parent && !!parent.tagName && blockElements.includes(parent.tagName.toLowerCase()); +} +/** + * Log to console the information about element that was replaced. + * Check UNSAFE_ELEMENTS for all recognized unsafe elements. + * + * @param elementName The name of the view element. + */ +function _logUnsafeElement(elementName) { + if (elementName === 'script') { + ckeditorerror_logWarning('domconverter-unsafe-script-element-detected'); + } + if (elementName === 'style') { + ckeditorerror_logWarning('domconverter-unsafe-style-element-detected'); + } +} +/** + * While rendering the editor content, the {@link module:engine/view/domconverter~DomConverter} detected a `