@jackuait/blok 0.23.3 → 0.23.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const e=require(`./chunk-BL1yB9zm.cjs`),t=require(`./constants-BZUc1kAY.cjs`),n=require(`./objectSpread2-iNkE6aJh.cjs`),r=require(`./tw-fzSjDKon.cjs`),i=require(`./types-BQNH-yx9.cjs`),a=require(`./lightweight-i18n-BnIqQ5Cf.cjs`);e.t(((e,t)=>{function n(){}t.exports=Object.assign(n,{default:n,register:n,revert:function(){},__esModule:!0})}))();var o=class extends Error{},s=class e{get isDestroyed(){return this._isDestroyed}markDestroyed(){this._isDestroyed=!0}constructor({config:n,eventsDispatcher:r}){if(this.nodes={},this._isDestroyed=!1,this.listeners=new t.qi,this.readOnlyMutableListeners={on:(e,t,n,r=!1)=>{let i=this.listeners.on(e,t,n,r);i&&this.mutableListenerIds.push(i)},clearAll:()=>{for(let e of this.mutableListenerIds)this.listeners.offById(e);this.mutableListenerIds=[]}},this.mutableListenerIds=[],new.target===e)throw TypeError(`Constructors for abstract class Module are not allowed.`);this.config=n,this.eventsDispatcher=r,this.Blok={}}set state(e){this.Blok=e}removeAllNodes(){for(let e in this.nodes){let t=this.nodes[e];t instanceof HTMLElement&&t.remove()}}get isRtl(){var e;return((e=this.config.i18n)==null?void 0:e.direction)===`rtl`}},c=function(e){return Object.setPrototypeOf(this,{get id(){return e.id},get name(){return e.name},get config(){return e.config},get holder(){return e.holder},get parentId(){return e.parentId},get isEmpty(){return e.isEmpty},get selected(){return e.selected},get preservedData(){return e.preservedData},get preservedTunes(){return e.preservedTunes},set stretched(t){e.setStretchState(t)},get stretched(){return e.stretched},get focusable(){return e.focusable},call(t,n){return e.call(t,n)},save(){return e.save()},validate(t){return e.validate(t)},dispatchChange(){e.dispatchChange()},getActiveToolboxEntry(){return e.getActiveToolboxEntry()}}),Object.defineProperties(this,{id:{get(){return e.id},enumerable:!0,configurable:!0},name:{get(){return e.name},enumerable:!0,configurable:!0}}),this},l=class{constructor(e,t,n,r,i,a,o,s,c,l){this.toolInstance=e,this.getToolRenderedElement=t,this.tunesManager=n,this.name=r,this.getIsEmpty=i,this.inputManager=a,this.callToolUpdated=o,this.toggleEmptyMark=s,this.lastSavedDataInternal=c,this.lastSavedTunesInternal=l}async save(){var e=this;let t=await e.extractToolData();if(t===void 0)return;let r=window.performance.now(),i=e.tunesManager.extractTunesData();e.lastSavedDataInternal=t,e.lastSavedTunesInternal=n.t({},i);let a=window.performance.now();return{id:e.name,tool:e.name,data:t,tunes:i,time:a-r}}async setData(e){var n=this;let r=n.toolInstance.setData;if(typeof r==`function`)try{return await r.call(n.toolInstance,e),n.lastSavedDataInternal=e,!0}catch(e){return t.Ea(`Tool ${n.name} setData failed: ${e instanceof Error?e.message:String(e)}`,`warn`),!1}let i=n.getToolRenderedElement();if(!i)return!1;let a=i.getAttribute(`contenteditable`)===`true`,o=e.text,s=typeof o==`string`,c=Object.keys(e).length===0&&n.name===`paragraph`;return a&&(s||c)?(i.innerHTML=s?o:``,n.lastSavedDataInternal=e,n.inputManager.dropCache(),n.toggleEmptyMark(),n.callToolUpdated(),!0):!1}async validate(e){var t=this;return t.toolInstance.validate instanceof Function?await t.toolInstance.validate(e):!0}async exportDataAsString(e){return t.Ri(await this.data,e)}get data(){return this.save().then(e=>e&&!t.ba(e.data)?e.data:{})}get lastSavedData(){return this.lastSavedDataInternal}get lastSavedTunes(){return this.lastSavedTunesInternal}get preservedData(){return this.lastSavedDataInternal}get preservedTunes(){return this.lastSavedTunesInternal}async extractToolData(){var e=this;try{let t=e.getToolRenderedElement();if(t===null)return;let r=await e.toolInstance.save(t);if(!e.getIsEmpty())return r;if(r==null)return;if(typeof r!=`object`)return r;let i=n.t({},r);return e.sanitizeEmptyFields(i),i}catch(n){let r=n instanceof Error?n:Error(String(n));t.Ea(`Saving process for ${e.name} tool failed due to the ${r}`,`log`,r);return}}sanitizeEmptyFields(e){let n=n=>{let r=e[n];if(typeof r!=`string`)return;let i=document.createElement(`div`);i.innerHTML=r,t.Qi.isEmpty(i)&&(e[n]=``)};n(`text`),n(`html`)}},u=class{constructor(e,t){this.holder=e,this.onInputEvent=t,this.cachedInputs=[],this.inputIndex=0,this.handleFocus=()=>{this.dropCache(),this.updateCurrentInput()}}get inputs(){if(this.cachedInputs.length!==0)return this.cachedInputs;let e=t.Qi.findAllInputs(this.holder);return e.length>0&&this.inputIndex>e.length-1&&(this.inputIndex=e.length-1),this.cachedInputs=e,e}get currentInput(){return this.inputs[this.inputIndex]}set currentInput(e){if(e===void 0)return;let t=this.inputs.findIndex(t=>t===e||t.contains(e));t!==-1&&(this.inputIndex=t)}get currentInputIndex(){return this.inputIndex}get firstInput(){return this.inputs[0]}get lastInput(){let e=this.inputs;return e[e.length-1]}get nextInput(){return this.inputs[this.inputIndex+1]}get previousInput(){return this.inputs[this.inputIndex-1]}updateCurrentInput(){var e;let n=t.Ai.anchorNode,r=document.activeElement,i=e=>{if(!e)return;let n=e instanceof HTMLElement?e:e.parentElement;if(n===null)return;let r=this.inputs.find(e=>e===n||e.contains(n));if(r!==void 0)return r;let i=n.closest(t.Qi.allInputsSelector);if(i instanceof HTMLElement)return this.inputs.find(e=>e===i)};if(t.Qi.isNativeInput(r)){this.currentInput=r;return}let a=(e=i(n))==null?r instanceof HTMLElement?i(r):void 0:e;if(a!==void 0){this.currentInput=a;return}r instanceof HTMLElement&&this.inputs.includes(r)&&(this.currentInput=r)}dropCache(){this.cachedInputs=[]}addInputEvents(){this.inputs.forEach(e=>{e.addEventListener(`focus`,this.handleFocus),t.Qi.isNativeInput(e)&&e.addEventListener(`input`,this.onInputEvent)})}removeInputEvents(){this.inputs.forEach(e=>{e.removeEventListener(`focus`,this.handleFocus),t.Qi.isNativeInput(e)&&e.removeEventListener(`input`,this.onInputEvent)})}destroy(){this.removeInputEvents(),this.cachedInputs=[]}},d=`block changed`,f=`block:rendered`,p=`blocks:rendered`,m=`block-settings-closed`,h=`block-settings-opened`,g=`blok mobile layout toggled`,_=`fake cursor is about to be toggled`,v=`fake cursor have been set`,y=`redactor dom changed`,b=(e,t)=>{let{type:n,target:r,addedNodes:i,removedNodes:a}=e;return e.type===`attributes`&&(e.attributeName===`data-blok-empty`||e.attributeName===`data-blok-toggle-open`)?!1:t.contains(r)?!0:n===`childList`?Array.from(i).some(e=>e===t)?!0:Array.from(a).some(e=>e===t):!1},x=class{constructor(e,t,n){this.getToolElement=e,this.blokEventBus=t,this.onMutation=n,this.redactorDomChangedCallback=null}watch(){var e;this.redactorDomChangedCallback=e=>{let{mutations:t}=e,n=this.getToolElement();if(n===null)return;let r=t.filter(e=>b(e,n));r.length>0&&this.onMutation(r)},(e=this.blokEventBus)==null||e.on(`redactor dom changed`,this.redactorDomChangedCallback)}unwatch(){if(this.redactorDomChangedCallback){var e;(e=this.blokEventBus)==null||e.off(`redactor dom changed`,this.redactorDomChangedCallback),this.redactorDomChangedCallback=null}}handleMutation(e){let t=e===void 0,n=e instanceof InputEvent,r=!t&&!n?this.detectToolRootChange(e):null;return{shouldFireUpdate:this.shouldFireUpdate(e),newToolRoot:r}}detectToolRootChange(e){let t=this.getToolElement();if(t===null)return null;for(let n of e){if(!Array.from(n.removedNodes).includes(t))continue;let e=n.addedNodes[n.addedNodes.length-1];if(e instanceof HTMLElement)return e}return null}destroy(){this.unwatch()}shouldFireUpdate(e){let n=e===void 0,r=e instanceof InputEvent;if(n||r)return!0;let i=this.getToolElement();return!(e.length>0&&e.every(e=>{let{addedNodes:n,removedNodes:r,target:a}=e,o=[...Array.from(n),...Array.from(r),a],s=e=>{if(!t.Qi.isElement(e)){var n;return(n=e.parentElement)==null?t.Qi.isElement(a)?a:null:n}return e.isConnected?e:t.Qi.isElement(a)?a:null};return o.every(e=>{let t=s(e);if(t===null)return!1;let n=t.closest(`[data-blok-mutation-free="true"]`);return n!==null&&i!==null&&i.contains(n)})}))}},ee=class{constructor(e,t,n,r,i){this.holder=e,this.getContentElement=t,this.getStretched=n,this.blokEventBus=r,this.styleManager=i}set selected(e){var n,r;e?this.holder.setAttribute(t.Ma.selected,`true`):this.holder.removeAttribute(t.Ma.selected),this.handleFakeCursor(e);let i=e&&t.Ai.isRangeInsideContainer(this.holder),a=!e&&t.Ai.isFakeCursorInsideContainer(this.holder);!i&&!a||((n=this.blokEventBus)==null||n.emit(`fake cursor is about to be toggled`,{state:e}),i&&t.Ai.addFakeCursor(),a&&t.Ai.removeFakeCursor(this.holder),(r=this.blokEventBus)==null||r.emit(`fake cursor have been set`,{state:e}))}get selected(){return this.holder.getAttribute(t.Ma.selected)===`true`}handleFakeCursor(e){let t=this.getContentElement(),n=this.getStretched();t&&this.styleManager.updateContentState(e,n)}},S,C=class e{constructor(e,t){this.holder=e,this.contentElement=t}static get wrapperStyles(){return e.styles.wrapper}static get contentStyles(){return e.styles.content}setStretchState(e,n=!1){e?this.holder.setAttribute(t.Ma.stretched,`true`):this.holder.removeAttribute(t.Ma.stretched),this.contentElement&&!n&&this.updateContentState(!1,e)}get stretched(){return this.holder.getAttribute(t.Ma.stretched)===`true`}updateContentState(e,t){this.contentElement&&(this.contentElement.className=this.getContentClasses(e,t))}getContentClasses(t,n){return t&&n?r.n(e.styles.content,e.styles.contentSelected,e.styles.contentStretched):t?r.n(e.styles.content,e.styles.contentSelected):n?r.n(e.styles.content,e.styles.contentStretched):e.styles.content}};S=C,S.styles={wrapper:`relative opacity-100 first:mt-0 last:pb-0 last:mb-0 [&_a]:cursor-pointer [&_a]:underline [&_a]:text-link [&_b]:font-bold [&_i]:italic`,content:`relative mx-auto transition-colors duration-150 ease-out max-w-blok-content`,contentSelected:`bg-selection rounded-[4px] **:[[contenteditable]]:select-none [&_img]:opacity-55 **:data-[blok-tool=stub]:opacity-55`,contentStretched:`max-w-none`};var w=class{constructor(e,t,n,r,i){this.toolInstance=e,this.name=t,this.id=n,this.tunesManager=r,this.config=i,this.toolRenderedElementInternal=null,this.contentElementInternal=null,this.readyResolver=null,this.ready=new Promise(e=>{this.readyResolver=e})}get toolRenderedElement(){return this.toolRenderedElementInternal}set toolRenderedElement(e){this.toolRenderedElementInternal=e}get contentElement(){return this.contentElementInternal}get pluginsContent(){if(this.toolRenderedElementInternal===null)throw Error(`Block pluginsContent is not yet initialized`);return this.toolRenderedElementInternal}compose(){let e=t.Qi.make(`div`,this.getWrapperStyles()),n=t.Qi.make(`div`,this.getContentStyles());this.contentElementInternal=n,e.setAttribute(t.Ma.element,``),n.setAttribute(t.Ma.elementContent,``),n.setAttribute(`data-blok-testid`,`block-content`),e.setAttribute(t.Ma.testid,t.Fi.blockWrapper),this.name&&!e.hasAttribute(`data-blok-component`)&&e.setAttribute(`data-blok-component`,this.name),e.setAttribute(`data-blok-id`,this.id);let r=this.toolInstance.render();r instanceof Promise?this.handleAsyncRender(r,n,e):this.handleSyncRender(r,n,e);let i=this.tunesManager.wrapContent(n);return e.appendChild(i),e}refreshToolRootElement(e){let n=e.querySelector(`[${t.Ma.elementContent}]`);if(!n)return;let r=n.firstElementChild;r&&r!==this.toolRenderedElementInternal&&(this.toolRenderedElementInternal=r)}handleSyncRender(e,t,n){this.toolRenderedElementInternal=e,this.addToolDataAttributes(e,n),t.appendChild(e),this.invokeRenderedLifecycle()}handleAsyncRender(e,n,r){e.then(e=>{this.toolRenderedElementInternal=e,this.addToolDataAttributes(e,r),n.appendChild(e),this.invokeRenderedLifecycle()}).catch(e=>{var n;t.Ea(`Tool render promise rejected: %o`,`error`,e),(n=this.readyResolver)==null||n.call(this)})}invokeRenderedLifecycle(){let e=this.toolInstance.rendered;if(typeof e==`function`){let n=this.readyResolver,r=this.toolInstance,i=this.name;requestAnimationFrame(()=>{try{e.call(r)}catch(e){t.Ea(`${i}: rendered() threw: ${e instanceof Error?e.message:String(e)}`,`warn`)}finally{n==null||n()}})}else{var n;(n=this.readyResolver)==null||n.call(this)}}addToolDataAttributes(e,t){this.name&&!t.hasAttribute(`data-blok-component`)&&t.setAttribute(`data-blok-component`,this.name);let n=`data-blok-placeholder`,r=this.config.placeholder,i=typeof r==`string`?r.trim():``;if(this.name===`paragraph`)return;let a=[`empty:before:pointer-events-none`,`empty:before:text-gray-text`,`empty:before:cursor-text`,`empty:before:content-[attr(data-blok-placeholder)]`,`data-[blok-empty=true]:before:pointer-events-none`,`data-[blok-empty=true]:before:text-gray-text`,`data-[blok-empty=true]:before:cursor-text`,`data-[blok-empty=true]:before:content-[attr(data-blok-placeholder)]`];if(i.length>0){e.setAttribute(n,i),e.classList.add(...a);return}r===!1&&e.hasAttribute(n)&&e.removeAttribute(n)}getWrapperStyles(){return C.wrapperStyles}getContentStyles(){return C.contentStyles}},te=class{constructor(e,t,n){this.tunes=e,this.blockAPI=n,this.tunesInstances=new Map,this.defaultTunesInstances=new Map,this.unavailableTunesData={},this.composeTunes(t)}getMenuConfig(e){let n=[],r=[],i=(e,n)=>{if(e){if(t.Qi.isElement(e)){n.push({type:t.ki.Html,element:e});return}if(Array.isArray(e)){n.push(...e);return}n.push(e)}};return i(e,n),[...this.tunesInstances.values(),...this.defaultTunesInstances.values()].map(e=>e.render()).forEach(e=>{i(e,r)}),{toolTunes:n,commonTunes:r}}wrapContent(e){return[...this.tunesInstances.values(),...this.defaultTunesInstances.values()].reduce((e,n)=>{if(t.xa(n.wrap))try{return n.wrap(e)}catch(r){return t.Ea(`Tune ${n.constructor.name} wrap method throws an Error %o`,`warn`,r),e}return e},e)}extractTunesData(){let e=n.t({},this.unavailableTunesData);return[...this.tunesInstances.entries(),...this.defaultTunesInstances.entries()].forEach(([n,r])=>{if(t.xa(r.save))try{e[n]=r.save()}catch(e){t.Ea(`Tune ${r.constructor.name} save method throws an Error %o`,`warn`,e)}}),e}get userTunes(){return this.tunesInstances}get defaultTunes(){return this.defaultTunesInstances}composeTunes(e){Array.from(this.tunes.values()).forEach(t=>{(t.isInternal?this.defaultTunesInstances:this.tunesInstances).set(t.name,t.create(e[t.name],this.blockAPI))}),Object.entries(e).forEach(([e,t])=>{this.tunesInstances.has(e)||(this.unavailableTunesData[e]=t)})}},T=function(e){return e.RENDERED=`rendered`,e.MOVED=`moved`,e.UPDATED=`updated`,e.REMOVED=`removed`,e.ON_PASTE=`onPaste`,e}({}),ne=class extends t.Ii{constructor({id:e=t.aa(),data:n,tool:r,readOnly:i,tunesData:a,parentId:o,contentIds:s,bindMutationWatchersImmediately:d=!1,lastEditedAt:f,lastEditedBy:p},m){super(),this.blokEventBus=null,this.draggableCleanup=null,this.destroyCallbacks=new Set,this.didMutated=(e=void 0)=>{let t=this.mutationHandler.handleMutation(e);t.newToolRoot&&(this.toolRenderer.toolRenderedElement=t.newToolRoot),t.shouldFireUpdate&&(this.inputManager.dropCache(),this.inputManager.updateCurrentInput(),this.toggleInputsEmptyMark(),this.call(T.UPDATED),this.emit(`didMutated`,this))};let h=e===``?t.aa():e;if(this.name=r.name,this.id=h,this.parentId=o==null?null:o,this.contentIds=s==null?[]:s,this.lastEditedAt=f==null?Date.now():f,this.lastEditedBy=p==null?null:p,this.settings=r.settings,this.config=this.settings,this.blokEventBus=m||null,this.blockAPI=new c(this),this.readOnly=i,this.tool=r,this.toolInstance=r.create(n,this.blockAPI,i),this.tunes=r.tunes,this.tunesManager=new te(this.tunes,a,this.blockAPI),this.toolRenderer=new w(this.toolInstance,this.name,this.id,this.tunesManager,this.config),this.holder=this.toolRenderer.compose(),this.ready=this.toolRenderer.ready,this.styleManager=new C(this.holder,this.toolRenderer.contentElement),this.selectionManager=new ee(this.holder,()=>this.toolRenderer.contentElement,()=>this.styleManager.stretched,this.blokEventBus,this.styleManager),this.inputManager=new u(this.holder,()=>this.didMutated()),this.mutationHandler=new x(()=>this.toolRenderer.toolRenderedElement,this.blokEventBus,e=>this.didMutated(e)),this.dataPersistenceManager=new l(this.toolInstance,()=>this.toolRenderer.toolRenderedElement,this.tunesManager,this.name,()=>this.isEmpty,this.inputManager,()=>this.call(T.UPDATED),()=>this.toggleInputsEmptyMark(),n,a),!i){let e=()=>{this.mutationHandler.watch(),this.inputManager.addInputEvents(),this.toggleInputsEmptyMark()};d?e():window.requestIdleCallback(e)}}setupDraggable(e,t){this.cleanupDraggable(),this.draggableCleanup=t.setupDragHandle(e,this)}cleanupDraggable(){this.draggableCleanup&&(this.draggableCleanup(),this.draggableCleanup=null)}call(e,n){let r=this.toolInstance[e];if(t.xa(r))try{r.call(this.toolInstance,n)}catch(n){t.Ea(`Error during '${e}' call: ${n instanceof Error?n.message:String(n)}`,`error`)}}async mergeWith(e){var n=this;if(!t.xa(n.toolInstance.merge))throw Error(`Block tool "${n.name}" does not support merging`);await n.toolInstance.merge(e)}getContentOffset(e){if(typeof this.toolInstance.getContentOffset==`function`)return this.toolInstance.getContentOffset(e)}getToolbarAnchorElement(){if(typeof this.toolInstance.getToolbarAnchorElement==`function`)return this.toolInstance.getToolbarAnchorElement()}async save(){var e=this;let t=await e.dataPersistenceManager.save();if(t!==void 0)return t.id=e.id,t}async validate(e){return this.dataPersistenceManager.validate(e)}getTunes(){let e=typeof this.toolInstance.renderSettings==`function`?this.toolInstance.renderSettings():[];return this.tunesManager.getMenuConfig(e)}updateCurrentInput(){this.inputManager.updateCurrentInput()}dispatchChange(){this.didMutated()}async setData(e){return this.dataPersistenceManager.setData(e)}addDestroyCallback(e){return this.destroyCallbacks.add(e),()=>{this.destroyCallbacks.delete(e)}}destroy(){let e=Array.from(this.destroyCallbacks);this.destroyCallbacks.clear(),e.forEach(e=>e()),this.mutationHandler.destroy(),this.inputManager.destroy(),this.draggableCleanup&&(this.draggableCleanup(),this.draggableCleanup=null),super.destroy(),t.xa(this.toolInstance.destroy)&&this.toolInstance.destroy()}setReadOnly(e){this.readOnly!==e&&(this.readOnly=e,e?(this.inputManager.removeInputEvents(),this.mutationHandler.unwatch()):(this.inputManager.addInputEvents(),this.mutationHandler.watch()),typeof this.toolInstance.setReadOnly==`function`&&this.toolInstance.setReadOnly(e))}setPlaceholder(e){let t=this.toolInstance;typeof t.setPlaceholder==`function`&&t.setPlaceholder(e)}async getActiveToolboxEntry(){var e=this;let n=e.tool.toolbox;if(!n)return;if(n.length===1)return Promise.resolve(n[0]);let r=await e.data;return n.find(e=>e.data!==void 0&&t.Ui(e.data,r))}async exportDataAsString(){var e=this,t;return e.dataPersistenceManager.exportDataAsString((t=e.tool.conversionConfig)==null?{}:t)}get inputs(){return this.inputManager.inputs}get currentInput(){return this.inputManager.currentInput}get currentInputIndex(){return this.inputManager.currentInputIndex}set currentInput(e){this.inputManager.currentInput=e}get firstInput(){return this.inputManager.firstInput}get lastInput(){return this.inputManager.lastInput}get nextInput(){return this.inputManager.nextInput}get previousInput(){return this.inputManager.previousInput}get data(){return this.dataPersistenceManager.data}get preservedData(){return this.dataPersistenceManager.preservedData}get preservedTunes(){return this.dataPersistenceManager.preservedTunes}get sanitize(){return this.tool.sanitizeConfig}get mergeable(){return t.xa(this.toolInstance.merge)}get focusable(){return this.inputs.length!==0}get isEmpty(){let e=t.Qi.isEmpty(this.pluginsContent,`/`),n=!this.hasMedia;return e&&n}get hasMedia(){return!!this.holder.querySelector([`img`,`iframe`,`video`,`audio`,`source`,`input`,`textarea`,`twitterwidget`].join(`,`))}set selected(e){this.selectionManager.selected=e}get selected(){return this.selectionManager.selected}setStretchState(e){this.styleManager.setStretchState(e,this.selected)}set stretched(e){this.setStretchState(e)}get stretched(){return this.styleManager.stretched}get pluginsContent(){return this.toolRenderer.pluginsContent}unwatchBlockMutations(){this.mutationHandler.unwatch()}refreshToolRootElement(){this.toolRenderer.refreshToolRootElement(this.holder),this.inputManager.dropCache()}toggleInputsEmptyMark(){this.inputs.forEach(t.ea)}};function re(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.includes(r))continue;n[r]=e[r]}return n}function ie(e,t){if(e==null)return{};var n,r,i=re(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.includes(n)||{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}var ae=[`file`,`url`,`withBorder`,`withBackground`,`stretched`],oe=[`caption`,`alignment`],se=[`content`,`withHeadings`,`withHeadingColumn`,`stretched`],ce=[`parent`,`content`],le={general:null,note:`blue`,important:`purple`,warning:`orange`,additional:`yellow`,recommendation:`green`,caution:`red`},ue={blue:`note`,purple:`important`,orange:`warning`,yellow:`additional`,green:`recommendation`,red:`caution`},de=`💡`,fe=(e,t,n,r)=>{let i=`${t}.${n}`;e.has(i)||(e.add(i),console.warn(`[Blok migration] ${t} block ${r} unsupported field "${n}" (no Blok equivalent)`))},pe=(e,t)=>typeof e!=`object`||!e?!1:e[t]!==void 0,me=(e,t)=>{e.type===`quote`&&pe(e.data,`alignment`)&&fe(t,`quote`,`alignment`,`ignored`)},he=e=>typeof e==`object`&&`text`in e&&!(`content`in e),ge=e=>typeof e==`string`?{content:e}:he(e)?{content:e.text,checked:e.checked}:e,_e=e=>e.some(e=>{let t=ge(e);return t.items!==void 0&&t.items.length>0}),ve=e=>typeof e==`object`&&!!e&&`text`in e&&typeof e.text==`string`,ye=e=>typeof e==`object`&&!!e&&`checked`in e&&typeof e.checked==`boolean`,be=e=>typeof e==`object`&&!!e&&`style`in e&&typeof e.style==`string`,xe=e=>typeof e==`object`&&!!e&&`start`in e&&typeof e.start==`number`,Se=e=>typeof e==`object`&&!!e&&`items`in e,Ce=e=>typeof e==`object`&&!!e&&`style`in e&&`items`in e&&Array.isArray(e.items),we=e=>e.type===`list`&&Ce(e.data),Te=e=>e.type===`checklist`&&typeof e.data==`object`&&e.data!==null&&Array.isArray(e.data.items),Ee=e=>e.type===`linkTool`&&typeof e.data==`object`&&e.data!==null&&typeof e.data.link==`string`,De=e=>{if(e.type!==`toggleList`)return!1;let t=e.data;return typeof t==`object`&&!!t&&`title`in t},Oe=e=>{if(e.type!==`callout`)return!1;let t=e.data;return typeof t==`object`&&!!t&&`body`in t},ke=e=>e.type===`quote`&&(pe(e.data,`caption`)||pe(e.data,`alignment`)),Ae=e=>{if(e.type!==`image`)return!1;let t=e.data;if(typeof t!=`object`||!t)return!1;let n=t.file;if(typeof n==`object`&&n&&typeof n.url==`string`)return!0;let r=typeof t.url==`string`,i=`withBorder`in t||`withBackground`in t||`stretched`in t;return r&&i},je=e=>{if(e.type!==`table`)return!1;let t=_t(e.data);return t===null?!1:t.some(e=>Array.isArray(e)&&e.some(e=>typeof e==`string`))},Me=e=>e.type===`raw`&&pe(e.data,`html`),Ne=e=>e.type===`warning`&&typeof e.data==`object`&&e.data!==null,Pe=e=>{if(e.type!==`attaches`)return!1;let t=e.data,n=typeof t==`object`&&t?t.file:void 0;return typeof n==`object`&&!!n&&typeof n.url==`string`},Fe=e=>{if(!we(e))return!1;let t=e.data.items;return _e(t)},Ie=e=>e.parent!==void 0||e.content!==void 0&&e.content.length>0,Le=e=>{let t=e.some(Ie),n=e.some(we),r=e.some(De),i=e.some(Oe),a=e.some(Ae),o=e.some(Te),s=e.some(Ee),c=e.some(ke),l=e.some(je),u=e.some(Me),d=e.some(Ne),f=e.some(Pe),p=n||r||i||a||o||s||c||l||u||d||f;return t&&!p?{format:`hierarchical`,hasHierarchy:!0}:p?{format:`legacy`,hasHierarchy:t||l||d||e.some(Fe)||e.some(e=>{var t;return De(e)&&((t=e.data.body)==null?void 0:t.blocks)!==void 0&&e.data.body.blocks.length>0})||e.some(e=>{var t;return Oe(e)&&((t=e.data.body)==null?void 0:t.blocks)!==void 0&&e.data.body.blocks.length>0})}:{format:`flat`,hasHierarchy:!1}},Re=(e,r,i,a,o,s,c)=>{let l=[];return e.forEach((e,u)=>{let d=ge(e),f=t.aa();l.push(f);let p=a===`ordered`&&i===0&&u===0&&o!==void 0&&o!==1,m=d.items&&d.items.length>0,h=n.t(n.t({id:f,type:`list`,data:n.t(n.t({text:d.content,checked:d.checked,style:a},i>0?{depth:i}:{}),p?{start:o}:{})},s===void 0?{}:{tunes:s}),r===void 0?{}:{parent:r});if(c.push(h),!m||!d.items)return;let g=Re(d.items,f,i+1,a,void 0,s,c);g.length>0&&(h.content=g)}),l},ze=(e,t)=>{let n=[],r=e.style,i=e.start;return Re(e.items,void 0,0,r,i,t,n),n},Be=(e,r,i,a)=>{var o;if(e.parent!==void 0){a.push(e);return}let s=(o=e.id)==null?t.aa():o;i.push(s),a.push(n.t(n.t({},e),{},{id:s,parent:r}))},Ve=(e,t)=>{let n=[],r=[];for(let i of e){let e=$e([i]);for(let i of e)Be(i,t,n,r)}for(let e of r){let r=e.parent!==void 0,a=e.id!==void 0&&n.includes(e.id);if(!r&&!a){var i;throw Error(`expandLegacyBodyBlocks: orphaned block emitted (type=${e.type}, id=${(i=e.id)==null?`<none>`:i}). Every root-level expansion must be re-parented to ${t}.`)}}return{childIds:n,childBlocks:r}},He=e=>{var r,i,a;let o=[],s=(r=e.id)==null?t.aa():r,{childIds:c,childBlocks:l}=Ve((i=(a=e.data.body)==null?void 0:a.blocks)==null?[]:i,s),u=n.t(n.t({id:s},e.tunes===void 0?{}:{tunes:e.tunes}),c.length>0?{content:c}:{}),d=typeof e.data.isExpanded==`boolean`?{isOpen:e.data.isExpanded}:{};return typeof e.data.titleVariant==`number`?o.push(n.t(n.t({},u),{},{type:`header`,data:n.t({text:e.data.title,level:e.data.titleVariant,isToggleable:!0},d)})):o.push(n.t(n.t({},u),{},{type:`toggle`,data:n.t({text:e.data.title},d)})),o.push(...l),o},Ue=e=>{var r,i,a,o,s;let c=[],l=(r=e.id)==null?t.aa():r,{childIds:u,childBlocks:d}=Ve((i=(a=e.data.body)==null?void 0:a.blocks)==null?[]:i,l),f=(o=e.data.variant)==null?`general`:o,p=f in le?le[f]:null,m=e.data.isEmojiVisible===!1?``:(s=e.data.emoji)==null?de:s;return c.push(n.t(n.t({id:l,type:`callout`,data:{emoji:m,textColor:null,backgroundColor:p}},e.tunes===void 0?{}:{tunes:e.tunes}),u.length>0?{content:u}:{})),c.push(...d),c},We=(e,r)=>{var i,a;let o=(i=e.data)==null?{}:i,{file:s,url:c,withBorder:l,withBackground:u,stretched:d}=o,f=ie(o,ae);u===!0&&fe(r,`image`,`withBackground`,`dropped`);let p=typeof s==`object`&&s?s.url:void 0,m=typeof p==`string`?p:c,h=typeof m==`string`?m:``;return n.t(n.t({},e),{},{id:(a=e.id)==null?t.aa():a,data:n.t(n.t(n.t({url:h},f),l===!0?{frame:`border`}:{}),d===!0?{size:`full`}:{})})},Ge=(e,t)=>ze({style:`checklist`,items:e.items},t),Ke=(e,r)=>{var i,a;let o=(i=e.data.meta)==null?{}:i,s=typeof o.image==`object`&&o.image!==null?o.image.url:o.image;return o.site_name!==void 0&&fe(r,`linkTool`,`site_name`,`dropped`),n.t(n.t({},e),{},{id:(a=e.id)==null?t.aa():a,type:`bookmark`,data:n.t(n.t(n.t(n.t(n.t({url:e.data.link},o.title===void 0?{}:{title:o.title}),o.description===void 0?{}:{description:o.description}),typeof s==`string`?{image:s}:{}),o.favicon===void 0?{}:{favicon:o.favicon}),o.domain===void 0?{}:{domain:o.domain})})},qe=(e,r)=>{var i,a;me(e,r);let o=(i=e.data)==null?{}:i,{caption:s,alignment:c}=o,l=ie(o,oe),u=n.t(n.t({},e),{},{id:(a=e.id)==null?t.aa():a,data:l});return typeof s!=`string`||s.length===0?[u]:[u,{id:t.aa(),type:`paragraph`,data:{text:s}}]},Je=e=>{var r,i,a;let o=(r=e.id)==null?t.aa():r,s=(i=e.data)==null?{}:i,{content:c,withHeadings:l,withHeadingColumn:u,stretched:d}=s,f=ie(s,se),p=(a=_t(s))==null?[]:a,m=[],h=p.map(e=>Array.isArray(e)?e.map(e=>{if(gt(e))return e;let n=typeof e==`string`?e:``;if(n.length===0)return{blocks:[]};let r=t.aa();return m.push({id:r,type:`paragraph`,data:{text:n},parent:o}),{blocks:[r]}}):e);return[n.t(n.t({},e),{},{id:o,data:n.t(n.t(n.t({},f),{},{withHeadings:l===!0,withHeadingColumn:u===!0},d===!0?{stretched:!0}:{}),{},{content:h})}),...m]},Ye=e=>{var r,i;let a=(r=e.data)==null?void 0:r.html;return n.t(n.t({},e),{},{id:(i=e.id)==null?t.aa():i,type:`code`,data:{code:typeof a==`string`?a:``}})},Xe=`⚠️`,Ze=e=>{var r,i;let a=(r=e.id)==null?t.aa():r,o=(i=e.data)==null?{}:i,s=typeof o.title==`string`?o.title:``,c=typeof o.message==`string`?o.message:``,l=[];for(let e of[s,c])e.length!==0&&l.push({id:t.aa(),type:`paragraph`,data:{text:e},parent:a});let u=l.map(e=>e.id);return[n.t(n.t({id:a,type:`callout`,data:{emoji:Xe,textColor:null,backgroundColor:`orange`}},e.tunes===void 0?{}:{tunes:e.tunes}),u.length>0?{content:u}:{}),...l]},Qe=(e,r)=>{var i,a;let o=(i=e.data)==null?{}:i,s=typeof o.file==`object`&&o.file!==null?o.file:{},c=typeof s.url==`string`?s.url:``,l=typeof o.title==`string`?o.title:void 0;return(s.name!==void 0||s.size!==void 0||s.extension!==void 0)&&fe(r,`attaches`,`file metadata`,`dropped`),n.t(n.t({},e),{},{id:(a=e.id)==null?t.aa():a,type:`bookmark`,data:n.t({url:c},l===void 0?{}:{title:l})})},$e=e=>{let r=[],i=new Set;for(let o of e)if(we(o)){let e=ze(o.data,o.tunes);r.push(...e)}else if(Te(o)){let e=Ge(o.data,o.tunes);r.push(...e)}else if(Ee(o))r.push(Ke(o,i));else if(De(o)){let e=He(o);r.push(...e)}else if(Oe(o)){let e=Ue(o);r.push(...e)}else if(Ae(o))r.push(We(o,i));else if(ke(o)){let e=qe(o,i);r.push(...e)}else if(je(o))r.push(...Je(o));else if(Me(o))r.push(Ye(o));else if(Ne(o))r.push(...Ze(o));else if(Pe(o))r.push(Qe(o,i));else{var a;r.push(n.t(n.t({},o),{},{id:(a=o.id)==null?t.aa():a}))}return r},et=(e,t)=>{e&&t.add(e)},tt=e=>{let{parent:t,content:n}=e;return ie(e,ce)},nt=(e,t,n)=>{let r=[];for(let i of e){let e=t.get(i);if(e&&e.type===`list`){let i=rt(e,t,n);r.push(...i)}}return r},rt=(e,t,n)=>{let r=[];e.id&&n.add(e.id);let i=e.data,a={content:ve(i)?i.text:``,checked:ye(i)?i.checked:void 0},o=e.content;return o!==void 0&&o.length>0&&(a.items=nt(o,t,n)),a.items!==void 0&&a.items.length===0&&delete a.items,r.push(a),r},it=(e,t,r)=>{let i=rt(e,t,r),a=e.data,o=be(a)?a.style:`unordered`,s=xe(a)?a.start:void 0;return n.t({id:e.id,type:`list`,data:n.t({style:o,items:i},o===`ordered`&&s!==void 0&&s!==1?{start:s}:{})},e.tunes===void 0?{}:{tunes:e.tunes})};function at(e,t,n){let r=[];for(let i of e){if(n.has(i))continue;let e=t.get(i);if(e!==void 0){if(ut(e)){r.push(it(e,t,n));continue}if(st(e)){r.push(ot(e,t,n));continue}if(ct(e)){r.push(lt(e,t,n));continue}if(dt(e)){r.push(ft(e,t,n));continue}et(e.id,n),r.push(tt(e))}}return r}var ot=(e,t,r)=>{var i;et(e.id,r);let a=e.data,o=ve(a)?a.text:``,s=typeof(a==null?void 0:a.isOpen)==`boolean`?a.isOpen:void 0,c=at((i=e.content)==null?[]:i,t,r);return n.t({id:e.id,type:`toggleList`,data:n.t(n.t({title:o},s===void 0?{}:{isExpanded:s}),c.length>0?{body:{blocks:c}}:{})},e.tunes===void 0?{}:{tunes:e.tunes})},st=e=>e.type===`toggle`,ct=e=>{if(e.type!==`header`)return!1;let t=e.data;return typeof t==`object`&&!!t&&t.isToggleable===!0},lt=(e,t,r)=>{var i;et(e.id,r);let a=e.data,o=ve(a)?a.text:``,s=typeof(a==null?void 0:a.level)==`number`?a.level:void 0,c=typeof(a==null?void 0:a.isOpen)==`boolean`?a.isOpen:void 0,l=at((i=e.content)==null?[]:i,t,r);return n.t({id:e.id,type:`toggleList`,data:n.t(n.t(n.t({title:o},s===void 0?{}:{titleVariant:s}),c===void 0?{}:{isExpanded:c}),l.length>0?{body:{blocks:l}}:{})},e.tunes===void 0?{}:{tunes:e.tunes})},ut=e=>{if(e.type!==`list`)return!1;let t=e.data,n=ve(t),r=Se(t);return n&&!r},dt=e=>{if(e.type!==`callout`)return!1;let t=e.data;return typeof t==`object`&&!!t&&!(`body`in t)},ft=(e,t,r)=>{var i,a;et(e.id,r);let o=e.data,s=o.backgroundColor,c=s==null||(i=ue[s])==null?`general`:i,l=o.emoji,u=typeof l==`string`&&l.length>0,d=u?l:null,f=at((a=e.content)==null?[]:a,t,r);return n.t({id:e.id,type:`callout`,data:n.t({title:``,variant:c,emoji:d,isEmojiVisible:u},f.length>0?{body:{blocks:f}}:{})},e.tunes===void 0?{}:{tunes:e.tunes})},pt=(e,t,n)=>{if(!e.id||!e.parent||!t.has(e.parent))return;let r=n.get(e.parent);if(r===void 0){n.set(e.parent,[e.id]);return}r.push(e.id)},mt=(e,t,n)=>{let r=(Array.isArray(e)?e:[]).filter(e=>n.has(e));for(let e of t)r.includes(e)||r.push(e);return r},ht=e=>{let t=e.map(e=>n.t({},e)),r=new Map;for(let e of t)e.id&&r.set(e.id,e);let i=new Map;for(let e of t)pt(e,r,i);for(let[e,t]of i){let n=r.get(e);n!==void 0&&(n.content=mt(n.content,t,r))}let a=new Map;for(let e of t)e.id&&a.set(e.id,e);let o=t.some(ut),s=t.some(st),c=t.some(e=>ct(e)&&!e.parent),l=t.some(dt);if(!o&&!s&&!c&&!l)return t.map(tt);let u=[],d=new Set;for(let e of t){if(e.id&&d.has(e.id))continue;let t=ut(e),n=t&&!e.parent,r=st(e),i=r&&!e.parent,o=ct(e),s=o&&!e.parent,c=dt(e),l=c&&!e.parent,f=!t&&!r&&!o&&!c;if(n){let t=it(e,a,d);u.push(t)}if(i){let t=ot(e,a,d);u.push(t)}if(s){let t=lt(e,a,d);u.push(t)}if(l){let t=ft(e,a,d);u.push(t)}f&&(u.push(tt(e)),et(e.id,d))}return u},gt=e=>typeof e==`object`&&!!e&&Array.isArray(e.blocks),_t=e=>{if(typeof e!=`object`||!e)return null;let t=e.content;return Array.isArray(t)?t:null},vt=(e,t,n)=>{if(gt(e))for(let r of e.blocks)typeof r!=`string`||n.has(r)||n.set(r,t)},yt=(e,t,n)=>{Array.isArray(e)&&e.forEach(e=>vt(e,t,n))},bt=(e,t)=>{if(e.id===void 0||e.id===null)return;let n=_t(e.data);if(n===null)return;let r=e.id;n.forEach(e=>yt(e,r,t))},xt=e=>{let t=new Map;return e.filter(e=>e.type===`table`).forEach(e=>bt(e,t)),t.size===0?e:e.map(e=>{if(e.id===void 0||e.id===null)return e;let r=t.get(e.id);return r===void 0||e.parent!==void 0&&e.parent!==null?e:n.t(n.t({},e),{},{parent:r})})},St=/^cell-([1-9]\d*)-([1-9]\d*)$/,Ct=e=>{if(typeof e!=`string`)return null;let t=St.exec(e);if(t===null)return null;let n=Number(t[1])-1,r=Number(t[2])-1;return n<0||r<0?null:{row:n,col:r}},wt=(e,t,n)=>{let r=_t(e.data);if(r===null)return!1;let i=r[t];if(!Array.isArray(i))return!1;let a=i[n];return gt(a)&&a.blocks.length===0},Tt=e=>{let t=new Set;return e.filter(e=>e.type===`table`).forEach(e=>{let n=_t(e.data);n==null||n.forEach(e=>{Array.isArray(e)&&e.forEach(e=>{gt(e)&&e.blocks.forEach(e=>{typeof e==`string`&&t.add(e)})})})}),t},Et=e=>{let t=e.filter(e=>e.type===`table`&&e.id!==void 0&&e.id!==null);if(t.length!==1)return e;let r=Tt(e),i=new Map;for(let t of e)if(t.id!==void 0&&t.id!==null){var a;i.set(t.id,((a=i.get(t.id))==null?0:a)+1)}let o=new Map,s=new Map;for(let a of e){var c,l;if(a.id===void 0||a.id===null||a.parent!==void 0&&a.parent!==null||r.has(a.id)||((c=i.get(a.id))==null?0:c)>1)continue;let e=Ct(a.id);if(e===null)continue;let u=t.filter(t=>wt(t,e.row,e.col));if(u.length!==1)continue;let d=u[0].id;o.set(a.id,d);let f=(l=s.get(d))==null?[]:l;f.push(n.t(n.t({},e),{},{id:a.id})),s.set(d,f)}return o.size===0?e:e.map(e=>{if(e.id!==void 0&&e.id!==null&&o.has(e.id))return n.t(n.t({},e),{},{parent:o.get(e.id)});if(e.type===`table`&&e.id!==void 0&&e.id!==null&&s.has(e.id)){var t;let r=(t=s.get(e.id))==null?[]:t,i=_t(e.data);if(i===null)return e;let a=i.map((e,t)=>Array.isArray(e)?e.map((e,i)=>{let a=r.find(e=>e.row===t&&e.col===i);return a===void 0||!gt(e)?e:n.t(n.t({},e),{},{blocks:[...e.blocks,a.id]})}):e);return n.t(n.t({},e),{},{data:n.t(n.t({},e.data),{},{content:a})})}return e})},Dt=(e,t)=>t===`legacy`?e!==`legacy`:!1,Ot=(e,t)=>e===`legacy`||e===`auto`&&t===`legacy`,kt=`blok-block--target`,At=1800;function jt(e){e.classList.remove(kt),e.offsetWidth,e.classList.add(kt);let t={removed:!1},n=()=>{t.removed||(t.removed=!0,e.classList.remove(kt),e.removeEventListener(`animationend`,r))},r=t=>{t.target===e&&n()};e.addEventListener(`animationend`,r),window.setTimeout(n,At)}var Mt=class extends s{constructor(...e){var n;super(...e),n=this,this.insert=(e,n={},r={},i,a,o,s)=>{let l=e==null?this.config.defaultBlock:e,u=(()=>{if(!l)return l;let e=i==null?this.Blok.BlockManager.currentBlockIndex:i,n=this.Blok.BlockManager.getBlockByIndex(e);return n!==void 0&&t.Yi(n)&&t.Xi(l)?`paragraph`:l})();return new c(this.Blok.BlockManager.insert({id:s,tool:u,data:n,index:i,needToFocus:a,replace:o}))},this.composeBlockData=async e=>{let t=n.Blok.Tools.blockTools.get(e);if(t===void 0)throw Error(`Block Tool with type "${e}" not found`);return new ne({tool:t,api:n.Blok.API,readOnly:!0,data:{},tunesData:{}}).data},this.update=async(e,t,r)=>{let{BlockManager:i}=n.Blok,a=i.getBlockById(e);if(a===void 0)throw Error(`Block with id "${e}" not found`);return new c(await i.update(a,t,r))},this.convert=async(e,r,i)=>{var a,o;let{BlockManager:s,Tools:l}=n.Blok,u=s.getBlockById(e);if(!u)throw Error(`Block with id "${e}" not found`);let d=l.blockTools.get(u.name),f=l.blockTools.get(r);if(!f)throw Error(`Block Tool with type "${r}" not found`);let p=(d==null||(a=d.conversionConfig)==null?void 0:a.export)!==void 0,m=((o=f.conversionConfig)==null?void 0:o.import)!==void 0;if(p&&m)return new c(await s.convert(u,r,i));{let e=[p?!1:t.ua(u.name),m?!1:t.ua(r)].filter(Boolean).join(` and `);throw Error(`Conversion from "${u.name}" to "${r}" is not possible. ${e} tool(s) should provide a "conversionConfig"`)}},this.insertMany=(e,t=this.Blok.BlockManager.blocks.length-1)=>{this.validateIndex(t);let n=xt(e).map(({id:e,type:t,data:n,tunes:r,parent:i,content:a,lastEditedAt:o,lastEditedBy:s})=>this.Blok.BlockManager.composeBlock({id:e,tool:t||this.config.defaultBlock,data:n,tunes:r,parentId:i,contentIds:a,lastEditedAt:o,lastEditedBy:s}));return this.Blok.BlockManager.insertMany(n,t),n.map(e=>new c(e))},this.insertInsideParent=(e,t,n)=>(this.Blok.BlockManager.suppressStopCapturing||this.Blok.YjsManager.stopCapturing(),new c(this.Blok.BlockManager.insertInsideParent(e,t,n))),this.splitBlock=(e,t,n,r,i)=>{this.Blok.YjsManager.stopCapturing();let a=this.Blok.BlockManager.splitBlockWithData(e,t,n,r,i);return queueMicrotask(()=>{this.Blok.YjsManager.stopCapturing()}),new c(a)}}get methods(){let e=this;return{get isSyncingFromYjs(){return e.Blok.BlockManager.isSyncingFromYjs},clear:()=>this.clear(),render:e=>this.render(e),renderFromHTML:e=>this.renderFromHTML(e),delete:e=>this.delete(e),move:(e,t)=>this.move(e,t),getBlockByIndex:e=>this.getBlockByIndex(e),getById:e=>this.getById(e),getCurrentBlockIndex:()=>this.getCurrentBlockIndex(),getBlockIndex:e=>this.getBlockIndex(e),getBlocksCount:()=>this.getBlocksCount(),getBlockByElement:e=>this.getBlockByElement(e),getChildren:e=>this.getChildren(e),insert:this.insert,insertMany:this.insertMany,update:this.update,composeBlockData:this.composeBlockData,convert:this.convert,setBlockParent:(e,t)=>this.setBlockParent(e,t),stopBlockMutationWatching:e=>this.stopBlockMutationWatching(e),splitBlock:this.splitBlock,insertInsideParent:this.insertInsideParent,transact:e=>this.transact(e),transactWithoutCapture:e=>this.transactWithoutCapture(e),setPointerDragActive:e=>this.setPointerDragActive(e)}}getBlocksCount(){return this.Blok.BlockManager.blocks.length}getCurrentBlockIndex(){return this.Blok.BlockManager.currentBlockIndex}getBlockIndex(e){let n=this.Blok.BlockManager.getBlockById(e);if(!n){t.Da("There is no block with id `"+e+"`",`warn`);return}return this.Blok.BlockManager.getBlockIndex(n)}getBlockByIndex(e){let n=this.Blok.BlockManager.getBlockByIndex(e);if(n===void 0){t.Da("There is no block at index `"+e+"`",`warn`);return}return new c(n)}getById(e){let n=this.Blok.BlockManager.getBlockById(e);return n===void 0?(t.Da("There is no block with id `"+e+"`",`warn`),null):new c(n)}getBlockByElement(e){let n=this.Blok.BlockManager.getBlock(e);if(n===void 0){var r,i;t.Da(`There is no block corresponding to element <${(r=(i=e.tagName)==null?void 0:i.toLowerCase())==null?`unknown`:r}>`,`warn`);return}return new c(n)}getChildren(e){return this.Blok.BlockManager.blocks.filter(t=>t.parentId===e).map(e=>new c(e))}move(e,t){this.Blok.BlockManager.move(e,t)}async delete(e=this.Blok.BlockManager.currentBlockIndex){var n=this;let r=n.Blok.BlockManager.getBlockByIndex(e);if(r===void 0){t.Da(`There is no block at index \`${e}\``,`warn`);return}try{await n.Blok.BlockManager.removeBlock(r)}catch(e){t.Da(e,`warn`);return}n.Blok.BlockManager.currentBlock&&n.Blok.Caret.setToBlock(n.Blok.BlockManager.currentBlock,n.Blok.Caret.positions.END),n.Blok.Toolbar.close()}async clear(){var e=this;await e.Blok.BlockManager.clear(!0),e.Blok.InlineToolbar.close()}async render(e){var t=this;if(e===void 0||e.blocks===void 0)throw Error(`Incorrect data passed to the render() method`);t.Blok.ModificationsObserver.disable(),t.Blok.Renderer.markRenderStart();try{await t.Blok.BlockManager.clear(),await t.Blok.Renderer.render(e.blocks)}finally{t.Blok.Renderer.markRenderEnd()}t.Blok.ModificationsObserver.enable(),t.processPendingHashScroll()}async renderFromHTML(e){var t=this;t.Blok.Renderer.markRenderStart();try{return await t.Blok.BlockManager.clear(),t.Blok.Paste.processText(e,!0)}finally{t.Blok.Renderer.markRenderEnd()}}async importMarkdown(e,t){var n=this;let{markdownToBlocks:r}=await Promise.resolve().then(()=>require(`../markdown.cjs`)),i={blocks:await r(e,t)};return await n.render(i),i}setBlockParent(e,n){let r=this.Blok.BlockManager.getBlockById(e);if(r===void 0){t.Da("There is no block with id `"+e+"`",`warn`);return}this.Blok.BlockManager.setBlockParent(r,n)}stopBlockMutationWatching(e){let t=this.Blok.BlockManager.getBlockByIndex(e);t!==void 0&&t.unwatchBlockMutations()}transact(e){this.Blok.BlockManager.transactForTool(e)}transactWithoutCapture(e){this.Blok.YjsManager.transactWithoutCapture(e)}setPointerDragActive(e){this.Blok.BlockManager.setPointerDragActive(e)}validateIndex(e){if(typeof e!=`number`)throw Error(`Index should be a number`);if(e<0)throw Error(`Index should be greater than or equal to 0`)}processPendingHashScroll(){var e,t;let n=this.Blok.Renderer.pendingHashScroll;if(n===null)return;this.Blok.Renderer.pendingHashScroll=null;let r=document.querySelector(`[data-blok-id="${CSS.escape(n)}"]`);if(r===null)return;let i=(e=(t=this.config.scrollToBlock)==null?void 0:t.topOffset)==null?0:e,a=r.getBoundingClientRect().top+window.scrollY-i;window.scrollTo({top:a,behavior:`smooth`});let o=this.Blok.BlockManager.getBlockById(n);o!==void 0&&this.Blok.BlockSelection.selectBlock(o),jt(r)}},Nt=(e,t)=>typeof e==`number`?t.BlockManager.getBlockByIndex(e):typeof e==`string`?t.BlockManager.getBlockById(e):t.BlockManager.getBlockById(e.id),Pt=class extends s{constructor(...e){super(...e),this.setToFirstBlock=(e=this.Blok.Caret.positions.DEFAULT,t=0)=>this.Blok.BlockManager.firstBlock?(this.Blok.Caret.setToBlock(this.Blok.BlockManager.firstBlock,e,t),!0):!1,this.setToLastBlock=(e=this.Blok.Caret.positions.DEFAULT,t=0)=>this.Blok.BlockManager.lastBlock?(this.Blok.Caret.setToBlock(this.Blok.BlockManager.lastBlock,e,t),!0):!1,this.setToPreviousBlock=(e=this.Blok.Caret.positions.DEFAULT,t=0)=>this.Blok.BlockManager.previousBlock?(this.Blok.Caret.setToBlock(this.Blok.BlockManager.previousBlock,e,t),!0):!1,this.setToNextBlock=(e=this.Blok.Caret.positions.DEFAULT,t=0)=>this.Blok.BlockManager.nextBlock?(this.Blok.Caret.setToBlock(this.Blok.BlockManager.nextBlock,e,t),!0):!1,this.setToBlock=(e,t=this.Blok.Caret.positions.DEFAULT,n=0)=>{let r=Nt(e,this.Blok);return r===void 0?!1:(this.Blok.Caret.setToBlock(r,t,n),!0)},this.focus=(e=!1)=>e?this.setToLastBlock(this.Blok.Caret.positions.END):this.setToFirstBlock(this.Blok.Caret.positions.START),this.updateLastCaretAfterPosition=()=>{this.Blok.YjsManager.updateLastCaretAfterPosition()}}get methods(){return{setToFirstBlock:this.setToFirstBlock,setToLastBlock:this.setToLastBlock,setToPreviousBlock:this.setToPreviousBlock,setToNextBlock:this.setToNextBlock,setToBlock:this.setToBlock,focus:this.focus,updateLastCaretAfterPosition:this.updateLastCaretAfterPosition}}},Ft=class extends s{get methods(){return{emit:(e,t)=>this.emit(e,t),off:(e,t)=>this.off(e,t),on:(e,t)=>this.on(e,t)}}on(e,t){this.eventsDispatcher.on(e,t)}emit(e,t){this.eventsDispatcher.emit(e,t)}off(e,t){this.eventsDispatcher.off(e,t)}},It=class extends s{get methods(){return{undo:()=>this.undo(),redo:()=>this.redo(),canUndo:()=>this.canUndo(),canRedo:()=>this.canRedo(),clear:()=>this.clear()}}undo(){this.Blok.YjsManager.undo()}redo(){this.Blok.YjsManager.redo()}canUndo(){return this.Blok.YjsManager.canUndo()}canRedo(){return this.Blok.YjsManager.canRedo()}clear(){this.Blok.YjsManager.clear()}},Lt=class extends s{constructor(...e){super(...e),this.cachedMethods=null}get methods(){return this.cachedMethods===null&&(this.cachedMethods={t:e=>this.Blok.I18n.t(e),has:e=>this.Blok.I18n.has(e),getEnglishTranslation:e=>this.Blok.I18n.getEnglishTranslation(e),getLocale:()=>this.Blok.I18n.getLocale()}),this.cachedMethods}},Rt=class extends s{get methods(){let e=this.config;return{blocks:this.Blok.BlocksAPI.methods,caret:this.Blok.CaretAPI.methods,tools:this.Blok.ToolsAPI.methods,events:this.Blok.EventsAPI.methods,history:this.Blok.HistoryAPI.methods,listeners:this.Blok.ListenersAPI.methods,notifier:this.Blok.NotifierAPI.methods,sanitizer:this.Blok.SanitizerAPI.methods,saver:this.Blok.SaverAPI.methods,selection:this.Blok.SelectionAPI.methods,styles:this.Blok.StylesAPI.classes,toolbar:this.Blok.ToolbarAPI.methods,inlineToolbar:this.Blok.InlineToolbarAPI.methods,tooltip:this.Blok.TooltipAPI.methods,i18n:this.Blok.I18nAPI.methods,readOnly:this.Blok.ReadOnlyAPI.methods,ui:this.Blok.UiAPI.methods,theme:this.Blok.ThemeAPI.methods,config:{get linkPaste(){return e.linkPaste},get link(){return e.link}},rectangleSelection:this.Blok.RectangleSelection}}},zt=class extends s{get methods(){return{close:()=>this.close(),open:()=>this.open()}}open(){this.Blok.InlineToolbar.tryToShow()}close(){this.Blok.InlineToolbar.close()}},Bt=class extends s{get methods(){return{on:(e,t,n,r)=>this.on(e,t,n,r),off:(e,t,n,r)=>this.off(e,t,n,r),offById:e=>this.offById(e)}}on(e,t,n,r){return this.listeners.on(e,t,n,r)}off(e,t,n,r){this.listeners.off(e,t,n,r)}offById(e){this.listeners.offById(e)}},Vt=class{constructor(e=i.t){this.notifierModule=null,this.loadingPromise=null,this.position=e}loadNotifierModule(){return this.notifierModule===null?(this.loadingPromise===null&&(this.loadingPromise=Promise.resolve().then(()=>require(`./notifier-CFYHvVe5.cjs`)).then(e=>{let t=e;if(!this.isNotifierModule(t))throw Error(`notifier module does not expose a "show" method.`);return this.notifierModule=t,t}).catch(e=>{throw this.loadingPromise=null,e})),this.loadingPromise):Promise.resolve(this.notifierModule)}show(e){this.loadNotifierModule().then(t=>{t.show(e,this.position)}).catch(e=>{console.error(`[Blok] Failed to display notification. Reason:`,e)})}isNotifierModule(e){return typeof e==`object`&&!!e&&`show`in e&&typeof e.show==`function`}},Ht=class extends s{constructor({config:e,eventsDispatcher:t}){var n;super({config:e,eventsDispatcher:t}),this.builtInNotifier=new Vt((n=e.notifierPosition)==null?i.t:n),this.customNotifier=e.notifier}get methods(){return{show:e=>this.show(e)}}show(e){if(this.customNotifier!==void 0){this.customNotifier(e);return}this.builtInNotifier.show(e)}},Ut=class extends s{get methods(){let e=()=>this.isEnabled;return{toggle:e=>this.toggle(e),set:e=>this.set(e),get isEnabled(){return e()}}}toggle(e){return this.Blok.ReadOnly.toggle(e)}set(e){return this.Blok.ReadOnly.set(e)}get isEnabled(){return this.Blok.ReadOnly.isEnabled}},Wt=class extends s{get methods(){return{clean:(e,t)=>this.clean(e,t)}}clean(e,n){return t.Ei(e,n)}},Gt=class extends s{get methods(){return{save:()=>this.save()}}async save(){var e=this,n,r;let i=`Blok's content can not be saved in read-only mode`;if(e.Blok.ReadOnly.isEnabled)throw t.Da(i,`warn`),Error(i);let a=await e.Blok.Saver.save();if(a!==void 0)return a;let o=(n=(r=e.Blok.Saver).getLastSaveError)==null?void 0:n.call(r);throw o instanceof Error?o:Error(o===void 0?`Blok's content can not be saved because collecting data failed`:String(o))}},Kt=class extends s{constructor(...e){super(...e),this.selectionUtils=new t.Ai}get methods(){return{findParentTag:(e,t)=>this.findParentTag(e,t),expandToTag:e=>this.expandToTag(e),save:()=>this.selectionUtils.save(),restore:()=>this.selectionUtils.restore(),setFakeBackground:()=>this.selectionUtils.setFakeBackground(),removeFakeBackground:()=>this.selectionUtils.removeFakeBackground(),clearFakeBackground:()=>this.selectionUtils.clearFakeBackground()}}findParentTag(e,t){return this.selectionUtils.findParentTag(e,t)}expandToTag(e){this.selectionUtils.expandToTag(e)}},qt=class extends s{get classes(){return{block:`blok-block`,inlineToolButton:`blok-inline-tool-button`,inlineToolButtonActive:`blok-inline-tool-button--active`,input:`blok-input`,loader:`blok-loader`,button:`blok-button`,settingsButton:`blok-settings-button`,settingsButtonActive:`blok-settings-button--active`,settingsButtonFocused:`blok-settings-button--focused`,settingsButtonFocusedAnimated:`blok-settings-button--focused-animated`}}},Jt=class extends s{get methods(){return{close:e=>this.close(e),open:()=>this.open(),toggleBlockSettings:(e,t,n)=>this.toggleBlockSettings(e,t,n),toggleToolbox:e=>this.toggleToolbox(e)}}open(){this.Blok.Toolbar.moveAndOpen()}close(e){this.Blok.Toolbar.close(e)}toggleBlockSettings(e,n,r){if(this.Blok.BlockManager.currentBlockIndex===-1){t.Da(`Could't toggle the Toolbar because there is no block selected `,`warn`);return}(e==null?!this.Blok.BlockSettings.opened:e)?(this.Blok.Toolbar.moveAndOpen(),this.Blok.BlockSettings.open(void 0,n,r)):this.Blok.BlockSettings.close()}toggleToolbox(e){if(this.Blok.BlockManager.currentBlockIndex===-1){t.Da(`Could't toggle the Toolbox because there is no block selected `,`warn`);return}(e==null?!this.Blok.Toolbar.toolbox.opened:e)?(this.Blok.Toolbar.moveAndOpen(),this.Blok.Toolbar.toolbox.open()):this.Blok.Toolbar.toolbox.close()}},Yt=class extends s{get methods(){return{getBlockTools:()=>Array.from(this.Blok.Tools.blockTools.values()),getToolsConfig:()=>{let e={tools:this.config.tools};return this.config.inlineToolbar!==void 0&&(e.inlineToolbar=this.config.inlineToolbar),this.config.tunes!==void 0&&(e.tunes=this.config.tunes),this.config.theme!==void 0&&(e.theme=this.config.theme),e},update:(e,t)=>{this.Blok.Tools.updateToolConfig(e,t)}}}},Xt=class extends s{constructor({config:e,eventsDispatcher:t}){super({config:e,eventsDispatcher:t})}get methods(){return{show:(e,t,n)=>this.show(e,t,n),hide:()=>this.hide(),onHover:(e,t,n)=>this.onHover(e,t,n)}}show(e,n,r){t.Si(e,n,r)}hide(){t.bi()}onHover(e,n,r){t.xi(e,n,r)}},Zt=class extends s{get methods(){let e=this.Blok.UI;return{nodes:this.blokNodes,get isMobile(){return e.isMobile}}}get blokNodes(){return{wrapper:this.Blok.UI.nodes.wrapper,redactor:this.Blok.UI.nodes.redactor}}},Qt=class extends s{get methods(){let e=this.Blok.ThemeManager;return{get:()=>e.getMode(),set:t=>e.setMode(t),getResolved:()=>e.getResolved()}}},E=()=>new Map,$t=e=>{let t=E();return e.forEach((e,n)=>{t.set(n,e)}),t},en=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},tn=(e,t)=>{let n=[];for(let[r,i]of e)n.push(t(i,r));return n},nn=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},rn=()=>new Set,an=e=>e[e.length-1],on=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},sn=Array.from,cn=(e,t)=>{for(let n=0;n<e.length;n++)if(!t(e[n],n,e))return!1;return!0},ln=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},un=(e,t)=>{let n=Array(e);for(let r=0;r<e;r++)n[r]=t(r,n);return n},dn=Array.isArray,fn=class{constructor(){this._observers=E()}on(e,t){return en(this._observers,e,rn).add(t),t}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return sn((this._observers.get(e)||E()).values()).forEach(e=>e(...t))}destroy(){this._observers=E()}},D=Math.floor,pn=Math.abs,mn=(e,t)=>e<t?e:t,hn=(e,t)=>e>t?e:t;Number.isNaN;var gn=e=>e===0?1/e<0:e<0,_n=2**53-1,vn=-(2**53-1),yn=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&D(e)===e);Number.isNaN,Number.parseInt;var bn=String.fromCharCode;String.fromCodePoint,bn(65535);var xn=e=>e.toLowerCase(),Sn=/^\s*/g,Cn=e=>e.replace(Sn,``),wn=/([A-Z])/g,Tn=(e,t)=>Cn(e.replace(wn,e=>`${t}${xn(e)}`)),En=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},Dn=typeof TextEncoder<`u`?new TextEncoder:null,On=Dn?e=>Dn.encode(e):En,kn=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});kn&&kn.decode(new Uint8Array).length===1&&(kn=null);var An=(e,t)=>un(t,()=>e).join(``),jn=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}},Mn=()=>new jn,Nn=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},O=e=>{let t=new Uint8Array(Nn(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},Pn=(e,t)=>{let n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(hn(n,t)*2),e.cpos=0)},k=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Fn=k,A=(e,t)=>{for(;t>127;)k(e,128|127&t),t=D(t/128);k(e,127&t)},In=(e,t)=>{let n=gn(t);for(n&&(t=-t),k(e,(t>63?128:0)|(n?64:0)|63&t),t=D(t/64);t>0;)k(e,(t>127?128:0)|127&t),t=D(t/128)},Ln=new Uint8Array(3e4),Rn=Ln.length/3,zn=Dn&&Dn.encodeInto?(e,t)=>{if(t.length<Rn){let n=Dn.encodeInto(t,Ln).written||0;A(e,n);for(let t=0;t<n;t++)k(e,Ln[t])}else j(e,On(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;A(e,r);for(let t=0;t<r;t++)k(e,n.codePointAt(t))},Bn=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=mn(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(hn(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},j=(e,t)=>{A(e,t.byteLength),Bn(e,t)},Vn=(e,t)=>{Pn(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Hn=(e,t)=>Vn(e,4).setFloat32(0,t,!1),Un=(e,t)=>Vn(e,8).setFloat64(0,t,!1),Wn=(e,t)=>Vn(e,8).setBigInt64(0,t,!1),Gn=new DataView(new ArrayBuffer(4)),Kn=e=>(Gn.setFloat32(0,e),Gn.getFloat32(0)===e),qn=(e,t)=>{switch(typeof t){case`string`:k(e,119),zn(e,t);break;case`number`:yn(t)&&pn(t)<=2147483647?(k(e,125),In(e,t)):Kn(t)?(k(e,124),Hn(e,t)):(k(e,123),Un(e,t));break;case`bigint`:k(e,122),Wn(e,t);break;case`object`:if(t===null)k(e,126);else if(dn(t)){k(e,117),A(e,t.length);for(let n=0;n<t.length;n++)qn(e,t[n])}else if(t instanceof Uint8Array)k(e,116),j(e,t);else{k(e,118);let n=Object.keys(t);A(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];zn(e,i),qn(e,t[i])}}break;case`boolean`:k(e,t?120:121);break;default:k(e,127)}},Jn=class extends jn{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&A(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}},Yn=e=>{e.count>0&&(In(e.encoder,e.count===1?e.s:-e.s),e.count>1&&A(e.encoder,e.count-2))},Xn=class{constructor(){this.encoder=new jn,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Yn(this),this.count=1,this.s=e)}toUint8Array(){return Yn(this),O(this.encoder)}},Zn=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);In(e.encoder,t),e.count>1&&A(e.encoder,e.count-2)}},Qn=class{constructor(){this.encoder=new jn,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Zn(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Zn(this),O(this.encoder)}},$n=class{constructor(){this.sarr=[],this.s=``,this.lensE=new Xn}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(e.length)}toUint8Array(){let e=new jn;return this.sarr.push(this.s),this.s=``,zn(e,this.sarr.join(``)),Bn(e,this.lensE.toUint8Array()),O(e)}},er=e=>Error(e),M=()=>{throw er(`Method unimplemented`)},N=()=>{throw er(`Unexpected case`)};crypto.subtle;var tr=crypto.getRandomValues.bind(crypto),nr=()=>tr(new Uint32Array(1))[0],rr=`10000000-1000-4000-8000-100000000000`,ir=()=>rr.replace(/[018]/g,e=>(e^nr()&15>>e/4).toString(16)),ar=Date.now,or=e=>new Promise(e);Promise.all.bind(Promise);var sr=e=>e===void 0?null:e,cr=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}};try{typeof localStorage<`u`&&localStorage&&(cr=localStorage)}catch(e){}var lr=cr,ur=Symbol(`Equality`),dr=(e,t)=>{var n;return e===t||!!(!(e==null||(n=e[ur])==null)&&n.call(e,t))||!1},fr=e=>typeof e==`object`,pr=Object.assign,mr=Object.keys,hr=(e,t)=>{for(let n in e)t(e[n],n)},gr=e=>mr(e).length,_r=e=>{for(let t in e)return!1;return!0},vr=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},yr=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),br=(e,t)=>e===t||gr(e)===gr(t)&&vr(e,(e,n)=>(e!==void 0||yr(t,n))&&dr(t[n],e)),xr=Object.freeze,Sr=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&Sr(e[t])}return xr(e)},Cr=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Cr(e,t,n+1)}},wr=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[ur]!=null)return e[ur](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!wr(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(gr(e)!==gr(t))return!1;for(let n in e)if(!yr(e,n)||!wr(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!wr(e[n],t[n]))return!1;break;default:return!1}return!0},Tr=(e,t)=>t.includes(e),Er=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`;typeof navigator<`u`&&/Mac/.test(navigator.platform);var P,Dr=[],Or=()=>{if(P===void 0)if(Er){P=E();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&P.set(t,``),t=r):t===null?Dr.push(r):(P.set(t,r),t=null)}t!==null&&P.set(t,``)}else typeof location==`object`?(P=E(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);P.set(`--${Tn(t,`-`)}`,n),P.set(`-${Tn(t,`-`)}`,n)}})):P=E();return P},kr=e=>Or().has(e),Ar=e=>sr(Er?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:lr.getItem(e)),jr=e=>kr(`--`+e)||Ar(e)!==null,Mr=jr(`production`),Nr=Er&&Tr(process.env.FORCE_COLOR,[`true`,`1`,`2`])||!kr(`--no-colors`)&&!jr(`no-color`)&&(!Er||process.stdout.isTTY)&&(!Er||kr(`--color`)||Ar(`COLORTERM`)!==null||(Ar(`TERM`)||``).includes(`color`)),Pr=class{constructor(e,t){this.left=e,this.right=t}},F=(e,t)=>new Pr(e,t),Fr=e=>e.next()>=.5,Ir=(e,t,n)=>D(e.next()*(n+1-t)+t),Lr=(e,t,n)=>D(e.next()*(n+1-t)+t),Rr=(e,t,n)=>Lr(e,t,n),zr=e=>bn(Rr(e,97,122)),Br=(e,t=0,n=20)=>{let r=Rr(e,t,n),i=``;for(let t=0;t<r;t++)i+=zr(e);return i},Vr=(e,t)=>t[Rr(e,0,t.length-1)],Hr,Ur=Symbol(`0schema`),Wr=class{constructor(){this._rerrs=[]}extend(e,t,n,r=null){this._rerrs.push({path:e,expected:t,has:n,message:r})}toString(){let e=[];for(let t=this._rerrs.length-1;t>0;t--){let n=this._rerrs[t];e.push(An(` `,(this._rerrs.length-t)*2)+`${n.path==null?``:`[${n.path}] `}${n.has} doesn't match ${n.expected}. ${n.message}`)}return e.join(`
1
+ const e=require(`./chunk-BL1yB9zm.cjs`),t=require(`./constants-Y3Af_xZ7.cjs`),n=require(`./objectSpread2-iNkE6aJh.cjs`),r=require(`./tw-fzSjDKon.cjs`),i=require(`./types-BQNH-yx9.cjs`),a=require(`./lightweight-i18n-BnIqQ5Cf.cjs`);e.t(((e,t)=>{function n(){}t.exports=Object.assign(n,{default:n,register:n,revert:function(){},__esModule:!0})}))();var o=class extends Error{},s=class e{get isDestroyed(){return this._isDestroyed}markDestroyed(){this._isDestroyed=!0}constructor({config:n,eventsDispatcher:r}){if(this.nodes={},this._isDestroyed=!1,this.listeners=new t.qi,this.readOnlyMutableListeners={on:(e,t,n,r=!1)=>{let i=this.listeners.on(e,t,n,r);i&&this.mutableListenerIds.push(i)},clearAll:()=>{for(let e of this.mutableListenerIds)this.listeners.offById(e);this.mutableListenerIds=[]}},this.mutableListenerIds=[],new.target===e)throw TypeError(`Constructors for abstract class Module are not allowed.`);this.config=n,this.eventsDispatcher=r,this.Blok={}}set state(e){this.Blok=e}removeAllNodes(){for(let e in this.nodes){let t=this.nodes[e];t instanceof HTMLElement&&t.remove()}}get isRtl(){var e;return((e=this.config.i18n)==null?void 0:e.direction)===`rtl`}},c=function(e){return Object.setPrototypeOf(this,{get id(){return e.id},get name(){return e.name},get config(){return e.config},get holder(){return e.holder},get parentId(){return e.parentId},get isEmpty(){return e.isEmpty},get selected(){return e.selected},get preservedData(){return e.preservedData},get preservedTunes(){return e.preservedTunes},set stretched(t){e.setStretchState(t)},get stretched(){return e.stretched},get focusable(){return e.focusable},call(t,n){return e.call(t,n)},save(){return e.save()},validate(t){return e.validate(t)},dispatchChange(){e.dispatchChange()},getActiveToolboxEntry(){return e.getActiveToolboxEntry()}}),Object.defineProperties(this,{id:{get(){return e.id},enumerable:!0,configurable:!0},name:{get(){return e.name},enumerable:!0,configurable:!0}}),this},l=class{constructor(e,t,n,r,i,a,o,s,c,l){this.toolInstance=e,this.getToolRenderedElement=t,this.tunesManager=n,this.name=r,this.getIsEmpty=i,this.inputManager=a,this.callToolUpdated=o,this.toggleEmptyMark=s,this.lastSavedDataInternal=c,this.lastSavedTunesInternal=l}async save(){var e=this;let t=await e.extractToolData();if(t===void 0)return;let r=window.performance.now(),i=e.tunesManager.extractTunesData();e.lastSavedDataInternal=t,e.lastSavedTunesInternal=n.t({},i);let a=window.performance.now();return{id:e.name,tool:e.name,data:t,tunes:i,time:a-r}}async setData(e){var n=this;let r=n.toolInstance.setData;if(typeof r==`function`)try{return await r.call(n.toolInstance,e),n.lastSavedDataInternal=e,!0}catch(e){return t.Ea(`Tool ${n.name} setData failed: ${e instanceof Error?e.message:String(e)}`,`warn`),!1}let i=n.getToolRenderedElement();if(!i)return!1;let a=i.getAttribute(`contenteditable`)===`true`,o=e.text,s=typeof o==`string`,c=Object.keys(e).length===0&&n.name===`paragraph`;return a&&(s||c)?(i.innerHTML=s?o:``,n.lastSavedDataInternal=e,n.inputManager.dropCache(),n.toggleEmptyMark(),n.callToolUpdated(),!0):!1}async validate(e){var t=this;return t.toolInstance.validate instanceof Function?await t.toolInstance.validate(e):!0}async exportDataAsString(e){return t.Ri(await this.data,e)}get data(){return this.save().then(e=>e&&!t.ba(e.data)?e.data:{})}get lastSavedData(){return this.lastSavedDataInternal}get lastSavedTunes(){return this.lastSavedTunesInternal}get preservedData(){return this.lastSavedDataInternal}get preservedTunes(){return this.lastSavedTunesInternal}async extractToolData(){var e=this;try{let t=e.getToolRenderedElement();if(t===null)return;let r=await e.toolInstance.save(t);if(!e.getIsEmpty())return r;if(r==null)return;if(typeof r!=`object`)return r;let i=n.t({},r);return e.sanitizeEmptyFields(i),i}catch(n){let r=n instanceof Error?n:Error(String(n));t.Ea(`Saving process for ${e.name} tool failed due to the ${r}`,`log`,r);return}}sanitizeEmptyFields(e){let n=n=>{let r=e[n];if(typeof r!=`string`)return;let i=document.createElement(`div`);i.innerHTML=r,t.Qi.isEmpty(i)&&(e[n]=``)};n(`text`),n(`html`)}},u=class{constructor(e,t){this.holder=e,this.onInputEvent=t,this.cachedInputs=[],this.inputIndex=0,this.handleFocus=()=>{this.dropCache(),this.updateCurrentInput()}}get inputs(){if(this.cachedInputs.length!==0)return this.cachedInputs;let e=t.Qi.findAllInputs(this.holder);return e.length>0&&this.inputIndex>e.length-1&&(this.inputIndex=e.length-1),this.cachedInputs=e,e}get currentInput(){return this.inputs[this.inputIndex]}set currentInput(e){if(e===void 0)return;let t=this.inputs.findIndex(t=>t===e||t.contains(e));t!==-1&&(this.inputIndex=t)}get currentInputIndex(){return this.inputIndex}get firstInput(){return this.inputs[0]}get lastInput(){let e=this.inputs;return e[e.length-1]}get nextInput(){return this.inputs[this.inputIndex+1]}get previousInput(){return this.inputs[this.inputIndex-1]}updateCurrentInput(){var e;let n=t.Ai.anchorNode,r=document.activeElement,i=e=>{if(!e)return;let n=e instanceof HTMLElement?e:e.parentElement;if(n===null)return;let r=this.inputs.find(e=>e===n||e.contains(n));if(r!==void 0)return r;let i=n.closest(t.Qi.allInputsSelector);if(i instanceof HTMLElement)return this.inputs.find(e=>e===i)};if(t.Qi.isNativeInput(r)){this.currentInput=r;return}let a=(e=i(n))==null?r instanceof HTMLElement?i(r):void 0:e;if(a!==void 0){this.currentInput=a;return}r instanceof HTMLElement&&this.inputs.includes(r)&&(this.currentInput=r)}dropCache(){this.cachedInputs=[]}addInputEvents(){this.inputs.forEach(e=>{e.addEventListener(`focus`,this.handleFocus),t.Qi.isNativeInput(e)&&e.addEventListener(`input`,this.onInputEvent)})}removeInputEvents(){this.inputs.forEach(e=>{e.removeEventListener(`focus`,this.handleFocus),t.Qi.isNativeInput(e)&&e.removeEventListener(`input`,this.onInputEvent)})}destroy(){this.removeInputEvents(),this.cachedInputs=[]}},d=`block changed`,f=`block:rendered`,p=`blocks:rendered`,m=`block-settings-closed`,h=`block-settings-opened`,g=`blok mobile layout toggled`,_=`fake cursor is about to be toggled`,v=`fake cursor have been set`,y=`redactor dom changed`,b=(e,t)=>{let{type:n,target:r,addedNodes:i,removedNodes:a}=e;return e.type===`attributes`&&(e.attributeName===`data-blok-empty`||e.attributeName===`data-blok-toggle-open`)?!1:t.contains(r)?!0:n===`childList`?Array.from(i).some(e=>e===t)?!0:Array.from(a).some(e=>e===t):!1},x=class{constructor(e,t,n){this.getToolElement=e,this.blokEventBus=t,this.onMutation=n,this.redactorDomChangedCallback=null}watch(){var e;this.redactorDomChangedCallback=e=>{let{mutations:t}=e,n=this.getToolElement();if(n===null)return;let r=t.filter(e=>b(e,n));r.length>0&&this.onMutation(r)},(e=this.blokEventBus)==null||e.on(`redactor dom changed`,this.redactorDomChangedCallback)}unwatch(){if(this.redactorDomChangedCallback){var e;(e=this.blokEventBus)==null||e.off(`redactor dom changed`,this.redactorDomChangedCallback),this.redactorDomChangedCallback=null}}handleMutation(e){let t=e===void 0,n=e instanceof InputEvent,r=!t&&!n?this.detectToolRootChange(e):null;return{shouldFireUpdate:this.shouldFireUpdate(e),newToolRoot:r}}detectToolRootChange(e){let t=this.getToolElement();if(t===null)return null;for(let n of e){if(!Array.from(n.removedNodes).includes(t))continue;let e=n.addedNodes[n.addedNodes.length-1];if(e instanceof HTMLElement)return e}return null}destroy(){this.unwatch()}shouldFireUpdate(e){let n=e===void 0,r=e instanceof InputEvent;if(n||r)return!0;let i=this.getToolElement();return!(e.length>0&&e.every(e=>{let{addedNodes:n,removedNodes:r,target:a}=e,o=[...Array.from(n),...Array.from(r),a],s=e=>{if(!t.Qi.isElement(e)){var n;return(n=e.parentElement)==null?t.Qi.isElement(a)?a:null:n}return e.isConnected?e:t.Qi.isElement(a)?a:null};return o.every(e=>{let t=s(e);if(t===null)return!1;let n=t.closest(`[data-blok-mutation-free="true"]`);return n!==null&&i!==null&&i.contains(n)})}))}},ee=class{constructor(e,t,n,r,i){this.holder=e,this.getContentElement=t,this.getStretched=n,this.blokEventBus=r,this.styleManager=i}set selected(e){var n,r;e?this.holder.setAttribute(t.Ma.selected,`true`):this.holder.removeAttribute(t.Ma.selected),this.handleFakeCursor(e);let i=e&&t.Ai.isRangeInsideContainer(this.holder),a=!e&&t.Ai.isFakeCursorInsideContainer(this.holder);!i&&!a||((n=this.blokEventBus)==null||n.emit(`fake cursor is about to be toggled`,{state:e}),i&&t.Ai.addFakeCursor(),a&&t.Ai.removeFakeCursor(this.holder),(r=this.blokEventBus)==null||r.emit(`fake cursor have been set`,{state:e}))}get selected(){return this.holder.getAttribute(t.Ma.selected)===`true`}handleFakeCursor(e){let t=this.getContentElement(),n=this.getStretched();t&&this.styleManager.updateContentState(e,n)}},S,C=class e{constructor(e,t){this.holder=e,this.contentElement=t}static get wrapperStyles(){return e.styles.wrapper}static get contentStyles(){return e.styles.content}setStretchState(e,n=!1){e?this.holder.setAttribute(t.Ma.stretched,`true`):this.holder.removeAttribute(t.Ma.stretched),this.contentElement&&!n&&this.updateContentState(!1,e)}get stretched(){return this.holder.getAttribute(t.Ma.stretched)===`true`}updateContentState(e,t){this.contentElement&&(this.contentElement.className=this.getContentClasses(e,t))}getContentClasses(t,n){return t&&n?r.n(e.styles.content,e.styles.contentSelected,e.styles.contentStretched):t?r.n(e.styles.content,e.styles.contentSelected):n?r.n(e.styles.content,e.styles.contentStretched):e.styles.content}};S=C,S.styles={wrapper:`relative opacity-100 first:mt-0 last:pb-0 last:mb-0 [&_a]:cursor-pointer [&_a]:underline [&_a]:text-link [&_b]:font-bold [&_i]:italic`,content:`relative mx-auto transition-colors duration-150 ease-out max-w-blok-content`,contentSelected:`bg-selection rounded-[4px] **:[[contenteditable]]:select-none [&_img]:opacity-55 **:data-[blok-tool=stub]:opacity-55`,contentStretched:`max-w-none`};var w=class{constructor(e,t,n,r,i){this.toolInstance=e,this.name=t,this.id=n,this.tunesManager=r,this.config=i,this.toolRenderedElementInternal=null,this.contentElementInternal=null,this.readyResolver=null,this.ready=new Promise(e=>{this.readyResolver=e})}get toolRenderedElement(){return this.toolRenderedElementInternal}set toolRenderedElement(e){this.toolRenderedElementInternal=e}get contentElement(){return this.contentElementInternal}get pluginsContent(){if(this.toolRenderedElementInternal===null)throw Error(`Block pluginsContent is not yet initialized`);return this.toolRenderedElementInternal}compose(){let e=t.Qi.make(`div`,this.getWrapperStyles()),n=t.Qi.make(`div`,this.getContentStyles());this.contentElementInternal=n,e.setAttribute(t.Ma.element,``),n.setAttribute(t.Ma.elementContent,``),n.setAttribute(`data-blok-testid`,`block-content`),e.setAttribute(t.Ma.testid,t.Fi.blockWrapper),this.name&&!e.hasAttribute(`data-blok-component`)&&e.setAttribute(`data-blok-component`,this.name),e.setAttribute(`data-blok-id`,this.id);let r=this.toolInstance.render();r instanceof Promise?this.handleAsyncRender(r,n,e):this.handleSyncRender(r,n,e);let i=this.tunesManager.wrapContent(n);return e.appendChild(i),e}refreshToolRootElement(e){let n=e.querySelector(`[${t.Ma.elementContent}]`);if(!n)return;let r=n.firstElementChild;r&&r!==this.toolRenderedElementInternal&&(this.toolRenderedElementInternal=r)}handleSyncRender(e,t,n){this.toolRenderedElementInternal=e,this.addToolDataAttributes(e,n),t.appendChild(e),this.invokeRenderedLifecycle()}handleAsyncRender(e,n,r){e.then(e=>{this.toolRenderedElementInternal=e,this.addToolDataAttributes(e,r),n.appendChild(e),this.invokeRenderedLifecycle()}).catch(e=>{var n;t.Ea(`Tool render promise rejected: %o`,`error`,e),(n=this.readyResolver)==null||n.call(this)})}invokeRenderedLifecycle(){let e=this.toolInstance.rendered;if(typeof e==`function`){let n=this.readyResolver,r=this.toolInstance,i=this.name;requestAnimationFrame(()=>{try{e.call(r)}catch(e){t.Ea(`${i}: rendered() threw: ${e instanceof Error?e.message:String(e)}`,`warn`)}finally{n==null||n()}})}else{var n;(n=this.readyResolver)==null||n.call(this)}}addToolDataAttributes(e,t){this.name&&!t.hasAttribute(`data-blok-component`)&&t.setAttribute(`data-blok-component`,this.name);let n=`data-blok-placeholder`,r=this.config.placeholder,i=typeof r==`string`?r.trim():``;if(this.name===`paragraph`)return;let a=[`empty:before:pointer-events-none`,`empty:before:text-gray-text`,`empty:before:cursor-text`,`empty:before:content-[attr(data-blok-placeholder)]`,`data-[blok-empty=true]:before:pointer-events-none`,`data-[blok-empty=true]:before:text-gray-text`,`data-[blok-empty=true]:before:cursor-text`,`data-[blok-empty=true]:before:content-[attr(data-blok-placeholder)]`];if(i.length>0){e.setAttribute(n,i),e.classList.add(...a);return}r===!1&&e.hasAttribute(n)&&e.removeAttribute(n)}getWrapperStyles(){return C.wrapperStyles}getContentStyles(){return C.contentStyles}},te=class{constructor(e,t,n){this.tunes=e,this.blockAPI=n,this.tunesInstances=new Map,this.defaultTunesInstances=new Map,this.unavailableTunesData={},this.composeTunes(t)}getMenuConfig(e){let n=[],r=[],i=(e,n)=>{if(e){if(t.Qi.isElement(e)){n.push({type:t.ki.Html,element:e});return}if(Array.isArray(e)){n.push(...e);return}n.push(e)}};return i(e,n),[...this.tunesInstances.values(),...this.defaultTunesInstances.values()].map(e=>e.render()).forEach(e=>{i(e,r)}),{toolTunes:n,commonTunes:r}}wrapContent(e){return[...this.tunesInstances.values(),...this.defaultTunesInstances.values()].reduce((e,n)=>{if(t.xa(n.wrap))try{return n.wrap(e)}catch(r){return t.Ea(`Tune ${n.constructor.name} wrap method throws an Error %o`,`warn`,r),e}return e},e)}extractTunesData(){let e=n.t({},this.unavailableTunesData);return[...this.tunesInstances.entries(),...this.defaultTunesInstances.entries()].forEach(([n,r])=>{if(t.xa(r.save))try{e[n]=r.save()}catch(e){t.Ea(`Tune ${r.constructor.name} save method throws an Error %o`,`warn`,e)}}),e}get userTunes(){return this.tunesInstances}get defaultTunes(){return this.defaultTunesInstances}composeTunes(e){Array.from(this.tunes.values()).forEach(t=>{(t.isInternal?this.defaultTunesInstances:this.tunesInstances).set(t.name,t.create(e[t.name],this.blockAPI))}),Object.entries(e).forEach(([e,t])=>{this.tunesInstances.has(e)||(this.unavailableTunesData[e]=t)})}},T=function(e){return e.RENDERED=`rendered`,e.MOVED=`moved`,e.UPDATED=`updated`,e.REMOVED=`removed`,e.ON_PASTE=`onPaste`,e}({}),ne=class extends t.Ii{constructor({id:e=t.aa(),data:n,tool:r,readOnly:i,tunesData:a,parentId:o,contentIds:s,bindMutationWatchersImmediately:d=!1,lastEditedAt:f,lastEditedBy:p},m){super(),this.blokEventBus=null,this.draggableCleanup=null,this.destroyCallbacks=new Set,this.didMutated=(e=void 0)=>{let t=this.mutationHandler.handleMutation(e);t.newToolRoot&&(this.toolRenderer.toolRenderedElement=t.newToolRoot),t.shouldFireUpdate&&(this.inputManager.dropCache(),this.inputManager.updateCurrentInput(),this.toggleInputsEmptyMark(),this.call(T.UPDATED),this.emit(`didMutated`,this))};let h=e===``?t.aa():e;if(this.name=r.name,this.id=h,this.parentId=o==null?null:o,this.contentIds=s==null?[]:s,this.lastEditedAt=f==null?Date.now():f,this.lastEditedBy=p==null?null:p,this.settings=r.settings,this.config=this.settings,this.blokEventBus=m||null,this.blockAPI=new c(this),this.readOnly=i,this.tool=r,this.toolInstance=r.create(n,this.blockAPI,i),this.tunes=r.tunes,this.tunesManager=new te(this.tunes,a,this.blockAPI),this.toolRenderer=new w(this.toolInstance,this.name,this.id,this.tunesManager,this.config),this.holder=this.toolRenderer.compose(),this.ready=this.toolRenderer.ready,this.styleManager=new C(this.holder,this.toolRenderer.contentElement),this.selectionManager=new ee(this.holder,()=>this.toolRenderer.contentElement,()=>this.styleManager.stretched,this.blokEventBus,this.styleManager),this.inputManager=new u(this.holder,()=>this.didMutated()),this.mutationHandler=new x(()=>this.toolRenderer.toolRenderedElement,this.blokEventBus,e=>this.didMutated(e)),this.dataPersistenceManager=new l(this.toolInstance,()=>this.toolRenderer.toolRenderedElement,this.tunesManager,this.name,()=>this.isEmpty,this.inputManager,()=>this.call(T.UPDATED),()=>this.toggleInputsEmptyMark(),n,a),!i){let e=()=>{this.mutationHandler.watch(),this.inputManager.addInputEvents(),this.toggleInputsEmptyMark()};d?e():window.requestIdleCallback(e)}}setupDraggable(e,t){this.cleanupDraggable(),this.draggableCleanup=t.setupDragHandle(e,this)}cleanupDraggable(){this.draggableCleanup&&(this.draggableCleanup(),this.draggableCleanup=null)}call(e,n){let r=this.toolInstance[e];if(t.xa(r))try{r.call(this.toolInstance,n)}catch(n){t.Ea(`Error during '${e}' call: ${n instanceof Error?n.message:String(n)}`,`error`)}}async mergeWith(e){var n=this;if(!t.xa(n.toolInstance.merge))throw Error(`Block tool "${n.name}" does not support merging`);await n.toolInstance.merge(e)}getContentOffset(e){if(typeof this.toolInstance.getContentOffset==`function`)return this.toolInstance.getContentOffset(e)}getToolbarAnchorElement(){if(typeof this.toolInstance.getToolbarAnchorElement==`function`)return this.toolInstance.getToolbarAnchorElement()}async save(){var e=this;let t=await e.dataPersistenceManager.save();if(t!==void 0)return t.id=e.id,t}async validate(e){return this.dataPersistenceManager.validate(e)}getTunes(){let e=typeof this.toolInstance.renderSettings==`function`?this.toolInstance.renderSettings():[];return this.tunesManager.getMenuConfig(e)}updateCurrentInput(){this.inputManager.updateCurrentInput()}dispatchChange(){this.didMutated()}async setData(e){return this.dataPersistenceManager.setData(e)}addDestroyCallback(e){return this.destroyCallbacks.add(e),()=>{this.destroyCallbacks.delete(e)}}destroy(){let e=Array.from(this.destroyCallbacks);this.destroyCallbacks.clear(),e.forEach(e=>e()),this.mutationHandler.destroy(),this.inputManager.destroy(),this.draggableCleanup&&(this.draggableCleanup(),this.draggableCleanup=null),super.destroy(),t.xa(this.toolInstance.destroy)&&this.toolInstance.destroy()}setReadOnly(e){this.readOnly!==e&&(this.readOnly=e,e?(this.inputManager.removeInputEvents(),this.mutationHandler.unwatch()):(this.inputManager.addInputEvents(),this.mutationHandler.watch()),typeof this.toolInstance.setReadOnly==`function`&&this.toolInstance.setReadOnly(e))}setPlaceholder(e){let t=this.toolInstance;typeof t.setPlaceholder==`function`&&t.setPlaceholder(e)}async getActiveToolboxEntry(){var e=this;let n=e.tool.toolbox;if(!n)return;if(n.length===1)return Promise.resolve(n[0]);let r=await e.data;return n.find(e=>e.data!==void 0&&t.Ui(e.data,r))}async exportDataAsString(){var e=this,t;return e.dataPersistenceManager.exportDataAsString((t=e.tool.conversionConfig)==null?{}:t)}get inputs(){return this.inputManager.inputs}get currentInput(){return this.inputManager.currentInput}get currentInputIndex(){return this.inputManager.currentInputIndex}set currentInput(e){this.inputManager.currentInput=e}get firstInput(){return this.inputManager.firstInput}get lastInput(){return this.inputManager.lastInput}get nextInput(){return this.inputManager.nextInput}get previousInput(){return this.inputManager.previousInput}get data(){return this.dataPersistenceManager.data}get preservedData(){return this.dataPersistenceManager.preservedData}get preservedTunes(){return this.dataPersistenceManager.preservedTunes}get sanitize(){return this.tool.sanitizeConfig}get mergeable(){return t.xa(this.toolInstance.merge)}get focusable(){return this.inputs.length!==0}get isEmpty(){let e=t.Qi.isEmpty(this.pluginsContent,`/`),n=!this.hasMedia;return e&&n}get hasMedia(){return!!this.holder.querySelector([`img`,`iframe`,`video`,`audio`,`source`,`input`,`textarea`,`twitterwidget`].join(`,`))}set selected(e){this.selectionManager.selected=e}get selected(){return this.selectionManager.selected}setStretchState(e){this.styleManager.setStretchState(e,this.selected)}set stretched(e){this.setStretchState(e)}get stretched(){return this.styleManager.stretched}get pluginsContent(){return this.toolRenderer.pluginsContent}unwatchBlockMutations(){this.mutationHandler.unwatch()}refreshToolRootElement(){this.toolRenderer.refreshToolRootElement(this.holder),this.inputManager.dropCache()}toggleInputsEmptyMark(){this.inputs.forEach(t.ea)}};function re(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.includes(r))continue;n[r]=e[r]}return n}function ie(e,t){if(e==null)return{};var n,r,i=re(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.includes(n)||{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}var ae=[`file`,`url`,`withBorder`,`withBackground`,`stretched`],oe=[`caption`,`alignment`],se=[`content`,`withHeadings`,`withHeadingColumn`,`stretched`],ce=[`parent`,`content`],le={general:null,note:`blue`,important:`purple`,warning:`orange`,additional:`yellow`,recommendation:`green`,caution:`red`},ue={blue:`note`,purple:`important`,orange:`warning`,yellow:`additional`,green:`recommendation`,red:`caution`},de=`💡`,fe=(e,t,n,r)=>{let i=`${t}.${n}`;e.has(i)||(e.add(i),console.warn(`[Blok migration] ${t} block ${r} unsupported field "${n}" (no Blok equivalent)`))},pe=(e,t)=>typeof e!=`object`||!e?!1:e[t]!==void 0,me=(e,t)=>{e.type===`quote`&&pe(e.data,`alignment`)&&fe(t,`quote`,`alignment`,`ignored`)},he=e=>typeof e==`object`&&`text`in e&&!(`content`in e),ge=e=>typeof e==`string`?{content:e}:he(e)?{content:e.text,checked:e.checked}:e,_e=e=>e.some(e=>{let t=ge(e);return t.items!==void 0&&t.items.length>0}),ve=e=>typeof e==`object`&&!!e&&`text`in e&&typeof e.text==`string`,ye=e=>typeof e==`object`&&!!e&&`checked`in e&&typeof e.checked==`boolean`,be=e=>typeof e==`object`&&!!e&&`style`in e&&typeof e.style==`string`,xe=e=>typeof e==`object`&&!!e&&`start`in e&&typeof e.start==`number`,Se=e=>typeof e==`object`&&!!e&&`items`in e,Ce=e=>typeof e==`object`&&!!e&&`style`in e&&`items`in e&&Array.isArray(e.items),we=e=>e.type===`list`&&Ce(e.data),Te=e=>e.type===`checklist`&&typeof e.data==`object`&&e.data!==null&&Array.isArray(e.data.items),Ee=e=>e.type===`linkTool`&&typeof e.data==`object`&&e.data!==null&&typeof e.data.link==`string`,De=e=>{if(e.type!==`toggleList`)return!1;let t=e.data;return typeof t==`object`&&!!t&&`title`in t},Oe=e=>{if(e.type!==`callout`)return!1;let t=e.data;return typeof t==`object`&&!!t&&`body`in t},ke=e=>e.type===`quote`&&(pe(e.data,`caption`)||pe(e.data,`alignment`)),Ae=e=>{if(e.type!==`image`)return!1;let t=e.data;if(typeof t!=`object`||!t)return!1;let n=t.file;if(typeof n==`object`&&n&&typeof n.url==`string`)return!0;let r=typeof t.url==`string`,i=`withBorder`in t||`withBackground`in t||`stretched`in t;return r&&i},je=e=>{if(e.type!==`table`)return!1;let t=_t(e.data);return t===null?!1:t.some(e=>Array.isArray(e)&&e.some(e=>typeof e==`string`))},Me=e=>e.type===`raw`&&pe(e.data,`html`),Ne=e=>e.type===`warning`&&typeof e.data==`object`&&e.data!==null,Pe=e=>{if(e.type!==`attaches`)return!1;let t=e.data,n=typeof t==`object`&&t?t.file:void 0;return typeof n==`object`&&!!n&&typeof n.url==`string`},Fe=e=>{if(!we(e))return!1;let t=e.data.items;return _e(t)},Ie=e=>e.parent!==void 0||e.content!==void 0&&e.content.length>0,Le=e=>{let t=e.some(Ie),n=e.some(we),r=e.some(De),i=e.some(Oe),a=e.some(Ae),o=e.some(Te),s=e.some(Ee),c=e.some(ke),l=e.some(je),u=e.some(Me),d=e.some(Ne),f=e.some(Pe),p=n||r||i||a||o||s||c||l||u||d||f;return t&&!p?{format:`hierarchical`,hasHierarchy:!0}:p?{format:`legacy`,hasHierarchy:t||l||d||e.some(Fe)||e.some(e=>{var t;return De(e)&&((t=e.data.body)==null?void 0:t.blocks)!==void 0&&e.data.body.blocks.length>0})||e.some(e=>{var t;return Oe(e)&&((t=e.data.body)==null?void 0:t.blocks)!==void 0&&e.data.body.blocks.length>0})}:{format:`flat`,hasHierarchy:!1}},Re=(e,r,i,a,o,s,c)=>{let l=[];return e.forEach((e,u)=>{let d=ge(e),f=t.aa();l.push(f);let p=a===`ordered`&&i===0&&u===0&&o!==void 0&&o!==1,m=d.items&&d.items.length>0,h=n.t(n.t({id:f,type:`list`,data:n.t(n.t({text:d.content,checked:d.checked,style:a},i>0?{depth:i}:{}),p?{start:o}:{})},s===void 0?{}:{tunes:s}),r===void 0?{}:{parent:r});if(c.push(h),!m||!d.items)return;let g=Re(d.items,f,i+1,a,void 0,s,c);g.length>0&&(h.content=g)}),l},ze=(e,t)=>{let n=[],r=e.style,i=e.start;return Re(e.items,void 0,0,r,i,t,n),n},Be=(e,r,i,a)=>{var o;if(e.parent!==void 0){a.push(e);return}let s=(o=e.id)==null?t.aa():o;i.push(s),a.push(n.t(n.t({},e),{},{id:s,parent:r}))},Ve=(e,t)=>{let n=[],r=[];for(let i of e){let e=$e([i]);for(let i of e)Be(i,t,n,r)}for(let e of r){let r=e.parent!==void 0,a=e.id!==void 0&&n.includes(e.id);if(!r&&!a){var i;throw Error(`expandLegacyBodyBlocks: orphaned block emitted (type=${e.type}, id=${(i=e.id)==null?`<none>`:i}). Every root-level expansion must be re-parented to ${t}.`)}}return{childIds:n,childBlocks:r}},He=e=>{var r,i,a;let o=[],s=(r=e.id)==null?t.aa():r,{childIds:c,childBlocks:l}=Ve((i=(a=e.data.body)==null?void 0:a.blocks)==null?[]:i,s),u=n.t(n.t({id:s},e.tunes===void 0?{}:{tunes:e.tunes}),c.length>0?{content:c}:{}),d=typeof e.data.isExpanded==`boolean`?{isOpen:e.data.isExpanded}:{};return typeof e.data.titleVariant==`number`?o.push(n.t(n.t({},u),{},{type:`header`,data:n.t({text:e.data.title,level:e.data.titleVariant,isToggleable:!0},d)})):o.push(n.t(n.t({},u),{},{type:`toggle`,data:n.t({text:e.data.title},d)})),o.push(...l),o},Ue=e=>{var r,i,a,o,s;let c=[],l=(r=e.id)==null?t.aa():r,{childIds:u,childBlocks:d}=Ve((i=(a=e.data.body)==null?void 0:a.blocks)==null?[]:i,l),f=(o=e.data.variant)==null?`general`:o,p=f in le?le[f]:null,m=e.data.isEmojiVisible===!1?``:(s=e.data.emoji)==null?de:s;return c.push(n.t(n.t({id:l,type:`callout`,data:{emoji:m,textColor:null,backgroundColor:p}},e.tunes===void 0?{}:{tunes:e.tunes}),u.length>0?{content:u}:{})),c.push(...d),c},We=(e,r)=>{var i,a;let o=(i=e.data)==null?{}:i,{file:s,url:c,withBorder:l,withBackground:u,stretched:d}=o,f=ie(o,ae);u===!0&&fe(r,`image`,`withBackground`,`dropped`);let p=typeof s==`object`&&s?s.url:void 0,m=typeof p==`string`?p:c,h=typeof m==`string`?m:``;return n.t(n.t({},e),{},{id:(a=e.id)==null?t.aa():a,data:n.t(n.t(n.t({url:h},f),l===!0?{frame:`border`}:{}),d===!0?{size:`full`}:{})})},Ge=(e,t)=>ze({style:`checklist`,items:e.items},t),Ke=(e,r)=>{var i,a;let o=(i=e.data.meta)==null?{}:i,s=typeof o.image==`object`&&o.image!==null?o.image.url:o.image;return o.site_name!==void 0&&fe(r,`linkTool`,`site_name`,`dropped`),n.t(n.t({},e),{},{id:(a=e.id)==null?t.aa():a,type:`bookmark`,data:n.t(n.t(n.t(n.t(n.t({url:e.data.link},o.title===void 0?{}:{title:o.title}),o.description===void 0?{}:{description:o.description}),typeof s==`string`?{image:s}:{}),o.favicon===void 0?{}:{favicon:o.favicon}),o.domain===void 0?{}:{domain:o.domain})})},qe=(e,r)=>{var i,a;me(e,r);let o=(i=e.data)==null?{}:i,{caption:s,alignment:c}=o,l=ie(o,oe),u=n.t(n.t({},e),{},{id:(a=e.id)==null?t.aa():a,data:l});return typeof s!=`string`||s.length===0?[u]:[u,{id:t.aa(),type:`paragraph`,data:{text:s}}]},Je=e=>{var r,i,a;let o=(r=e.id)==null?t.aa():r,s=(i=e.data)==null?{}:i,{content:c,withHeadings:l,withHeadingColumn:u,stretched:d}=s,f=ie(s,se),p=(a=_t(s))==null?[]:a,m=[],h=p.map(e=>Array.isArray(e)?e.map(e=>{if(gt(e))return e;let n=typeof e==`string`?e:``;if(n.length===0)return{blocks:[]};let r=t.aa();return m.push({id:r,type:`paragraph`,data:{text:n},parent:o}),{blocks:[r]}}):e);return[n.t(n.t({},e),{},{id:o,data:n.t(n.t(n.t({},f),{},{withHeadings:l===!0,withHeadingColumn:u===!0},d===!0?{stretched:!0}:{}),{},{content:h})}),...m]},Ye=e=>{var r,i;let a=(r=e.data)==null?void 0:r.html;return n.t(n.t({},e),{},{id:(i=e.id)==null?t.aa():i,type:`code`,data:{code:typeof a==`string`?a:``}})},Xe=`⚠️`,Ze=e=>{var r,i;let a=(r=e.id)==null?t.aa():r,o=(i=e.data)==null?{}:i,s=typeof o.title==`string`?o.title:``,c=typeof o.message==`string`?o.message:``,l=[];for(let e of[s,c])e.length!==0&&l.push({id:t.aa(),type:`paragraph`,data:{text:e},parent:a});let u=l.map(e=>e.id);return[n.t(n.t({id:a,type:`callout`,data:{emoji:Xe,textColor:null,backgroundColor:`orange`}},e.tunes===void 0?{}:{tunes:e.tunes}),u.length>0?{content:u}:{}),...l]},Qe=(e,r)=>{var i,a;let o=(i=e.data)==null?{}:i,s=typeof o.file==`object`&&o.file!==null?o.file:{},c=typeof s.url==`string`?s.url:``,l=typeof o.title==`string`?o.title:void 0;return(s.name!==void 0||s.size!==void 0||s.extension!==void 0)&&fe(r,`attaches`,`file metadata`,`dropped`),n.t(n.t({},e),{},{id:(a=e.id)==null?t.aa():a,type:`bookmark`,data:n.t({url:c},l===void 0?{}:{title:l})})},$e=e=>{let r=[],i=new Set;for(let o of e)if(we(o)){let e=ze(o.data,o.tunes);r.push(...e)}else if(Te(o)){let e=Ge(o.data,o.tunes);r.push(...e)}else if(Ee(o))r.push(Ke(o,i));else if(De(o)){let e=He(o);r.push(...e)}else if(Oe(o)){let e=Ue(o);r.push(...e)}else if(Ae(o))r.push(We(o,i));else if(ke(o)){let e=qe(o,i);r.push(...e)}else if(je(o))r.push(...Je(o));else if(Me(o))r.push(Ye(o));else if(Ne(o))r.push(...Ze(o));else if(Pe(o))r.push(Qe(o,i));else{var a;r.push(n.t(n.t({},o),{},{id:(a=o.id)==null?t.aa():a}))}return r},et=(e,t)=>{e&&t.add(e)},tt=e=>{let{parent:t,content:n}=e;return ie(e,ce)},nt=(e,t,n)=>{let r=[];for(let i of e){let e=t.get(i);if(e&&e.type===`list`){let i=rt(e,t,n);r.push(...i)}}return r},rt=(e,t,n)=>{let r=[];e.id&&n.add(e.id);let i=e.data,a={content:ve(i)?i.text:``,checked:ye(i)?i.checked:void 0},o=e.content;return o!==void 0&&o.length>0&&(a.items=nt(o,t,n)),a.items!==void 0&&a.items.length===0&&delete a.items,r.push(a),r},it=(e,t,r)=>{let i=rt(e,t,r),a=e.data,o=be(a)?a.style:`unordered`,s=xe(a)?a.start:void 0;return n.t({id:e.id,type:`list`,data:n.t({style:o,items:i},o===`ordered`&&s!==void 0&&s!==1?{start:s}:{})},e.tunes===void 0?{}:{tunes:e.tunes})};function at(e,t,n){let r=[];for(let i of e){if(n.has(i))continue;let e=t.get(i);if(e!==void 0){if(ut(e)){r.push(it(e,t,n));continue}if(st(e)){r.push(ot(e,t,n));continue}if(ct(e)){r.push(lt(e,t,n));continue}if(dt(e)){r.push(ft(e,t,n));continue}et(e.id,n),r.push(tt(e))}}return r}var ot=(e,t,r)=>{var i;et(e.id,r);let a=e.data,o=ve(a)?a.text:``,s=typeof(a==null?void 0:a.isOpen)==`boolean`?a.isOpen:void 0,c=at((i=e.content)==null?[]:i,t,r);return n.t({id:e.id,type:`toggleList`,data:n.t(n.t({title:o},s===void 0?{}:{isExpanded:s}),c.length>0?{body:{blocks:c}}:{})},e.tunes===void 0?{}:{tunes:e.tunes})},st=e=>e.type===`toggle`,ct=e=>{if(e.type!==`header`)return!1;let t=e.data;return typeof t==`object`&&!!t&&t.isToggleable===!0},lt=(e,t,r)=>{var i;et(e.id,r);let a=e.data,o=ve(a)?a.text:``,s=typeof(a==null?void 0:a.level)==`number`?a.level:void 0,c=typeof(a==null?void 0:a.isOpen)==`boolean`?a.isOpen:void 0,l=at((i=e.content)==null?[]:i,t,r);return n.t({id:e.id,type:`toggleList`,data:n.t(n.t(n.t({title:o},s===void 0?{}:{titleVariant:s}),c===void 0?{}:{isExpanded:c}),l.length>0?{body:{blocks:l}}:{})},e.tunes===void 0?{}:{tunes:e.tunes})},ut=e=>{if(e.type!==`list`)return!1;let t=e.data,n=ve(t),r=Se(t);return n&&!r},dt=e=>{if(e.type!==`callout`)return!1;let t=e.data;return typeof t==`object`&&!!t&&!(`body`in t)},ft=(e,t,r)=>{var i,a;et(e.id,r);let o=e.data,s=o.backgroundColor,c=s==null||(i=ue[s])==null?`general`:i,l=o.emoji,u=typeof l==`string`&&l.length>0,d=u?l:null,f=at((a=e.content)==null?[]:a,t,r);return n.t({id:e.id,type:`callout`,data:n.t({title:``,variant:c,emoji:d,isEmojiVisible:u},f.length>0?{body:{blocks:f}}:{})},e.tunes===void 0?{}:{tunes:e.tunes})},pt=(e,t,n)=>{if(!e.id||!e.parent||!t.has(e.parent))return;let r=n.get(e.parent);if(r===void 0){n.set(e.parent,[e.id]);return}r.push(e.id)},mt=(e,t,n)=>{let r=(Array.isArray(e)?e:[]).filter(e=>n.has(e));for(let e of t)r.includes(e)||r.push(e);return r},ht=e=>{let t=e.map(e=>n.t({},e)),r=new Map;for(let e of t)e.id&&r.set(e.id,e);let i=new Map;for(let e of t)pt(e,r,i);for(let[e,t]of i){let n=r.get(e);n!==void 0&&(n.content=mt(n.content,t,r))}let a=new Map;for(let e of t)e.id&&a.set(e.id,e);let o=t.some(ut),s=t.some(st),c=t.some(e=>ct(e)&&!e.parent),l=t.some(dt);if(!o&&!s&&!c&&!l)return t.map(tt);let u=[],d=new Set;for(let e of t){if(e.id&&d.has(e.id))continue;let t=ut(e),n=t&&!e.parent,r=st(e),i=r&&!e.parent,o=ct(e),s=o&&!e.parent,c=dt(e),l=c&&!e.parent,f=!t&&!r&&!o&&!c;if(n){let t=it(e,a,d);u.push(t)}if(i){let t=ot(e,a,d);u.push(t)}if(s){let t=lt(e,a,d);u.push(t)}if(l){let t=ft(e,a,d);u.push(t)}f&&(u.push(tt(e)),et(e.id,d))}return u},gt=e=>typeof e==`object`&&!!e&&Array.isArray(e.blocks),_t=e=>{if(typeof e!=`object`||!e)return null;let t=e.content;return Array.isArray(t)?t:null},vt=(e,t,n)=>{if(gt(e))for(let r of e.blocks)typeof r!=`string`||n.has(r)||n.set(r,t)},yt=(e,t,n)=>{Array.isArray(e)&&e.forEach(e=>vt(e,t,n))},bt=(e,t)=>{if(e.id===void 0||e.id===null)return;let n=_t(e.data);if(n===null)return;let r=e.id;n.forEach(e=>yt(e,r,t))},xt=e=>{let t=new Map;return e.filter(e=>e.type===`table`).forEach(e=>bt(e,t)),t.size===0?e:e.map(e=>{if(e.id===void 0||e.id===null)return e;let r=t.get(e.id);return r===void 0||e.parent!==void 0&&e.parent!==null?e:n.t(n.t({},e),{},{parent:r})})},St=/^cell-([1-9]\d*)-([1-9]\d*)$/,Ct=e=>{if(typeof e!=`string`)return null;let t=St.exec(e);if(t===null)return null;let n=Number(t[1])-1,r=Number(t[2])-1;return n<0||r<0?null:{row:n,col:r}},wt=(e,t,n)=>{let r=_t(e.data);if(r===null)return!1;let i=r[t];if(!Array.isArray(i))return!1;let a=i[n];return gt(a)&&a.blocks.length===0},Tt=e=>{let t=new Set;return e.filter(e=>e.type===`table`).forEach(e=>{let n=_t(e.data);n==null||n.forEach(e=>{Array.isArray(e)&&e.forEach(e=>{gt(e)&&e.blocks.forEach(e=>{typeof e==`string`&&t.add(e)})})})}),t},Et=e=>{let t=e.filter(e=>e.type===`table`&&e.id!==void 0&&e.id!==null);if(t.length!==1)return e;let r=Tt(e),i=new Map;for(let t of e)if(t.id!==void 0&&t.id!==null){var a;i.set(t.id,((a=i.get(t.id))==null?0:a)+1)}let o=new Map,s=new Map;for(let a of e){var c,l;if(a.id===void 0||a.id===null||a.parent!==void 0&&a.parent!==null||r.has(a.id)||((c=i.get(a.id))==null?0:c)>1)continue;let e=Ct(a.id);if(e===null)continue;let u=t.filter(t=>wt(t,e.row,e.col));if(u.length!==1)continue;let d=u[0].id;o.set(a.id,d);let f=(l=s.get(d))==null?[]:l;f.push(n.t(n.t({},e),{},{id:a.id})),s.set(d,f)}return o.size===0?e:e.map(e=>{if(e.id!==void 0&&e.id!==null&&o.has(e.id))return n.t(n.t({},e),{},{parent:o.get(e.id)});if(e.type===`table`&&e.id!==void 0&&e.id!==null&&s.has(e.id)){var t;let r=(t=s.get(e.id))==null?[]:t,i=_t(e.data);if(i===null)return e;let a=i.map((e,t)=>Array.isArray(e)?e.map((e,i)=>{let a=r.find(e=>e.row===t&&e.col===i);return a===void 0||!gt(e)?e:n.t(n.t({},e),{},{blocks:[...e.blocks,a.id]})}):e);return n.t(n.t({},e),{},{data:n.t(n.t({},e.data),{},{content:a})})}return e})},Dt=(e,t)=>t===`legacy`?e!==`legacy`:!1,Ot=(e,t)=>e===`legacy`||e===`auto`&&t===`legacy`,kt=`blok-block--target`,At=1800;function jt(e){e.classList.remove(kt),e.offsetWidth,e.classList.add(kt);let t={removed:!1},n=()=>{t.removed||(t.removed=!0,e.classList.remove(kt),e.removeEventListener(`animationend`,r))},r=t=>{t.target===e&&n()};e.addEventListener(`animationend`,r),window.setTimeout(n,At)}var Mt=class extends s{constructor(...e){var n;super(...e),n=this,this.insert=(e,n={},r={},i,a,o,s)=>{let l=e==null?this.config.defaultBlock:e,u=(()=>{if(!l)return l;let e=i==null?this.Blok.BlockManager.currentBlockIndex:i,n=this.Blok.BlockManager.getBlockByIndex(e);return n!==void 0&&t.Yi(n)&&t.Xi(l)?`paragraph`:l})();return new c(this.Blok.BlockManager.insert({id:s,tool:u,data:n,index:i,needToFocus:a,replace:o}))},this.composeBlockData=async e=>{let t=n.Blok.Tools.blockTools.get(e);if(t===void 0)throw Error(`Block Tool with type "${e}" not found`);return new ne({tool:t,api:n.Blok.API,readOnly:!0,data:{},tunesData:{}}).data},this.update=async(e,t,r)=>{let{BlockManager:i}=n.Blok,a=i.getBlockById(e);if(a===void 0)throw Error(`Block with id "${e}" not found`);return new c(await i.update(a,t,r))},this.convert=async(e,r,i)=>{var a,o;let{BlockManager:s,Tools:l}=n.Blok,u=s.getBlockById(e);if(!u)throw Error(`Block with id "${e}" not found`);let d=l.blockTools.get(u.name),f=l.blockTools.get(r);if(!f)throw Error(`Block Tool with type "${r}" not found`);let p=(d==null||(a=d.conversionConfig)==null?void 0:a.export)!==void 0,m=((o=f.conversionConfig)==null?void 0:o.import)!==void 0;if(p&&m)return new c(await s.convert(u,r,i));{let e=[p?!1:t.ua(u.name),m?!1:t.ua(r)].filter(Boolean).join(` and `);throw Error(`Conversion from "${u.name}" to "${r}" is not possible. ${e} tool(s) should provide a "conversionConfig"`)}},this.insertMany=(e,t=this.Blok.BlockManager.blocks.length-1)=>{this.validateIndex(t);let n=xt(e).map(({id:e,type:t,data:n,tunes:r,parent:i,content:a,lastEditedAt:o,lastEditedBy:s})=>this.Blok.BlockManager.composeBlock({id:e,tool:t||this.config.defaultBlock,data:n,tunes:r,parentId:i,contentIds:a,lastEditedAt:o,lastEditedBy:s}));return this.Blok.BlockManager.insertMany(n,t),n.map(e=>new c(e))},this.insertInsideParent=(e,t,n)=>(this.Blok.BlockManager.suppressStopCapturing||this.Blok.YjsManager.stopCapturing(),new c(this.Blok.BlockManager.insertInsideParent(e,t,n))),this.splitBlock=(e,t,n,r,i)=>{this.Blok.YjsManager.stopCapturing();let a=this.Blok.BlockManager.splitBlockWithData(e,t,n,r,i);return queueMicrotask(()=>{this.Blok.YjsManager.stopCapturing()}),new c(a)}}get methods(){let e=this;return{get isSyncingFromYjs(){return e.Blok.BlockManager.isSyncingFromYjs},clear:()=>this.clear(),render:e=>this.render(e),renderFromHTML:e=>this.renderFromHTML(e),delete:e=>this.delete(e),move:(e,t)=>this.move(e,t),getBlockByIndex:e=>this.getBlockByIndex(e),getById:e=>this.getById(e),getCurrentBlockIndex:()=>this.getCurrentBlockIndex(),getBlockIndex:e=>this.getBlockIndex(e),getBlocksCount:()=>this.getBlocksCount(),getBlockByElement:e=>this.getBlockByElement(e),getChildren:e=>this.getChildren(e),insert:this.insert,insertMany:this.insertMany,update:this.update,composeBlockData:this.composeBlockData,convert:this.convert,setBlockParent:(e,t)=>this.setBlockParent(e,t),stopBlockMutationWatching:e=>this.stopBlockMutationWatching(e),splitBlock:this.splitBlock,insertInsideParent:this.insertInsideParent,transact:e=>this.transact(e),transactWithoutCapture:e=>this.transactWithoutCapture(e),setPointerDragActive:e=>this.setPointerDragActive(e)}}getBlocksCount(){return this.Blok.BlockManager.blocks.length}getCurrentBlockIndex(){return this.Blok.BlockManager.currentBlockIndex}getBlockIndex(e){let n=this.Blok.BlockManager.getBlockById(e);if(!n){t.Da("There is no block with id `"+e+"`",`warn`);return}return this.Blok.BlockManager.getBlockIndex(n)}getBlockByIndex(e){let n=this.Blok.BlockManager.getBlockByIndex(e);if(n===void 0){t.Da("There is no block at index `"+e+"`",`warn`);return}return new c(n)}getById(e){let n=this.Blok.BlockManager.getBlockById(e);return n===void 0?(t.Da("There is no block with id `"+e+"`",`warn`),null):new c(n)}getBlockByElement(e){let n=this.Blok.BlockManager.getBlock(e);if(n===void 0){var r,i;t.Da(`There is no block corresponding to element <${(r=(i=e.tagName)==null?void 0:i.toLowerCase())==null?`unknown`:r}>`,`warn`);return}return new c(n)}getChildren(e){return this.Blok.BlockManager.blocks.filter(t=>t.parentId===e).map(e=>new c(e))}move(e,t){this.Blok.BlockManager.move(e,t)}async delete(e=this.Blok.BlockManager.currentBlockIndex){var n=this;let r=n.Blok.BlockManager.getBlockByIndex(e);if(r===void 0){t.Da(`There is no block at index \`${e}\``,`warn`);return}try{await n.Blok.BlockManager.removeBlock(r)}catch(e){t.Da(e,`warn`);return}n.Blok.BlockManager.currentBlock&&n.Blok.Caret.setToBlock(n.Blok.BlockManager.currentBlock,n.Blok.Caret.positions.END),n.Blok.Toolbar.close()}async clear(){var e=this;await e.Blok.BlockManager.clear(!0),e.Blok.InlineToolbar.close()}async render(e){var t=this;if(e===void 0||e.blocks===void 0)throw Error(`Incorrect data passed to the render() method`);t.Blok.ModificationsObserver.disable(),t.Blok.Renderer.markRenderStart();try{await t.Blok.BlockManager.clear(),await t.Blok.Renderer.render(e.blocks)}finally{t.Blok.Renderer.markRenderEnd()}t.Blok.ModificationsObserver.enable(),t.processPendingHashScroll()}async renderFromHTML(e){var t=this;t.Blok.Renderer.markRenderStart();try{return await t.Blok.BlockManager.clear(),t.Blok.Paste.processText(e,!0)}finally{t.Blok.Renderer.markRenderEnd()}}async importMarkdown(e,t){var n=this;let{markdownToBlocks:r}=await Promise.resolve().then(()=>require(`../markdown.cjs`)),i={blocks:await r(e,t)};return await n.render(i),i}setBlockParent(e,n){let r=this.Blok.BlockManager.getBlockById(e);if(r===void 0){t.Da("There is no block with id `"+e+"`",`warn`);return}this.Blok.BlockManager.setBlockParent(r,n)}stopBlockMutationWatching(e){let t=this.Blok.BlockManager.getBlockByIndex(e);t!==void 0&&t.unwatchBlockMutations()}transact(e){this.Blok.BlockManager.transactForTool(e)}transactWithoutCapture(e){this.Blok.YjsManager.transactWithoutCapture(e)}setPointerDragActive(e){this.Blok.BlockManager.setPointerDragActive(e)}validateIndex(e){if(typeof e!=`number`)throw Error(`Index should be a number`);if(e<0)throw Error(`Index should be greater than or equal to 0`)}processPendingHashScroll(){var e,t;let n=this.Blok.Renderer.pendingHashScroll;if(n===null)return;this.Blok.Renderer.pendingHashScroll=null;let r=document.querySelector(`[data-blok-id="${CSS.escape(n)}"]`);if(r===null)return;let i=(e=(t=this.config.scrollToBlock)==null?void 0:t.topOffset)==null?0:e,a=r.getBoundingClientRect().top+window.scrollY-i;window.scrollTo({top:a,behavior:`smooth`});let o=this.Blok.BlockManager.getBlockById(n);o!==void 0&&this.Blok.BlockSelection.selectBlock(o),jt(r)}},Nt=(e,t)=>typeof e==`number`?t.BlockManager.getBlockByIndex(e):typeof e==`string`?t.BlockManager.getBlockById(e):t.BlockManager.getBlockById(e.id),Pt=class extends s{constructor(...e){super(...e),this.setToFirstBlock=(e=this.Blok.Caret.positions.DEFAULT,t=0)=>this.Blok.BlockManager.firstBlock?(this.Blok.Caret.setToBlock(this.Blok.BlockManager.firstBlock,e,t),!0):!1,this.setToLastBlock=(e=this.Blok.Caret.positions.DEFAULT,t=0)=>this.Blok.BlockManager.lastBlock?(this.Blok.Caret.setToBlock(this.Blok.BlockManager.lastBlock,e,t),!0):!1,this.setToPreviousBlock=(e=this.Blok.Caret.positions.DEFAULT,t=0)=>this.Blok.BlockManager.previousBlock?(this.Blok.Caret.setToBlock(this.Blok.BlockManager.previousBlock,e,t),!0):!1,this.setToNextBlock=(e=this.Blok.Caret.positions.DEFAULT,t=0)=>this.Blok.BlockManager.nextBlock?(this.Blok.Caret.setToBlock(this.Blok.BlockManager.nextBlock,e,t),!0):!1,this.setToBlock=(e,t=this.Blok.Caret.positions.DEFAULT,n=0)=>{let r=Nt(e,this.Blok);return r===void 0?!1:(this.Blok.Caret.setToBlock(r,t,n),!0)},this.focus=(e=!1)=>e?this.setToLastBlock(this.Blok.Caret.positions.END):this.setToFirstBlock(this.Blok.Caret.positions.START),this.updateLastCaretAfterPosition=()=>{this.Blok.YjsManager.updateLastCaretAfterPosition()}}get methods(){return{setToFirstBlock:this.setToFirstBlock,setToLastBlock:this.setToLastBlock,setToPreviousBlock:this.setToPreviousBlock,setToNextBlock:this.setToNextBlock,setToBlock:this.setToBlock,focus:this.focus,updateLastCaretAfterPosition:this.updateLastCaretAfterPosition}}},Ft=class extends s{get methods(){return{emit:(e,t)=>this.emit(e,t),off:(e,t)=>this.off(e,t),on:(e,t)=>this.on(e,t)}}on(e,t){this.eventsDispatcher.on(e,t)}emit(e,t){this.eventsDispatcher.emit(e,t)}off(e,t){this.eventsDispatcher.off(e,t)}},It=class extends s{get methods(){return{undo:()=>this.undo(),redo:()=>this.redo(),canUndo:()=>this.canUndo(),canRedo:()=>this.canRedo(),clear:()=>this.clear()}}undo(){this.Blok.YjsManager.undo()}redo(){this.Blok.YjsManager.redo()}canUndo(){return this.Blok.YjsManager.canUndo()}canRedo(){return this.Blok.YjsManager.canRedo()}clear(){this.Blok.YjsManager.clear()}},Lt=class extends s{constructor(...e){super(...e),this.cachedMethods=null}get methods(){return this.cachedMethods===null&&(this.cachedMethods={t:e=>this.Blok.I18n.t(e),has:e=>this.Blok.I18n.has(e),getEnglishTranslation:e=>this.Blok.I18n.getEnglishTranslation(e),getLocale:()=>this.Blok.I18n.getLocale()}),this.cachedMethods}},Rt=class extends s{get methods(){let e=this.config;return{blocks:this.Blok.BlocksAPI.methods,caret:this.Blok.CaretAPI.methods,tools:this.Blok.ToolsAPI.methods,events:this.Blok.EventsAPI.methods,history:this.Blok.HistoryAPI.methods,listeners:this.Blok.ListenersAPI.methods,notifier:this.Blok.NotifierAPI.methods,sanitizer:this.Blok.SanitizerAPI.methods,saver:this.Blok.SaverAPI.methods,selection:this.Blok.SelectionAPI.methods,styles:this.Blok.StylesAPI.classes,toolbar:this.Blok.ToolbarAPI.methods,inlineToolbar:this.Blok.InlineToolbarAPI.methods,tooltip:this.Blok.TooltipAPI.methods,i18n:this.Blok.I18nAPI.methods,readOnly:this.Blok.ReadOnlyAPI.methods,ui:this.Blok.UiAPI.methods,theme:this.Blok.ThemeAPI.methods,config:{get linkPaste(){return e.linkPaste},get link(){return e.link}},rectangleSelection:this.Blok.RectangleSelection}}},zt=class extends s{get methods(){return{close:()=>this.close(),open:()=>this.open()}}open(){this.Blok.InlineToolbar.tryToShow()}close(){this.Blok.InlineToolbar.close()}},Bt=class extends s{get methods(){return{on:(e,t,n,r)=>this.on(e,t,n,r),off:(e,t,n,r)=>this.off(e,t,n,r),offById:e=>this.offById(e)}}on(e,t,n,r){return this.listeners.on(e,t,n,r)}off(e,t,n,r){this.listeners.off(e,t,n,r)}offById(e){this.listeners.offById(e)}},Vt=class{constructor(e=i.t){this.notifierModule=null,this.loadingPromise=null,this.position=e}loadNotifierModule(){return this.notifierModule===null?(this.loadingPromise===null&&(this.loadingPromise=Promise.resolve().then(()=>require(`./notifier-CFYHvVe5.cjs`)).then(e=>{let t=e;if(!this.isNotifierModule(t))throw Error(`notifier module does not expose a "show" method.`);return this.notifierModule=t,t}).catch(e=>{throw this.loadingPromise=null,e})),this.loadingPromise):Promise.resolve(this.notifierModule)}show(e){this.loadNotifierModule().then(t=>{t.show(e,this.position)}).catch(e=>{console.error(`[Blok] Failed to display notification. Reason:`,e)})}isNotifierModule(e){return typeof e==`object`&&!!e&&`show`in e&&typeof e.show==`function`}},Ht=class extends s{constructor({config:e,eventsDispatcher:t}){var n;super({config:e,eventsDispatcher:t}),this.builtInNotifier=new Vt((n=e.notifierPosition)==null?i.t:n),this.customNotifier=e.notifier}get methods(){return{show:e=>this.show(e)}}show(e){if(this.customNotifier!==void 0){this.customNotifier(e);return}this.builtInNotifier.show(e)}},Ut=class extends s{get methods(){let e=()=>this.isEnabled;return{toggle:e=>this.toggle(e),set:e=>this.set(e),get isEnabled(){return e()}}}toggle(e){return this.Blok.ReadOnly.toggle(e)}set(e){return this.Blok.ReadOnly.set(e)}get isEnabled(){return this.Blok.ReadOnly.isEnabled}},Wt=class extends s{get methods(){return{clean:(e,t)=>this.clean(e,t)}}clean(e,n){return t.Ei(e,n)}},Gt=class extends s{get methods(){return{save:()=>this.save()}}async save(){var e=this,n,r;let i=`Blok's content can not be saved in read-only mode`;if(e.Blok.ReadOnly.isEnabled)throw t.Da(i,`warn`),Error(i);let a=await e.Blok.Saver.save();if(a!==void 0)return a;let o=(n=(r=e.Blok.Saver).getLastSaveError)==null?void 0:n.call(r);throw o instanceof Error?o:Error(o===void 0?`Blok's content can not be saved because collecting data failed`:String(o))}},Kt=class extends s{constructor(...e){super(...e),this.selectionUtils=new t.Ai}get methods(){return{findParentTag:(e,t)=>this.findParentTag(e,t),expandToTag:e=>this.expandToTag(e),save:()=>this.selectionUtils.save(),restore:()=>this.selectionUtils.restore(),setFakeBackground:()=>this.selectionUtils.setFakeBackground(),removeFakeBackground:()=>this.selectionUtils.removeFakeBackground(),clearFakeBackground:()=>this.selectionUtils.clearFakeBackground()}}findParentTag(e,t){return this.selectionUtils.findParentTag(e,t)}expandToTag(e){this.selectionUtils.expandToTag(e)}},qt=class extends s{get classes(){return{block:`blok-block`,inlineToolButton:`blok-inline-tool-button`,inlineToolButtonActive:`blok-inline-tool-button--active`,input:`blok-input`,loader:`blok-loader`,button:`blok-button`,settingsButton:`blok-settings-button`,settingsButtonActive:`blok-settings-button--active`,settingsButtonFocused:`blok-settings-button--focused`,settingsButtonFocusedAnimated:`blok-settings-button--focused-animated`}}},Jt=class extends s{get methods(){return{close:e=>this.close(e),open:()=>this.open(),toggleBlockSettings:(e,t,n)=>this.toggleBlockSettings(e,t,n),toggleToolbox:e=>this.toggleToolbox(e)}}open(){this.Blok.Toolbar.moveAndOpen()}close(e){this.Blok.Toolbar.close(e)}toggleBlockSettings(e,n,r){if(this.Blok.BlockManager.currentBlockIndex===-1){t.Da(`Could't toggle the Toolbar because there is no block selected `,`warn`);return}(e==null?!this.Blok.BlockSettings.opened:e)?(this.Blok.Toolbar.moveAndOpen(),this.Blok.BlockSettings.open(void 0,n,r)):this.Blok.BlockSettings.close()}toggleToolbox(e){if(this.Blok.BlockManager.currentBlockIndex===-1){t.Da(`Could't toggle the Toolbox because there is no block selected `,`warn`);return}(e==null?!this.Blok.Toolbar.toolbox.opened:e)?(this.Blok.Toolbar.moveAndOpen(),this.Blok.Toolbar.toolbox.open()):this.Blok.Toolbar.toolbox.close()}},Yt=class extends s{get methods(){return{getBlockTools:()=>Array.from(this.Blok.Tools.blockTools.values()),getToolsConfig:()=>{let e={tools:this.config.tools};return this.config.inlineToolbar!==void 0&&(e.inlineToolbar=this.config.inlineToolbar),this.config.tunes!==void 0&&(e.tunes=this.config.tunes),this.config.theme!==void 0&&(e.theme=this.config.theme),e},update:(e,t)=>{this.Blok.Tools.updateToolConfig(e,t)}}}},Xt=class extends s{constructor({config:e,eventsDispatcher:t}){super({config:e,eventsDispatcher:t})}get methods(){return{show:(e,t,n)=>this.show(e,t,n),hide:()=>this.hide(),onHover:(e,t,n)=>this.onHover(e,t,n)}}show(e,n,r){t.Si(e,n,r)}hide(){t.bi()}onHover(e,n,r){t.xi(e,n,r)}},Zt=class extends s{get methods(){let e=this.Blok.UI;return{nodes:this.blokNodes,get isMobile(){return e.isMobile}}}get blokNodes(){return{wrapper:this.Blok.UI.nodes.wrapper,redactor:this.Blok.UI.nodes.redactor}}},Qt=class extends s{get methods(){let e=this.Blok.ThemeManager;return{get:()=>e.getMode(),set:t=>e.setMode(t),getResolved:()=>e.getResolved()}}},E=()=>new Map,$t=e=>{let t=E();return e.forEach((e,n)=>{t.set(n,e)}),t},en=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},tn=(e,t)=>{let n=[];for(let[r,i]of e)n.push(t(i,r));return n},nn=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},rn=()=>new Set,an=e=>e[e.length-1],on=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},sn=Array.from,cn=(e,t)=>{for(let n=0;n<e.length;n++)if(!t(e[n],n,e))return!1;return!0},ln=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},un=(e,t)=>{let n=Array(e);for(let r=0;r<e;r++)n[r]=t(r,n);return n},dn=Array.isArray,fn=class{constructor(){this._observers=E()}on(e,t){return en(this._observers,e,rn).add(t),t}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return sn((this._observers.get(e)||E()).values()).forEach(e=>e(...t))}destroy(){this._observers=E()}},D=Math.floor,pn=Math.abs,mn=(e,t)=>e<t?e:t,hn=(e,t)=>e>t?e:t;Number.isNaN;var gn=e=>e===0?1/e<0:e<0,_n=2**53-1,vn=-(2**53-1),yn=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&D(e)===e);Number.isNaN,Number.parseInt;var bn=String.fromCharCode;String.fromCodePoint,bn(65535);var xn=e=>e.toLowerCase(),Sn=/^\s*/g,Cn=e=>e.replace(Sn,``),wn=/([A-Z])/g,Tn=(e,t)=>Cn(e.replace(wn,e=>`${t}${xn(e)}`)),En=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},Dn=typeof TextEncoder<`u`?new TextEncoder:null,On=Dn?e=>Dn.encode(e):En,kn=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});kn&&kn.decode(new Uint8Array).length===1&&(kn=null);var An=(e,t)=>un(t,()=>e).join(``),jn=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}},Mn=()=>new jn,Nn=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},O=e=>{let t=new Uint8Array(Nn(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},Pn=(e,t)=>{let n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(hn(n,t)*2),e.cpos=0)},k=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Fn=k,A=(e,t)=>{for(;t>127;)k(e,128|127&t),t=D(t/128);k(e,127&t)},In=(e,t)=>{let n=gn(t);for(n&&(t=-t),k(e,(t>63?128:0)|(n?64:0)|63&t),t=D(t/64);t>0;)k(e,(t>127?128:0)|127&t),t=D(t/128)},Ln=new Uint8Array(3e4),Rn=Ln.length/3,zn=Dn&&Dn.encodeInto?(e,t)=>{if(t.length<Rn){let n=Dn.encodeInto(t,Ln).written||0;A(e,n);for(let t=0;t<n;t++)k(e,Ln[t])}else j(e,On(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;A(e,r);for(let t=0;t<r;t++)k(e,n.codePointAt(t))},Bn=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=mn(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(hn(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},j=(e,t)=>{A(e,t.byteLength),Bn(e,t)},Vn=(e,t)=>{Pn(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Hn=(e,t)=>Vn(e,4).setFloat32(0,t,!1),Un=(e,t)=>Vn(e,8).setFloat64(0,t,!1),Wn=(e,t)=>Vn(e,8).setBigInt64(0,t,!1),Gn=new DataView(new ArrayBuffer(4)),Kn=e=>(Gn.setFloat32(0,e),Gn.getFloat32(0)===e),qn=(e,t)=>{switch(typeof t){case`string`:k(e,119),zn(e,t);break;case`number`:yn(t)&&pn(t)<=2147483647?(k(e,125),In(e,t)):Kn(t)?(k(e,124),Hn(e,t)):(k(e,123),Un(e,t));break;case`bigint`:k(e,122),Wn(e,t);break;case`object`:if(t===null)k(e,126);else if(dn(t)){k(e,117),A(e,t.length);for(let n=0;n<t.length;n++)qn(e,t[n])}else if(t instanceof Uint8Array)k(e,116),j(e,t);else{k(e,118);let n=Object.keys(t);A(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];zn(e,i),qn(e,t[i])}}break;case`boolean`:k(e,t?120:121);break;default:k(e,127)}},Jn=class extends jn{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&A(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}},Yn=e=>{e.count>0&&(In(e.encoder,e.count===1?e.s:-e.s),e.count>1&&A(e.encoder,e.count-2))},Xn=class{constructor(){this.encoder=new jn,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Yn(this),this.count=1,this.s=e)}toUint8Array(){return Yn(this),O(this.encoder)}},Zn=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);In(e.encoder,t),e.count>1&&A(e.encoder,e.count-2)}},Qn=class{constructor(){this.encoder=new jn,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Zn(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Zn(this),O(this.encoder)}},$n=class{constructor(){this.sarr=[],this.s=``,this.lensE=new Xn}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(e.length)}toUint8Array(){let e=new jn;return this.sarr.push(this.s),this.s=``,zn(e,this.sarr.join(``)),Bn(e,this.lensE.toUint8Array()),O(e)}},er=e=>Error(e),M=()=>{throw er(`Method unimplemented`)},N=()=>{throw er(`Unexpected case`)};crypto.subtle;var tr=crypto.getRandomValues.bind(crypto),nr=()=>tr(new Uint32Array(1))[0],rr=`10000000-1000-4000-8000-100000000000`,ir=()=>rr.replace(/[018]/g,e=>(e^nr()&15>>e/4).toString(16)),ar=Date.now,or=e=>new Promise(e);Promise.all.bind(Promise);var sr=e=>e===void 0?null:e,cr=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}};try{typeof localStorage<`u`&&localStorage&&(cr=localStorage)}catch(e){}var lr=cr,ur=Symbol(`Equality`),dr=(e,t)=>{var n;return e===t||!!(!(e==null||(n=e[ur])==null)&&n.call(e,t))||!1},fr=e=>typeof e==`object`,pr=Object.assign,mr=Object.keys,hr=(e,t)=>{for(let n in e)t(e[n],n)},gr=e=>mr(e).length,_r=e=>{for(let t in e)return!1;return!0},vr=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},yr=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),br=(e,t)=>e===t||gr(e)===gr(t)&&vr(e,(e,n)=>(e!==void 0||yr(t,n))&&dr(t[n],e)),xr=Object.freeze,Sr=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&Sr(e[t])}return xr(e)},Cr=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Cr(e,t,n+1)}},wr=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[ur]!=null)return e[ur](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!wr(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(gr(e)!==gr(t))return!1;for(let n in e)if(!yr(e,n)||!wr(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!wr(e[n],t[n]))return!1;break;default:return!1}return!0},Tr=(e,t)=>t.includes(e),Er=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`;typeof navigator<`u`&&/Mac/.test(navigator.platform);var P,Dr=[],Or=()=>{if(P===void 0)if(Er){P=E();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&P.set(t,``),t=r):t===null?Dr.push(r):(P.set(t,r),t=null)}t!==null&&P.set(t,``)}else typeof location==`object`?(P=E(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);P.set(`--${Tn(t,`-`)}`,n),P.set(`-${Tn(t,`-`)}`,n)}})):P=E();return P},kr=e=>Or().has(e),Ar=e=>sr(Er?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:lr.getItem(e)),jr=e=>kr(`--`+e)||Ar(e)!==null,Mr=jr(`production`),Nr=Er&&Tr(process.env.FORCE_COLOR,[`true`,`1`,`2`])||!kr(`--no-colors`)&&!jr(`no-color`)&&(!Er||process.stdout.isTTY)&&(!Er||kr(`--color`)||Ar(`COLORTERM`)!==null||(Ar(`TERM`)||``).includes(`color`)),Pr=class{constructor(e,t){this.left=e,this.right=t}},F=(e,t)=>new Pr(e,t),Fr=e=>e.next()>=.5,Ir=(e,t,n)=>D(e.next()*(n+1-t)+t),Lr=(e,t,n)=>D(e.next()*(n+1-t)+t),Rr=(e,t,n)=>Lr(e,t,n),zr=e=>bn(Rr(e,97,122)),Br=(e,t=0,n=20)=>{let r=Rr(e,t,n),i=``;for(let t=0;t<r;t++)i+=zr(e);return i},Vr=(e,t)=>t[Rr(e,0,t.length-1)],Hr,Ur=Symbol(`0schema`),Wr=class{constructor(){this._rerrs=[]}extend(e,t,n,r=null){this._rerrs.push({path:e,expected:t,has:n,message:r})}toString(){let e=[];for(let t=this._rerrs.length-1;t>0;t--){let n=this._rerrs[t];e.push(An(` `,(this._rerrs.length-t)*2)+`${n.path==null?``:`[${n.path}] `}${n.has} doesn't match ${n.expected}. ${n.message}`)}return e.join(`
2
2
  `)}},Gr=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[ur]?dr(e,t):dn(e)?cn(e,e=>ln(t,t=>Gr(e,t))):fr(e)?vr(e,(e,n)=>Gr(e,t[n])):!1;Hr=ur;var I=class{extends(e){let[t,n]=[this.shape,e.shape];return this.constructor._dilutes&&([n,t]=[t,n]),Gr(t,n)}equals(e){return this.constructor===e.constructor&&wr(this.shape,e.shape)}[Ur](){return!0}[Hr](e){return this.equals(e)}validate(e){return this.check(e)}check(e,t){M()}get nullable(){return Si(this,Li)}get optional(){return new ei(this)}cast(e){return Vi(e,this),e}expect(e){return Vi(e,this),e}};n.n(I,`_dilutes`,!1);var Kr=class extends I{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t=void 0){let n=(e==null?void 0:e.constructor)===this.shape&&(this._c==null||this._c(e));return!n&&(t==null||t.extend(null,this.shape.name,e==null?void 0:e.constructor.name,(e==null?void 0:e.constructor)===this.shape?`Check failed`:`Constructor match failed`)),n}},L=(e,t=null)=>new Kr(e,t);L(Kr);var qr=class extends I{constructor(e){super(),this.shape=e}check(e,t){let n=this.shape(e);return!n&&(t==null||t.extend(null,`custom prop`,e==null?void 0:e.constructor.name,`failed to check custom prop`)),n}},R=e=>new qr(e);L(qr);var Jr=class extends I{constructor(e){super(),this.shape=e}check(e,t){let n=this.shape.some(t=>t===e);return!n&&(t==null||t.extend(null,this.shape.join(` | `),e.toString())),n}},Yr=(...e)=>new Jr(e),Xr=L(Jr),Zr=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,e=>`\\`+e)),Qr=e=>{if(Mi.check(e))return[Zr(e)];if(Xr.check(e))return e.shape.map(e=>e+``);if(ji.check(e))return[`[+-]?\\d+.?\\d*`];if(Ni.check(e))return[`.*`];if(Ci.check(e))return e.shape.map(Qr).flat(1);N()};L(class extends I{constructor(e){super(),this.shape=e,this._r=RegExp(`^`+e.map(Qr).map(e=>`(${e.join(`|`)})`).join(``)+`$`)}check(e,t){let n=this._r.exec(e)!=null;return!n&&(t==null||t.extend(null,this._r.toString(),e.toString(),`String doesn't match string template.`)),n}});var $r=Symbol(`optional`),ei=class extends I{constructor(e){super(),this.shape=e}check(e,t){let n=e===void 0||this.shape.check(e);return!n&&(t==null||t.extend(null,`undefined (optional)`,`()`)),n}get[$r](){return!0}},ti=L(ei),ni=class extends I{check(e,t){return t==null||t.extend(null,`never`,typeof e),!1}};new ni,L(ni);var ri=class e extends I{constructor(e,t=!1){super(),this.shape=e,this._isPartial=t}get partial(){return new e(this.shape,!0)}check(e,t){return e==null?(t==null||t.extend(null,`object`,`null`),!1):vr(this.shape,(n,r)=>{let i=this._isPartial&&!yr(e,r)||n.check(e[r],t);return!i&&(t==null||t.extend(r.toString(),n.toString(),typeof e[r],`Object property does not match`)),i})}};n.n(ri,`_dilutes`,!0);var ii=e=>new ri(e),ai=L(ri),oi=R(e=>e!=null&&(e.constructor===Object||e.constructor==null)),si=class extends I{constructor(e,t){super(),this.shape={keys:e,values:t}}check(e,t){return e!=null&&vr(e,(n,r)=>{let i=this.shape.keys.check(r,t);return!i&&(t==null||t.extend(r+``,`Record`,typeof e,i?`Key doesn't match schema`:`Value doesn't match value`)),i&&this.shape.values.check(n,t)})}},ci=(e,t)=>new si(e,t),li=L(si),ui=class extends I{constructor(e){super(),this.shape=e}check(e,t){return e!=null&&vr(this.shape,(n,r)=>{let i=n.check(e[r],t);return!i&&(t==null||t.extend(r.toString(),`Tuple`,typeof n)),i})}},di=(...e)=>new ui(e);L(ui);var fi=class extends I{constructor(e){super(),this.shape=e.length===1?e[0]:new xi(e)}check(e,t){let n=dn(e)&&cn(e,e=>this.shape.check(e));return!n&&(t==null||t.extend(null,`Array`,``)),n}},pi=(...e)=>new fi(e),mi=L(fi),hi=R(e=>dn(e)),gi=class extends I{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t){let n=e instanceof this.shape&&(this._c==null||this._c(e));return!n&&(t==null||t.extend(null,this.shape.name,e==null?void 0:e.constructor.name)),n}},_i=(e,t=null)=>new gi(e,t);L(gi);var vi=_i(I),yi=L(class extends I{constructor(e){super(),this.len=e.length-1,this.args=di(...e.slice(-1)),this.res=e[this.len]}check(e,t){let n=e.constructor===Function&&e.length<=this.len;return!n&&(t==null||t.extend(null,`function`,typeof e)),n}}),bi=R(e=>typeof e==`function`);L(class extends I{constructor(e){super(),this.shape=e}check(e,t){let n=cn(this.shape,n=>n.check(e,t));return!n&&(t==null||t.extend(null,`Intersectinon`,typeof e)),n}},e=>e.shape.length>0);var xi=class extends I{constructor(e){super(),this.shape=e}check(e,t){let n=ln(this.shape,n=>n.check(e,t));return t==null||t.extend(null,`Union`,typeof e),n}};n.n(xi,`_dilutes`,!0);var Si=(...e)=>e.findIndex(e=>Ci.check(e))>=0?Si(...e.map(e=>Bi(e)).map(e=>Ci.check(e)?e.shape:[e]).flat(1)):e.length===1?e[0]:new xi(e),Ci=L(xi),wi=()=>!0,Ti=R(wi),Ei=L(qr,e=>e.shape===wi),Di=R(e=>typeof e==`bigint`),Oi=R(e=>e===Di),ki=R(e=>typeof e==`symbol`);R(e=>e===ki);var Ai=R(e=>typeof e==`number`),ji=R(e=>e===Ai),Mi=R(e=>typeof e==`string`),Ni=R(e=>e===Mi),Pi=R(e=>typeof e==`boolean`),Fi=R(e=>e===Pi),Ii=Yr(void 0);L(Jr,e=>e.shape.length===1&&e.shape[0]===void 0),Yr(void 0);var Li=Yr(null),Ri=L(Jr,e=>e.shape.length===1&&e.shape[0]===null);L(Uint8Array),L(Kr,e=>e.shape===Uint8Array);var zi=Si(Ai,Mi,Li,Ii,Di,Pi,ki);(()=>{let e=pi(Ti),t=ci(Mi,Ti),n=Si(Ai,Mi,Li,Pi,e,t);return e.shape=n,t.shape.values=n,n})();var Bi=e=>{if(vi.check(e))return e;if(oi.check(e)){let t={};for(let n in e)t[n]=Bi(e[n]);return ii(t)}else if(hi.check(e))return Si(...e.map(Bi));else if(zi.check(e))return Yr(e);else if(bi.check(e))return L(e);N()},Vi=Mr?()=>{}:(e,t)=>{let n=new Wr;if(!t.check(e,n))throw er(`Expected value to be of type ${t.constructor.name}.\n${n.toString()}`)},Hi=class{constructor(e){this.patterns=[],this.$state=e}if(e,t){return this.patterns.push({if:Bi(e),h:t}),this}else(e){return this.if(Ti,e)}done(){return(e,t)=>{for(let n=0;n<this.patterns.length;n++){let r=this.patterns[n];if(r.if.check(e))return r.h(e,t)}throw er(`Unhandled pattern`)}}},Ui=(e=>new Hi(e))(Ti).if(ji,(e,t)=>Ir(t,vn,_n)).if(Ni,(e,t)=>Br(t)).if(Fi,(e,t)=>Fr(t)).if(Oi,(e,t)=>BigInt(Ir(t,vn,_n))).if(Ci,(e,t)=>Wi(t,Vr(t,e.shape))).if(ai,(e,t)=>{let n={};for(let r in e.shape){let i=e.shape[r];if(ti.check(i)){if(Fr(t))continue;i=i.shape}n[r]=Ui(i,t)}return n}).if(mi,(e,t)=>{let n=[],r=Lr(t,0,42);for(let i=0;i<r;i++)n.push(Wi(t,e.shape));return n}).if(Xr,(e,t)=>Vr(t,e.shape)).if(Ri,(e,t)=>null).if(yi,(e,t)=>{let n=Wi(t,e.res);return()=>n}).if(Ei,(e,t)=>Wi(t,Vr(t,[Ai,Mi,Li,Ii,Di,Pi,pi(Ai),ci(Si(`a`,`b`,`c`),Ai)]))).if(li,(e,t)=>{let n={},r=Ir(t,0,3);for(let i=0;i<r;i++){let r=Wi(t,e.shape.keys);n[r]=Wi(t,e.shape.values)}return n}).done(),Wi=(e,t)=>Ui(Bi(t),e),Gi=typeof document<`u`?document:{};R(e=>e.nodeType===Xi),typeof DOMParser<`u`&&new DOMParser,R(e=>e.nodeType===qi),R(e=>e.nodeType===Ji);var Ki=e=>tn(e,(e,t)=>`${t}:${e};`).join(``),qi=Gi.ELEMENT_NODE,Ji=Gi.TEXT_NODE;Gi.CDATA_SECTION_NODE,Gi.COMMENT_NODE;var Yi=Gi.DOCUMENT_NODE;Gi.DOCUMENT_TYPE_NODE;var Xi=Gi.DOCUMENT_FRAGMENT_NODE;R(e=>e.nodeType===Yi);var z=Symbol,Zi=z(),Qi=z(),$i=z(),ea=z(),ta=z(),na=z(),ra=z(),ia=z(),aa=z(),oa=e=>{var t;e.length===1&&((t=e[0])==null?void 0:t.constructor)===Function&&(e=e[0]());let n=[],r=[],i=0;for(;i<e.length;i++){let t=e[i];if(t===void 0)break;if(t.constructor===String||t.constructor===Number)n.push(t);else if(t.constructor===Object)break}for(i>0&&r.push(n.join(``));i<e.length;i++){let t=e[i];t instanceof Symbol||r.push(t)}return r};ar();var sa={[Zi]:F(`font-weight`,`bold`),[Qi]:F(`font-weight`,`normal`),[$i]:F(`color`,`blue`),[ta]:F(`color`,`green`),[ea]:F(`color`,`grey`),[na]:F(`color`,`red`),[ra]:F(`color`,`purple`),[ia]:F(`color`,`orange`),[aa]:F(`color`,`black`)},ca=Nr?e=>{var t;e.length===1&&((t=e[0])==null?void 0:t.constructor)===Function&&(e=e[0]());let n=[],r=[],i=E(),a=[],o=0;for(;o<e.length;o++){let t=e[o],a=sa[t];if(a!==void 0)i.set(a.left,a.right);else{if(t===void 0)break;if(t.constructor===String||t.constructor===Number){let e=Ki(i);o>0||e.length>0?(n.push(`%c`+t),r.push(e)):n.push(t)}else break}}for(o>0&&(a=r,a.unshift(n.join(``)));o<e.length;o++){let t=e[o];t instanceof Symbol||a.push(t)}return a}:oa,la=(...e)=>{console.log(...ca(e)),da.forEach(t=>t.print(e))},ua=(...e)=>{console.warn(...ca(e)),e.unshift(ia),da.forEach(t=>t.print(e))},da=rn(),fa=e=>({[Symbol.iterator](){return this},next:e}),pa=(e,t)=>fa(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),ma=(e,t)=>fa(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}}),ha=class{constructor(e,t){this.clock=e,this.len=t}},ga=class{constructor(){this.clients=new Map}},_a=(e,t,n)=>t.clients.forEach((t,r)=>{let i=e.doc.store.clients.get(r);if(i!=null){let r=i[i.length-1],a=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<a;o=t[++r])$a(e,i,o.clock,o.len,n)}}),va=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=D((n+r)/2),a=e[i],o=a.clock;if(o<=t){if(t<o+a.len)return i;n=i+1}else r=i-1}return null},ya=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&va(n,t.clock)!==null},ba=e=>{e.clients.forEach(e=>{e.sort((e,t)=>e.clock-t.clock);let t,n;for(t=1,n=1;t<e.length;t++){let r=e[n-1],i=e[t];r.clock+r.len>=i.clock?e[n-1]=new ha(r.clock,hn(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},xa=e=>{let t=new ga;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,i)=>{if(!t.clients.has(i)){let a=r.slice();for(let t=n+1;t<e.length;t++)on(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return ba(t),t},Sa=(e,t,n,r)=>{en(e.clients,t,()=>[]).push(new ha(n,r))},Ca=()=>new ga,wa=(e,t)=>{A(e.restEncoder,t.clients.size),sn(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),A(e.restEncoder,t);let r=n.length;A(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},Ta=nr,Ea=class e extends fn{constructor({guid:e=ir(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:a=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=Ta(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Ka,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=a,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=or(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>or(e=>{let t=n=>{(n===void 0||n===!0)&&(this.off(`sync`,t),e())};this.on(`sync`,t)});this.on(`sync`,e=>{e===!1&&this.isSynced&&(this.whenSynced=s()),this.isSynced=e===void 0||e===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=s()}load(){let e=this._item;e!==null&&!this.shouldLoad&&W(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(sn(this.subdocs).map(e=>e.guid))}transact(e,t=null){return W(this,e,t)}get(e,t=K){let n=en(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==K&&r!==t)if(r===K){let r=new t;r._map=n._map,n._map.forEach(e=>{for(;e!==null;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;e!==null;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}else throw Error(`Type with the name ${e} has already been defined with a different constructor`);return n}getArray(e=``){return this.get(e,Uo)}getText(e=``){return this.get(e,ss)}getMap(e=``){return this.get(e,q)}getXmlElement(e=``){return this.get(e,us)}getXmlFragment(e=``){return this.get(e,ls)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,sn(this.subdocs).forEach(e=>e.destroy());let t=this._item;if(t!==null){this._item=null;let r=t.content;r.doc=new e(n.t(n.t({guid:this.guid},r.opts),{},{shouldLoad:!1})),r.doc._item=t,W(t.parent.doc,e=>{let n=r.doc;t.deleted||e.subdocsAdded.add(n),e.subdocsRemoved.add(this)},null,!0)}this.emit(`destroyed`,[!0]),this.emit(`destroy`,[this]),super.destroy()}},Da=class{constructor(){this.restEncoder=Mn()}toUint8Array(){return O(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){A(this.restEncoder,e)}writeDsLen(e){A(this.restEncoder,e)}},Oa=class extends Da{writeLeftID(e){A(this.restEncoder,e.client),A(this.restEncoder,e.clock)}writeRightID(e){A(this.restEncoder,e.client),A(this.restEncoder,e.clock)}writeClient(e){A(this.restEncoder,e)}writeInfo(e){Fn(this.restEncoder,e)}writeString(e){zn(this.restEncoder,e)}writeParentInfo(e){A(this.restEncoder,+!!e)}writeTypeRef(e){A(this.restEncoder,e)}writeLen(e){A(this.restEncoder,e)}writeAny(e){qn(this.restEncoder,e)}writeBuf(e){j(this.restEncoder,e)}writeJSON(e){zn(this.restEncoder,JSON.stringify(e))}writeKey(e){zn(this.restEncoder,e)}},ka=class{constructor(){this.restEncoder=Mn(),this.dsCurrVal=0}toUint8Array(){return O(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,A(this.restEncoder,t)}writeDsLen(e){e===0&&N(),A(this.restEncoder,e-1),this.dsCurrVal+=e}},Aa=class extends ka{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Qn,this.clientEncoder=new Xn,this.leftClockEncoder=new Qn,this.rightClockEncoder=new Qn,this.infoEncoder=new Jn(Fn),this.stringEncoder=new $n,this.parentInfoEncoder=new Jn(Fn),this.typeRefEncoder=new Xn,this.lenEncoder=new Xn}toUint8Array(){let e=Mn();return A(e,0),j(e,this.keyClockEncoder.toUint8Array()),j(e,this.clientEncoder.toUint8Array()),j(e,this.leftClockEncoder.toUint8Array()),j(e,this.rightClockEncoder.toUint8Array()),j(e,O(this.infoEncoder)),j(e,this.stringEncoder.toUint8Array()),j(e,O(this.parentInfoEncoder)),j(e,this.typeRefEncoder.toUint8Array()),j(e,this.lenEncoder.toUint8Array()),Bn(e,O(this.restEncoder)),O(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(+!!e)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){qn(this.restEncoder,e)}writeBuf(e){j(this.restEncoder,e)}writeJSON(e){qn(this.restEncoder,e)}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}},ja=(e,t,n,r)=>{r=hn(r,t[0].id.clock);let i=H(t,r);A(e.restEncoder,t.length-i),e.writeClient(n),A(e.restEncoder,r);let a=t[i];a.write(e,r-a.id.clock);for(let n=i+1;n<t.length;n++)t[n].write(e,0)},Ma=(e,t,n)=>{let r=new Map;n.forEach((e,n)=>{V(t,n)>e&&r.set(n,e)}),qa(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),A(e.restEncoder,r.size),sn(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{ja(e,t.clients.get(n),n,r)})},Na=(e,t)=>Ma(e,t.doc.store,t.beforeState),Pa=class{constructor(){this.l=[]}},Fa=()=>new Pa,Ia=(e,t)=>e.l.push(t),La=(e,t)=>{let n=e.l,r=n.length;e.l=n.filter(e=>t!==e),r===e.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},Ra=(e,t,n)=>Cr(e.l,[t,n]),za=class{constructor(e,t){this.client=e,this.clock=t}},Ba=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,B=(e,t)=>new za(e,t),Va=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw N()},Ha=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1},Ua=class{constructor(e,t){this.ds=e,this.sv=t}};((e,t)=>new Ua(e,t))(Ca(),new Map);var Wa=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!ya(t.ds,e.id),Ga=(e,t)=>{let n=en(e.meta,Ga,rn),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<V(r,n)&&U(e,B(n,t))}),_a(e,t.ds,e=>{}),n.add(t))},Ka=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}},qa=e=>{let t=new Map;return e.clients.forEach((e,n)=>{let r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},V=(e,t)=>{let n=e.clients.get(t);if(n===void 0)return 0;let r=n[n.length-1];return r.id.clock+r.length},Ja=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{let e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw N()}n.push(t)},H=(e,t)=>{let n=0,r=e.length-1,i=e[r],a=i.id.clock;if(a===t)return r;let o=D(t/(a+i.length-1)*r);for(;n<=r;){if(i=e[o],a=i.id.clock,a<=t){if(t<a+i.length)return o;n=o+1}else r=o-1;o=D((n+r)/2)}throw N()},Ya=(e,t)=>{let n=e.clients.get(t.client);return n[H(n,t.clock)]},Xa=(e,t,n)=>{let r=H(t,n),i=t[r];return i.id.clock<n&&i instanceof Y?(t.splice(r+1,0,js(e,i,n-i.id.clock)),r+1):r},U=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[Xa(e,n,t.clock)]},Za=(e,t,n)=>{let r=t.clients.get(n.client),i=H(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==ms&&r.splice(i+1,0,js(e,a,n.clock-a.id.clock+1)),a},Qa=(e,t,n)=>{let r=e.clients.get(t.id.client);r[H(r,t.id.clock)]=n},$a=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=Xa(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&Xa(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)},eo=class{constructor(e,t,n){this.doc=e,this.deleteSet=new ga,this.beforeState=qa(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}},to=(e,t)=>t.deleteSet.clients.size===0&&!nn(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(ba(t.deleteSet),Na(e,t),wa(e,t.deleteSet),!0),no=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&en(e.changed,t,rn).add(n)},ro=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0;n=r,r=e[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof Y&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}let a=t-i;return a&&e.splice(t+1-a,a),a},io=(e,t,n)=>{for(let[r,i]of e.clients.entries()){let e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){let a=i[r],o=a.clock+a.len;for(let r=H(e,a.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){let i=e[r];if(a.clock+a.len<=i.id.clock)break;i instanceof Y&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},ao=(e,t)=>{e.clients.forEach((e,n)=>{let r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){let n=e[t],i=mn(r.length-1,1+H(r,n.clock+n.len-1));for(let e=i,t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+ro(r,e)}})},oo=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,i=r.store,a=n.deleteSet,o=n._mergeStructs;try{ba(a),n.afterState=qa(n.doc.store),r.emit(`beforeObserverCalls`,[n,r]);let e=[];n.changed.forEach((t,r)=>e.push(()=>{(r._item===null||!r._item.deleted)&&r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((t,r)=>{r._dEH.l.length>0&&(r._item===null||!r._item.deleted)&&(t=t.filter(e=>e.target._item===null||!e.target._item.deleted),t.forEach(e=>{e.currentTarget=r,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{Ra(r._dEH,t,n)}))}),e.push(()=>r.emit(`afterTransaction`,[n,r])),e.push(()=>{n._needFormattingCleanup&&is(n)})}),Cr(e,[])}finally{r.gc&&io(a,i,r.gcFilter),ao(a,i),n.afterState.forEach((e,t)=>{let r=n.beforeState.get(t)||0;if(r!==e){let e=i.clients.get(t),n=hn(H(e,r),1);for(let t=e.length-1;t>=n;)t-=1+ro(e,t)}});for(let e=o.length-1;e>=0;e--){let{client:t,clock:n}=o[e].id,r=i.clients.get(t),a=H(r,n);a+1<r.length&&ro(r,a+1)>1||a>0&&ro(r,a)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(la(ia,Zi,`[yjs] `,Qi,na,`Changed the client-id because another client seems to be using it.`),r.clientID=Ta()),r.emit(`afterTransactionCleanup`,[n,r]),r._observers.has(`update`)){let e=new Oa;to(e,n)&&r.emit(`update`,[e.toUint8Array(),n.origin,r,n])}if(r._observers.has(`updateV2`)){let e=new Aa;to(e,n)&&r.emit(`updateV2`,[e.toUint8Array(),n.origin,r,n])}let{subdocsAdded:s,subdocsLoaded:c,subdocsRemoved:l}=n;(s.size>0||l.size>0||c.size>0)&&(s.forEach(e=>{e.clientID=r.clientID,e.collectionid==null&&(e.collectionid=r.collectionid),r.subdocs.add(e)}),l.forEach(e=>r.subdocs.delete(e)),r.emit(`subdocs`,[{loaded:c,added:s,removed:l},r,n]),l.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit(`afterAllTransactions`,[r,e])):oo(e,t+1)}}},W=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new eo(e,n,r),i.push(e._transaction),i.length===1&&e.emit(`beforeAllTransactions`,[e]),e.emit(`beforeTransaction`,[e._transaction,e]));try{o=t(e._transaction)}finally{if(a){let t=e._transaction===i[0];e._transaction=null,t&&oo(i,0)}}return o},so=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}},co=(e,t,n)=>{_a(e,n.deletions,n=>{n instanceof Y&&t.scope.some(t=>t===e.doc||Ha(t,n))&&As(n,!1)})},lo=(e,t,n)=>{let r=null,i=e.doc,a=e.scope;W(i,n=>{for(;t.length>0&&e.currStackItem===null;){let r=i.store,o=t.pop(),s=new Set,c=[],l=!1;_a(n,o.insertions,e=>{if(e instanceof Y){if(e.redone!==null){let{item:t,diff:i}=ks(r,e.id);i>0&&(t=U(n,B(t.id.client,t.id.clock+i))),e=t}!e.deleted&&a.some(t=>t===n.doc||Ha(t,e))&&c.push(e)}}),_a(n,o.deletions,e=>{e instanceof Y&&a.some(t=>t===n.doc||Ha(t,e))&&!ya(o.insertions,e.id)&&s.add(e)}),s.forEach(t=>{l=Ns(n,t,s,o.insertions,e.ignoreRemoteMapChanges,e)!==null||l});for(let t=c.length-1;t>=0;t--){let r=c[t];e.deleteFilter(r)&&(r.delete(n),l=!0)}e.currStackItem=l?o:null}n.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),r=n},e);let o=e.currStackItem;if(o!=null){let t=r.changedParentTypes;e.emit(`stack-item-popped`,[{stackItem:o,type:n,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return o},uo=class extends fn{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:a=!1,doc:o=dn(e)?e[0].doc:e instanceof Ea?e:e.doc}={}){super(),this.scope=[],this.doc=o,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=n,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=a,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!this.captureTransaction(e)||!this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)||!this.trackedOrigins.has(e.origin)&&(!e.origin||!this.trackedOrigins.has(e.origin.constructor)))return;let t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);let i=new ga;e.afterState.forEach((t,n)=>{let r=e.beforeState.get(n)||0,a=t-r;a>0&&Sa(i,n,r,a)});let a=ar(),o=!1;if(this.lastChange>0&&a-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){let t=r[r.length-1];t.deletions=xa([t.deletions,e.deleteSet]),t.insertions=xa([t.insertions,i])}else r.push(new so(e.deleteSet,i)),o=!0;!t&&!n&&(this.lastChange=a),_a(e,e.deleteSet,t=>{t instanceof Y&&this.scope.some(n=>n===e.doc||Ha(n,t))&&As(t,!0)});let s=[{stackItem:r[r.length-1],origin:e.origin,type:t?`redo`:`undo`,changedParentTypes:e.changedParentTypes},this];o?this.emit(`stack-item-added`,s):this.emit(`stack-item-updated`,s)},this.doc.on(`afterTransaction`,this.afterTransactionHandler),this.doc.on(`destroy`,()=>{this.destroy()})}addToScope(e){let t=new Set(this.scope);e=dn(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof K?e.doc!==this.doc:e!==this.doc)&&ua(`[yjs#509] Not same Y.Doc`),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(n=>{e&&(this.undoStack.forEach(e=>co(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>co(n,this,e)),this.redoStack=[]),this.emit(`stack-cleared`,[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=lo(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=lo(this,this.redoStack,`redo`)}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off(`afterTransaction`,this.afterTransactionHandler),super.destroy()}},fo=`You must not compute changes after the event-handler fired.`,po=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=mo(this.currentTarget,this.target))}deletes(e){return ya(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw er(fo);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(n!==null){let r=t._map.get(n),i,a;if(this.adds(r)){let e=r.left;for(;e!==null&&this.adds(e);)e=e.left;if(this.deletes(r))if(e!==null&&this.deletes(e))i=`delete`,a=an(e.content.getContent());else return;else e!==null&&this.deletes(e)?(i=`update`,a=an(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=an(r.content.getContent());else return;e.set(n,{action:i,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw er(fo);let t=this.target,n=rn(),r=rn(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null,a=()=>{e&&i.push(e)};for(let i=t._start;i!==null;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&((e===null||e.delete===void 0)&&(a(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?((e===null||e.insert===void 0)&&(a(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):((e===null||e.retain===void 0)&&(a(),e={retain:0}),e.retain+=i.length);e!==null&&e.retain===void 0&&a()}this._changes=e}return e}},mo=(e,t)=>{let n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},G=()=>{ua(`Invalid access: Add Yjs type to a document before reading data.`)},ho=80,go=0,_o=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=go++}},vo=e=>{e.timestamp=go++},yo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=go++},bo=(e,t,n)=>{if(e.length>=ho){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return yo(r,t,n),r}else{let r=new _o(t,n);return e.push(r),r}},xo=(e,t)=>{if(e._start===null||t===0||e._searchMarker===null)return null;let n=e._searchMarker.length===0?null:e._searchMarker.reduce((e,n)=>pn(t-e.index)<pn(t-n.index)?e:n),r=e._start,i=0;for(n!==null&&(r=n.p,i=n.index,vo(n));r.right!==null&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;r.left!==null&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&pn(n.index-i)<r.parent.length/ho?(yo(n,r,i),n):bo(e._searchMarker,r,i)},So=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){let i=e[r];if(n>0){let t=i.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(i.index-=t.length);if(t===null||t.marker===!0){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=hn(t,i.index+n))}},Co=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;en(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;Ra(r._eH,n,t)},K=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Fa(),this._dEH=Fa(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw M()}clone(){throw M()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){Ia(this._eH,e)}observeDeep(e){Ia(this._dEH,e)}unobserve(e){La(this._eH,e)}unobserveDeep(e){La(this._dEH,e)}toJSON(){}},wo=(e,t,n)=>{e.doc!=null||G(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t,i=[],a=e._start;for(;a!==null&&r>0;){if(a.countable&&!a.deleted){let e=a.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}a=a.right}return i},To=e=>{e.doc!=null||G();let t=[],n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){let e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},Eo=(e,t)=>{let n=0,r=e._start;for(e.doc!=null||G();r!==null;){if(r.countable&&!r.deleted){let i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},Do=(e,t)=>{let n=[];return Eo(e,(r,i)=>{n.push(t(r,i,e))}),n},Oo=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}let e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},ko=(e,t)=>{e.doc!=null||G();let n=xo(e,t),r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},Ao=(e,t,n,r)=>{let i=n,a=e.doc,o=a.clientID,s=a.store,c=n===null?t._start:n.right,l=[],u=()=>{l.length>0&&(i=new Y(B(o,V(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new xs(l)),i.integrate(e,0),l=[])};r.forEach(n=>{if(n===null)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(u(),n.constructor){case Uint8Array:case ArrayBuffer:i=new Y(B(o,V(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new hs(new Uint8Array(n))),i.integrate(e,0);break;case Ea:i=new Y(B(o,V(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new vs(n)),i.integrate(e,0);break;default:if(n instanceof K)i=new Y(B(o,V(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Os(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},jo=()=>er(`Length exceeded!`),Mo=(e,t,n,r)=>{if(n>t._length)throw jo();if(n===0)return t._searchMarker&&So(t._searchMarker,n,r.length),Ao(e,t,null,r);let i=n,a=xo(t,n),o=t._start;for(a!==null&&(o=a.p,n-=a.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&U(e,B(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&So(t._searchMarker,i,r.length),Ao(e,t,o,r)},No=(e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Ao(e,t,r,n)},Po=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=xo(t,n),s=t._start;for(o!==null&&(s=o.p,n-=o.index);s!==null&&n>0;s=s.right)!s.deleted&&s.countable&&(n<s.length&&U(e,B(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&U(e,B(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw jo();t._searchMarker&&So(t._searchMarker,i,-a+r)},Fo=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},Io=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new xs([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new xs([r]);break;case Uint8Array:s=new hs(r);break;case Ea:s=new vs(r);break;default:if(r instanceof K)s=new Os(r);else throw Error(`Unexpected content type`)}new Y(B(o,V(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},Lo=(e,t)=>{e.doc!=null||G();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Ro=e=>{let t={};return e.doc!=null||G(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},zo=(e,t)=>{e.doc!=null||G();let n=e._map.get(t);return n!==void 0&&!n.deleted},Bo=(e,t)=>{let n={};return e._map.forEach((e,r)=>{let i=e;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&Wa(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Vo=e=>(e.doc!=null||G(),pa(e._map.entries(),e=>!e[1].deleted)),Ho=class extends po{},Uo=class e extends K{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){let n=new e;return n.push(t),n}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof K?e.clone():e)),t}get length(){return this.doc!=null||G(),this._length}_callObserver(e,t){super._callObserver(e,t),Co(this,e,new Ho(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):W(this.doc,n=>{Mo(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):W(this.doc,t=>{No(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):W(this.doc,n=>{Po(n,this,e,t)})}get(e){return ko(this,e)}toArray(){return To(this)}slice(e=0,t=this.length){return wo(this,e,t)}toJSON(){return this.map(e=>e instanceof K?e.toJSON():e)}map(e){return Do(this,e)}forEach(e){Eo(this,e)}[Symbol.iterator](){return Oo(this)}_write(e){e.writeTypeRef(Cs)}},Wo=class extends po{constructor(e,t,n){super(e,t),this.keysChanged=n}},q=class e extends K{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return this.forEach((e,n)=>{t.set(n,e instanceof K?e.clone():e)}),t}_callObserver(e,t){Co(this,e,new Wo(this,e,t))}toJSON(){this.doc!=null||G();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof K?r.toJSON():r}}),e}get size(){return[...Vo(this)].length}keys(){return ma(Vo(this),e=>e[0])}values(){return ma(Vo(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return ma(Vo(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc!=null||G(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc===null?this._prelimContent.delete(e):W(this.doc,t=>{Fo(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):W(this.doc,n=>{Io(n,this,e,t)}),t}get(e){return Lo(this,e)}has(e){return zo(this,e)}clear(){this.doc===null?this._prelimContent.clear():W(this.doc,e=>{this.forEach(function(t,n,r){Fo(e,r,n)})})}_write(e){e.writeTypeRef(ws)}},Go=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&br(e,t),Ko=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&N(),this.right.content.constructor){case J:this.right.deleted||Xo(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}},qo=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case J:t.right.deleted||Xo(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&U(e,B(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);break}t.left=t.right,t.right=t.right.right}return t},Jo=(e,t,n,r)=>{let i=new Map,a=r?xo(t,n):null;return a?qo(e,new Ko(a.p.left,a.p,a.index,i),n-a.index):qo(e,new Ko(null,t._start,0,i),n)},Yo=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===J&&Go(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();let i=e.doc,a=i.clientID;r.forEach((r,o)=>{let s=n.left,c=n.right,l=new Y(B(a,V(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new J(o,r));l.integrate(e,0),n.right=l,n.forward()})},Xo=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},Zo=(e,t)=>{for(;;){var n;if(e.right===null||!(e.right.deleted||e.right.content.constructor===J&&Go((n=t[e.right.content.key])==null?null:n,e.right.content.value)))break;e.forward()}},Qo=(e,t,n,r)=>{let i=e.doc,a=i.clientID,o=new Map;for(let c in r){var s;let l=r[c],u=(s=n.currentAttributes.get(c))==null?null:s;if(!Go(u,l)){o.set(c,u);let{left:r,right:s}=n;n.right=new Y(B(a,V(i.store,a)),r,r&&r.lastId,s,s&&s.id,t,null,new J(c,l)),n.right.integrate(e,0),n.forward()}}return o},$o=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;Zo(n,i);let s=Qo(e,t,n,i),c=r.constructor===String?new Ss(r):r instanceof K?new Os(r):new ys(r),{left:l,right:u,index:d}=n;t._searchMarker&&So(t._searchMarker,n.index,c.getLength()),u=new Y(B(o,V(a.store,o)),l,l&&l.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=d,n.forward(),Yo(e,t,n,s)},es=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;Zo(n,i);let s=Qo(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===J));){if(!n.right.deleted)switch(n.right.content.constructor){case J:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(Go(o,a))s.delete(t);else{if(r===0)break iterationLoop;s.set(t,a)}n.right.delete(e)}else n.currentAttributes.set(t,a);break}default:r<n.right.length&&U(e,B(n.right.id.client,n.right.id.clock+r)),r-=n.right.length;break}n.forward()}if(r>0){let i=``;for(;r>0;r--)i+=`
3
3
  `;n.right=new Y(B(o,V(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Ss(i)),n.right.integrate(e,0),n.forward()}Yo(e,t,n,s)},ts=(e,t,n,r,i)=>{let a=t,o=E();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===J){let e=a.content;o.set(e.key,e)}a=a.right}let s=0,c=!1;for(;t!==a;){if(n===t&&(c=!0),!t.deleted){let n=t.content;switch(n.constructor){case J:{var l;let{key:a,value:d}=n,f=(l=r.get(a))==null?null:l;if(o.get(a)!==n||f===d){var u;t.delete(e),s++,!c&&((u=i.get(a))==null?null:u)===d&&f!==d&&(f===null?i.delete(a):i.set(a,f))}!c&&!t.deleted&&Xo(i,n);break}}}t=t.right}return s},ns=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;let n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===J){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},rs=e=>{let t=0;return W(e.doc,n=>{let r=e._start,i=e._start,a=E(),o=$t(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case J:Xo(o,i.content);break;default:t+=ts(n,r,i,a,o),a=$t(o),r=i;break}i=i.right}}),t},is=e=>{let t=new Set,n=e.doc;for(let[r,i]of e.afterState.entries()){let a=e.beforeState.get(r)||0;i!==a&&$a(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===J&&e.constructor!==ms&&t.add(e.parent)})}W(n,n=>{_a(e,e.deleteSet,e=>{if(e instanceof ms||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===J?t.add(r):ns(n,e)});for(let e of t)rs(e)})},as=(e,t,n)=>{let r=n,i=$t(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Os:case ys:case Ss:n<t.right.length&&U(e,B(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e);break}t.forward()}a&&ts(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&So(o._searchMarker,t.index,-r+n),t},os=class extends po{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{e===null?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(this._changes===null){let e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){let e=this.target.doc,t=[];W(e,e=>{let n=new Map,r=new Map,i=this.target._start,a=null,o={},s=``,c=0,l=0,u=()=>{if(a!==null){let e=null;switch(a){case`delete`:l>0&&(e={delete:l}),l=0;break;case`insert`:(typeof s==`object`||s.length>0)&&(e={insert:s},n.size>0&&(e.attributes={},n.forEach((t,n)=>{t!==null&&(e.attributes[n]=t)}))),s=``;break;case`retain`:c>0&&(e={retain:c},_r(o)||(e.attributes=pr({},o))),c=0;break}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case Os:case ys:this.adds(i)?this.deletes(i)||(u(),a=`insert`,s=i.content.getContent()[0],u()):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=1):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=1);break;case Ss:this.adds(i)?this.deletes(i)||(a!==`insert`&&(u(),a=`insert`),s+=i.content.str):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=i.length):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=i.length);break;case J:{let{key:t,value:s}=i.content;if(this.adds(i)){if(!this.deletes(i)){var d;if(Go((d=n.get(t))==null?null:d,s))s!==null&&i.delete(e);else{var f;a===`retain`&&u(),Go(s,(f=r.get(t))==null?null:f)?delete o[t]:o[t]=s}}}else if(this.deletes(i)){var p;r.set(t,s);let e=(p=n.get(t))==null?null:p;Go(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(Go(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),Xo(n,i.content));break}}i=i.right}for(u();t.length>0;){let e=t[t.length-1];if(e.retain!==void 0&&e.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},ss=class e extends K{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc!=null||G(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){console.error(e)}this._pending=null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);let n=new os(this,e,t);Co(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc!=null||G();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===Ss&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc===null?this._pending.push(()=>this.applyDelta(e)):W(this.doc,n=>{let r=new Ko(null,this._start,0,new Map);for(let i=0;i<e.length;i++){let a=e[i];if(a.insert!==void 0){let o=!t&&typeof a.insert==`string`&&i===e.length-1&&r.right===null&&a.insert.slice(-1)===`
4
4
  `?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&$o(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&as(n,r,a.delete):es(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc!=null||G();let r=[],i=new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(Wa(s,e)||t!==void 0&&Wa(s,t))switch(s.content.constructor){case Ss:{let r=i.get(`ychange`);e!==void 0&&!Wa(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!Wa(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case Os:case ys:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case J:Wa(s,e)&&(c(),Xo(i,s.content));break}s=s.right}c()};return e||t?W(a,n=>{e&&Ga(n,e),t&&Ga(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):W(r,r=>{let i=Jo(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),$o(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):W(r,r=>{let i=Jo(r,this,e,!n);$o(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):W(n,n=>{as(n,Jo(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):W(r,r=>{let i=Jo(r,this,e,!1);i.right!==null&&es(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):W(this.doc,t=>{Fo(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):W(this.doc,n=>{Io(n,this,e,t)})}getAttribute(e){return Lo(this,e)}getAttributes(){return Ro(this)}_write(e){e.writeTypeRef(Ts)}},cs=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc!=null||G()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===us||t.constructor===ls)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}else e=e.parent===this._root?null:e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},ls=class e extends K{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof K?e.clone():e)),t}get length(){return this.doc!=null||G(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new cs(this,e)}querySelector(e){e=e.toUpperCase();let t=new cs(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),sn(new cs(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){Co(this,e,new ds(this,t,e))}toString(){return Do(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),Eo(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):W(this.doc,n=>{Mo(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)W(this.doc,n=>{let r=e&&e instanceof K?e._item:e;Ao(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw er(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):W(this.doc,n=>{Po(n,this,e,t)})}toArray(){return To(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return ko(this,e)}slice(e=0,t=this.length){return wo(this,e,t)}forEach(e){Eo(this,e)}_write(e){e.writeTypeRef(Ds)}},us=class e extends ls{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName);return hr(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof K?e.clone():e)),t}toString(){let e=this.getAttributes(),t=[],n=[];for(let t in e)n.push(t);n.sort();let r=n.length;for(let i=0;i<r;i++){let r=n[i];t.push(r+`="`+e[r]+`"`)}let i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?` `+t.join(` `):``}>${super.toString()}</${i}>`}removeAttribute(e){this.doc===null?this._prelimAttrs.delete(e):W(this.doc,t=>{Fo(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):W(this.doc,n=>{Io(n,this,e,t)})}getAttribute(e){return Lo(this,e)}hasAttribute(e){return zo(this,e)}getAttributes(e){return e?Bo(this,e):Ro(this)}toDOM(e=document,t={},n){let r=e.createElement(this.nodeName),i=this.getAttributes();for(let e in i){let t=i[e];typeof t==`string`&&r.setAttribute(e,t)}return Eo(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Es),e.writeKey(this.nodeName)}},ds=class extends po{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(e=>{e===null?this.childListChanged=!0:this.attributesChanged.add(e)})}},fs=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw M()}mergeWith(e){return!1}write(e,t,n){throw M()}integrate(e,t){throw M()}},ps=0,ms=class extends fs{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Ja(e.doc.store,this)}write(e,t){e.writeInfo(ps),e.writeLen(this.length-t)}getMissing(e,t){return null}},hs=class e{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new e(this.content)}splice(e){throw M()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}},gs=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){let n=new e(this.len-t);return this.len=t,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Sa(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}},_s=(e,t)=>new Ea(n.t(n.t({guid:e},t),{},{shouldLoad:t.shouldLoad||t.autoLoad||!1})),vs=class e{constructor(e){e._item&&console.error(`This document was already integrated as a sub-document. You should create a second instance instead with the same guid.`),this.doc=e;let t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(_s(this.doc.guid,this.opts))}splice(e){throw M()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}},ys=class e{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new e(this.embed)}splice(e){throw M()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}},J=class e{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.key,this.value)}splice(e){throw M()}mergeWith(e){return!1}integrate(e,t){let n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}},bs=Ar(`node_env`)===`development`,xs=class e{constructor(e){this.arr=e,bs&&Sr(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeAny(t)}}getRef(){return 8}},Ss=class e{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split(``)}isCountable(){return!0}copy(){return new e(this.str)}splice(t){let n=new e(this.str.slice(t));this.str=this.str.slice(0,t);let r=this.str.charCodeAt(t-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+`�`,n.str=`�`+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}},Cs=0,ws=1,Ts=2,Es=3,Ds=4,Os=class e{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new e(this.type._copy())}splice(e){throw M()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;t!==null;)t.gc(e,!0),t=t.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}},ks=(e,t)=>{let n=t,r=0,i;do r>0&&(n=B(n.client,n.clock+r)),i=Ya(e,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof Y);return{item:i,diff:r}},As=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},js=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new Y(B(r,i+n),t,B(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&a.markDeleted(),t.keep&&(a.keep=!0),t.redone!==null&&(a.redone=B(t.redone.client,t.redone.clock+n)),t.right=a,a.right!==null&&(a.right.left=a),e._mergeStructs.push(a),a.parentSub!==null&&a.right===null&&a.parent._map.set(a.parentSub,a),t.length=n,a},Ms=(e,t)=>ln(e,e=>ya(e.deletions,t)),Ns=(e,t,n,r,i,a)=>{let o=e.doc,s=o.store,c=o.clientID,l=t.redone;if(l!==null)return U(e,l);let u=t.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||Ns(e,u,n,r,i,a)===null))return null;for(;u.redone!==null;)u=U(e,u.redone)}let p=u===null?t.parent:u.content.type;if(t.parentSub===null){for(d=t.left,f=t;d!==null;){let t=d;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:U(e,t.redone);if(t!==null&&t.parent._item===u){d=t;break}d=d.left}for(;f!==null;){let t=f;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:U(e,t.redone);if(t!==null&&t.parent._item===u){f=t;break}f=f.right}}else if(f=null,t.right&&!i){for(d=t;d!==null&&d.right!==null&&(d.right.redone||ya(r,d.right.id)||Ms(a.undoStack,d.right.id)||Ms(a.redoStack,d.right.id));)for(d=d.right;d.redone;)d=U(e,d.redone);if(d&&d.right!==null)return null}else d=p._map.get(t.parentSub)||null;let m=B(c,V(s,c)),h=new Y(m,d,d&&d.lastId,f,f&&f.id,p,t.parentSub,t.content.copy());return t.redone=m,As(h,!0),h.integrate(e,0),h},Y=class e extends fs{constructor(e,t,n,r,i,a,o,s){super(e,s.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=a,this.parentSub=o,this.redone=null,this.content=s,this.info=this.content.isCountable()?2:0}set marker(e){(this.info&8)>0!==e&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=V(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=V(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===za&&this.id.client!==this.parent.client&&this.parent.clock>=V(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Za(t,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=U(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ms||this.right&&this.right.constructor===ms)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===za){let e=Ya(n,this.parent);e.constructor===ms?this.parent=null:this.parent=e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Za(e,e.doc.store,B(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let t=this.left,n;if(t!==null)n=t.right;else if(this.parentSub!==null)for(n=this.parent._map.get(this.parentSub)||null;n!==null&&n.left!==null;)n=n.left;else n=this.parent._start;let r=new Set,i=new Set;for(;n!==null&&n!==this.right;){if(i.add(n),r.add(n),Ba(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(Ba(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(Ya(e.doc.store,n.origin)))r.has(Ya(e.doc.store,n.origin))||(t=n,r.clear());else break;n=n.right}this.left=t}if(this.left!==null){let e=this.left.right;this.right=e,this.left.right=this}else{let e;if(this.parentSub!==null)for(e=this.parent._map.get(this.parentSub)||null;e!==null&&e.left!==null;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}this.right===null?this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)):this.right.left=this,this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Ja(e.doc.store,this),this.content.integrate(e,this),no(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new ms(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:B(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Ba(e.origin,this.lastId)&&this.right===e&&Ba(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){let t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),Sa(e.deleteSet,this.id.client,this.id.clock,this.length),no(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw N();this.content.gc(e),t?Qa(e,this,new ms(this.id,this.length)):this.content=new gs(this.length)}write(e,t){let n=t>0?B(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,a=this.content.getRef()&31|(n===null?0:128)|(r===null?0:64)|(i===null?0:32);if(e.writeInfo(a),n!==null&&e.writeLeftID(n),r!==null&&e.writeRightID(r),n===null&&r===null){let t=this.parent;if(t._item!==void 0){let n=t._item;if(n===null){let n=Va(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===za?(e.writeParentInfo(!1),e.writeLeftID(t)):N();i!==null&&e.writeString(i)}this.content.write(e,t)}},Ps=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},Fs=`__ $YJS$ __`;Ps[Fs]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),Ps[Fs]=!0;var Is=[`local`,`load`,`no-capture`,`move`,`move-undo`,`move-redo`],Ls=class{constructor(){this.changeCallbacks=[],this.yblocks=null,this.undoManager=null}observe(e,t){this.yblocks=e,this.undoManager=t,this.yblocks.observeDeep((e,t)=>{let n=this.mapTransactionOrigin(t.origin);for(let t of e)this.handleYjsEvent(t,n)})}onBlocksChanged(e){return this.changeCallbacks.push(e),()=>{let t=this.changeCallbacks.indexOf(e);t!==-1&&this.changeCallbacks.splice(t,1)}}mapTransactionOrigin(e){if(this.undoManager&&e===this.undoManager)return this.undoManager.undoing?`undo`:`redo`;if(!this.isLocalOriginTag(e))return`remote`;switch(e){case`local`:return`local`;case`load`:return`load`;case`no-capture`:return`local`;case`move`:return`local`;case`move-undo`:return`undo`;case`move-redo`:return`redo`;default:return e}}isLocalOriginTag(e){return typeof e==`string`&&Is.includes(e)}handleYjsEvent(e,t){if(this.yblocks!==null){if(e.target===this.yblocks){this.handleArrayEvent(e,t);return}e.target instanceof q&&this.handleMapEvent(e.target,t)}}handleArrayEvent(e,t){let n=[],r=[];e.changes.added.forEach(e=>{let t=e.content.getContent();for(let e of t){if(!(e instanceof q))continue;let t=e.get(`id`);typeof t==`string`&&n.push(t)}}),e.changes.deleted.forEach(e=>{let t=this.extractBlockIdFromDeletedItem(e);t!==void 0&&r.push(t)});let i=new Set(n),a=new Set(r),o=n.filter(e=>a.has(e)),s=n.filter(e=>!a.has(e)),c=r.filter(e=>!i.has(e));for(let e of o)this.emitChange({type:`move`,blockId:e,origin:t});s.length===1&&this.emitChange({type:`add`,blockId:s[0],origin:t}),s.length>1&&this.emitChange({type:`batch-add`,blockIds:s,origin:t});for(let e of c)this.emitChange({type:`remove`,blockId:e,origin:t})}extractBlockIdFromDeletedItem(e){var t;let n=e.content.getContent();if(n.length===0)return;let r=n[0];if(!(r instanceof q))return;let i=r._map.get(`id`),a=i instanceof Y&&((t=i.content)==null?void 0:t.getContent()[0]);return typeof a==`string`?a:void 0}handleMapEvent(e,t){if(this.yblocks===null)return;if(this.isTopLevelYblock(e)){let n=e.get(`id`);typeof n==`string`&&this.emitChange({type:`update`,blockId:n,origin:t});return}let n=this.findParentBlock(e);n!==void 0&&this.emitChange({type:`update`,blockId:n.get(`id`),origin:t})}isTopLevelYblock(e){return this.yblocks===null?!1:this.yblocks.toArray().includes(e)}findParentBlock(e){if(this.yblocks!==null)return this.yblocks.toArray().find(t=>{let n=t.get(`data`),r=t.get(`tunes`);return n===e||r===e})}emitChange(e){for(let t of this.changeCallbacks)t(e)}destroy(){this.changeCallbacks=[],this.yblocks=null,this.undoManager=null}},Rs=class{constructor(e){this.ydoc=new Ea,this.yblocks=this.ydoc.getArray(`blocks`),this.serializer=e}fromJSON(e){this.ydoc.transact(()=>{this.yblocks.delete(0,this.yblocks.length);for(let t of e){let e=this.serializer.outputDataToYBlock(t);this.yblocks.push([e])}},`load`)}toJSON(){return this.yblocks.toArray().map(e=>this.serializer.yBlockToOutputData(e))}addBlock(e,t){let n=this.serializer.outputDataToYBlock(e);return this.transact(()=>{let e=Math.max(0,Math.min(t==null?this.yblocks.length:t,this.yblocks.length));this.yblocks.insert(e,[n])},`local`),n}removeBlock(e){let t=this.findBlockIndex(e);t!==-1&&this.transact(()=>{this.yblocks.delete(t,1)},`local`)}moveBlock(e,t,n){let r=this.findBlockIndex(e);if(r===-1||r===t)return;let i=n===`local`?`move`:n;this.transact(()=>{let e=this.yblocks.get(r),n=this.serializer.yBlockToOutputData(e);this.yblocks.delete(r,1);let i=Math.max(0,Math.min(t,this.yblocks.length));this.yblocks.insert(i,[this.serializer.outputDataToYBlock(n)])},i)}getBlockById(e){let t=this.findBlockIndex(e);if(t!==-1)return this.yblocks.get(t)}updateBlockData(e,n,r){let i=this.getBlockById(e);if(i===void 0)return!1;let a=i.get(`data`);return t.ca(a.get(n),r)?!1:(this.transact(()=>{a.set(n,r)},`local`),!0)}updateBlockTune(e,t,n){let r=this.getBlockById(e);r!==void 0&&this.transact(()=>{this.getOrCreateTunesMap(r).set(t,n)},`local`)}updateBlockMetadata(e,t,n){let r=this.getBlockById(e);if(r===void 0)return!1;let i=r.get(`lastEditedAt`),a=r.get(`lastEditedBy`);return i===t&&(n===null||a===n)?!1:(this.transact(()=>{r.set(`lastEditedAt`,t),n!==null&&r.set(`lastEditedBy`,n)},`local`),!0)}findBlockIndex(e){return this.yblocks.toArray().findIndex(t=>t.get(`id`)===e)}transact(e,t){this.ydoc.transact(e,t)}transactWithoutCapture(e){this.ydoc.transact(e,`no-capture`)}getOrCreateTunesMap(e){let t=e.get(`tunes`);if(t!==void 0)return t;let n=new q;return e.set(`tunes`,n),n}destroy(){this.ydoc.destroy()}},zs=new Set([` `,` `,`.`,`?`,`!`,`,`,`;`,`:`]),Bs=e=>zs.has(e),Vs=class{outputDataToYBlock(e){let t=new q;t.set(`id`,e.id),t.set(`type`,e.type);let n=this.normalizeBlockData(e.type,e.data);return t.set(`data`,this.objectToYMap(n)),e.tunes!==void 0&&t.set(`tunes`,this.objectToYMap(e.tunes)),e.parent!==void 0&&t.set(`parentId`,e.parent),e.content!==void 0&&t.set(`contentIds`,Uo.from(e.content)),e.lastEditedAt!==void 0&&t.set(`lastEditedAt`,e.lastEditedAt),e.lastEditedBy!==void 0&&t.set(`lastEditedBy`,e.lastEditedBy),t}yBlockToOutputData(e){let t=e.get(`id`),n=e.get(`type`),r=e.get(`data`);if(typeof t!=`string`)throw Error(`Block id must be a string`);if(typeof n!=`string`)throw Error(`Block type must be a string`);if(!(r instanceof q))throw Error(`Block data must be a Y.Map`);let i={id:t,type:n,data:this.yMapToObject(r)},a=e.get(`tunes`);a instanceof q&&a.size>0&&(i.tunes=this.yMapToObject(a));let o=e.get(`parentId`);typeof o==`string`&&(i.parent=o);let s=e.get(`contentIds`);s instanceof Uo&&s.length>0&&(i.content=s.toArray());let c=e.get(`lastEditedAt`);typeof c==`number`&&(i.lastEditedAt=c);let l=e.get(`lastEditedBy`);return typeof l==`string`&&(i.lastEditedBy=l),i}objectToYMap(e){let t=new q;for(let[n,r]of Object.entries(e))typeof r==`object`&&r&&!Array.isArray(r)?t.set(n,this.objectToYMap(r)):t.set(n,r);return t}yMapToObject(e){let t={};return e.forEach((e,n)=>{e instanceof q?t[n]=this.yMapToObject(e):t[n]=e}),t}normalizeBlockData(e,t){return e===`paragraph`&&Object.keys(t).length===0?{text:``}:t}},Hs=(e,t=!1)=>{let n=document.createTextNode(``);t?e.insertBefore(n,e.firstChild):e.appendChild(n);let r=document.createRange();r.setStart(n,0),r.setEnd(n,0);let i=window.getSelection();i&&(i.removeAllRanges(),i.addRange(r))},Us=(e,t)=>e===null?null:e.nodeType===Node.TEXT_NODE?e:Us(t?e.firstChild:e.lastChild,t),Ws=(e,n,r)=>{e.focus();let i=window.getSelection();if(!i)return;let a=r?t.Qi.getDeepestNode(e,!1):t.Qi.getDeepestNode(e,!0);if(!a)return;let o=document.createRange(),s=r?0:t.Qi.getContentLength(a);try{o.setStart(a,s),o.setEnd(a,s),i.removeAllRanges(),i.addRange(o)}catch(t){Gs(e,r)}},Gs=(e,n=!0)=>{var r,i,a,o;if(t.Qi.isNativeInput(e)){e.focus();let t=n?0:e.value.length;e.setSelectionRange(t,t);return}e.focus();let s=document.createRange(),c=window.getSelection();if(!c)return;let l=e.childNodes,u=n?(r=l[0])==null?null:r:(i=l[l.length-1])==null?null:i,d=Us(u,n);if(u===null){Hs(e),c.removeAllRanges(),c.addRange(s);return}if(d===null||d.nodeType!==Node.TEXT_NODE){Hs(e,n),c.removeAllRanges(),c.addRange(s);return}let f=(a=(o=d.textContent)==null?void 0:o.length)==null?0:a,p=n?0:f;s.setStart(d,p),s.setEnd(d,p),c.removeAllRanges(),c.addRange(s)},Ks=(e,t)=>{let n=e.getBoundingClientRect();if(n.height!==0||n.top!==0)return n;let r=e.startContainer,i=r.nodeType===Node.ELEMENT_NODE?r:r.parentElement;if(!i)return t.getBoundingClientRect();let a=i.getBoundingClientRect();return a.height!==0||a.top!==0?a:t.getBoundingClientRect()},qs=e=>{if(t.Qi.isNativeInput(e)&&e.tagName===`INPUT`)return!0;if(t.Qi.isNativeInput(e)){var n;let t=e,r=(n=t.selectionStart)==null?0:n;return!t.value.substring(0,r).includes(`
@@ -8,7 +8,7 @@ const e=require(`./chunk-BL1yB9zm.cjs`),t=require(`./constants-BZUc1kAY.cjs`),n=
8
8
  `);throw Error(`Hierarchy invariant violated at ${t}:\n${r}`)},Qc=class{constructor(e){this.dependencies=e}bindBlockEvents(e){let{blockEvents:t,listeners:n,onBlockMutated:r,getBlockIndex:i,shouldHandleEvent:a}=this.dependencies;n.on(e.holder,`keydown`,e=>{if(e instanceof KeyboardEvent){if(a&&!a(e))return;t.keydown(e)}}),n.on(e.holder,`keyup`,e=>{if(e instanceof KeyboardEvent){if(a&&!a(e))return;t.keyup(e)}}),n.on(e.holder,`input`,e=>{if(e instanceof InputEvent){if(a&&!a(e))return;t.input(e)}}),e.on(`didMutated`,e=>r(Wc,e,{index:i(e)}))}enableBindings(e){let{blockEvents:t,listeners:n}=this.dependencies;n.on(document,`cut`,e=>{t.handleCommandX(e)});for(let t of e)this.bindBlockEvents(t)}disableBindings(){this.dependencies.listeners.clearAll()}},$c=class{get readOnlyState(){return this.dependencies.moduleInstances.ReadOnly.isEnabled}constructor(e,t){this.dependencies=e,this.bindBlockEvents=t}composeBlock(e){let{tool:t,data:n={},id:r,tunes:i={},parentId:a,contentIds:o,bindEventsImmediately:s=!1,lastEditedAt:c,lastEditedBy:l}=e,u=this.dependencies.tools.get(t);if(u===void 0)throw Error(`Could not compose Block. Tool «${t}» not found.`);let d=new ne({id:r,data:n,tool:u,api:this.dependencies.API,readOnly:this.readOnlyState,tunesData:i,parentId:a,contentIds:o,bindMutationWatchersImmediately:s,lastEditedAt:c,lastEditedBy:l},this.dependencies.eventsDispatcher);return this.readOnlyState||(s?this.bindBlockEvents(d):window.requestIdleCallback(()=>{this.bindBlockEvents(d)},{timeout:2e3})),d}hasTool(e){return this.dependencies.tools.has(e)}getTool(e){return this.dependencies.tools.get(e)}},el=class{constructor(e,t,n){this.repository=e,this.onParentChanged=t,this.getIsSyncingFromYjs=n}getBlockDepth(e){let t=new Set;e.id!==void 0&&t.add(e.id);let n=(e,r)=>{if(e===null||t.has(e))return r;t.add(e);let i=this.repository.getBlockById(e);return i===void 0?r:n(i.parentId,r+1)};return n(e.parentId,0)}wouldFormCycle(e,t){let n=(t,r)=>{if(t===null)return!1;if(t===e||r.has(t))return!0;r.add(t);let i=this.repository.getBlockById(t);return i===void 0?!1:n(i.parentId,r)};return n(t,new Set)}setBlockParent(e,n){if(this.repository.getBlockIndex(e)===-1)return;if(n!==null&&this.wouldFormCycle(e.id,n))throw Error(`BlockHierarchy.setBlockParent: refusing to form cycle — assigning ${e.id} to parent ${n} would create a parent/child cycle.`);let r=n===null||this.repository.getBlockById(n)!==void 0;if(!r){var i;let r=typeof process<`u`?`production`:void 0,a=((i=this.getIsSyncingFromYjs)==null?void 0:i.call(this))===!0,o=`BlockHierarchy.setBlockParent: dangling parent id "${n}" for block "${e.id}" — parent block is not in the repository.`;if(!a&&(r===`test`||r===`development`))throw Error(o);t.Da(o,`error`)}let a=r?n:null,o=e.parentId,s=o===null?void 0:this.repository.getBlockById(o);s!==void 0&&(s.contentIds=s.contentIds.filter(t=>t!==e.id));let c=s!==void 0&&a!==o?s.holder.querySelector(`[data-blok-toggle-children]`):null;if(c&&e.holder.parentElement===c){let n=this.repository.blocks,r=n.indexOf(e),i=n.slice(0,r).reverse().find(e=>e.holder.closest(`[data-blok-toggle-children]`)===null);i?t.ta(e.holder,i.holder):s!==void 0&&t.ta(e.holder,s.holder)}let l=a===null?void 0:this.repository.getBlockById(a);if(l!==void 0&&!l.contentIds.includes(e.id)&&l.contentIds.push(e.id),e.parentId=a,a!==null&&l!==void 0){let t=l.contentIds.filter(t=>t!==e.id).map(e=>this.repository.getBlockById(e)).filter(e=>e!==void 0),n=t.length>0&&t.every(e=>e.holder.classList.contains(`hidden`)),r=l.holder.querySelector(`[data-blok-toggle-open="false"]`)!==null;(n||r)&&e.holder.classList.add(`hidden`)}if(a!==null&&l!==void 0){let n=l.holder.querySelector(`[data-blok-toggle-children], [data-blok-nested-blocks]`),r=e.holder.closest(`[${t.Ma.nestedBlocks}]`),i=e=>{var t;return(e==null||(t=e.parentElement)==null?void 0:t.matches(`[data-blok-column]`))===!0},a=e=>(e==null?void 0:e.matches(`[data-blok-columns]`))===!0,o=a(r)&&i(n),s=r!==null&&r!==n&&!(i(r)&&i(n))&&!a(n)&&!o;if(n&&!s){var u,d;let r=this.repository.blocks,i=r.indexOf(e),a=(u=(d=r.slice(i+1).find(e=>e.holder.parentElement===n))==null?void 0:d.holder)==null?null:u;a===null?t.ra(n,e.holder):t.na(e.holder,a)}}if(a===null&&e.holder.closest(`[data-blok-column]`)!==null){let n=this.repository.blocks,r=n.indexOf(e),i=e=>e.holder.closest(`[${t.Ma.nestedBlocks}]`)===null,a=n.slice(0,r).reverse().find(i),o=n.slice(r+1).find(i);a===void 0?o!==void 0&&t.na(e.holder,o.holder):t.ta(e.holder,a.holder)}this.updateBlockIndentation(e),a!==null&&this.onParentChanged!==void 0&&this.onParentChanged(a)}hasColumnAncestor(e){let t=(e,n)=>{if(e===null||n.has(e))return!1;n.add(e);let r=this.repository.getBlockById(e);return r===void 0?!1:r.name===`column`||r.name===`column_list`?!0:t(r.parentId,n)};return t(e.parentId,new Set)}updateBlockIndentation(e){let{holder:t}=e;if(t.closest(`[data-blok-table-cell-blocks]`)){t.style.marginLeft=``,t.setAttribute(`data-blok-depth`,`0`);return}if(t.closest(`[data-blok-toggle-children]`)){t.style.marginLeft=``,t.setAttribute(`data-blok-depth`,String(this.getBlockDepth(e)));return}if(e.name===`column_list`||t.closest(`[data-blok-columns]`)||this.hasColumnAncestor(e)){t.style.marginLeft=``,t.setAttribute(`data-blok-depth`,`0`);return}let n=this.getBlockDepth(e),r=n*24;t.style.marginLeft=r>0?`${r}px`:``,t.setAttribute(`data-blok-depth`,n.toString())}},tl=class{constructor(e){this.ctx=e}get dependencies(){return this.ctx.dependencies}get repository(){return this.ctx.repository}get factory(){return this.ctx.factory}get hierarchy(){return this.ctx.hierarchy}get yjsSync(){return this.ctx.yjsSync}get blockDidMutated(){return this.ctx.blockDidMutated}insert(e={},r){var i;let{id:a=void 0,tool:o,data:s,index:c,needToFocus:l=!0,replace:u=!1,tunes:d,skipYjsSync:f=!1,appendToWorkingArea:p=!1,forceTopLevel:m=!1}=e,h=c==null?this.ctx.rawCurrentBlockIndex+ +!u:c;if(u){var g;(g=this.repository.getBlockByIndex(h))==null||g.unwatchBlockMutations()}let _=(()=>{var e;let n=o==null?this.dependencies.config.defaultBlock:o;if(n===void 0)throw Error(`Could not insert Block. Tool name is not specified.`);let r=u||(e=this.repository.getBlockByIndex(h-1))==null?this.repository.getBlockByIndex(h):e;if(r!==void 0&&t.Yi(r)&&t.Xi(n)){var i;return(i=this.dependencies.config.defaultBlock)==null?`paragraph`:i}return n})(),v=this.factory.composeBlock(n.t(n.t(n.t({tool:_,bindEventsImmediately:!0},a!==void 0&&{id:a}),s!==void 0&&{data:s}),d!==void 0&&{tunes:d})),y=u?this.repository.getBlockByIndex(h):void 0;if(u&&y===void 0)throw Error(`Could not replace Block at index ${h}. Block not found.`);let b=(i=y==null?void 0:y.parentId)==null?null:i,x=y==null?void 0:y.id;if(u&&y!==void 0&&this.blockDidMutated(Gc,y,{index:h}),r.insert(h,v,u,p,m),u&&b!==null&&x!==void 0&&this.ctx.transferParentLinkToNewBlock(x,v,b),!u&&!m&&v.parentId===null){let e=this.repository.getBlockByIndex(h-1),t=(e==null?void 0:e.parentId)!==null&&(e==null?void 0:e.parentId)!==void 0?this.repository.getBlockById(e.parentId):void 0;t!==void 0&&t.name===`column`&&this.hierarchy.setBlockParent(v,t.id)}let ee=this.ctx.rawCurrentBlockIndex;if(l?this.ctx.rawCurrentBlockIndex=h:h<=this.ctx.rawCurrentBlockIndex&&this.ctx.rawCurrentBlockIndex++,this.blockDidMutated(Uc,v,{index:h}),!f&&(!this.yjsSync.isSyncingFromYjs||this.dependencies.YjsManager.getBlockById(v.id)===void 0)){var S;this.dependencies.YjsManager.addBlock({id:v.id,type:v.name,data:v.preservedData,parent:(S=v.parentId)==null?void 0:S},h)}if(this.ctx.rawCurrentBlockIndex!==ee&&!this.ctx.suppressStopCapturing){var C;(C=this.dependencies.YjsManager)==null||C.stopCapturing()}return this.ctx.assertHierarchyInvariantInDev(`insert`),v}insertDefaultBlockAtIndex(e,t=!1,n=!1,r,i=!1){let a=this.dependencies.config.defaultBlock;if(a===void 0)throw Error(`Could not insert default Block. Default block tool is not defined in the configuration.`);return this.ctx.insert({tool:a,index:e,needToFocus:t,skipYjsSync:n,forceTopLevel:i},r)}insertAtEnd(e){return this.ctx.currentBlockIndexValue=this.repository.length-1,this.ctx.insert({appendToWorkingArea:!0},e)}split(e){let n=this.ctx.currentBlock;if(n===void 0)throw Error(`Cannot split: no current block`);let r=t.aa(),i=this.ctx.rawCurrentBlockIndex+1;return this.yjsSync.withAtomicOperation(()=>{var a,o;let s=this.dependencies.Caret.extractFragmentFromCaretPosition(),c=document.createElement(`div`);c.appendChild(s);let l=t.Qi.isEmpty(c)?``:c.innerHTML,u=(a=(o=n.holder.querySelector(`[contenteditable="true"]`))==null?void 0:o.innerHTML)==null?``:a;this.dependencies.YjsManager.transact(()=>{var e;this.dependencies.YjsManager.updateBlockData(n.id,`text`,u),this.dependencies.YjsManager.addBlock({id:r,type:n.name,data:{text:l},parent:(e=n.parentId)==null?void 0:e},i)});let d=this.ctx.insert({id:r,tool:n.name,data:{text:l},needToFocus:!1,skipYjsSync:!0},e);return this.ctx.rawCurrentBlockIndex=i,n.parentId!==null&&this.hierarchy.setBlockParent(d,n.parentId),d})}splitBlockWithData(e,n,r,i,a,o){let s=this.repository.getBlockById(e);if(s===void 0)throw Error(`Block with id "${e}" not found`);let c=t.aa();return this.yjsSync.withAtomicOperation(()=>{this.dependencies.YjsManager.transact(()=>{var t;for(let[t,r]of Object.entries(n))this.dependencies.YjsManager.updateBlockData(e,t,r);this.dependencies.YjsManager.addBlock({id:c,type:r,data:i,parent:(t=s.parentId)==null?void 0:t},a)});let t=s.holder.querySelector(`[contenteditable="true"]`);t!==null&&typeof n.text==`string`&&(t.innerHTML=n.text);let l=this.ctx.insert({id:c,tool:r,data:i,index:a,needToFocus:!1,skipYjsSync:!0},o);return this.ctx.rawCurrentBlockIndex=a,s.parentId!==null&&this.hierarchy.setBlockParent(l,s.parentId),this.ctx.assertHierarchyInvariantInDev(`splitBlockWithData`),l})}insertInsideParent(e,n,r,i){var a;if(this.repository.getBlockById(e)===void 0)throw Error(`Parent block with id "${e}" not found`);let o=t.aa(),s=(a=this.dependencies.config.defaultBlock)==null?`paragraph`:a,c=i==null?{text:``}:i;return this.yjsSync.withAtomicOperation(()=>{this.dependencies.YjsManager.transact(()=>{this.dependencies.YjsManager.addBlock({id:o,type:s,data:c,parent:e},n)});let t=this.ctx.insert({id:o,tool:s,data:c,index:n,needToFocus:!1,skipYjsSync:!0},r);return this.ctx.rawCurrentBlockIndex=n,this.hierarchy.setBlockParent(t,e),this.ctx.assertHierarchyInvariantInDev(`insertInsideParent`),t},{extendThroughRAF:!0})}async paste(e,t,n=!1,r){var i=this,a,o,s,c,l;let u=i.ctx.currentBlock,d=(a=u==null||(o=u.holder)==null?void 0:o.querySelector(`[data-blok-toggle-children]`))==null?null:a,f=d!==null&&!d.contains((s=u==null?void 0:u.currentInput)==null?null:s)?(c=u==null?void 0:u.id)==null?null:c:(l=u==null?void 0:u.parentId)==null?null:l,p=n?u==null?void 0:u.id:void 0,m=i.yjsSync.withAtomicOperation(()=>i.ctx.insert({tool:e,replace:n,needToFocus:!1,skipYjsSync:!0},r),{extendThroughRAF:!0});i.ctx.rawCurrentBlockIndex=i.repository.getBlockIndex(m),await m.ready,i.yjsSync.withAtomicOperation(()=>{m.call(T.ON_PASTE,t),m.refreshToolRootElement()},{extendThroughRAF:!0}),f!==null&&(n&&p!==void 0?i.ctx.transferParentLinkToNewBlock(p,m,f):i.hierarchy.setBlockParent(m,f));let h=await m.save();if(h!==void 0){var g;i.dependencies.YjsManager.addBlock({id:m.id,type:m.name,data:h.data,parent:(g=m.parentId)==null?void 0:g},i.repository.getBlockIndex(m))}return m}},nl=`block-moved`,rl,il=`blok-announcer`,al=[`absolute`,`w-px`,`h-px`,`p-0`,`-m-px`,`overflow-hidden`,`[clip:rect(0,0,0,0)]`,`whitespace-nowrap`,`border-0`].join(` `),ol=class e{constructor(){this.liveRegion=null,this.clearTimeoutId=null,this.createLiveRegion()}static getInstance(){return e.instance||(e.instance=new e),e.instance}static addReference(){e.referenceCount++}createLiveRegion(){let e=document.getElementById(il);if(e){this.liveRegion=e;return}let t=document.createElement(`div`);t.id=il,t.className=al,t.setAttribute(`role`,`status`),t.setAttribute(`aria-live`,`polite`),t.setAttribute(`aria-atomic`,`true`),t.setAttribute(`data-blok-announcer`,``),document.body.appendChild(t),this.liveRegion=t}announce(e,t={}){let{politeness:n=`polite`,clearAfter:r=1e3}=t;this.liveRegion||this.createLiveRegion(),this.liveRegion&&(this.clearTimeoutId!==null&&clearTimeout(this.clearTimeoutId),this.liveRegion.setAttribute(`aria-live`,n),this.liveRegion.textContent=``,requestAnimationFrame(()=>{this.liveRegion&&(this.liveRegion.textContent=e)}),this.clearTimeoutId=setTimeout(()=>{this.liveRegion&&(this.liveRegion.textContent=``)},r))}destroy(){e.referenceCount--,!(e.referenceCount>0)&&(this.clearTimeoutId!==null&&(clearTimeout(this.clearTimeoutId),this.clearTimeoutId=null),this.liveRegion&&(this.liveRegion.remove(),this.liveRegion=null),e.instance=null)}};rl=ol,rl.instance=null,rl.referenceCount=0;var sl=(e,t)=>{ol.getInstance().announce(e,t)},cl=()=>{ol.addReference(),ol.getInstance()},ll=()=>{ol.getInstance().destroy()},ul=class{constructor(e){this.ctx=e}get dependencies(){return this.ctx.dependencies}get repository(){return this.ctx.repository}get factory(){return this.ctx.factory}get hierarchy(){return this.ctx.hierarchy}get yjsSync(){return this.ctx.yjsSync}get blockDidMutated(){return this.ctx.blockDidMutated}async update(e,t,n,r){var i=this,a;if(!n&&!r)return e;let o=await e.data,s=i.repository.getBlockIndex(e);if(s===-1)return e;let c=i.factory.composeBlock({id:e.id,tool:e.name,data:Object.assign({},o,n==null?{}:n),tunes:r==null?e.preservedTunes:r,parentId:(a=e.parentId)==null?void 0:a,contentIds:e.contentIds.length>0?[...e.contentIds]:void 0,bindEventsImmediately:!0});if(t.replace(s,c),i.blockDidMutated(Wc,c,{index:s}),n!==void 0)for(let[t,r]of Object.entries(n))i.dependencies.YjsManager.updateBlockData(e.id,t,r);if(r!==void 0)for(let[t,n]of Object.entries(r))i.dependencies.YjsManager.updateBlockTune(e.id,t,n);return c}replace(e,n,r,i){let a=this.repository.getBlockIndex(e);if(a===-1)return e;let o=t.aa(),s=e.parentId,c=[...e.contentIds];this.dependencies.YjsManager.transact(()=>{this.dependencies.YjsManager.removeBlock(e.id),this.dependencies.YjsManager.addBlock({id:o,type:n,data:r},a)});let l=this.ctx.insert({id:o,tool:n,data:r,index:a,replace:!0,skipYjsSync:!0},i);s!==null&&this.ctx.transferParentLinkToNewBlock(e.id,l,s);let u=n===`toggle`||n===`callout`||n===`column_list`||n===`column`||n===`header`&&r.isToggleable===!0;if(c.length>0&&!u){let e=this.repository.getBlockIndex(l);c.forEach((t,n)=>{let r=this.repository.getBlockById(t);r!==void 0&&(this.hierarchy.setBlockParent(r,null),i.insert(e+1+n,r,!1,!1))}),l.contentIds=[]}else l.contentIds=[],this.reparentChildren(c,l.id);return this.ctx.assertHierarchyInvariantInDev(`replace`),l}reparentChildren(e,t){for(let n of e){let e=this.repository.getBlockById(n);e!==void 0&&this.hierarchy.setBlockParent(e,t)}}move(e,n,r,i,a=!1){if(isNaN(e)||isNaN(n)){t.Ea(`Warning during 'move' call: incorrect indices provided.`,`warn`);return}if(!this.repository.validateIndex(e)||!this.repository.validateIndex(n)){t.Ea(`Warning during 'move' call: indices cannot be lower than 0 or greater than the amount of blocks.`,`warn`);return}let o=this.repository.getBlockByIndex(n),s=this.repository.getBlockByIndex(e);if(o!==void 0&&s!==void 0&&t.Yi(s)&&t.Xi(o.name)){t.Ea(`Warning during 'move' call: '${o.name}' is restricted in table cells.`,`warn`);return}let c=s===void 0?null:s.parentId;if(o!==void 0&&!this.dependencies.YjsManager.isInMoveGroup){let e=o.parentId===null?void 0:this.repository.getBlockById(o.parentId);if(e!==void 0&&e.name===`column`&&c!==o.parentId)return}this.ctx.suppressStopCapturing=!0;try{i.move(e,n,r,a);let t=o===void 0?-1:this.repository.getBlockIndex(o),s=t>=0?t:e;this.ctx.currentBlockIndexValue=s;let l=o==null?this.ctx.currentBlock:o;if(l===void 0)throw Error(`Could not move Block. Block at index ${e} is not available.`);l.parentId!==c&&!this.dependencies.YjsManager.isInMoveGroup&&this.hierarchy.setBlockParent(l,c),this.blockDidMutated(nl,l,{fromIndex:n,toIndex:s}),this.dependencies.YjsManager.moveBlock(l.id,s),this.ctx.assertHierarchyInvariantInDev(`move`)}finally{this.ctx.suppressStopCapturing=!1}}async mergeBlocks(e,r,i){var a=this;if(a.repository.getBlockIndex(e)===-1||a.repository.getBlockIndex(r)===-1||e.parentId!==r.parentId)return;let o=async t=>{if(a.repository.getBlockIndex(e)===-1||a.repository.getBlockIndex(r)===-1)return;let o=n.t(n.t({},await e.data),t);a.repository.getBlockIndex(e)===-1||a.repository.getBlockIndex(r)===-1||(a.dependencies.YjsManager.transact(()=>{for(let[t,n]of Object.entries(o))a.dependencies.YjsManager.updateBlockData(e.id,t,n);a.dependencies.YjsManager.removeBlock(r.id)}),a.yjsSync.withAtomicOperation(()=>{e.mergeWith(t).then(()=>a.ctx.removeBlock(r,!0,!0,i)),a.ctx.currentBlockIndexValue=a.repository.getBlockIndex(e)}))},s=e.name===r.name&&e.mergeable,c=s?await r.data:void 0;if(s&&t.ba(c)){console.error(`Could not merge Block. Failed to extract original Block data.`);return}if(s&&c!==void 0){let[n]=t.Oi([{data:c,tool:r.name}],e.tool.sanitizeConfig,a.dependencies.config.sanitizer);await o(n.data);return}if(e.mergeable&&t.Hi(r,`export`)&&t.Hi(e,`import`)){var l;let n=await r.exportDataAsString(),i=(l=e.tool.conversionConfig)==null?void 0:l.import;await o(t.zi(t.Ei(n,t.Ca(i)&&t.Sa(e.tool.sanitizeConfig[i])?e.tool.sanitizeConfig[i]:e.tool.sanitizeConfig),e.tool.conversionConfig))}}async convert(e,n,r,i){var a=this,o;let s=await e.save();if(!s||s.data===void 0)throw Error(`Could not convert Block. Failed to extract original Block data.`);let c=a.factory.getTool(n);if(!c)throw Error(`Could not convert Block. Tool «${n}» not found.`);let l=await e.exportDataAsString(),u=(o=c.conversionConfig)==null?void 0:o.import,d=t.Ca(u)&&t.Sa(c.sanitizeConfig[u])?c.sanitizeConfig[u]:c.sanitizeConfig,f=t.zi(t.Ei(l,t.Di(a.dependencies.config.sanitizer,d)),c.conversionConfig,c.settings),p=i?Object.assign(f,i):f;a.dependencies.YjsManager.stopCapturing();let m=a.ctx.suppressStopCapturing;a.ctx.suppressStopCapturing=!0;try{return a.yjsSync.withAtomicOperation(()=>a.ctx.replace(e,c.name,p,r),{extendThroughRAF:!0})}finally{queueMicrotask(()=>{a.ctx.suppressStopCapturing=m,a.dependencies.YjsManager.stopCapturing()})}}moveCurrentBlockUp(e){let t=this.ctx.currentBlockIndexValue;if(t<=0){sl(this.dependencies.I18n.t(`a11y.atTop`),{politeness:`polite`});return}this.move(t-1,t,!1,e),this.refocusCurrentBlock();let n=this.ctx.currentBlockIndexValue+1,r=this.repository.length;sl(this.dependencies.I18n.t(`a11y.movedUp`,{position:n,total:r}),{politeness:`assertive`})}moveCurrentBlockDown(e){let t=this.ctx.currentBlockIndexValue;if(t<0||t>=this.repository.length-1){sl(this.dependencies.I18n.t(`a11y.atBottom`),{politeness:`polite`});return}this.move(t+1,t,!1,e),this.refocusCurrentBlock();let n=this.ctx.currentBlockIndexValue+1,r=this.repository.length;sl(this.dependencies.I18n.t(`a11y.movedDown`,{position:n,total:r}),{politeness:`assertive`})}refocusCurrentBlock(){let e=this.ctx.currentBlock;e!==void 0&&this.dependencies.Caret.setToBlock(e,this.dependencies.Caret.positions.END)}},dl=class{constructor(e){this.ctx=e}get dependencies(){return this.ctx.dependencies}get repository(){return this.ctx.repository}get blockDidMutated(){return this.ctx.blockDidMutated}removeBlock(e,t=!0,n=!1,r){return new Promise(i=>{let a=this.repository.getBlockIndex(e);if(!this.repository.validateIndex(a))throw Error(`Can't find a Block to remove`);let o=e.parentId===null?void 0:this.repository.getBlockById(e.parentId);o!==void 0&&(o.contentIds=o.contentIds.filter(t=>t!==e.id));let s=e.name===`column`||e.name===`column_list`,c=s?this.collectDescendants(e):[];if(s)for(let e of c)e.parentId=null,e.contentIds=[];else this.promoteChildrenToRoot(e,e.contentIds);r.remove(a);for(let e of c){let t=this.repository.getBlockIndex(e);t<0||(r.remove(t),n||this.dependencies.YjsManager.removeBlock(e.id))}this.blockDidMutated(Gc,e,{index:a}),n||this.dependencies.YjsManager.removeBlock(e.id);let l=this.repository.length===0;if(this.ctx.rawCurrentBlockIndex>=a&&this.ctx.currentBlockIndexValue--,l&&t){this.ctx.insert({},r),i();return}if(l){this.ctx.currentBlockIndexValue=-1,i();return}a===0&&this.ctx.currentBlockIndexValue<0&&(this.ctx.currentBlockIndexValue=0),o!==void 0&&o.name===`column`&&o.contentIds.length===0&&this.repository.getBlockIndex(o)>=0&&this.removeBlock(o,t,n,r),this.ctx.assertHierarchyInvariantInDev(`removeBlock`),i()})}collectDescendants(e){let t=[],n=new Set([e.id]),r=[...e.contentIds];for(;r.length>0;){let e=r.pop();if(e===void 0||n.has(e))continue;n.add(e);let i=this.repository.getBlockById(e);i!==void 0&&(t.push(i),r.push(...i.contentIds))}return t}promoteChildrenToRoot(e,n){let r=e.holder.parentElement!==null;for(let a of n){var i;let n=this.repository.getBlockById(a);n!==void 0&&(n.parentId=null,n.holder.classList.remove(`hidden`),r&&((i=n.holder.parentElement)==null?void 0:i.matches(`[data-blok-toggle-children]`))===!0&&t.na(n.holder,e.holder))}}},fl=class{constructor(e,t,n,r,i,a=-1){this.suppressStopCapturing=!1,this.dependencies=e,this.repository=t,this.factory=n,this.hierarchy=r,this.blockDidMutated=i,this.currentBlockIndex=a,this.insertion=new tl(this),this.removal=new dl(this),this.mutation=new ul(this)}setYjsSync(e){this._yjsSync=e}get yjsSync(){return this._yjsSync}get rawCurrentBlockIndex(){return this.currentBlockIndex}set rawCurrentBlockIndex(e){this.currentBlockIndex=e}get currentBlockIndexValue(){return this.currentBlockIndex}set currentBlockIndexValue(e){if(this.currentBlockIndex!==e&&!this.suppressStopCapturing){var t;(t=this.dependencies.YjsManager)==null||t.stopCapturing()}this.currentBlockIndex=e}get currentBlock(){if(this.currentBlockIndex!==-1)return this.repository.getBlockByIndex(this.currentBlockIndex)}get nextBlock(){if(this.currentBlockIndex===-1||this.currentBlockIndex===this.repository.length-1)return null;let e=this.repository.getBlockByIndex(this.currentBlockIndex+1);return e==null?null:e}get previousBlock(){if(this.currentBlockIndex===-1||this.currentBlockIndex===0)return null;let e=this.repository.getBlockByIndex(this.currentBlockIndex-1);return e==null?null:e}get nextVisibleBlock(){var e;return this.currentBlockIndex===-1||(e=this.repository.blocks.slice(this.currentBlockIndex+1).find(e=>!e.holder.classList.contains(`hidden`)))==null?null:e}get previousVisibleBlock(){var e;return this.currentBlockIndex===-1||(e=this.repository.blocks.slice(0,this.currentBlockIndex).reverse().find(e=>!e.holder.classList.contains(`hidden`)))==null?null:e}insert(e={},t){return this.insertion.insert(e,t)}insertDefaultBlockAtIndex(e,t=!1,n=!1,r,i=!1){return this.insertion.insertDefaultBlockAtIndex(e,t,n,r,i)}insertAtEnd(e){return this.insertion.insertAtEnd(e)}insertInsideParent(e,t,n,r){return this.insertion.insertInsideParent(e,t,n,r)}split(e){return this.insertion.split(e)}splitBlockWithData(e,t,n,r,i,a){return this.insertion.splitBlockWithData(e,t,n,r,i,a)}paste(e,t,n=!1,r){return this.insertion.paste(e,t,n,r)}removeBlock(e,t=!0,n=!1,r){return this.removal.removeBlock(e,t,n,r)}update(e,t,n,r){return this.mutation.update(e,t,n,r)}replace(e,t,n,r){return this.mutation.replace(e,t,n,r)}move(e,t,n,r,i=!1){this.mutation.move(e,t,n,r,i)}mergeBlocks(e,t,n){return this.mutation.mergeBlocks(e,t,n)}convert(e,t,n,r){return this.mutation.convert(e,t,n,r)}moveCurrentBlockUp(e){this.mutation.moveCurrentBlockUp(e)}moveCurrentBlockDown(e){this.mutation.moveCurrentBlockDown(e)}transferParentLinkToNewBlock(e,t,n){let r=this.repository.getBlockById(n);if(r===void 0){t.parentId=n;return}let i=r.contentIds.indexOf(e);if(this.hierarchy.setBlockParent(t,n),i<0)return;let a=r.contentIds.filter(n=>n!==e&&n!==t.id);a.splice(i,0,t.id),r.contentIds=a}assertHierarchyInvariantInDev(e){let t=typeof process<`u`?`production`:void 0;if(t!==`test`&&t!==`development`)return;let r=Xc(this.repository.blocks.map(e=>n.t(n.t({id:e.id,type:e.name,data:{}},e.parentId!==null&&e.parentId!==void 0?{parent:e.parentId}:{}),Array.isArray(e.contentIds)&&e.contentIds.length>0?{content:[...e.contentIds]}:{}))).filter(e=>e.kind===`child-not-in-parent-content`||e.kind===`content-parent-mismatch`||e.kind===`content-duplicate`);if(r.length===0)return;let i=r.map(e=>` - ${e.message}`).join(`
9
9
  `);throw Error(`Hierarchy invariant violated at BlockOperations.${e}:\n${i}`)}},pl=class{constructor(){this._blocks=null}initialize(e){this._blocks=e}get blocksStore(){if(this._blocks===null)throw Error(`BlockRepository: blocks store is not initialized. Call initialize() before accessing blocks.`);return this._blocks}get blocks(){return this.blocksStore.array}get firstBlock(){return this.blocksStore[0]}get lastBlock(){return this.blocksStore[this.blocksStore.length-1]}get length(){return this.blocksStore.length}getBlockByIndex(e){let t=e===-1?this.blocksStore.length-1:e;return this.blocksStore[t]}getBlockIndex(e){return this.blocksStore.indexOf(e)}getBlockById(e){return this.blocksStore.array.find(t=>t.id===e)}getBlock(e){if(!e)return;let n=t.Qi.isElement(e)?e:e.parentNode;if(!n)return;let r=n.closest(t.Na(t.Ma.element));if(r)return this.blocks.find(e=>e.holder===r)}getBlockByChildNode(e){if(!(e instanceof Node))return;let n=t.Qi.isElement(e)?e:e.parentNode;if(!n)return;let r=n.closest(t.Na(t.Ma.element));if(r)return this.blocks.find(e=>e.holder===r)}validateIndex(e){return!(e<0||e>=this.blocksStore.length)}isBlokEmpty(){return this.blocks.every(e=>e.isEmpty)}getNextContentfulBlock(e){return this.blocks.slice(e+1).find(e=>!!e.inputs.length)}getPreviousContentfulBlock(e){return this.blocks.slice(0,e).reverse().find(e=>!!e.inputs.length)}resolveToRootBlock(e){if(e.parentId===null)return e;let t=this.getBlockById(e.parentId);return t===void 0?e:this.resolveToRootBlock(t)}getBlockAtNodeIndex(e){return this.blocksStore[e]}},ml={SHIFT:[`SHIFT`],CMD:[`CMD`,`CONTROL`,`COMMAND`,`WINDOWS`,`CTRL`],ALT:[`ALT`,`OPTION`]},hl={0:`Digit0`,1:`Digit1`,2:`Digit2`,3:`Digit3`,4:`Digit4`,5:`Digit5`,6:`Digit6`,7:`Digit7`,8:`Digit8`,9:`Digit9`,A:`KeyA`,B:`KeyB`,C:`KeyC`,D:`KeyD`,E:`KeyE`,F:`KeyF`,G:`KeyG`,H:`KeyH`,I:`KeyI`,J:`KeyJ`,K:`KeyK`,L:`KeyL`,M:`KeyM`,N:`KeyN`,O:`KeyO`,P:`KeyP`,Q:`KeyQ`,R:`KeyR`,S:`KeyS`,T:`KeyT`,U:`KeyU`,V:`KeyV`,W:`KeyW`,X:`KeyX`,Y:`KeyY`,Z:`KeyZ`,BACKSPACE:`Backspace`,ENTER:`Enter`,ESCAPE:`Escape`,LEFT:`ArrowLeft`,UP:`ArrowUp`,RIGHT:`ArrowRight`,DOWN:`ArrowDown`,INSERT:`Insert`,DELETE:`Delete`,".":`Period`,"[":`BracketLeft`,"]":`BracketRight`},gl=e=>Object.keys(ml).find(t=>ml[t].includes(e)),_l=class{constructor(e){this.commands={SHIFT:!1,CMD:!1,ALT:!1},this.keys={},this.name=e.name,this.element=e.on,this.callback=e.callback,this.parseShortcutName(e.name),this.executeShortcut=e=>{this.execute(e)},this.element.addEventListener(`keydown`,this.executeShortcut,!1)}remove(){this.element.removeEventListener(`keydown`,this.executeShortcut)}parseShortcutName(e){let t=e.split(`+`);for(let e of t){let t=e.toUpperCase(),n=gl(t);n===void 0?this.keys[t]=!0:this.commands[n]=!0}}checkModifiers(e){let t={CMD:e.ctrlKey||e.metaKey,SHIFT:e.shiftKey,ALT:e.altKey};return Object.keys(this.commands).every(e=>this.commands[e]===t[e])}checkKeys(e){return Object.keys(this.keys).every(t=>{let n=hl[t];return e.code===n})}execute(e){let t=this.checkModifiers(e),n=this.checkKeys(e);t&&n&&this.callback(e)}},vl=e=>e instanceof HTMLElement?e.tagName.toLowerCase()+(e.className?`.${e.className}`:``):e instanceof Document?`document`:String(e),X=new class{constructor(){this.registeredShortcuts=new Map}add(e){if(this.findShortcut(e.on,e.name)){let t=vl(e.on);throw Error(`Shortcut ${e.name} is already registered for ${t}. Please remove it before add a new handler.`)}let t=new _l({name:e.name,on:e.on,callback:e.handler}),n=this.registeredShortcuts.get(e.on)||[];this.registeredShortcuts.set(e.on,[...n,t])}remove(e,t){let n=this.findShortcut(e,t);if(!n)return;n.remove();let r=this.registeredShortcuts.get(e);if(!r)return;let i=r.filter(e=>e!==n);if(i.length===0){this.registeredShortcuts.delete(e);return}this.registeredShortcuts.set(e,i)}findShortcut(e,t){return(this.registeredShortcuts.get(e)||[]).find(({name:e})=>e===t)}},yl=class{constructor(e,t){this.registeredShortcutNames=[],this.wrapper=e,this.handlers=t}register(){setTimeout(()=>{let e=[`CMD+SHIFT+UP`,`CMD+SHIFT+DOWN`];for(let e of this.registeredShortcutNames)X.remove(document,e);this.registeredShortcutNames.length=0;for(let t of e)X.remove(document,t);X.add({name:`CMD+SHIFT+UP`,on:document,handler:e=>{this.shouldHandleShortcut(e)&&(e.preventDefault(),this.handlers.onMoveUp())}}),this.registeredShortcutNames.push(`CMD+SHIFT+UP`),X.add({name:`CMD+SHIFT+DOWN`,on:document,handler:e=>{this.shouldHandleShortcut(e)&&(e.preventDefault(),this.handlers.onMoveDown())}}),this.registeredShortcutNames.push(`CMD+SHIFT+DOWN`)},0)}unregister(){for(let e of this.registeredShortcutNames)X.remove(document,e);this.registeredShortcutNames.length=0}shouldHandleShortcut(e){let t=e.target;return t instanceof HTMLElement&&this.wrapper.contains(t)}},bl=class{get isSyncingFromYjs(){return this.yjsSyncCount>0}constructor(e,t,n,r,i){this.yjsSyncCount=0,this.moveSyncScheduled=!1,this.dependencies=e,this.repository=t,this.factory=n,this.handlers=r,this.blocksStore=i}beginAtomicOperation(){this.yjsSyncCount++;let e=this.dependencies.operations;return e&&(e.suppressStopCapturing=!0),()=>{this.yjsSyncCount--,e&&this.yjsSyncCount===0&&(e.suppressStopCapturing=!1)}}endAtomicOperation(e,t){t?requestAnimationFrame(e):e()}withAtomicOperation(e,t){let n=this.beginAtomicOperation();try{let r=e();return this.endAtomicOperation(n,(t==null?void 0:t.extendThroughRAF)===!0),r}catch(e){throw n(),e}}async withAtomicOperationAsync(e,t){var n=this;let r=n.beginAtomicOperation();try{await e(),n.endAtomicOperation(r,(t==null?void 0:t.extendThroughRAF)===!0)}catch(e){throw r(),e}}subscribe(){return this.dependencies.YjsManager.onBlocksChanged(e=>{(e.origin===`undo`||e.origin===`redo`||e.origin===`remote`)&&this.syncBlockFromYjs(e)})}syncBlockFromYjs(e){if(e.type===`update`){this.handleYjsUpdate(e.blockId);return}if(e.type===`move`){this.handleYjsMove();return}if(e.type===`add`){this.handleYjsAdd(e.blockId);return}if(e.type===`batch-add`){this.handleYjsBatchAdd(e.blockIds);return}e.type===`remove`&&this.handleYjsRemove(e.blockId)}handleYjsUpdate(e){var t=this,n;let r=this.repository.getBlockById(e),i=this.dependencies.YjsManager.getBlockById(e);if(r===void 0||i===void 0)return;let a=this.dependencies.YjsManager.yMapToObject(i.get(`data`)),o=i.get(`tunes`),s=o===void 0?{}:this.dependencies.YjsManager.yMapToObject(o),c=i.get(`lastEditedAt`),l=(n=i.get(`lastEditedBy`))==null?null:n;if(i.has(`parentId`)){let e=i.get(`parentId`),t=e===void 0?null:e;t!==r.parentId&&this.withAtomicOperation(()=>{this.handlers.setBlockParent(r,t)})}let u=r.preservedTunes,d=Object.keys(s),f=Object.keys(u);if(d.length!==f.length||d.some(e=>s[e]!==u[e])){var p;let t=this.handlers.getBlockIndex(r),n=this.factory.composeBlock({id:r.id,tool:r.name,data:a,tunes:s,contentIds:r.contentIds.length>0?[...r.contentIds]:void 0,parentId:(p=r.parentId)==null?void 0:p,bindEventsImmediately:!0,lastEditedAt:c,lastEditedBy:l});this.withAtomicOperation(()=>{this.handlers.replaceBlock(t,n),this.reconcileOrphanedChildren(e)&&n.call(T.RENDERED)},{extendThroughRAF:!0})}else this.withAtomicOperationAsync(async()=>{if(!await r.setData(a)){var n;let i=t.handlers.getBlockIndex(r),o=t.factory.composeBlock({id:r.id,tool:r.name,data:a,tunes:r.preservedTunes,contentIds:r.contentIds.length>0?[...r.contentIds]:void 0,parentId:(n=r.parentId)==null?void 0:n,bindEventsImmediately:!0,lastEditedAt:c,lastEditedBy:l});t.handlers.replaceBlock(i,o),t.reconcileOrphanedChildren(e)&&o.call(T.RENDERED)}},{extendThroughRAF:!0})}handleYjsAdd(e){var t;if(this.repository.getBlockById(e)!==void 0)return;let n=this.dependencies.YjsManager.getBlockById(e);if(n===void 0)return;let r=n.get(`type`),i=this.dependencies.YjsManager.yMapToObject(n.get(`data`)),a=n.get(`parentId`),o=n.get(`lastEditedAt`),s=(t=n.get(`lastEditedBy`))==null?null:t,c=this.dependencies.YjsManager.toJSON().findIndex(t=>t.id===e);c!==-1&&this.withAtomicOperation(()=>{let t=this.factory.composeBlock({id:e,tool:r,data:i,parentId:a==null?void 0:a,bindEventsImmediately:!0,lastEditedAt:o,lastEditedBy:s});this.blocksStore.insert(c,t),this.handlers.onBlockAdded(t,c),a!==void 0&&this.handlers.setBlockParent(t,a),this.reconcileOrphanedChildren(e)&&t.call(T.RENDERED)},{extendThroughRAF:!0})}reconcileOrphanedChildren(e){let t=Array.from(this.repository.blocks).filter(t=>{if(t.parentId===e)return!1;let n=this.dependencies.YjsManager.getBlockById(t.id);return n===void 0?!1:n.get(`parentId`)===e});for(let n of t)this.handlers.setBlockParent(n,e);return t.length>0}handleYjsBatchAdd(e){let t=this.dependencies.YjsManager.toJSON(),n=[];for(let i of e){var r;if(this.repository.getBlockById(i)!==void 0)continue;let e=this.dependencies.YjsManager.getBlockById(i);if(e===void 0)continue;let a=e.get(`type`),o=this.dependencies.YjsManager.yMapToObject(e.get(`data`)),s=e.get(`parentId`),c=e.get(`lastEditedAt`),l=(r=e.get(`lastEditedBy`))==null?null:r,u=t.findIndex(e=>e.id===i);u!==-1&&n.push({blockId:i,toolName:a,data:o,parentId:s==null?void 0:s,lastEditedAt:c,lastEditedBy:l,targetIndex:u})}n.length!==0&&this.withAtomicOperation(()=>{let e=[];for(let t of n){let n=this.factory.composeBlock({id:t.blockId,tool:t.toolName,data:t.data,parentId:t.parentId,bindEventsImmediately:!0,lastEditedAt:t.lastEditedAt,lastEditedBy:t.lastEditedBy});this.blocksStore.addToArray(t.targetIndex,n),e.push({block:n,targetIndex:t.targetIndex,parentId:t.parentId})}for(let{block:t,targetIndex:n,parentId:r}of e)this.blocksStore.activateBlock(t),this.handlers.onBlockAdded(t,n),r!==void 0&&this.handlers.setBlockParent(t,r)},{extendThroughRAF:!0})}handleYjsRemove(e){let n=this.repository.getBlockById(e);if(n===void 0)return;let r=this.handlers.getBlockIndex(n);r!==-1&&this.withAtomicOperation(()=>{if(this.handlers.onBlockRemoved(n,r),n.parentId!==null){let e=this.repository.getBlockById(n.parentId);e!==void 0&&(e.contentIds=e.contentIds.filter(e=>e!==n.id))}let e=n.holder.parentElement!==null;for(let r of n.contentIds){var i;let a=this.repository.getBlockById(r);if(a===void 0)continue;a.parentId=null,a.holder.classList.remove(`hidden`);let o=a.holder.parentElement,s=(o==null?void 0:o.matches(`[data-blok-toggle-children]`))===!0||(o==null?void 0:o.matches(`[data-blok-columns]`))===!0||(o==null||(i=o.parentElement)==null?void 0:i.matches(`[data-blok-column]`))===!0;e&&s&&n.holder.contains(a.holder)&&t.na(a.holder,n.holder)}this.blocksStore.remove(r),this.blocksStore.length===0&&this.handlers.insertDefaultBlock(!0)},{extendThroughRAF:!0})}handleYjsMove(){this.moveSyncScheduled||(this.moveSyncScheduled=!0,queueMicrotask(()=>{this.moveSyncScheduled=!1,this.syncBlockOrderFromYjs()}))}syncBlockOrderFromYjs(){let e=this.dependencies.YjsManager.toJSON(),t=new Map;for(let e of this.repository.blocks)t.set(e.id,e);e.forEach((e,n)=>{let r=e.id;if(r===void 0)return;let i=t.get(r);if(i===void 0)return;let a=this.handlers.getBlockIndex(i);a!==n&&this.blocksStore.move(n,a)})}updateBlocksStore(e){this.blocksStore=e}async syncBlockDataToYjs(e,t){var n=this;if(t!==void 0)for(let[r,i]of Object.entries(t.data))n.dependencies.YjsManager.updateBlockData(e.id,r,i)}isBlockDataChanged(e,t,n){let r=this.dependencies.YjsManager.getBlockById(e);return r===void 0?!0:r.get(`data`).get(t)!==n}},xl=class extends s{constructor(...e){super(...e),this._isPointerDragActive=!1,this._currentBlockIndex=-1,this._blocks=null,this.parentsSyncScheduled=new Set,this.pendingParentSyncPromise=null}get currentBlockIndex(){return this._currentBlockIndex}set currentBlockIndex(e){this.operations&&(this.operations.currentBlockIndexValue=e),this._currentBlockIndex=e}get firstBlock(){return this.repository.firstBlock}get lastBlock(){return this.repository.lastBlock}get currentBlock(){var e;return(e=this.operations)==null?void 0:e.currentBlock}set currentBlock(e){if(e===void 0){this.unsetCurrentBlock();return}this.currentBlockIndex=this.repository.getBlockIndex(e)}get nextBlock(){var e,t;return(e=(t=this.operations)==null?void 0:t.nextBlock)==null?null:e}get nextContentfulBlock(){return this.repository.getNextContentfulBlock(this.currentBlockIndex)}get previousContentfulBlock(){return this.repository.getPreviousContentfulBlock(this.currentBlockIndex)}get previousBlock(){var e,t;return(e=(t=this.operations)==null?void 0:t.previousBlock)==null?null:e}get nextVisibleBlock(){var e,t;return(e=(t=this.operations)==null?void 0:t.nextVisibleBlock)==null?null:e}get previousVisibleBlock(){var e,t;return(e=(t=this.operations)==null?void 0:t.previousVisibleBlock)==null?null:e}get blocks(){return this.repository.blocks}setPlaceholder(e){var t,n;this.config.placeholder=e;let r=(t=this.config.defaultBlock)==null?`paragraph`:t;(n=this.Blok.Tools.blockTools.get(r))==null||n.setDefaultPlaceholder(e);for(let t of this.blocks)t.setPlaceholder(e)}get isBlokEmpty(){return this.repository.isBlokEmpty()}get isSyncingFromYjs(){return this.yjsSync.isSyncingFromYjs}setPointerDragActive(e){this._isPointerDragActive=e}prepare(){let e=new Kc(this.Blok.UI.nodes.redactor,this.eventsDispatcher);this._blocks=new Proxy(e,{set:Kc.set,get:Kc.get}),this.initializeServices(),this.listeners.on(document,`copy`,e=>{this.Blok.BlockEvents.handleCommandC(e)}),this.shortcuts.register(),this.yjsSync.subscribe()}initializeServices(){this.repository=new pl,this.repository.initialize(this.blocksStore),this.eventBinder=new Qc({blockEvents:this.Blok.BlockEvents,listeners:this.readOnlyMutableListeners,eventsDispatcher:this.eventsDispatcher,getBlockIndex:e=>this.repository.getBlockIndex(e),onBlockMutated:this.blockDidMutated.bind(this),shouldHandleEvent:e=>{let t=e.target;if(t instanceof Element){let e=t.closest(`[data-blok-testid="blok-editor"]`);return e===null||e===this.Blok.UI.nodes.wrapper}return!0}}),this.factory=new $c({API:this.Blok.API,eventsDispatcher:this.eventsDispatcher,tools:this.Blok.Tools.blockTools,moduleInstances:this.Blok},this.bindBlockEvents.bind(this)),this.hierarchy=new el(this.repository,e=>{this.yjsSync.isSyncingFromYjs||this.scheduleParentSync(e)},()=>{var e;return!!((e=this.yjsSync)!=null&&e.isSyncingFromYjs)}),this.operations=new fl({config:this.config,YjsManager:this.Blok.YjsManager,Caret:this.Blok.Caret,I18n:this.Blok.I18n,eventsDispatcher:this.eventsDispatcher},this.repository,this.factory,this.hierarchy,this.blockDidMutated.bind(this),this._currentBlockIndex),this.yjsSync=new bl({YjsManager:this.Blok.YjsManager,operations:this.operations},this.repository,this.factory,{addToDom:(e,t)=>{this.blocksStore.insert(t,e)},removeFromDom:e=>{this.blocksStore.remove(e)},moveInDom:(e,t)=>{this.blocksStore.move(e,t)},getBlockIndex:e=>this.repository.getBlockIndex(e),insertDefaultBlock:e=>this.insert({skipYjsSync:e}),updateIndentation:e=>{this.hierarchy.updateBlockIndentation(e)},setBlockParent:(e,t)=>{this.hierarchy.setBlockParent(e,t)},replaceBlock:(e,t)=>{this.blocksStore.replace(e,t)},onBlockRemoved:(e,t)=>{this.blockDidMutated(Gc,e,{index:t})},onBlockAdded:(e,t)=>{this.blockDidMutated(Uc,e,{index:t})}},this.blocksStore),this.operations.setYjsSync(this.yjsSync),this.shortcuts=new yl(this.Blok.UI.nodes.wrapper,{onMoveUp:this.moveCurrentBlockUp.bind(this),onMoveDown:this.moveCurrentBlockDown.bind(this)})}get blocksStore(){if(this._blocks===null)throw Error(`BlockManager: blocks store is not initialized. Call prepare() before accessing blocks.`);return this._blocks}toggleReadOnly(e){e?this.eventBinder.disableBindings():this.eventBinder.enableBindings(this.blocks)}composeBlock(e){return this.factory.composeBlock(e)}insert(e={}){this._currentBlockIndex=this.operations.currentBlockIndexValue;let t=this.operations.insert(e,this.blocksStore);return this._currentBlockIndex=this.operations.currentBlockIndexValue,t}insertMany(e,t=0){let r=new Map;for(let t of e)r.set(t.id,t);this.reconcileChildrenToParents(e,r),this.reconcileParentsToChildren(e,r),this.assertInsertManyHierarchy(e);let i=e.map(e=>{let t=e.preservedTunes;return n.t(n.t(n.t({id:e.id,type:e.name,data:e.preservedData},Object.keys(t).length>0&&{tunes:t}),e.parentId!==null&&{parent:e.parentId}),e.contentIds.length>0&&{content:e.contentIds})});this.Blok.YjsManager.fromJSON(i),this.yjsSync.withAtomicOperation(()=>{this.blocksStore.insertMany(e,t)},{extendThroughRAF:!0}),e.forEach(e=>{e.parentId!==null&&this.updateBlockIndentation(e)})}async update(e,t,n){var r=this;return r.operations.update(e,r.blocksStore,t,n)}replace(e,t,n){return this.operations.replace(e,t,n,this.blocksStore)}async paste(e,t,n=!1){var r=this;return r.operations.paste(e,t,n,r.blocksStore)}insertDefaultBlockAtIndex(e,t=!1,n=!1,r=!1){this._currentBlockIndex=this.operations.currentBlockIndexValue;let i=this.operations.insertDefaultBlockAtIndex(e,t,n,this.blocksStore,r);return this._currentBlockIndex=this.operations.currentBlockIndexValue,i}insertAtEnd(){return this.operations.insertAtEnd(this.blocksStore)}async mergeBlocks(e,t){var n=this;return n.operations.mergeBlocks(e,t,n.blocksStore)}removeBlock(e,t=!0,n=!1){this._currentBlockIndex=this.operations.currentBlockIndexValue;let r=this.operations.removeBlock(e,t,n,this.blocksStore);return this._currentBlockIndex=this.operations.currentBlockIndexValue,r}deleteSelectedBlocksAndInsertReplacement(){let e=this.blocks.map((e,t)=>({block:e,index:t})).filter(({block:e})=>e.selected).sort((e,t)=>t.index-e.index);if(e.length===0)return;let n=e.length===this.blocks.length,r=e[e.length-1].index,i=e.map(({block:e})=>e.id),a=this.config.defaultBlock;if(a===void 0)throw Error(`Could not insert default Block. Default block tool is not defined in the configuration.`);let o=n?t.aa():void 0;this.Blok.YjsManager.transact(()=>{for(let e of i)this.Blok.YjsManager.removeBlock(e);n&&o!==void 0&&this.Blok.YjsManager.addBlock({id:o,type:a,data:{}},r)});for(let{block:t}of e)this.removeBlock(t,!1,!0);if(n&&o!==void 0)return this.insert({id:o,tool:a,index:r,needToFocus:!0,skipYjsSync:!0})}removeAllBlocks(){let e=[...this.blocks].map(e=>e.id);for(this.Blok.YjsManager.transact(()=>{for(let t of e)this.Blok.YjsManager.removeBlock(t)});this.blocksStore.length>0;)this.blocksStore.remove(this.blocksStore.length-1);this.unsetCurrentBlock(),this.insert();let t=this.currentBlock,n=t==null?void 0:t.firstInput;n!==void 0&&n.focus()}split(){this._currentBlockIndex=this.operations.currentBlockIndexValue;let e=this.operations.split(this.blocksStore);return this._currentBlockIndex=this.operations.currentBlockIndexValue,e}transactForTool(e){this.Blok.YjsManager.stopCapturing();let t=this.operations.suppressStopCapturing;this.operations.suppressStopCapturing=!0;try{e()}finally{queueMicrotask(()=>{queueMicrotask(()=>{this.pendingParentSyncPromise===null?(this.Blok.YjsManager.stopCapturing(),this.operations.suppressStopCapturing=t):this.pendingParentSyncPromise.then(()=>{this.Blok.YjsManager.stopCapturing(),this.operations.suppressStopCapturing=t})})})}}insertInsideParent(e,t,n){this._currentBlockIndex=this.operations.currentBlockIndexValue;let r=this.operations.insertInsideParent(e,t,this.blocksStore,n);return this._currentBlockIndex=this.operations.currentBlockIndexValue,r}get suppressStopCapturing(){var e,t;return(e=(t=this.operations)==null?void 0:t.suppressStopCapturing)==null?!1:e}splitBlockWithData(e,t,n,r,i){return this.operations.splitBlockWithData(e,t,n,r,i,this.blocksStore)}getBlockByIndex(e){return this.repository.getBlockByIndex(e)}getBlockIndex(e){return this.repository.getBlockIndex(e)}getBlockById(e){return this.repository.getBlockById(e)}resolveToRootBlock(e){return this.repository.resolveToRootBlock(e)}getBlockDepth(e){return this.hierarchy.getBlockDepth(e)}setBlockParent(e,t){let n=e.parentId;if(this.hierarchy.setBlockParent(e,t),this.yjsSync.isSyncingFromYjs)return;let r=this.Blok.YjsManager.getBlockById(e.id);if(r!==void 0){if(this.Blok.YjsManager.isInMoveGroup){this.Blok.YjsManager.transactWithoutCapture(()=>{t===null?r.delete(`parentId`):r.set(`parentId`,t),this.syncParentContentIdsToYjs(e.id,n,t)}),this.Blok.YjsManager.recordParentChangeForPendingMove(e.id,n,t);return}this.Blok.YjsManager.transact(()=>{t===null?r.delete(`parentId`):r.set(`parentId`,t),this.syncParentContentIdsToYjs(e.id,n,t)})}}reparentFromHistoryReplay(e,t){this.yjsSync.withAtomicOperation(()=>{this.hierarchy.setBlockParent(e,t)})}syncParentContentIdsToYjs(e,t,n){t!==null&&t!==n&&this.removeChildFromParentYContent(t,e),n!==null&&this.appendChildToParentYContent(n,e)}removeChildFromParentYContent(e,t){let n=this.Blok.YjsManager.getBlockById(e);if(n===void 0)return;let r=n.get(`contentIds`);if(!(r instanceof Uo))return;let i=r.toArray().indexOf(t);i!==-1&&r.delete(i,1)}appendChildToParentYContent(e,t){let n=this.Blok.YjsManager.getBlockById(e);if(n===void 0)return;let r=n.get(`contentIds`),i=r instanceof Uo?r:new Uo;if(r instanceof Uo||n.set(`contentIds`,i),i.toArray().includes(t))return;let a=this.repository.getBlockById(e),o=a===void 0?-1:a.contentIds.indexOf(t),s=o===-1?i.length:Math.min(o,i.length);i.insert(s,[t])}updateBlockIndentation(e){return this.hierarchy.updateBlockIndentation(e)}getBlock(e){return this.repository.getBlock(e)}setCurrentBlockByChildNode(e){let n=this.repository.getBlockByChildNode(e);if(!n)return;let r=n.holder.closest(`[${t.Ma.editor}]`),i=this.Blok.UI.nodes.wrapper;if(r!=null&&r.isEqualNode(i))return this.currentBlockIndex=this.repository.getBlockIndex(n),n.updateCurrentInput(),n}getBlockByChildNode(e){return this.repository.getBlockByChildNode(e)}move(e,t=this.currentBlockIndex,n=!1,r=!1){this._currentBlockIndex=this.operations.currentBlockIndexValue,this.operations.move(e,t,n,this.blocksStore,r),this._currentBlockIndex=this.operations.currentBlockIndexValue}async convert(e,t,n){var r=this;return r.operations.convert(e,t,r.blocksStore,n)}unsetCurrentBlock(){this.currentBlockIndex=-1}async clear(e=!1){var n=this;let r=[...n.blocks],i=r.map(e=>e.id),a=e?t.aa():void 0,o=n.config.defaultBlock;n.Blok.YjsManager.transact(()=>{for(let e of i)n.Blok.YjsManager.removeBlock(e);e&&a!==void 0&&o!==void 0&&n.Blok.YjsManager.addBlock({id:a,type:o,data:{}},0)});for(let e of r){let t=n.getBlockIndex(e);t!==-1&&(n.blocksStore.remove(t),n.blockDidMutated(Gc,e,{index:t}))}n.unsetCurrentBlock(),e&&a!==void 0&&n.insert({id:a,skipYjsSync:!0}),n.Blok.UI.checkEmptiness()}moveCurrentBlockUp(){var e;(e=this.Blok.DragManager)!=null&&e.isDragging||(this._currentBlockIndex=this.operations.currentBlockIndexValue,this.operations.moveCurrentBlockUp(this.blocksStore),this._currentBlockIndex=this.operations.currentBlockIndexValue)}moveCurrentBlockDown(){var e;(e=this.Blok.DragManager)!=null&&e.isDragging||(this._currentBlockIndex=this.operations.currentBlockIndexValue,this.operations.moveCurrentBlockDown(this.blocksStore),this._currentBlockIndex=this.operations.currentBlockIndexValue)}async destroy(){var e=this;e.shortcuts.unregister(),await Promise.all(e.blocks.map(e=>e.destroy()))}bindBlockEvents(e){this.eventBinder.bindBlockEvents(e)}blockDidMutated(e,t,r){let i=n.t({target:new c(t)},r),a=new CustomEvent(e,{detail:n.t({},i)});return Object.prototype.propertyIsEnumerable.call(a,`type`)||Object.defineProperty(a,`type`,{value:e,enumerable:!0,configurable:!0}),Object.prototype.propertyIsEnumerable.call(a,`detail`)||Object.defineProperty(a,`detail`,{value:i,enumerable:!0,configurable:!0}),this.eventsDispatcher.emit(d,{event:a}),e===`block-changed`&&!this.yjsSync.isSyncingFromYjs&&!this._isPointerDragActive&&this.syncBlockDataToYjs(t),t}reconcileChildrenToParents(e,t){for(let n of e){if(n.parentId===null)continue;let e=t.get(n.parentId);if(e===void 0){n.parentId=null;continue}e.contentIds.includes(n.id)||e.contentIds.push(n.id)}}reconcileParentsToChildren(e,t){for(let n of e)n.contentIds.length!==0&&(n.contentIds=n.contentIds.filter(e=>this.resolveChildForParent(n,e,t)))}resolveChildForParent(e,t,n){let r=n.get(t);return r===void 0?!1:r.parentId===null?(r.parentId=e.id,!0):r.parentId===e.id}assertInsertManyHierarchy(e){let r=e.map(e=>n.t(n.t({id:e.id,type:e.name,data:{}},e.parentId!==null&&{parent:e.parentId}),e.contentIds.length>0&&{content:e.contentIds})),i=typeof process<`u`?`production`:void 0;if(i===`test`||i===`development`){Zc(r,`BlockManager.insertMany`);return}let a=Xc(r);a.length!==0&&t.Da(`BlockManager.insertMany produced output with hierarchy drift: ${a.map(e=>e.message).join(`; `)}`,`error`)}scheduleParentSync(e){this.parentsSyncScheduled.size===0&&queueMicrotask(()=>this.flushParentSyncs()),this.parentsSyncScheduled.add(e)}flushParentSyncs(){let e=[];for(let t of this.parentsSyncScheduled){let n=this.repository.getBlockById(t);n!==void 0&&e.push(this.syncBlockDataToYjs(n))}this.parentsSyncScheduled.clear(),e.length>0&&(this.pendingParentSyncPromise=Promise.all(e).then(()=>{this.pendingParentSyncPromise=null}))}async syncBlockDataToYjs(e){var t=this;let n=await e.save();if(n===void 0)return;let r={value:!1};t.Blok.YjsManager.transact(()=>{var i,a;for(let[i,a]of Object.entries(n.data))t.Blok.YjsManager.updateBlockData(e.id,i,a)&&(r.value=!0);r.value&&(e.lastEditedAt=Date.now(),e.lastEditedBy=(i=(a=t.config.user)==null?void 0:a.id)==null?null:i,t.Blok.YjsManager.updateBlockMetadata(e.id,e.lastEditedAt,e.lastEditedBy))})}},Sl=class extends s{constructor(...e){super(...e),this.anyBlockSelectedCache=null,this._navigationModeEnabled=!1,this.navigationFocusIndex=-1,this.needToSelectAll=!1,this.nativeInputSelected=!1,this.readyToBlockSelection=!1,this.selection=new t.Ai}get sanitizerConfig(){return t.Di(this.config.sanitizer,{p:{},h1:{},h2:{},h3:{},h4:{},h5:{},h6:{},ol:{},ul:{},li:{},br:!0,img:{src:!0,width:!0,height:!0},a:{href:!0},b:{},i:{},u:{},mark:{style:!0}})}get allBlocksSelected(){let{BlockManager:e}=this.Blok;return e.blocks.every(e=>e.selected)}set allBlocksSelected(e){let{BlockManager:t}=this.Blok;for(let n of t.blocks)n.selected=e;this.clearCache()}get anyBlockSelected(){let{BlockManager:e}=this.Blok;return this.anyBlockSelectedCache===null&&(this.anyBlockSelectedCache=e.blocks.some(e=>e.selected)),this.anyBlockSelectedCache}get selectedBlocks(){return this.Blok.BlockManager.blocks.filter(e=>e.selected)}get navigationModeEnabled(){return this._navigationModeEnabled}get navigationFocusedBlock(){if(!(!this._navigationModeEnabled||this.navigationFocusIndex<0))return this.Blok.BlockManager.getBlockByIndex(this.navigationFocusIndex)}prepare(){this.selection=new t.Ai,X.add({name:`CMD+A`,handler:e=>{let{BlockManager:t,ReadOnly:n}=this.Blok;if(n.isEnabled){e.preventDefault(),this.selectAllBlocks();return}t.currentBlock&&this.handleCommandA(e)},on:this.Blok.UI.nodes.redactor})}toggleReadOnly(){let e=t.Ai.get();e==null||e.removeAllRanges(),this.allBlocksSelected=!1}unSelectBlockByIndex(e){let{BlockManager:t}=this.Blok,n=typeof e==`number`?t.getBlockByIndex(e):t.currentBlock;n&&(n.selected=!1,this.clearCache())}clearSelection(e,n=!1){let{RectangleSelection:r}=this.Blok;this.needToSelectAll=!1,this.nativeInputSelected=!1,this.readyToBlockSelection=!1,this._navigationModeEnabled&&this.disableNavigationMode();let i=e&&e instanceof KeyboardEvent,a=e,o=i&&a.key&&a.key.length===1;this.anyBlockSelected&&i&&o&&!t.Ai.isSelectionExists&&this.replaceSelectedBlocksWithPrintableKey(e),this.Blok.CrossBlockSelection.clear(e),n&&this.selection.restore(),r.isRectActivated()&&this.Blok.RectangleSelection.clearSelection(),this.anyBlockSelected&&(this.allBlocksSelected=!1)}async copySelectedBlocks(e){var n=this;e.preventDefault();let r=e.clipboardData;if(!r)return;let i=t.Qi.make(`div`),a=[],o=(e=>{let t=[],r=new Set,i=e=>{if(!r.has(e.id)){r.add(e.id),t.push(e);for(let t of e.contentIds){let e=n.Blok.BlockManager.getBlockById(t);e!==void 0&&!r.has(e.id)&&i(e)}}};for(let t of e)i(t);return t})(n.selectedBlocks).map(e=>({id:e.id,tool:e.name,data:e.preservedData,tunes:e.preservedTunes,parentId:e.parentId,contentIds:e.contentIds}));n.selectedBlocks.forEach(e=>{var r;let o=t.Ei(e.holder.innerHTML,n.sanitizerConfig),s=t.Qi.make(`div`);s.innerHTML=o;let c=(r=s.textContent)==null?``:r;if(a.push(c),!Array.from(s.childNodes).some(e=>e.nodeType===Node.ELEMENT_NODE)&&c.trim().length>0){let e=t.Qi.make(`p`);e.innerHTML=s.innerHTML,i.appendChild(e)}else for(;s.firstChild;)i.appendChild(s.firstChild)});let s=a.join(`
10
10
 
11
- `),c=i.innerHTML;r.setData(`text/plain`,s),r.setData(`text/html`,c);try{r.setData(n.Blok.Paste.MIME_TYPE,JSON.stringify(o))}catch(e){e instanceof Error&&console.warn(`Failed to set custom clipboard data:`,e.message)}}selectBlockByIndex(e){let{BlockManager:t}=this.Blok,n=t.getBlockByIndex(e);n!==void 0&&this.selectBlock(n)}selectBlock(e){this.selection.save();let n=t.Ai.get();n==null||n.removeAllRanges();let r=e;r.selected=!0,this.clearCache(),this.Blok.InlineToolbar.close()}unselectBlock(e){let t=e;t.selected=!1,this.clearCache()}clearCache(){this.anyBlockSelectedCache=null}enableNavigationMode(){let{BlockManager:e}=this.Blok;if(this._navigationModeEnabled)return;this._navigationModeEnabled=!0;let t=e.currentBlockIndex>=0?e.currentBlockIndex:0;this.setNavigationFocus(t)}disableNavigationMode(e=!1){if(!this._navigationModeEnabled)return;let t=this.navigationFocusedBlock;if(t&&t.holder.removeAttribute(`data-blok-navigation-focused`),this._navigationModeEnabled=!1,e&&t){let{Caret:e,BlockManager:n}=this.Blok;n.currentBlockIndex=this.navigationFocusIndex,e.setToBlock(t,e.positions.END)}this.navigationFocusIndex=-1}navigateNext(){if(!this._navigationModeEnabled)return!1;let{BlockManager:e}=this.Blok,t=this.navigationFocusIndex+1;return t>=e.blocks.length?!1:(this.setNavigationFocus(t),!0)}navigatePrevious(){if(!this._navigationModeEnabled)return!1;let e=this.navigationFocusIndex-1;return e<0?!1:(this.setNavigationFocus(e),!0)}setNavigationFocus(e){let{BlockManager:n}=this.Blok,r=n.getBlockByIndex(e);if(!r)return;let i=this.navigationFocusedBlock;i&&i.holder.removeAttribute(`data-blok-navigation-focused`),this.navigationFocusIndex=e,r.holder.setAttribute(`data-blok-navigation-focused`,`true`);let a=t.Ai.get();a==null||a.removeAllRanges(),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),r.holder.scrollIntoView({behavior:`smooth`,block:`nearest`})}destroy(){X.remove(this.Blok.UI.nodes.redactor,`CMD+A`)}handleCommandA(e){if(this.Blok.RectangleSelection.clearSelection(),t.Qi.isNativeInput(e.target)&&!this.readyToBlockSelection){this.readyToBlockSelection=!0;return}let n=this.Blok.BlockManager.getBlock(e.target);if(!n)return;let r=n.inputs;if(r.length>1&&!this.readyToBlockSelection){this.readyToBlockSelection=!0;return}if(r.length===1&&!this.needToSelectAll){this.needToSelectAll=!0;return}if(this.needToSelectAll){e.preventDefault(),this.selectAllBlocks(),this.needToSelectAll=!1,this.readyToBlockSelection=!1;return}this.readyToBlockSelection&&(e.preventDefault(),this.selectBlock(n),this.needToSelectAll=!0)}selectAllBlocks(){this.selection.save();let e=t.Ai.get();e==null||e.removeAllRanges(),this.allBlocksSelected=!0,this.Blok.InlineToolbar.close(),this.Blok.Toolbar.moveAndOpenForMultipleBlocks()}replaceSelectedBlocksWithPrintableKey(e){let{BlockManager:n,Caret:r}=this.Blok,i=n.deleteSelectedBlocksAndInsertReplacement();i&&r.setToBlock(i),t.va(()=>{let t=e.key;r.insertContentAtCaretPosition(t.length>1?``:t)},20)()}},Cl=127,wl=e=>{for(let t of e){if(t.trim().length===0)continue;if(t>=`0`&&t<=`9`||t.toLowerCase()!==t.toUpperCase())return!1;let e=t.codePointAt(0);if(typeof e==`number`&&e>Cl)return!1}return!0},Tl=e=>{var t;return e.nodeType===Node.TEXT_NODE?[e]:(t=e.hasChildNodes)!=null&&t.call(e)?Array.from(e.childNodes).flatMap(e=>Tl(e)):[]},El=e=>{var t,n;let r=Tl(e);if(r.length===0)return null;let i=r[r.length-1],a=(t=[...r].reverse().find(e=>{var t;return!wl((t=e.textContent)==null?``:t)}))==null?null:t;return a&&a!==i&&wl((n=i.textContent)==null?``:n)&&a.parentNode!==e?a:i},Dl=class e extends s{get positions(){return{START:`start`,END:`end`,DEFAULT:`default`}}static get DATA_ATTR(){return{shadowCaret:`data-blok-shadow-caret`}}setToBlock(e,n=this.positions.DEFAULT,r=0){let{BlockManager:i,BlockSelection:a}=this.Blok;if(a.clearSelection(),!e.focusable){var o;(o=window.getSelection())==null||o.removeAllRanges(),a.selectBlock(e),i.currentBlock=e;return}let s=n===this.positions.START?e.firstInput:n===this.positions.END?e.lastInput:e.currentInput;if(!s)return;let{node:c,offset:l}=(e=>{if(n===this.positions.START)return{node:t.Qi.getDeepestNode(e,!1),offset:0};if(n===this.positions.END)return this.resolveEndPositionNode(e);let{node:i,offset:a}=t.Qi.getNodeByOffset(e,r);return i?{node:i,offset:a}:{node:t.Qi.getDeepestNode(e,!1),offset:0}})(s);if(!c)return;this.set(c,l),i.setCurrentBlockByChildNode(e.holder);let u=i.currentBlock;u&&(u.currentInput=s)}resolveEndPositionNode(e){let n=t.Qi.getDeepestNode(e,!0);if(n instanceof HTMLElement&&t.Qi.isNativeInput(n))return{node:n,offset:t.Qi.getContentLength(n)};let r=El(e);return r?{node:r,offset:t.Qi.getContentLength(r)}:n?{node:n,offset:t.Qi.getContentLength(n)}:{node:null,offset:0}}setToInput(e,t=this.positions.DEFAULT,n=0){let{currentBlock:r}=this.Blok.BlockManager;this.setCaretToInputPosition(e,t,n),r&&(r.currentInput=e)}setToBlockAtXPosition(e,t,n){let{BlockManager:r,BlockSelection:i}=this.Blok;if(i.clearSelection(),!e.focusable){var a;(a=window.getSelection())==null||a.removeAllRanges(),i.selectBlock(e),r.currentBlock=e;return}let o=n?e.firstInput:e.lastInput;if(!o)return;if(t!==null)ec(o,t,n);else{let e=n?this.positions.START:this.positions.END;this.setCaretToInputPosition(o,e,0)}r.setCurrentBlockByChildNode(e.holder);let s=r.currentBlock;s&&(s.currentInput=o)}setToInputAtXPosition(e,t,n){let{currentBlock:r}=this.Blok.BlockManager;if(t!==null)ec(e,t,n);else{let t=n?this.positions.START:this.positions.END;this.setCaretToInputPosition(e,t,0)}r&&(r.currentInput=e)}setCaretToInputPosition(e,t,n){if(t===this.positions.START){this.setCaretToStart(e);return}if(t===this.positions.END){this.setCaretToEnd(e);return}this.setCaretToOffset(e,n)}setCaretToStart(e){let n=t.Qi.getDeepestNode(e,!1);n&&this.set(n,0)}setCaretToEnd(e){let n=t.Qi.getDeepestNode(e,!0);n&&this.set(n,t.Qi.getContentLength(n))}setCaretToOffset(e,n){let{node:r,offset:i}=t.Qi.getNodeByOffset(e,n);if(r){this.set(r,i);return}this.setCaretToEnd(e)}set(e,n=0){let{top:r,bottom:i}=t.Ai.setCursor(e,n),{innerHeight:a}=window;if(r<0){window.scrollBy(0,r-30);return}i>a&&window.scrollBy(0,i-a+30)}setToTheLastBlock(){let e=this.Blok.BlockManager.lastBlock;if(e)if(e.tool.isDefault&&e.isEmpty)this.setToBlock(e);else{let e=this.Blok.BlockManager.insertAtEnd();this.setToBlock(e)}}extractFragmentFromCaretPosition(){let e=t.Ai.get();if(!e||!e.rangeCount)return;let n=e.getRangeAt(0),r=this.Blok.BlockManager.currentBlock;if(!r)return;let i=r.currentInput;if(n.deleteContents(),!i)return;if(t.Qi.isNativeInput(i)){var a;let e=i,t=document.createDocumentFragment(),n=(a=e.selectionStart)==null?0:a,r=e.value.substring(0,n);return t.textContent=e.value.substring(n),e.value=r,t}let o=n.cloneRange();return o.selectNodeContents(i),o.setStart(n.endContainer,n.endOffset),o.extractContents()}navigateNext(e=!1){let{BlockManager:n}=this.Blok,{currentBlock:r,nextVisibleBlock:i}=n;if(r===void 0)return!1;let{nextInput:a,currentInput:o}=r,s=o===void 0?void 0:t.hi(o),c=e||s||!r.focusable;if(a&&c)return this.setToInput(a,this.positions.START),!0;let l=()=>{if(i===null||r.parentId===null||r.holder.parentElement!==null&&r.holder.parentElement===i.holder.parentElement)return i;let e=this.resolveContainerToExit(r.parentId);return this.shouldExitContainer(r,i,e)?this.findFirstBlockAfterParent(e):i},u=(()=>{let e=l();return e===null?r.tool.isDefault||!c?null:n.insertAtEnd():e})();return u!==null&&c?(this.setToBlock(u,this.positions.START),!0):!1}navigatePrevious(e=!1){let{currentBlock:n,previousVisibleBlock:r}=this.Blok.BlockManager;if(!n)return!1;let{previousInput:i,currentInput:a}=n,o=a===void 0?void 0:t.gi(a),s=e||o||!n.focusable;if(i&&s)return this.setToInput(i,this.positions.END),!0;let c=(()=>{if(r===null||n.parentId===null||n.holder.parentElement!==null&&n.holder.parentElement===r.holder.parentElement)return r;let e=this.resolveContainerToExit(n.parentId);return this.shouldExitContainer(n,r,e)?this.findFirstBlockBeforeParent(e):r})();return c!==null&&s?(this.setToBlock(c,this.positions.END),!0):!1}navigateToBlock(e,t){if(e===null)return!1;let{BlockManager:n,BlockSelection:r}=this.Blok;return r.clearSelection(),e.focusable?this.setToBlockAtXPosition(e,null,t):(r.selectBlock(e),n.currentBlock=e),!0}navigateVerticalNext(){let{BlockManager:e}=this.Blok,{currentBlock:n,nextVisibleBlock:r}=e;if(n===void 0)return!1;if(!n.focusable||n.isEmpty)return this.navigateToBlock(r,!0);let{currentInput:i}=n;if(!(i===void 0||Js(i)))return!1;let a=tc(),{nextInput:o}=n;if(o)return this.setToInputAtXPosition(o,a,!0),!0;if(r!==null&&n.parentId!==null&&n.holder.parentElement!==null&&n.holder.parentElement===r.holder.parentElement)return this.setToBlockAtXPosition(r,a,!0),!0;let s=n.parentId===null?null:this.resolveContainerToExit(n.parentId);if(s!==null&&this.shouldExitContainer(n,r,s)){let t=this.findFirstBlockAfterParent(s);if(t!==null)return this.setToBlockAtXPosition(t,a,!0),!0;let n=e.insertAtEnd();return this.setToBlock(n,this.positions.START),!0}if(r!==null)return this.setToBlockAtXPosition(r,a,!0),!0;let c=i===void 0?!0:t.hi(i);if(!n.tool.isDefault&&c){let t=e.insertAtEnd();return this.setToBlock(t,this.positions.START),!0}return!1}navigateVerticalPrevious(){let{BlockManager:e}=this.Blok,{currentBlock:t,previousVisibleBlock:n}=e;if(t===void 0)return!1;if(!t.focusable||t.isEmpty)return this.navigateToBlock(n,!1);let{currentInput:r}=t;if(!(r===void 0||qs(r)))return!1;let i=tc(),{previousInput:a}=t;if(a)return this.setToInputAtXPosition(a,i,!1),!0;if(n!==null&&t.parentId!==null&&t.holder.parentElement!==null&&t.holder.parentElement===n.holder.parentElement)return this.setToBlockAtXPosition(n,i,!1),!0;let o=t.parentId===null?null:this.resolveContainerToExit(t.parentId);if(o!==null&&this.shouldExitContainer(t,n,o)){let e=this.findFirstBlockBeforeParent(o);return e===null?!1:(this.setToBlockAtXPosition(e,i,!1),!0)}return n===null?!1:(this.setToBlockAtXPosition(n,i,!1),!0)}findFirstBlockBeforeParent(e){let{BlockManager:t}=this.Blok,n=t.blocks,r=n.findIndex(t=>t.id===e);return r<=0?null:n[r-1]}findFirstBlockAfterParent(e){var t;let{BlockManager:n}=this.Blok,r=n.blocks,i=r.findIndex(t=>t.id===e);return i===-1||(t=r.slice(i+1).find(t=>!this.isWithinContainer(t,e)))==null?null:t}resolveContainerToExit(e){var t;let n=(t=this.Blok.BlockManager.getBlockById)==null?void 0:t.bind(this.Blok.BlockManager);if(n===void 0)return e;let r=n(e);return r===void 0||r.parentId===null?e:this.resolveContainerToExit(r.parentId)}isWithinContainer(e,t){var n;let r=e.parentId;if(r===null)return!1;if(r===t)return!0;let i=(n=this.Blok.BlockManager.getBlockById)==null?void 0:n.bind(this.Blok.BlockManager);if(i===void 0)return!1;let a=i(r);return a===void 0?!1:this.isWithinContainer(a,t)}shouldExitContainer(e,t,n){return e.parentId===null?!1:t===null||t.id===n?!0:this.isWithinContainer(t,n)}createShadow(t){let n=document.createElement(`span`);n.setAttribute(e.DATA_ATTR.shadowCaret,``),n.setAttribute(`data-blok-testid`,`shadow-caret`),t.insertAdjacentElement(`beforeend`,n)}restoreCaret(e){let n=e.querySelector(`[data-blok-testid="shadow-caret"]`);if(!n)return;new t.Ai().expandToTag(n);let r=document.createRange();r.selectNode(n),r.extractContents()}insertContentAtCaretPosition(e){let n=document.createDocumentFragment(),r=document.createElement(`div`),i=t.Ai.get(),a=t.Ai.range;if(!i||!a)return;r.innerHTML=e,Array.from(r.childNodes).forEach(e=>n.appendChild(e)),n.childNodes.length===0&&n.appendChild(new Text);let o=n.lastChild;a.deleteContents(),a.insertNode(n);let s=document.createRange(),c=o.nodeType===Node.TEXT_NODE?o:o.firstChild;c!==null&&c.textContent!==null&&s.setStart(c,c.textContent.length),i.removeAllRanges(),i.addRange(s)}},Ol=class extends s{constructor(...e){super(...e),this.firstSelectedBlock=null,this.lastSelectedBlock=null,this.onMouseUp=()=>{this.listeners.off(document,`mouseover`,this.onMouseOver),this.listeners.off(document,`mouseup`,this.onMouseUp),this.isCrossBlockSelectionStarted&&(this.Blok.UI.disableHoverForCooldown(),this.Blok.UI.resetBlockHoverState(),this.Blok.Toolbar.moveAndOpenForMultipleBlocks())},this.onMouseOver=e=>{let n=e,{BlockManager:r,BlockSelection:i,DragManager:a}=this.Blok;if(a.isDragging||this.Blok.UI.someToolbarOpened||this.Blok.RectangleSelection.isRectActivated()||n.relatedTarget===null&&n.target===null)return;let o=r.getBlockByChildNode(n.relatedTarget)||this.lastSelectedBlock,s=r.getBlockByChildNode(n.target);if(!o||!s)return;let c=r.resolveToRootBlock(o),l=r.resolveToRootBlock(s);if(l!==c){if(this.firstSelectedBlock&&c===this.firstSelectedBlock){var u;(u=t.Ai.get())==null||u.removeAllRanges(),c.selected=!0,l.selected=!0,i.clearCache();return}if(this.firstSelectedBlock&&l===this.firstSelectedBlock){let e=r.blocks.indexOf(c),t=r.blocks.indexOf(l),n=Math.min(e,t),a=Math.max(e,t);for(let e of Array.from({length:a-n+1},(e,t)=>n+t))r.blocks[e].selected=!1;i.clearCache();return}this.Blok.InlineToolbar.close(),this.toggleBlocksSelectedState(c,l),this.lastSelectedBlock=l}}}async prepare(){var e=this;e.listeners.on(document,`mousedown`,t=>{e.enableCrossBlockSelection(t)})}watchSelection(e){if(e.button!==t.ja.LEFT)return;let{BlockManager:n}=this.Blok,r=n.getBlock(e.target);r&&(this.firstSelectedBlock=r,this.lastSelectedBlock=r,this.listeners.on(document,`mouseover`,this.onMouseOver),this.listeners.on(document,`mouseup`,this.onMouseUp))}get isCrossBlockSelectionStarted(){return!!this.firstSelectedBlock&&!!this.lastSelectedBlock&&this.firstSelectedBlock!==this.lastSelectedBlock}toggleBlockSelectedState(e=!0){let{BlockManager:n,BlockSelection:r}=this.Blok,i=n.currentBlock;if(!this.lastSelectedBlock&&!i)return;if(!this.lastSelectedBlock&&i&&(this.lastSelectedBlock=this.firstSelectedBlock=i),this.firstSelectedBlock===this.lastSelectedBlock&&this.firstSelectedBlock){var a;this.firstSelectedBlock.selected=!0,r.clearCache(),(a=t.Ai.get())==null||a.removeAllRanges(),this.Blok.Toolbar.close()}if(!this.lastSelectedBlock)return;let o=n.blocks.indexOf(this.lastSelectedBlock)+(e?1:-1),s=n.blocks[o];s&&(this.lastSelectedBlock.selected===s.selected?(this.lastSelectedBlock.selected=!1,r.clearCache(),this.Blok.Toolbar.close()):(s.selected=!0,r.clearCache(),this.Blok.Toolbar.close()),this.lastSelectedBlock=s,this.Blok.InlineToolbar.close(),s.holder.scrollIntoView({block:`nearest`}),this.isCrossBlockSelectionStarted&&this.Blok.Toolbar.moveAndOpenForMultipleBlocks())}clear(e){let{BlockManager:t,BlockSelection:n,Caret:r}=this.Blok;if(!this.firstSelectedBlock||!this.lastSelectedBlock)return;let i=t.blocks.indexOf(this.firstSelectedBlock),a=t.blocks.indexOf(this.lastSelectedBlock);if(!n.anyBlockSelected||i===-1||a===-1){this.firstSelectedBlock=this.lastSelectedBlock=null;return}if(e&&e instanceof KeyboardEvent)switch(e.key){case`ArrowDown`:case`ArrowRight`:r.setToBlock(t.blocks[Math.max(i,a)],r.positions.END);break;case`ArrowUp`:case`ArrowLeft`:r.setToBlock(t.blocks[Math.min(i,a)],r.positions.START);break;default:r.setToBlock(t.blocks[Math.max(i,a)],r.positions.END)}this.firstSelectedBlock=this.lastSelectedBlock=null}enableCrossBlockSelection(e){let{UI:n,Toolbar:r}=this.Blok;if(!n.nodes.redactor||this.Blok.RectangleSelection.isRectActivated())return;let i=r.nodes.wrapper;i&&i.contains(e.target)||(t.Ai.isCollapsed||this.Blok.BlockSelection.clearSelection(e),n.nodes.redactor.contains(e.target)?this.watchSelection(e):this.Blok.BlockSelection.clearSelection(e))}toggleBlocksSelectedState(e,t){let{BlockManager:n,BlockSelection:r}=this.Blok,i=n.blocks.indexOf(e),a=n.blocks.indexOf(t),o=e.selected!==t.selected,s=Math.min(i,a),c=Math.max(i,a);for(let i of Array.from({length:c-s+1},(e,t)=>s+t)){let a=n.blocks[i];a!==this.firstSelectedBlock&&a!==(o?e:t)&&(n.blocks[i].selected=!n.blocks[i].selected,r.clearCache())}this.Blok.Toolbar.close()}},kl=`cubic-bezier(0.2, 0, 0, 1)`,Al=350,jl=()=>{var e,t,n;return(e=(t=(n=window).matchMedia)==null?void 0:t.call(n,`(prefers-reduced-motion: reduce)`).matches)==null?!1:e},Ml=()=>{var e,t,n;return(e=(t=(n=window).matchMedia)==null?void 0:t.call(n,`(max-width: 650px)`).matches)==null?!1:e},Nl=new Set,Pl=(e,t)=>{let n={done:!1},r=()=>{n.done||(n.done=!0,clearTimeout(a),e.removeEventListener(`transitionend`,i),Nl.delete(r),t())},i=t=>{t.target===e&&r()},a=setTimeout(r,Al);e.addEventListener(`transitionend`,i),Nl.add(r)},Fl=()=>{for(let e of[...Nl])e()},Il=(e,t)=>{let n=e.reduce((e,t)=>e+t,0),r=t.reduce((e,t)=>e+t,0);return e.length!==t.length||n<=0||r<=0?[...t]:e.map(e=>e/n*r)},Ll=e=>{let{holders:t,startWidths:n,newColumnHolder:r}=e,i=n.reduce((e,t)=>e+t,0);if(t.length!==n.length||t.length===0||i<=0||jl()||Ml())return;let a=t.map(e=>Number(e.style.flexGrow)||1),o=Il(n,a),s=t[0].parentElement,c=r;t.forEach((e,t)=>{let n=e;n.style.flexGrow=String(o[t])}),c&&(c.style.opacity=`0`),t[0].offsetWidth;let l=`flex-grow 200ms ${kl}, opacity 200ms ${kl}`;t.forEach((e,t)=>{let n=e;n.style.transition=l,n.style.flexGrow=String(a[t])}),c&&(c.style.opacity=`1`),s==null||s.setAttribute(`data-blok-column-drop-animating`,``),Pl(t[0],()=>{t.forEach((e,t)=>{let n=e;n.style.removeProperty(`transition`),n.style.flexGrow=String(a[t])}),c==null||c.style.removeProperty(`opacity`),s==null||s.removeAttribute(`data-blok-column-drop-animating`)})},Rl=e=>{var t,n;let r=Array.from((t=(n=e.parentElement)==null?void 0:n.children)==null?[]:t),i=r.indexOf(e);return r.slice(i+1).filter(e=>e instanceof HTMLElement&&e.hasAttribute(`data-blok-element`)).map(e=>({element:e,top:e.getBoundingClientRect().top}))},zl=e=>{if(!jl())for(let{element:t,top:n}of e){if(!t.isConnected)continue;let e=n-t.getBoundingClientRect().top;Math.abs(e)<1||(t.style.transform=`translateY(${e}px)`,t.offsetWidth,t.style.transition=`transform 200ms ${kl}`,t.style.transform=``,Pl(t,()=>{t.style.removeProperty(`transition`),t.style.removeProperty(`transform`)}))}},Bl=e=>{let{preview:t,targetRect:n}=e;if(jl()){t.remove();return}t.style.transition=`left 200ms ${kl}, top 200ms ${kl}, opacity 200ms ${kl}`,t.style.left=`${n.left}px`,t.style.top=`${n.top}px`,t.style.opacity=`0`,Pl(t,()=>t.remove())},Vl=(e,n)=>{var r;let i=e.blocks.getChildren(n).map(e=>e.holder),a=(r=i[0])==null?void 0:r.closest(`[${t.oi}]`);a instanceof HTMLElement&&t.di(a,i,e.readOnly.isEnabled,e,n)},Hl=(e,t)=>{if(e.blocks.transact!==void 0){e.blocks.transact(t);return}t()},Ul=(e,n,r,i)=>{var a,o,s;if(r.length===0||r.includes(n))return null;let c=e.blocks.getBlockIndex(n);if(c===void 0)return null;for(let t of r)if(e.blocks.getBlockIndex(t)===void 0)return null;if(((a=e.blocks.getById(n))==null?void 0:a.parentId)!==null)return null;let l=(o=e.blocks.getById(n))==null?void 0:o.holder,u=(s=l==null?void 0:l.getBoundingClientRect().width)==null?0:s,d=l===void 0?null:Rl(l),f={listId:null,columnHolders:[],sourcesColumnHolder:null};return Hl(e,()=>{let a=e.blocks.insert(t.ci,{noSeed:!0},{},c,!1,!1);f.listId=a.id;let o=e.blocks.insert(t.ui,{noSeed:!0},{},c+1,!1,!1),s=e.blocks.insert(t.ui,{noSeed:!0},{},c+2,!1,!1);e.blocks.setBlockParent(o.id,a.id),e.blocks.setBlockParent(s.id,a.id);let l=i===`left`?s:o,u=i===`left`?o:s;f.columnHolders=[o.holder,s.holder],f.sourcesColumnHolder=u.holder,e.blocks.setBlockParent(n,l.id);for(let t of r)e.blocks.setBlockParent(t,u.id)}),l!==void 0&&f.columnHolders.length===2&&(Ll({holders:f.columnHolders,startWidths:i===`left`?[0,u]:[u,0],newColumnHolder:f.sourcesColumnHolder}),d!==null&&zl(d)),f.listId},Wl=(e,n)=>{let r=n.filter(t=>{var n;return e.blocks.getBlockIndex(t)===void 0?!1:((n=e.blocks.getById(t))==null?void 0:n.parentId)===null});if(r.length<2)return null;let i=e.blocks.getBlockIndex(r[0]);if(i===void 0)return null;let a={listId:null};return Hl(e,()=>{let n=e.blocks.insert(t.ci,{noSeed:!0},{},i,!1,!1);a.listId=n.id;let o=r.map((n,r)=>e.blocks.insert(t.ui,{noSeed:!0},{},i+1+r,!1,!1));for(let t of o)e.blocks.setBlockParent(t.id,n.id);r.forEach((t,n)=>{e.blocks.setBlockParent(t,o[n].id)}),t.fi(e,n.id),Vl(e,n.id)}),a.listId},Gl=(e,n,r,i)=>{var a;if(r.length===0)return null;let o=e.blocks.getBlockIndex(n);if(o===void 0)return null;for(let t of r)if(e.blocks.getBlockIndex(t)===void 0)return null;let s=e.blocks.getById(n),c=s==null?void 0:s.parentId;if(c==null)return null;let l=i===`left`?o:o+1,u=(a=e.blocks.getById(c))==null?void 0:a.holder,d=new Map(e.blocks.getChildren(c).map(e=>[e.holder,e.holder.getBoundingClientRect().width])),f=u===void 0?null:Rl(u),p={columnId:null};if(Hl(e,()=>{let n=e.blocks.insert(t.ui,{noSeed:!0},{},l,!1,!1);p.columnId=n.id,e.blocks.setBlockParent(n.id,c);for(let t of r)e.blocks.setBlockParent(t,n.id);t.fi(e,c),Vl(e,c)}),p.columnId!==null){var m,h;let t=e.blocks.getChildren(c);Ll({holders:t.map(e=>e.holder),startWidths:t.map(e=>{var t;return(t=d.get(e.holder))==null?0:t}),newColumnHolder:(m=(h=t.find(e=>e.id===p.columnId))==null?void 0:h.holder)==null?null:m}),f!==null&&zl(f)}return p.columnId},Z={previewOffsetX:10,previewOffsetY:0,dragThreshold:5,autoScrollZone:50,autoScrollSpeed:10,announcementThrottleMs:300,leftDropZone:50,sideZoneRatio:.25,sideZoneMin:48,sideBandRatio:.6},Kl={base:`fixed pointer-events-none z-10000 opacity-80 transition-none`,content:`relative mx-auto max-w-blok-content`},ql=(e,t,n,r,i=Z.dragThreshold)=>{let a=n-e,o=r-t;return Math.sqrt(a*a+o*o)>=i},Jl=class{constructor(e,t,n){this.lastAnnouncedDropIndex=null,this.pendingAnnouncementIndex=null,this.announcementTimeoutId=null,this.blockManager=e,this.i18n=t,this.announcer=n}announceDropPosition(e,t){if(t===`left`||t===`right`)return;let n=this.blockManager.getBlockIndex(e),r=t===`top`?n:n+1;this.lastAnnouncedDropIndex!==r&&(this.pendingAnnouncementIndex=r,this.announcementTimeoutId===null&&(this.announcementTimeoutId=setTimeout(()=>{if(this.pendingAnnouncementIndex===null)return;let e=this.pendingAnnouncementIndex;if(this.announcementTimeoutId=null,this.pendingAnnouncementIndex=null,this.lastAnnouncedDropIndex===e)return;this.lastAnnouncedDropIndex=e;let t=this.blockManager.blocks.length,n=this.i18n.t(`a11y.dropPosition`,{position:e+1,total:t});this.announcer.announce(n,{politeness:`polite`})},Z.announcementThrottleMs)))}announceDropComplete(e,t,n){let r=this.blockManager.getBlockIndex(e),i=this.blockManager.blocks.length;if(n){let e=this.i18n.t(`a11y.blocksMoved`,{count:t.length,position:r+1});this.announcer.announce(e,{politeness:`assertive`})}else{let e=this.i18n.t(`a11y.blockMoved`,{position:r+1,total:i});this.announcer.announce(e,{politeness:`assertive`})}}announceDuplicateComplete(e){let t=e[0];if(!t)return;let n=this.blockManager.getBlockIndex(t),r=e.length;if(r>1){let e=this.i18n.t(`a11y.blocksDuplicated`,{count:r,position:n+1});this.announcer.announce(e,{politeness:`assertive`})}else{let e=this.i18n.t(`a11y.blockDuplicated`,{position:n+1});this.announcer.announce(e,{politeness:`assertive`})}}reset(){this.announcementTimeoutId!==null&&(clearTimeout(this.announcementTimeoutId),this.announcementTimeoutId=null),this.lastAnnouncedDropIndex=null,this.pendingAnnouncementIndex=null}getLastAnnouncedIndex(){return this.lastAnnouncedDropIndex}},Yl=class{constructor(e,t,n){this.blockManager=e,this.yjsManager=t,this.blockSelection=n}moveBlocks(e,t,n){return this.blockManager.getBlockIndex(t)===-1||e.some(e=>this.blockManager.getBlockIndex(e)===-1)?{movedBlocks:[],targetIndex:-1}:e.length===1?this.moveSingleBlock(e[0],t,n):this.moveMultipleBlocks(e,t,n)}async prepareDuplicates(e,t,n){var r=this;if(r.blockManager.getBlockIndex(t)===-1||e.some(e=>r.blockManager.getBlockIndex(e)===-1))return{sortedBlocks:[],sourceIds:new Set,validResults:[],baseInsertIndex:-1,aborted:!0};let i=[...e].sort((e,t)=>r.blockManager.getBlockIndex(e)-r.blockManager.getBlockIndex(t)),a=await Promise.all(i.map(async e=>{let t=await e.save();return t?{saved:t,toolName:e.name}:null})),o=r.blockManager.getBlockIndex(t);if(o===-1)return{sortedBlocks:[],sourceIds:new Set,validResults:[],baseInsertIndex:-1,aborted:!0};let s=n===`top`?o:o+1,c=a.filter(e=>e!==null);return{sortedBlocks:i,sourceIds:new Set(i.map(e=>e.id)),validResults:c,baseInsertIndex:s,aborted:!1}}applyDuplicates(e){if(e.aborted||e.validResults.length===0)return{duplicatedBlocks:[],targetIndex:e.baseInsertIndex};let t=e.validResults.map(({saved:t,toolName:n},r)=>this.blockManager.insert({tool:n,data:structuredClone(t.data),tunes:structuredClone(t.tunes),index:e.baseInsertIndex+r,needToFocus:!1}));if(this.blockManager.setBlockParent!==void 0){let n=new Map;e.sortedBlocks.forEach((e,r)=>{n.set(e.id,t[r].id)}),e.sortedBlocks.forEach((r,i)=>{let a=r.parentId;if(a!==null&&e.sourceIds.has(a)){let e=n.get(a);e!==void 0&&this.blockManager.setBlockParent!==void 0&&this.blockManager.setBlockParent(t[i],e)}})}let n=this.blockSelection;return n&&(n.clearSelection(),t.forEach(e=>{n.selectBlock(e)})),{duplicatedBlocks:t,targetIndex:e.baseInsertIndex}}async duplicateBlocks(e,t,n){var r=this;let i=await r.prepareDuplicates(e,t,n);return r.applyDuplicates(i)}moveSingleBlock(e,t,n){let r=this.blockManager.getBlockIndex(e),i=this.blockManager.getBlockIndex(t),a=n===`top`?i:i+1,o=r<a?a-1:a;if(r===o)return{movedBlocks:[e],targetIndex:r};this.blockManager.move(o,r,!1);let s=this.blockManager.getBlockIndex(e);return this.blockSelection&&this.blockSelection.selectBlock(e),{movedBlocks:[e],targetIndex:s}}moveMultipleBlocks(e,t,n){var r;let i=[...e].sort((e,t)=>this.blockManager.getBlockIndex(e)-this.blockManager.getBlockIndex(t)),a=this.blockManager.getBlockIndex(t),o=n===`top`?a:a+1,s=new Set(e.map(e=>e.id)),c=i.filter(e=>e.parentId===null||!s.has(e.parentId)),l=(r=c[0])==null?i[0]:r,u=o>this.blockManager.getBlockIndex(l),d=i.length>1,f=()=>{u?this.moveBlocksDown(c,o):this.moveBlocksUp(c,o)};d&&this.yjsManager?this.yjsManager.transactMoves(f):f();let p=this.blockSelection;return p&&(p.clearSelection(),i.forEach(e=>{p.selectBlock(e)})),{movedBlocks:i,targetIndex:o}}moveBlocksDown(e,t){let n=new Map;e.forEach(e=>{n.set(e,this.blockManager.getBlockIndex(e))}),[...e].reverse().forEach((e,n)=>{let r=this.blockManager.getBlockIndex(e),i=t-1-n;this.blockManager.move(i,r,!1,!0)}),e.forEach(e=>{var t;e.call(T.MOVED,{fromIndex:(t=n.get(e))==null?0:t,toIndex:this.blockManager.getBlockIndex(e),isGroupMove:!0})})}moveBlocksUp(e,t){let n=new Map;e.forEach(e=>{n.set(e,this.blockManager.getBlockIndex(e))}),e.forEach((e,n)=>{let r=this.blockManager.getBlockIndex(e),i=t+n;r!==i&&this.blockManager.move(i,r,!1,!0)}),e.forEach(e=>{var t;e.call(T.MOVED,{fromIndex:(t=n.get(e))==null?0:t,toIndex:this.blockManager.getBlockIndex(e),isGroupMove:!0})})}},Xl=class{constructor(){this.element=null}createSingle(e,n,i){var a,o,s;let c=t.Qi.make(`div`,Kl.base);c.setAttribute(`data-blok-testid`,`drag-preview`);let l=e.cloneNode(!0);(a=l.querySelector(`[data-blok-toggle-children]`))==null||a.remove(),l.className=r.n(Kl.content,n?`max-w-none`:``);let u=e.getBoundingClientRect().width;u>0&&(l.style.width=`${u}px`);let d=l.firstElementChild;d&&(d.className=r.n(d.className,`m-0!`)),c.appendChild(l);let f=(o=i==null||(s=i.contentIds)==null?void 0:s.length)==null?0:o;if(f>0){let e=t.Qi.make(`span`,`absolute bottom-1 right-1 text-xs text-gray-400 bg-white/80 px-1 rounded`);e.setAttribute(`data-blok-children-badge`,``),e.textContent=`+${f}`,c.appendChild(e)}return this.element=c,c}createMulti(e){let n=t.Qi.make(`div`,Kl.base);n.setAttribute(`data-blok-testid`,`drag-preview`);let i=e.map(e=>{let t=e.holder.getBoundingClientRect(),n=e.holder.querySelector(`[data-blok-element-content]`);if(!n)return{width:0,height:0,element:null,holderHeight:0};let r=n.getBoundingClientRect();return{width:r.width,height:r.height,element:n,holderHeight:t.height}}),a=i.reduce((e,t,n)=>{if(n===0)e.push(0);else{let t=e[n-1],r=i[n-1].holderHeight;e.push(t+r)}return e},[]),o=Math.max(...i.map(e=>e.width),0),s=i.length-1,c=s>=0?a[s]+i[s].height:0;return e.forEach((t,o)=>{var s;let c=i[o];if(!c.element)return;let l=c.element.cloneNode(!0);(s=l.querySelector(`[data-blok-toggle-children]`))==null||s.remove(),l.className=r.n(Kl.content,t.stretched?`max-w-none`:``);let u=l.firstElementChild;u&&(u.className=r.n(u.className,`m-0!`)),l.style.position=`absolute`,l.style.top=`${a[o]}px`,l.style.left=`0`,l.style.zIndex=`${e.length-o}`,n.appendChild(l)}),n.style.width=`${o}px`,n.style.height=`${c}px`,this.element=n,n}updatePosition(e,t){this.element&&(this.element.style.left=`${e+Z.previewOffsetX}px`,this.element.style.top=`${t+Z.previewOffsetY}px`)}show(){this.element&&(this.element.style.display=`block`)}hide(){this.element&&(this.element.style.display=`none`)}getElement(){return this.element}exists(){return this.element!==null}release(){let e=this.element;return this.element=null,e}destroy(){this.element&&this.element.parentNode&&this.element.remove(),this.element=null}},Zl=e=>e.type===`tracking`||e.type===`dragging`,Q=e=>e.type===`dragging`||e.type===`dropped`,Ql=class{constructor(){this.state={type:`idle`}}getState(){return this.state}startTracking(e,t,n,r){if(this.state.type!==`idle`)throw Error(`Cannot start tracking from state "${this.state.type}", must be idle`);let i=t.length>1;return this.state={type:`tracking`,sourceBlock:e,sourceBlocks:t,isMultiBlockDrag:i,startX:n,startY:r},this.state}startDrag(){if(this.state.type!==`tracking`)throw Error(`Cannot start drag from state "${this.state.type}", must be tracking`);return this.state={type:`dragging`,sourceBlock:this.state.sourceBlock,sourceBlocks:this.state.sourceBlocks,isMultiBlockDrag:this.state.isMultiBlockDrag,targetBlock:null,targetEdge:null,targetParentId:null,startX:this.state.startX,startY:this.state.startY},this.state}updateTarget(e,t,r=null){if(this.state.type!==`dragging`)throw Error(`Cannot update target from state "${this.state.type}", must be dragging`);this.state=n.t(n.t({},this.state),{},{targetBlock:e,targetEdge:t,targetParentId:r})}drop(){if(this.state.type!==`dragging`)throw Error(`Cannot drop from state "${this.state.type}", must be dragging`);if(!this.state.targetBlock||!this.state.targetEdge)throw Error(`Cannot drop: no valid target`);return this.state={type:`dropped`,sourceBlock:this.state.sourceBlock,sourceBlocks:this.state.sourceBlocks,isMultiBlockDrag:this.state.isMultiBlockDrag,targetBlock:this.state.targetBlock,targetEdge:this.state.targetEdge,targetParentId:this.state.targetParentId},this.state}cancel(){if(this.state.type!==`tracking`&&this.state.type!==`dragging`)throw Error(`Cannot cancel from state "${this.state.type}", must be tracking or dragging`);return this.state={type:`cancelled`,sourceBlock:this.state.sourceBlock,sourceBlocks:this.state.sourceBlocks},this.state}reset(){return this.state={type:`idle`},this.state}getSourceBlocks(){switch(this.state.type){case`tracking`:case`dragging`:case`dropped`:case`cancelled`:return this.state.sourceBlocks;case`idle`:return null}}getSourceBlock(){switch(this.state.type){case`tracking`:case`dragging`:case`dropped`:case`cancelled`:return this.state.sourceBlock;case`idle`:return null}}isMultiBlockDrag(){switch(this.state.type){case`tracking`:case`dragging`:case`dropped`:return this.state.isMultiBlockDrag;case`cancelled`:case`idle`:return!1}}isSourceBlock(e){let t=this.getSourceBlocks();return t?t.includes(e):!1}},$l=e=>{let t=e.holder.getAttribute(`data-list-depth`);if(t!==null&&t!==``){let e=parseInt(t,10);return isNaN(e)?null:e}let n=e.holder.querySelector(`[data-list-depth]`);if(!n)return null;let r=n.getAttribute(`data-list-depth`);if(r&&r!==``){let e=parseInt(r,10);return isNaN(e)?0:e}return 0},eu=class{constructor(e){this.blockManager=e}getDepth(e){return $l(e)}calculateTargetDepth(e,t){var n,r;let i=this.blockManager.getBlockIndex(e),a=t===`top`?i:i+1;if(a===0)return 0;let o=this.blockManager.getBlockByIndex(a-1);if(!o)return 0;let s=(n=$l(o))==null?0:n,c=this.blockManager.getBlockByIndex(a),l=c?(r=$l(c))==null?0:r:0;return l>0&&l<=s+1?l:s>0?s:0}},tu=class{constructor(e,t){this.sourceBlocks=[],this.ui=e,this.blockManager=t,this.listItemDepth=new eu(t)}setSourceBlocks(e){this.sourceBlocks=e}findDropTargetBlock(e,n,r){let i=e.closest(`[data-blok-toggle-body-placeholder]`);if(i){let e=i.closest(t.Na(t.Ma.element));if(!(e instanceof HTMLElement))return{block:void 0,holder:null};let n=this.blockManager.blocks.find(t=>t.holder===e);if(n)return{block:n,holder:e}}let a=e.closest(t.Na(t.Ma.element));if(a instanceof HTMLElement)return{block:this.blockManager.blocks.find(e=>e.holder===a),holder:a};let o=this.findBlockInLeftDropZone(n,r);return o?{block:o,holder:o.holder}:{block:void 0,holder:null}}findBlockInLeftDropZone(e,t){let n=this.ui.contentRect.left-e;if(n<0||n>Z.leftDropZone)return null;for(let e of this.blockManager.blocks){if(this.sourceBlocks.includes(e))continue;let n=e.holder.getBoundingClientRect();if(t>=n.top&&t<=n.bottom)return e}return null}determineDropTarget(e,t,n,r){let i=this.determineColumnGapTarget(e,n);if(i&&i.block!==r)return i;let a=this.findDropTargetBlock(e,t,n);if(!a.holder||!a.block||a.block===r)return null;let{block:o,holder:s}=this.redirectColumnContainerTarget(a.block,a.holder);if(this.sourceBlocks.length>1&&this.sourceBlocks.includes(o))return null;let c=o.holder.closest(`[data-blok-table-cell-blocks]`),l=r.holder.closest(`[data-blok-table-cell-blocks]`);if(c!==null&&l!==c)return this.redirectToTableBlock(c,n);let u=this.determineHorizontalTarget(o,s,t,n);if(u)return u;let d=s.getBoundingClientRect(),f=n<d.top+d.height/2,p=this.blockManager.getBlockIndex(o),m=p>0?this.blockManager.getBlockByIndex(p-1):null,h=m&&!this.sourceBlocks.includes(m)&&m.parentId===o.parentId;if(f&&p>0&&h){let t=this.calculateTargetDepth(m,`bottom`,r);return this.resolveToggleNesting({block:m,edge:`bottom`,depth:t,parentId:null},e)}let g=f?`top`:`bottom`,_=this.calculateTargetDepth(o,g,r);return this.resolveToggleNesting({block:o,edge:g,depth:_,parentId:null},e)}determineHorizontalTarget(e,t,n,r){if(window.innerWidth<651)return null;if(e.name===`column_list`)return this.outerColumnListTarget(e,t,n,r);if(e.name===`column`)return null;let i=t.querySelector(`[data-blok-element-content]`),a=i instanceof HTMLElement?i.getBoundingClientRect():t.getBoundingClientRect();if(t.closest(`[data-blok-columns]`)instanceof HTMLElement){let t=a.height*(1-Z.sideBandRatio)/2;if(!(r>=a.top+t&&r<=a.bottom-t))return null;let i=Math.max(a.width*Z.sideZoneRatio,Z.sideZoneMin),o=n<=a.left+i,s=n>=a.right-i;return o&&this.isFirstColumnChild(e)?{block:e,edge:`left`,depth:0,parentId:this.findEnclosingColumnId(e)}:s&&this.isLastColumnChild(e)?{block:e,edge:`right`,depth:0,parentId:this.findEnclosingColumnId(e)}:null}let o=a.height*(1-Z.sideBandRatio)/2;if(!(r>=a.top+o&&r<=a.bottom-o))return null;let s=Math.max(a.width*Z.sideZoneRatio,Z.sideZoneMin),c=n<=a.left+s,l=n>=a.right-s;return!c&&!l?null:{block:e,edge:c?`left`:`right`,depth:0,parentId:this.findEnclosingColumnId(e)}}outerColumnListTarget(e,t,n,r){let i=t.querySelector(`[data-blok-element-content]`),a=i instanceof HTMLElement?i.getBoundingClientRect():t.getBoundingClientRect(),o=a.height*(1-Z.sideBandRatio)/2;if(!(r>=a.top+o&&r<=a.bottom-o))return null;let s=Math.max(a.width*Z.sideZoneRatio,Z.sideZoneMin),c=n<=a.left+s,l=n>=a.right-s;if(!c&&!l)return null;let u=c?`left`:`right`,d=this.blockManager.blocks.filter(t=>t.parentId===e.id),f=u===`left`?d[0]:d[d.length-1];if(f===void 0)return null;let p=this.blockManager.blocks.find(e=>e.parentId===f.id);return p===void 0?null:{block:p,edge:u,depth:0,parentId:f.id}}columnHolderOf(e){let n=e.holder.closest(`[data-blok-column]`);if(!(n instanceof HTMLElement))return null;let r=n.closest(t.Na(t.Ma.element));return r instanceof HTMLElement?r:null}isFirstColumnChild(e){let t=this.columnHolderOf(e);return t!==null&&this.previousColumnHolder(t)===null}isLastColumnChild(e){let t=this.columnHolderOf(e);return t!==null&&this.nextColumnHolder(t)===null}nextColumnHolder(e){let n=e.nextElementSibling;return n===null?null:n instanceof HTMLElement&&n.matches(t.Na(t.Ma.element))?n:this.nextColumnHolder(n)}previousColumnHolder(e){let n=e.previousElementSibling;return n===null?null:n instanceof HTMLElement&&n.matches(t.Na(t.Ma.element))?n:this.previousColumnHolder(n)}firstBlockInColumnHolder(e){let n=e.querySelector(t.Na(t.Ma.element));return n instanceof HTMLElement?this.blockManager.blocks.find(e=>e.holder===n):void 0}lastChildOfColumn(e){let t=this.blockManager.blocks.filter(t=>t.parentId===e.id);return t[t.length-1]}redirectColumnContainerTarget(e,t){if(e.name!==`column`)return{block:e,holder:t};let n=this.lastChildOfColumn(e);return n===void 0||this.sourceBlocks.includes(n)?{block:e,holder:t}:{block:n,holder:n.holder}}determineColumnGapTarget(e,t){if(window.innerWidth<651)return null;let n=e.closest(`[data-blok-column-resizer]`);if(!(n instanceof HTMLElement))return null;let r=this.stackIntoGapColumn(n,t);if(r!==null)return r;let i=this.nextColumnHolder(n),a=i===null?void 0:this.firstBlockInColumnHolder(i);return a===void 0?null:{block:a,edge:`left`,depth:0,parentId:this.findEnclosingColumnId(a)}}stackIntoGapColumn(e,t){let n=this.previousColumnHolder(e),r=this.nextColumnHolder(e);if(n===null||r===null)return null;let i=this.blockManager.blocks.find(e=>e.holder===n),a=this.blockManager.blocks.find(e=>e.holder===r);if(i===void 0||a===void 0)return null;let o=this.columnContentBottom(i),s=this.columnContentBottom(a);return o===null||s===null?null:t>o&&t<=s?this.stackIntoColumnTarget(i):t>s&&t<=o?this.stackIntoColumnTarget(a):null}columnContentBottom(e){let t=this.lastChildOfColumn(e);if(t===void 0)return null;let n=t.holder.querySelector(`[data-blok-element-content]`);return(n instanceof HTMLElement?n.getBoundingClientRect():t.holder.getBoundingClientRect()).bottom}stackIntoColumnTarget(e){let t=this.lastChildOfColumn(e);return t===void 0||this.sourceBlocks.includes(t)?null:{block:t,edge:`bottom`,depth:0,parentId:null}}findEnclosingColumnId(e){let t=e=>{if(e===null)return null;let n=this.blockManager.getBlockById(e);return n===void 0?null:n.name===`column`?n.id:t(n.parentId)};return t(e.parentId)}calculateTargetDepth(e,t,n){let r=this.blockManager.getBlockIndex(e),i=t===`top`?r:r+1;if(i===0)return 0;let a=this.blockManager.getBlockByIndex(i-1);if(!a)return 0;let o=this.listItemDepth.getDepth(a),s=o!==null,c=o==null?0:o,l=this.blockManager.getBlockByIndex(i),u=l?this.listItemDepth.getDepth(l):null,d=u!==null,f=u==null?0:u,p=n?this.listItemDepth.getDepth(n):null;return p===null?f>0&&f<=c+1?f:c>0?c:0:this.predictListItemDepth(p,c,s,f,d)}predictListItemDepth(e,t,n,r,i){let a=n?t+1:0;return e>a?a:i&&r>e&&r<=a?r:n&&!i&&t>e&&t<=a?t:e}isOpenToggle(e){return e.holder.querySelector(`[data-blok-toggle-open="true"]`)!==null}getToggleChildIndicatorDepth(e){return 0}resolveToggleNesting(e,t){let{block:r,edge:i}=e;if(i===`bottom`&&this.isOpenToggle(r)&&!(this.sourceBlocks.length>0&&this.sourceBlocks.every(e=>e.parentId===r.id))){let t=this.getToggleChildIndicatorDepth(r);return n.t(n.t({},e),{},{parentId:r.id,depth:t})}if(r.parentId!==null){let t=this.blockManager.getBlockById(r.parentId);if(t!==void 0&&this.isOpenToggle(t)){let r=this.getToggleChildIndicatorDepth(t);return n.t(n.t({},e),{},{parentId:t.id,depth:r})}}return n.t(n.t({},e),{},{parentId:null})}redirectToTableBlock(e,n){let r=e.closest(t.Na(t.Ma.element)),i=r?this.blockManager.blocks.find(e=>e.holder===r):void 0;if(!i)return null;let a=i.holder.getBoundingClientRect();return{block:i,edge:n<a.top+a.height/2?`top`:`bottom`,depth:0,parentId:null}}},nu=class{constructor(e){this.animationFrameId=null,this.scrollDirection=null,this.scrollContainer=e}start(e){let t=window.innerHeight,n=e<Z.autoScrollZone,r=e>t-Z.autoScrollZone;if(!n&&!r){this.stop();return}let i=n?`up`:`down`;this.scrollDirection!==i&&(this.stop(),this.scrollDirection=i),this.animationFrameId===null&&(this.animationFrameId=requestAnimationFrame(this.scroll.bind(this)))}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.scrollDirection=null}scroll(){if(this.scrollDirection===null)return;let e=(this.scrollDirection===`up`?-1:1)*Z.autoScrollSpeed;this.scrollContainer?this.scrollContainer.scrollTop+=e:window.scrollBy(0,e),this.animationFrameId=requestAnimationFrame(this.scroll.bind(this))}destroy(){this.stop()}},ru=500,iu=`data-blok-spring-loading`,au=`data-blok-spring-loaded`,ou=700;function su(e){return e.holder.querySelector(`[data-blok-toggle-open="false"]`)!==null}var cu=class{constructor(){this.timerId=null,this.currentBlock=null}update(e){if(e!==this.currentBlock){if(this.clearTimer(),e===null||!su(e)){this.currentBlock=null;return}this.currentBlock=e,e.holder.setAttribute(iu,``),this.timerId=setTimeout(()=>{if(this.timerId=null,this.currentBlock){this.currentBlock.holder.removeAttribute(iu),this.currentBlock.call(`expand`),this.currentBlock.holder.setAttribute(au,``);let e=this.currentBlock;setTimeout(()=>e.holder.removeAttribute(au),ou),this.currentBlock=null}},ru)}}cancel(){this.clearTimer(),this.currentBlock=null}clearTimer(){this.timerId!==null&&(clearTimeout(this.timerId),this.timerId=null),this.currentBlock&&(this.currentBlock.holder.removeAttribute(iu),this.currentBlock=null)}},lu=e=>{if(!e||e===document.body)return null;let t=e.parentElement;if(!t||t===document.body)return null;let n=window.getComputedStyle(t).overflowY,r=n===`auto`||n===`scroll`,i=t.scrollHeight>t.clientHeight;return r&&i?t:lu(t)},uu=class{constructor(e){this.blockManager=e}getDescendants(e){let t=$l(e);if(t===null)return[];let n=this.blockManager.getBlockIndex(e);return this.collectDescendants(n+1,t,[])}collectDescendants(e,t,n){if(e>=this.blockManager.blocks.length)return n;let r=this.blockManager.getBlockByIndex(e);if(!r)return n;let i=$l(r);return i===null||i<=t?n:this.collectDescendants(e+1,t,[...n,r])}},du=class extends s{constructor(...e){super(...e),this.stateMachine=new Ql,this.preview=new Xl,this.targetDetector=null,this.operations=null,this.a11y=null,this.autoScroll=null,this.springLoader=new cu,this.listItemDescendants=null,this.boundHandlers=null,this.dragHandleCleanups=new WeakMap,this.sourceBlockDestroyUnsubs=[]}get isDragging(){return Q(this.stateMachine.getState())}async prepare(){}lazyInit(){this.targetDetector&&this.operations&&this.a11y&&this.listItemDescendants||(this.targetDetector=new tu({contentRect:this.Blok.UI.contentRect},this.Blok.BlockManager),this.operations=new Yl(this.Blok.BlockManager,this.Blok.YjsManager,this.Blok.BlockSelection),this.a11y=new Jl(this.Blok.BlockManager,this.Blok.I18n,{announce:sl}),this.listItemDescendants=new uu(this.Blok.BlockManager))}cancelTracking(){Zl(this.stateMachine.getState())&&!Q(this.stateMachine.getState())&&this.cleanup(!1,!0)}onSourceBlockDestroyed(){Zl(this.stateMachine.getState())&&this.cleanup(!0,!0)}setupDragHandle(e,n){var r;(r=this.dragHandleCleanups.get(e))==null||r();let i=r=>{var i;if(r.button!==0||document.querySelector(`[${t.Ma.popoverOpened}]`)!==null)return;let a=e.closest(`[${t.Ma.id}]`),o=(i=a==null?void 0:a.getAttribute(t.Ma.id))==null?null:i;if(o!==null){let e=this.Blok.BlockManager.getBlockById(o);if(e===void 0)return;this.startDragTracking(r,e);return}this.startDragTracking(r,n)};e.addEventListener(`mousedown`,i);let a=()=>{e.removeEventListener(`mousedown`,i),this.dragHandleCleanups.get(e)===a&&this.dragHandleCleanups.delete(e)};return this.dragHandleCleanups.set(e,a),a}startDragTracking(e,t){var n;this.lazyInit();let r=t.holder.querySelector(`[data-blok-element-content]`);if(!r||!(r instanceof HTMLElement))return;let i=t.selected,a=i?this.Blok.BlockSelection.selectedBlocks:[t],o=!i&&this.listItemDescendants?this.listItemDescendants.getDescendants(t):[],s=!i&&((n=t.contentIds)==null?void 0:n.length)>0,c=o.length===0&&s?this.getHierarchyDescendants(t):[],l=o.length>0?o:c,u=l.length>0?[t,...l]:a,d=new Set(u.map(e=>e.id)),f=u.filter(e=>e.parentId===null||!d.has(e.parentId));f.length>1&&c.length===0?this.preview.createMulti(f):this.preview.createSingle(r,t.stretched,t),this.preview.hide();let p=this.preview.getElement();p&&document.body.appendChild(p),this.stateMachine.startTracking(t,u,e.clientX,e.clientY),this.sourceBlockDestroyUnsubs=u.filter(e=>typeof e.addDestroyCallback==`function`).map(e=>e.addDestroyCallback(()=>this.onSourceBlockDestroyed()));let m=lu(this.Blok.UI.nodes.wrapper);this.autoScroll=new nu(m),this.targetDetector&&this.targetDetector.setSourceBlocks(u),this.boundHandlers={onMouseMove:this.onMouseMove.bind(this),onMouseUp:this.onMouseUp.bind(this),onKeyDown:this.onKeyDown.bind(this),onKeyUp:this.onKeyUp.bind(this)},document.addEventListener(`mousemove`,this.boundHandlers.onMouseMove),document.addEventListener(`mouseup`,this.boundHandlers.onMouseUp),document.addEventListener(`keydown`,this.boundHandlers.onKeyDown),document.addEventListener(`keyup`,this.boundHandlers.onKeyUp)}onMouseMove(e){let t=this.stateMachine.getState(),n=this.stateMachine.getSourceBlock(),r=this.stateMachine.getSourceBlocks();if(!n||!r)return;let{startX:i,startY:a}=t;!Q(t)&&ql(i,a,e.clientX,e.clientY)&&this.startActualDrag(r.length),this.preview.updatePosition(e.clientX,e.clientY),this.updateDropTarget(e.clientX,e.clientY),this.autoScroll&&Q(t)&&this.autoScroll.start(e.clientY)}startActualDrag(e){Fl(),this.stateMachine.startDrag(),this.Blok.Toolbar.skipNextSettingsToggle(),this.preview.show();let n=this.Blok.UI.nodes.wrapper;n.setAttribute(t.Ma.dragging,`true`),e>1&&n.setAttribute(t.Ma.draggingMulti,`true`),e===1&&this.Blok.BlockSelection.clearSelection(),t.bi(),this.Blok.Toolbar.close({setExplicitlyClosed:!1});let r=e>1?`a11y.dragStartedMultiple`:`a11y.dragStarted`,i=e>1?{count:e}:void 0;sl(this.Blok.I18n.t(r,i),{politeness:`assertive`})}updateDropTarget(e,t){let n=this.stateMachine.getState(),r=this.stateMachine.getSourceBlock();if(!Q(n)||!r||!this.targetDetector)return;let i=this.stateMachine.getState();i.type===`dragging`&&i.targetBlock&&(i.targetBlock.holder.removeAttribute(`data-drop-indicator`),i.targetBlock.holder.style.removeProperty(`--drop-indicator-depth`),this.clearContentIndicatorOffsets(i.targetBlock)),this.preview.hide();let a=document.elementFromPoint(e,t);if(this.preview.show(),!a){this.stateMachine.updateTarget(null,null),this.springLoader.update(null);return}let o=this.targetDetector.determineDropTarget(a,e,t,r);if(!o){this.stateMachine.updateTarget(null,null),this.springLoader.update(null);return}this.stateMachine.updateTarget(o.block,o.edge,o.parentId),this.springLoader.update(o.block),o.block.holder.setAttribute(`data-drop-indicator`,o.edge),o.block.holder.style.setProperty(`--drop-indicator-depth`,String(o.depth)),this.applyContentIndicatorOffsets(o.block),this.applySideIndicatorHeight(o.block,o.edge),this.centerSideIndicatorInGutter(o.block,o.edge),this.a11y&&this.a11y.announceDropPosition(o.block,o.edge)}applyContentIndicatorOffsets(e){let t=e.holder.querySelector(`[data-blok-element-content]`);if(!(t instanceof HTMLElement))return;let n=e.holder.getBoundingClientRect(),r=t.getBoundingClientRect();e.holder.style.setProperty(`--drop-indicator-side-left`,`${r.left-n.left}px`),e.holder.style.setProperty(`--drop-indicator-side-right`,`${n.right-r.right}px`)}applySideIndicatorHeight(e,t){if(t!==`left`&&t!==`right`)return;let n=e.holder.closest(`[data-blok-columns]`);if(!(n instanceof HTMLElement))return;let r=e.holder.getBoundingClientRect(),i=n.getBoundingClientRect();e.holder.style.setProperty(`--drop-indicator-side-top`,`${i.top-r.top}px`),e.holder.style.setProperty(`--drop-indicator-side-bottom`,`${r.bottom-i.bottom}px`)}centerSideIndicatorInGutter(e,t){if(t!==`left`&&t!==`right`)return;let n=e.holder.closest(`[data-blok-column]`),r=n instanceof HTMLElement?n.closest(`[data-blok-element]`):null;if(!(r instanceof HTMLElement))return;let i=t===`left`?r.previousElementSibling:r.nextElementSibling;if(!(i instanceof HTMLElement)||!i.hasAttribute(`data-blok-column-resizer`))return;let a=e.holder.getBoundingClientRect(),o=i.getBoundingClientRect(),s=o.left+o.width/2,c=parseFloat(getComputedStyle(e.holder).getPropertyValue(`--blok-space-2`))||0;t===`left`?e.holder.style.setProperty(`--drop-indicator-side-left`,`${s-a.left+c}px`):e.holder.style.setProperty(`--drop-indicator-side-right`,`${a.right-s+c}px`)}clearContentIndicatorOffsets(e){e.holder.style.removeProperty(`--drop-indicator-side-left`),e.holder.style.removeProperty(`--drop-indicator-side-right`),e.holder.style.removeProperty(`--drop-indicator-side-top`),e.holder.style.removeProperty(`--drop-indicator-side-bottom`)}onMouseUp(e){let t=this.stateMachine.getState(),n=this.stateMachine.getSourceBlock(),r=this.stateMachine.getSourceBlocks();if(!n||!r||!Q(t)){this.cleanup();return}let{targetBlock:i,targetEdge:a,targetParentId:o}=t;if(!i||!a){this.cleanup();return}if(this.stateMachine.drop(),!this.operations){this.cleanup();return}if(a===`left`||a===`right`){this.handleColumnDrop(n,r,i,a,o),this.cleanup(!1,e.altKey);return}e.altKey?this.handleDuplicate(r,i,a):this.handleDrop(n,r,i,a),this.cleanup(!1,e.altKey)}handleColumnDrop(e,t,n,r,i){let a=this.Blok.API.methods,o=(t.length>0?t:[e]).filter(e=>e.id!==n.id),s=new Set(o.map(e=>e.id)),c=o.filter(e=>e.parentId===null||!s.has(e.parentId)).map(e=>e.id);if(c.length===0)return;let l=new Set(c.map(e=>{var t;return(t=this.Blok.BlockManager.getBlockById(e))==null?void 0:t.parentId}).filter(e=>e!=null)),u=i===null?Ul(a,n.id,c,r):Gl(a,i,c,r);this.reseedEmptiedColumns(l),u!==null&&this.settleDroppedPreview(c[0])}settleDroppedPreview(e){var t,n;let r=this.preview.release();if(r===null)return;let i=(t=this.Blok.BlockManager.getBlockById(e))==null?void 0:t.holder,a=(n=i==null?void 0:i.querySelector(`[data-blok-element-content]`))==null?i:n;if(a==null){r.remove();return}let o=a.getBoundingClientRect();Bl({preview:r,targetRect:{left:o.left,top:o.top}})}reseedEmptiedColumns(e){for(let t of e){let e=this.Blok.BlockManager.getBlockById(t);e!==void 0&&e.name===`column`&&e.contentIds.length===0&&e.call(`rendered`)}}handleDrop(e,t,n,r){let i=this.Blok.YjsManager;if(i!==void 0&&typeof i.transactMoves==`function`){i.transactMoves(()=>{this.handleDropImpl(e,t,n,r)});return}this.handleDropImpl(e,t,n,r)}handleDropImpl(e,t,n,r){let i=t.length>1;if(!this.operations)return;let a=new Map;for(let e of t)a.set(e.id,e.parentId);let o=this.operations.moveBlocks(t,n,r);if(o.movedBlocks.length===0)return;let s=this.resolveParentForDrop(n,r,t,a),c=new Set(o.movedBlocks.map(e=>e.id)),l=[],u=new Set;for(let e of o.movedBlocks){if(e.parentId!==null&&c.has(e.parentId)){this.Blok.BlockManager.setBlockParent(e,e.parentId);continue}if(e.parentId===s&&s!==null){this.Blok.BlockManager.setBlockParent(e,s);continue}let t=e.parentId;t!==null&&u.add(t),s!==null&&u.add(s),this.Blok.BlockManager.setBlockParent(e,s),l.push(e)}for(let e of u){let t=this.Blok.BlockManager.getBlockById(e);t!==void 0&&t.call(`rendered`)}s!==null&&l.length>0&&this.hideBlocksIfParentCollapsed(s,l);let d=this.Blok.BlockManager.getBlockByIndex(o.targetIndex);this.a11y&&d&&this.a11y.announceDropComplete(d,t,i),this.Blok.Toolbar.moveAndOpen(e)}resolveParentForDrop(e,t,n,r){return t===`bottom`&&this.isToggleableBlock(e)&&this.isOpenToggle(e)&&!(n.length>0&&n.every(t=>((r==null?void 0:r.has(t.id))===!0?r.get(t.id):t.parentId)===e.id))?e.id:e.parentId===null?null:e.parentId}isToggleableBlock(e){return e.holder.querySelector(`[data-blok-toggle-open]`)!==null}isOpenToggle(e){return e.holder.querySelector(`[data-blok-toggle-open="true"]`)!==null}hideBlocksIfParentCollapsed(e,t){if(t.length===0)return;let n=this.Blok.BlockManager.getBlockById(e);if(n===void 0)return;let r=n.holder.querySelector(`[data-blok-toggle-open]`);if((r==null?void 0:r.getAttribute(`data-blok-toggle-open`))===`false`)for(let e of t)e.holder.classList.add(`hidden`)}async handleDuplicate(e,t,n){var r=this;if(!r.operations)return;let i=await r.operations.prepareDuplicates(e,t,n);if(i.aborted)return;let a={current:{duplicatedBlocks:[],targetIndex:i.baseInsertIndex}},o=()=>{if(!r.operations||(a.current=r.operations.applyDuplicates(i),a.current.duplicatedBlocks.length===0))return;let o=r.resolveParentForDrop(t,n,e);for(let e of a.current.duplicatedBlocks)e.parentId!==o&&r.Blok.BlockManager.setBlockParent(e,o)};typeof r.Blok.BlockManager.transactForTool==`function`?r.Blok.BlockManager.transactForTool(o):o();let s=a.current;if(s.duplicatedBlocks.length===0)return;let c=r.resolveParentForDrop(t,n,e),l=new Set;for(let e of s.duplicatedBlocks)e.parentId===c&&c!==null&&l.add(c);for(let e of l){let t=r.Blok.BlockManager.getBlockById(e);t!==void 0&&t.call(`rendered`)}if(c!==null){let e=s.duplicatedBlocks.filter(e=>e.parentId===c);r.hideBlocksIfParentCollapsed(c,e)}r.a11y&&r.a11y.announceDuplicateComplete(s.duplicatedBlocks),r.Blok.Toolbar.moveAndOpen(s.duplicatedBlocks[0])}onKeyDown(e){if(e.key===`Escape`){this.cleanup(!0);return}e.key===`Alt`&&Q(this.stateMachine.getState())&&this.setDuplicationMode(!0)}onKeyUp(e){e.key===`Alt`&&Q(this.stateMachine.getState())&&this.setDuplicationMode(!1)}setDuplicationMode(e){let n=this.Blok.UI.nodes.wrapper;e?n.setAttribute(t.Ma.duplicating,`true`):n.removeAttribute(t.Ma.duplicating)}cleanup(e=!1,n=!1){if(e&&Q(this.stateMachine.getState())&&sl(this.Blok.I18n.t(`a11y.dropCancelled`),{politeness:`polite`}),e){var r,i,a,o;(r=(i=this.Blok.UI).resetBlockHoverState)==null||r.call(i),(a=(o=this.Blok.Toolbar).resetExplicitlyClosed)==null||a.call(o)}this.autoScroll&&(this.autoScroll.destroy(),this.autoScroll=null),this.a11y&&this.a11y.reset();let s=this.stateMachine.getState();(s.type===`dragging`||s.type===`dropped`)&&s.targetBlock&&(s.targetBlock.holder.removeAttribute(`data-drop-indicator`),s.targetBlock.holder.style.removeProperty(`--drop-indicator-depth`),this.clearContentIndicatorOffsets(s.targetBlock)),this.springLoader.cancel(),this.preview.destroy();let c=this.Blok.UI.nodes.wrapper;c.removeAttribute(t.Ma.dragging),c.removeAttribute(t.Ma.draggingMulti),c.removeAttribute(t.Ma.duplicating),this.boundHandlers&&(document.removeEventListener(`mousemove`,this.boundHandlers.onMouseMove),document.removeEventListener(`mouseup`,this.boundHandlers.onMouseUp),document.removeEventListener(`keydown`,this.boundHandlers.onKeyDown),document.removeEventListener(`keyup`,this.boundHandlers.onKeyUp),this.boundHandlers=null),this.sourceBlockDestroyUnsubs.forEach(e=>e()),this.sourceBlockDestroyUnsubs=[];let l=this.stateMachine.getSourceBlock();if(this.stateMachine.reset(),this.targetDetector&&this.targetDetector.setSourceBlocks([]),e||n)return;let u=l==null?this.Blok.BlockManager.currentBlock:l;u&&this.Blok.Toolbar.moveAndOpen(u)}getHierarchyDescendants(e){let t=[],n=e=>{for(let r of e.contentIds){let e=this.Blok.BlockManager.getBlockById(r);e!==void 0&&(t.push(e),n(e))}};return n(e),t}destroy(){Fl(),this.cleanup()}},fu=new Set([`ar`,`dv`,`fa`,`he`,`ku`,`ps`,`sd`,`ug`,`ur`,`yi`]),pu=e=>fu.has(e)?`rtl`:`ltr`,mu=(e,t)=>({dictionary:t,direction:pu(e)}),hu=`am.ar.az.bg.bn.bs.cs.da.de.dv.el.en.es.et.fa.fi.fil.fr.gu.he.hi.hr.hu.hy.id.it.ja.ka.km.kn.ko.ku.lo.lt.lv.mk.ml.mn.mr.ms.my.ne.nl.no.pa.pl.ps.pt.ro.ru.sd.si.sk.sl.sq.sr.sv.sw.ta.te.th.tr.ug.uk.ur.vi.yi.zh`.split(`.`),gu=mu(`en`,a.r),_u=new Map;_u.set(`en`,gu);var vu={am:()=>Promise.resolve().then(()=>require(`./messages-Dh79ToYM.cjs`)),ar:()=>Promise.resolve().then(()=>require(`./messages-DIeUb2w-.cjs`)),az:()=>Promise.resolve().then(()=>require(`./messages-BscUmD6D.cjs`)),bg:()=>Promise.resolve().then(()=>require(`./messages-D6y13edn.cjs`)),bn:()=>Promise.resolve().then(()=>require(`./messages-C8f4kUOB.cjs`)),bs:()=>Promise.resolve().then(()=>require(`./messages-JyzorVPx.cjs`)),cs:()=>Promise.resolve().then(()=>require(`./messages-DUbZA-w_.cjs`)),da:()=>Promise.resolve().then(()=>require(`./messages-B4ZVgIh5.cjs`)),de:()=>Promise.resolve().then(()=>require(`./messages-BLNieIb-.cjs`)),dv:()=>Promise.resolve().then(()=>require(`./messages-BEEGgtPo.cjs`)),el:()=>Promise.resolve().then(()=>require(`./messages-BRbGk1-Z.cjs`)),en:()=>Promise.resolve({default:a.r}),es:()=>Promise.resolve().then(()=>require(`./messages-C3SZsVB9.cjs`)),et:()=>Promise.resolve().then(()=>require(`./messages-JYea02IT.cjs`)),fa:()=>Promise.resolve().then(()=>require(`./messages-BL-E2Kw3.cjs`)),fi:()=>Promise.resolve().then(()=>require(`./messages-4Qka94cm.cjs`)),fil:()=>Promise.resolve().then(()=>require(`./messages-BX86v7Ev.cjs`)),fr:()=>Promise.resolve().then(()=>require(`./messages-Dh9psewW.cjs`)),gu:()=>Promise.resolve().then(()=>require(`./messages-CNMPtWiq.cjs`)),he:()=>Promise.resolve().then(()=>require(`./messages-Dv4oyF7T.cjs`)),hi:()=>Promise.resolve().then(()=>require(`./messages-Df6vXDrY.cjs`)),hr:()=>Promise.resolve().then(()=>require(`./messages-Vp8CpYh3.cjs`)),hu:()=>Promise.resolve().then(()=>require(`./messages-cSHh8Zgv.cjs`)),hy:()=>Promise.resolve().then(()=>require(`./messages-Br_qu_wR.cjs`)),id:()=>Promise.resolve().then(()=>require(`./messages-sTyGkmbu.cjs`)),it:()=>Promise.resolve().then(()=>require(`./messages-AtTKtjsQ.cjs`)),ja:()=>Promise.resolve().then(()=>require(`./messages-BJcc9h6p.cjs`)),ka:()=>Promise.resolve().then(()=>require(`./messages-BWh9I5Jv2.cjs`)),km:()=>Promise.resolve().then(()=>require(`./messages-PpRvDwOa2.cjs`)),kn:()=>Promise.resolve().then(()=>require(`./messages-DLYl6KdK2.cjs`)),ko:()=>Promise.resolve().then(()=>require(`./messages-9bK437Rh.cjs`)),ku:()=>Promise.resolve().then(()=>require(`./messages-z2DzBRgO.cjs`)),lo:()=>Promise.resolve().then(()=>require(`./messages-uOISsfmj.cjs`)),lt:()=>Promise.resolve().then(()=>require(`./messages-BwCw0TJ1.cjs`)),lv:()=>Promise.resolve().then(()=>require(`./messages-DVAU-8rH.cjs`)),mk:()=>Promise.resolve().then(()=>require(`./messages-CHEpECGv.cjs`)),ml:()=>Promise.resolve().then(()=>require(`./messages-7wDDggws.cjs`)),mn:()=>Promise.resolve().then(()=>require(`./messages-9VzB9Djh.cjs`)),mr:()=>Promise.resolve().then(()=>require(`./messages-CVerbLou.cjs`)),ms:()=>Promise.resolve().then(()=>require(`./messages-BYpvkG9S.cjs`)),my:()=>Promise.resolve().then(()=>require(`./messages-CbKOqXT6.cjs`)),ne:()=>Promise.resolve().then(()=>require(`./messages-LX9PuLsT.cjs`)),nl:()=>Promise.resolve().then(()=>require(`./messages-CcO-3_4k.cjs`)),no:()=>Promise.resolve().then(()=>require(`./messages-D1XTyTJz.cjs`)),pa:()=>Promise.resolve().then(()=>require(`./messages-CJC94Hci.cjs`)),pl:()=>Promise.resolve().then(()=>require(`./messages-D0th-I9S.cjs`)),ps:()=>Promise.resolve().then(()=>require(`./messages-CMP5dbqQ.cjs`)),pt:()=>Promise.resolve().then(()=>require(`./messages-CgFAGUJX.cjs`)),ro:()=>Promise.resolve().then(()=>require(`./messages-BDer7I67.cjs`)),ru:()=>Promise.resolve().then(()=>require(`./messages-DoA0Ecoi.cjs`)),sd:()=>Promise.resolve().then(()=>require(`./messages-CHP0nYRn.cjs`)),si:()=>Promise.resolve().then(()=>require(`./messages-CdEZ98_p.cjs`)),sk:()=>Promise.resolve().then(()=>require(`./messages-BhTlR4PP.cjs`)),sl:()=>Promise.resolve().then(()=>require(`./messages-D86p1eQY.cjs`)),sq:()=>Promise.resolve().then(()=>require(`./messages-C73dKqPT.cjs`)),sr:()=>Promise.resolve().then(()=>require(`./messages-CcTkC677.cjs`)),sv:()=>Promise.resolve().then(()=>require(`./messages-XqCqLy0k.cjs`)),sw:()=>Promise.resolve().then(()=>require(`./messages-DJ-RX5EJ.cjs`)),ta:()=>Promise.resolve().then(()=>require(`./messages-CxIknrw4.cjs`)),te:()=>Promise.resolve().then(()=>require(`./messages-Dln2T0zJ.cjs`)),th:()=>Promise.resolve().then(()=>require(`./messages-B5bSFRCa.cjs`)),tr:()=>Promise.resolve().then(()=>require(`./messages-CMm8FeOL.cjs`)),ug:()=>Promise.resolve().then(()=>require(`./messages-DC-yFRyF.cjs`)),uk:()=>Promise.resolve().then(()=>require(`./messages-lvo-9Be0.cjs`)),ur:()=>Promise.resolve().then(()=>require(`./messages-T8hCmys7.cjs`)),vi:()=>Promise.resolve().then(()=>require(`./messages-1jzEPeW5.cjs`)),yi:()=>Promise.resolve().then(()=>require(`./messages-DG9l5agQ.cjs`)),zh:()=>Promise.resolve().then(()=>require(`./messages-BeQVEC9q.cjs`))},yu=async e=>{let t=_u.get(e);if(t!==void 0)return t;let n=vu[e],r=mu(e,(await n()).default);return _u.set(e,r),r},bu=class extends s{constructor(...e){super(...e),this.i18nextWrapper=null,this.locale=`en`,this.defaultLocale=`en`,this.usingI18next=!1,this.lightweightI18n=new a.t}t(e,t){return this.usingI18next&&this.i18nextWrapper!==null?this.i18nextWrapper.t(e,t):this.lightweightI18n.t(e,t)}getEnglishTranslation(e){var t;return(t=a.r[e])==null?``:t}has(e){return this.usingI18next&&this.i18nextWrapper!==null?this.i18nextWrapper.has(e):this.lightweightI18n.has(e)}async setLocale(e){var t=this;try{if(e===`en`){t.locale=`en`,t.usingI18next=!1;return}let n=await yu(e);if(await t.ensureI18nextLoaded(e,n),t.i18nextWrapper===null)return;t.i18nextWrapper.instance.hasResourceBundle(e,`translation`)||t.i18nextWrapper.instance.addResourceBundle(e,`translation`,n.dictionary),await t.i18nextWrapper.changeLanguage(e),t.locale=e,t.usingI18next=!0}catch(n){console.warn(`Failed to load locale "${e}". Falling back to "${t.defaultLocale}".`,n),t.locale=t.defaultLocale,t.defaultLocale===`en`&&(t.usingI18next=!1)}}async detectAndSetLocale(){var e=this;let t=e.detectBrowserLocale();return await e.setLocale(t),e.locale}setDictionary(e){this.usingI18next&&this.i18nextWrapper!==null?this.i18nextWrapper.setDictionary(e):this.lightweightI18n.setDictionary(e)}getLocale(){return this.locale}getDirection(){return pu(this.locale)}getDirectionForLocale(e){return pu(e)}async prepare(){var e=this,t;let n=e.config.i18n;e.applyDefaultLocale(n==null?void 0:n.defaultLocale);let r=n==null?void 0:n.locale;r===void 0||r===`auto`?await e.detectAndSetLocale():await e.setLocale(r),(n==null?void 0:n.messages)!==void 0&&e.setDictionary(n.messages),e.updateConfigDirection((t=n==null?void 0:n.direction)==null?e.getDirection():t)}async ensureI18nextLoaded(e,t){var n=this;if(n.i18nextWrapper!==null)return;let{loadI18next:r}=await Promise.resolve().then(()=>require(`./i18next-loader-DVakgVCy.cjs`));n.i18nextWrapper=await r(e,t)}updateConfigDirection(e){this.config.i18n===void 0&&(this.config.i18n={}),this.config.i18n.direction=e}applyDefaultLocale(e){e!==void 0&&(this.defaultLocale=e)}isLocaleSupported(e){return hu.includes(e)}detectBrowserLocale(){var e;if(typeof navigator>`u`)return this.defaultLocale;let t=(e=navigator.languages)==null?[navigator.language]:e;for(let e of t){if(!e)continue;let t=this.matchLanguageTag(e);if(t!==null)return t}return this.defaultLocale}matchLanguageTag(e){let t=e.toLowerCase();if(this.isLocaleSupported(t))return t;let n=t.split(`-`)[0];return n!==void 0&&this.isLocaleSupported(n)?n:null}},xu=class extends s{constructor({config:e,eventsDispatcher:t}){super({config:e,eventsDispatcher:t}),this.disabled=!1,this.batchingTimeout=null,this.batchingOnChangeQueue=new Map,this.batchTime=400,this.mutationObserver=new MutationObserver(e=>{this.redactorChanged(e)}),this.eventsDispatcher.on(d,e=>{this.particularBlockChanged(e.event)}),this.eventsDispatcher.on(_,()=>{this.disable()}),this.eventsDispatcher.on(v,()=>{this.enable()})}enable(){this.mutationObserver.observe(this.Blok.UI.nodes.redactor,{childList:!0,subtree:!0,characterData:!0,attributes:!0}),this.disabled=!1}disable(){this.mutationObserver.disconnect(),this.disabled=!0}particularBlockChanged(e){this.disabled||!t.xa(this.config.onChange)||(this.batchingOnChangeQueue.set(`block:${e.detail.target.id}:event:${e.type}`,e),this.batchingTimeout&&clearTimeout(this.batchingTimeout),this.batchingTimeout=setTimeout(()=>{let e=Array.from(this.batchingOnChangeQueue.values());if(e.length===0)return;let t=e.length===1?e[0]:e;this.config.onChange&&this.config.onChange(this.Blok.API.methods,t),this.batchingOnChangeQueue.clear()},this.batchTime))}destroy(){this.disabled=!0,this.mutationObserver.disconnect(),this.batchingTimeout!==null&&(clearTimeout(this.batchingTimeout),this.batchingTimeout=null),this.batchingOnChangeQueue.clear()}redactorChanged(e){this.eventsDispatcher.emit(y,{mutations:e})}},Su=new Set([`table`,`thead`,`tbody`,`tfoot`,`tr`,`th`,`td`,`caption`,`colgroup`,`col`,`ul`,`ol`,`li`,`dl`,`dt`,`dd`,`details`,`summary`]),Cu=e=>typeof e==`string`?[e]:e&&typeof e==`object`?Object.keys(e):[];function wu(e){let t=document.createElement(`div`);return t.innerHTML=e,Eu(t)?(Du(t),t.innerHTML):e}var Tu=[`figure.callout`,`ul.to-do-list`,`ul.toggle`,`ol.numbered-list`,`ul.bulleted-list`,`.notion-text-equation-token`,`[class*="block-color-"]`,`figure.equation`].join(`, `);function Eu(e){return e.querySelector(Tu)!==null}function Du(e){e.querySelectorAll(`del, strike`).forEach(e=>{let t=document.createElement(`s`);t.innerHTML=e.innerHTML,e.replaceWith(t)})}var Ou=`text/_notion-blocks-v3-production`;function ku(e){let t=Nu(e);if(typeof t!=`object`||!t||Array.isArray(t))return null;let n=t.blocks;if(!Array.isArray(n))return null;let r=new Map;if(n.forEach(e=>{var t;let n=e==null||(t=e.blockSubtree)==null?void 0:t.block;n!=null&&Object.keys(n).forEach(e=>{var t;let i=(t=n[e])==null?void 0:t.value;typeof i==`object`&&i&&r.set(e,i)})}),r.size===0)return null;let i=n.map(e=>e==null?void 0:e.blockId).filter(e=>typeof e==`string`),a=[],o=new Set,s=(e,t)=>{if(o.has(e))return;let n=r.get(e);if(n===void 0)return;if(o.add(e),n.type===`table`){Au(n,t,r,o,a);return}let i=Mu(n,r),c=Array.isArray(n.content)?n.content:[];if(i===null){c.forEach(e=>s(e,t));return}let l={id:e,tool:i.tool,data:i.data};if(t!==null&&(l.parentId=t),a.push(l),n.type===`callout`){var u;let t=Ju((u=n.properties)==null?void 0:u.title,r);t.length>0&&a.push({id:`${e}:callout-body`,tool:`paragraph`,data:{text:t},parentId:e})}c.forEach(t=>s(t,e))};return i.forEach(e=>{if(!r.has(e)){a.push({id:e,tool:`bookmark`,data:{url:nd(e)}});return}s(e,null)}),a}function Au(e,t,n,r,i){var a;let o=e.id,s=(a=e.format)==null?{}:a,c=(Array.isArray(e.content)?e.content:[]).filter(e=>typeof e==`string`),l=ju(s.table_block_column_order,c,n),u=[],d=c.map(e=>{var t,i;r.add(e);let a=(t=(i=n.get(e))==null?void 0:i.properties)==null?{}:t;return l.map(t=>{let r=`${e}:${t}`;return u.push({id:r,tool:`paragraph`,data:{text:Ju(a[t],n)},parentId:o}),{blocks:[r]}})}),f={id:o,tool:`table`,data:{withHeadings:s.table_block_row_header===!0,withHeadingColumn:s.table_block_column_header===!0,content:d}};t!==null&&(f.parentId=t),i.push(f),u.forEach(e=>i.push(e))}function ju(e,t,n){if(Array.isArray(e)&&e.length>0)return e.filter(e=>typeof e==`string`);for(let e of t){var r;let t=(r=n.get(e))==null?void 0:r.properties,i=t==null?[]:Object.keys(t);if(i.length>0)return i}return[]}function Mu(e,r){var i;let a=(i=e.properties)==null?{}:i,o=Ju(a.title,r);switch(e.type){case`text`:return{tool:`paragraph`,data:{text:o}};case`header`:return Vu(o,1,e.format);case`sub_header`:return Vu(o,2,e.format);case`sub_sub_header`:return Vu(o,3,e.format);case`quote`:var s;return{tool:`quote`,data:((s=e.format)==null?void 0:s.quote_size)===`large`?{text:o,size:`large`}:{text:o}};case`divider`:return{tool:`divider`,data:{}};case`code`:return{tool:`code`,data:{code:$(a.title),language:qu(a.language),lineNumbers:!1}};case`to_do`:return{tool:`list`,data:{text:o,style:`checklist`,checked:Gu(a.checked)}};case`bulleted_list`:return{tool:`list`,data:{text:o,style:`unordered`}};case`numbered_list`:return{tool:`list`,data:{text:o,style:`ordered`}};case`toggle`:return{tool:`toggle`,data:{text:o,isOpen:!0}};case`column_list`:return{tool:`column_list`,data:{}};case`column`:{var c;let t=(c=e.format)==null?void 0:c.column_ratio;return{tool:`column`,data:typeof t==`number`&&t!==1?{widthRatio:t}:{}}}case`table_row`:return null;case`equation`:return{tool:`code`,data:{code:$(a.title),language:`latex`,lineNumbers:!1}};case`bookmark`:var l;return Pu(a,(l=e.format)==null?{}:l,o);case`image`:var u;return Fu(`image`,a,(u=e.format)==null?{}:u,o,e.id);case`file`:var d;return Fu(`file`,a,(d=e.format)==null?{}:d,o,e.id);case`video`:var f;return zu(a,(f=e.format)==null?{}:f,o,e.id);case`audio`:var p;return Hu(a,(p=e.format)==null?{}:p,o,e.id);case`pdf`:var m;return Fu(`file`,a,(m=e.format)==null?{}:m,o,e.id);case`drive`:case`embed`:case`tweet`:case`gist`:case`codepen`:case`figma`:case`maps`:case`miro`:case`loom`:case`typeform`:case`invision`:case`framer`:case`whimsical`:case`abstract`:var h;return Bu(a,(h=e.format)==null?{}:h,o);case`callout`:{var g;let n=(g=e.format)==null?{}:g,r=typeof n.page_icon==`string`&&n.page_icon.length>0?n.page_icon:t.Nr,{textColor:i,backgroundColor:a}=ld(n.block_color);return{tool:`callout`,data:{emoji:r,textColor:i,backgroundColor:a}}}case`page`:return{tool:`bookmark`,data:n.t({url:nd(e.id)},o.length>0?{title:o}:{})};case`tab`:return null;case`transclusion_container`:return null;case`transclusion_reference`:return null;case`table_of_contents`:case`breadcrumb`:case`copy_indicator`:case`link_to_page`:case`alias`:return null;default:return{tool:`paragraph`,data:{text:o}}}}function Nu(e){try{return JSON.parse(e)}catch(e){return null}}function Pu(e,t,n){let r=Wu(e.link);if(r===null)return{tool:`paragraph`,data:{text:n}};let i={url:r},a=$(e.title),o=$(e.description);return a.length>0&&(i.title=a),o.length>0&&(i.description=o),typeof t.bookmark_cover==`string`&&(i.image=t.bookmark_cover),typeof t.bookmark_icon==`string`&&(i.favicon=t.bookmark_icon),{tool:`bookmark`,data:i}}function Fu(e,t,n,r,i){let a=Wu(t.source,n.display_source);if(a===null)return rd(i,t,r);if(e===`image`){let e={url:a},r=Iu(n.block_alignment);r!==null&&(e.alignment=r),Object.assign(e,Lu(t.caption));let i=$(t.alt_text);i.length>0&&(e.alt=i);let o=Ru(n.image_edit_metadata);return o!==null&&(e.crop=o),{tool:`image`,data:e}}let o={url:a},s=$(t.title);return s.length>0&&(o.fileName=s),Object.assign(o,Lu(t.caption)),{tool:`file`,data:o}}function Iu(e){return e===`left`||e===`right`?e:null}function Lu(e){let t=$(e);return t.length>0?{caption:t,captionVisible:!0}:{}}function Ru(e){if(typeof e!=`object`||!e)return null;let t=e.crop;if(typeof t!=`object`||!t)return null;let{x:n,y:r,width:i,height:a,unit:o}=t;if(o!==`%`||typeof n!=`number`||typeof r!=`number`||typeof i!=`number`||typeof a!=`number`||n===0&&r===0&&i===100&&a===100)return null;let s={x:n,y:r,w:i,h:a},c=e.mask;return(c===`circle`||c===`ellipse`)&&(s.shape=c),s}function zu(e,t,n,r){let i=Wu(e.source,t.display_source);if(i===null)return rd(r,e,n);let a=Uu(i);if(a!==null)return a;let o={url:i},s=Iu(t.block_alignment);return s!==null&&(o.alignment=s),Object.assign(o,Lu(e.caption)),{tool:`video`,data:o}}function Bu(e,t,n){var r;let i=Wu(e.source,t.display_source);return i===null?{tool:`paragraph`,data:{text:n}}:(r=Uu(i))==null?{tool:`bookmark`,data:{url:i}}:r}function Vu(e,t,n){return(n==null?void 0:n.toggleable)===!0?{tool:`header`,data:{text:e,level:t,isToggleable:!0,isOpen:!0}}:{tool:`header`,data:{text:e,level:t}}}function Hu(e,t,n,r){let i=Wu(e.source,t.display_source);if(i===null)return rd(r,e,n);let a={url:i},o=$(e.title);return o.length>0&&(a.title=o,a.fileName=o),{tool:`audio`,data:a}}function Uu(e){let n=t.$n(e);return n===null?null:{tool:`embed`,data:{service:n.service,source:e,embed:n.embedUrl,kind:n.kind}}}function Wu(...e){for(let t of e){let e=(typeof t==`string`?t:$(t)).trim();if(/^https?:\/\//i.test(e))return e}return null}function Gu(e){return Array.isArray(e)&&Array.isArray(e[0])&&e[0][0]===`Yes`}var Ku=new Map(t.mr.map(e=>[e.name.toLowerCase(),e.id]));function qu(e){var n;return!Array.isArray(e)||!Array.isArray(e[0])||typeof e[0][0]!=`string`||(n=Ku.get(e[0][0].toLowerCase()))==null?t.or:n}function $(e){return Array.isArray(e)?e.map(e=>Array.isArray(e)&&typeof e[0]==`string`?e[0]:``).join(``):``}function Ju(e,t){return Array.isArray(e)?e.map(e=>Yu(e,t)).join(``):``}function Yu(e,t){if(!Array.isArray(e))return``;let n=typeof e[0]==`string`?e[0]:``,r=Array.isArray(e[1])?e[1]:[],i=[`e`,`p`,`d`,`u`],a=e=>Array.isArray(e)&&e[0]===`h`,o=e=>Array.isArray(e)&&i.includes(e[0]),s=r.filter(e=>!a(e)&&!o(e)).reduce((e,t)=>ud(t,e),Xu(n,r,t)),c=sd(r.filter(a));return c.length>0?`<mark style="${c}">${s}</mark>`:s}function Xu(e,t,n){let r=Zu(t,`e`);if(r!==null)return`<code>${fd(r)}</code>`;let i=Zu(t,`p`);if(i!==null)return ad(i,e,n);let a=$u(t);return a===null?Qu(t,`u`)||Qu(t,`d`)?``:fd(e):fd(td(a))}function Zu(e,t){for(let n of e)if(Array.isArray(n)&&n[0]===t&&typeof n[1]==`string`)return n[1];return null}function Qu(e,t){return e.some(e=>Array.isArray(e)&&e[0]===t)}function $u(e){for(let t of e)if(Array.isArray(t)&&t[0]===`d`&&ed(t[1]))return t[1];return null}function ed(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function td(e){let t=(t,n)=>{let r=typeof e[t]==`string`?e[t]:``,i=typeof e[n]==`string`?e[n]:``;return r.length===0?``:i.length>0?`${r} ${i}`:r};return[t(`start_date`,`start_time`),t(`end_date`,`end_time`)].filter(e=>e.length>0).join(` → `)}function nd(e){return`https://www.notion.so/${e.replace(/-/g,``)}`}function rd(e,t,n){let r=n.length>0?n:id(t.source),i={url:nd(e)};return r.length>0&&(i.title=r),{tool:`bookmark`,data:i}}function id(e){let t=Array.isArray(e)?e[0]:void 0,n=Array.isArray(t)?t[0]:void 0;if(typeof n!=`string`)return``;let r=/^attachment:[^:]+:(.+)$/.exec(n);if(r===null)return``;try{return decodeURIComponent(r[1])}catch(e){return r[1]}}function ad(e,t,n){var r;let i=$(n==null||(r=n.get(e))==null||(r=r.properties)==null?void 0:r.title),a=i.length>0?i:`Untitled`;return`<a href="${pd(nd(e))}">${fd(a)}</a>`}function od(e){if(typeof e!=`string`||e.length===0||e===`default`)return null;let t=e.endsWith(`_background`)?{mode:`bg`,name:e.slice(0,-11)}:{mode:`text`,name:e};return t.name===`default`?null:t}function sd(e){let n=e.map(e=>od(Array.isArray(e)?e[1]:void 0)).filter(e=>e!==null),r=n.find(e=>e.mode===`text`),i=n.find(e=>e.mode===`bg`),a=[];return r&&a.push(`color: ${t.ai(r.name,`text`)}`),i&&a.push(`background-color: ${t.ai(i.name,`bg`)}`),a.join(`; `)}var cd=new Set(t.ri.map(e=>e.name));function ld(e){let t=od(e);return t===null||!cd.has(t.name)?{textColor:null,backgroundColor:null}:t.mode===`text`?{textColor:t.name,backgroundColor:null}:{textColor:null,backgroundColor:t.name}}function ud(e,t){if(!Array.isArray(e))return t;switch(e[0]){case`b`:return`<b>${t}</b>`;case`i`:return`<i>${t}</i>`;case`s`:return`<s>${t}</s>`;case`c`:return`<code>${t}</code>`;case`_`:return`<u>${t}</u>`;case`a`:{let n=dd(e[1]);return n===null?t:`<a href="${pd(n)}">${t}</a>`}default:return t}}function dd(e){if(typeof e!=`string`)return null;let t=e.trim();return/^(?:https?:|mailto:|tel:|#|\/|\.\/|\.\.\/)/i.test(t)?t:null}function fd(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function pd(e){return fd(e).replace(/"/g,`&quot;`)}var md=[`text/next-space-blocks`,`text/next-space-content`];function hd(e){let t=kd(e);if(typeof t!=`object`||!t||Array.isArray(t))return null;let n=t.blocks;if(!Array.isArray(n)||n.length===0)return null;let r=new Map;if(n.forEach(e=>{let t=e==null?void 0:e.subTree;typeof t!=`object`||!t||Object.values(t).forEach(e=>{typeof e==`object`&&e&&typeof e.uuid==`string`&&r.set(e.uuid,e)})}),r.size===0)return null;let i=n.map(e=>e==null?void 0:e.id).filter(e=>typeof e==`string`),a=[],o=new Set,s=(e,t)=>{if(o.has(e))return;let n=r.get(e);if(n===void 0)return;if(o.add(e),n.type===27){gd(n,t,r,o,a);return}let i=_d(n);if(i===null)return;let c={id:e,tool:i.tool,data:i.data};if(t!==null&&(c.parentId=t),a.push(c),n.type===13){var l;let t=Ad(((l=n.data)==null?{}:l).segments);t.length>0&&a.push({id:`${e}:callout-body`,tool:`paragraph`,data:{text:t},parentId:e})}(Array.isArray(n.subNodes)?n.subNodes:[]).forEach(t=>s(t,e))};return i.forEach(e=>s(e,null)),a}function gd(e,t,n,r,i){var a;let o=e.uuid,s=(a=e.data)==null?{}:a,c=Nd(s.format)?s.format:{},l=(Array.isArray(e.subNodes)?e.subNodes:[]).filter(e=>typeof e==`string`),u=Array.isArray(c.tableBlockColumnOrder)?c.tableBlockColumnOrder.filter(e=>typeof e==`string`):[],d=[],f=l.map(e=>{var t,i;r.add(e);let a=(t=(i=n.get(e))==null?void 0:i.data)==null?{}:t,s=Nd(a.collectionProperties)?a.collectionProperties:{};return u.map(t=>{let n=`${e}:${t}`;return d.push({id:n,tool:`paragraph`,data:{text:Ad(s[t])},parentId:o}),{blocks:[n]}})}),p={id:o,tool:`table`,data:{withHeadings:c.tableBlockRowHeader===!0,withHeadingColumn:c.tableBlockColumnHeader===!0,content:f}};t!==null&&(p.parentId=t),i.push(p),d.forEach(e=>i.push(e))}function _d(e){var t;let n=(t=e.data)==null?{}:t,r=Ad(n.segments);switch(e.type){case 1:return{tool:`paragraph`,data:{text:r}};case 3:return{tool:`list`,data:{text:r,style:`checklist`,checked:n.checked===!0}};case 4:return{tool:`list`,data:{text:r,style:`unordered`}};case 5:return{tool:`list`,data:{text:r,style:`ordered`}};case 7:return{tool:`header`,data:{text:r,level:n.level}};case 38:return{tool:`header`,data:{text:r,level:n.level,isToggleable:!0,isOpen:!0}};case 6:return{tool:`toggle`,data:{text:r,isOpen:!0}};case 9:return{tool:`divider`,data:{}};case 12:return{tool:`quote`,data:{text:r}};case 13:return vd(e,n);case 25:return{tool:`code`,data:{code:jd(n.segments),language:Od(xd(n.format)),lineNumbers:!1}};case 23:return{tool:`code`,data:{code:jd(n.segments),language:`latex`,lineNumbers:!1}};case 10:return{tool:`column_list`,data:{}};case 11:{let e=n.columnRatio;return{tool:`column`,data:typeof e==`number`&&e!==1?{widthRatio:e}:{}}}case 14:return Sd(e,n,r);case 21:return Td(n,r);case 28:return null;default:return{tool:`paragraph`,data:{text:r}}}}function vd(e,n){let r=Nd(n.icon)?n.icon:{};return{tool:`callout`,data:{emoji:typeof r.value==`string`&&r.value.length>0?r.value:t.Nr,textColor:bd(e.textColor),backgroundColor:bd(e.backgroundColor)}}}var yd=new Set(t.ri.map(e=>e.name));function bd(e){if(typeof e!=`string`||e.length===0)return null;let t=e.toLowerCase()===`grey`?`gray`:e.toLowerCase();return yd.has(t)?t:null}function xd(e){return Nd(e)?e.language:void 0}function Sd(e,t,n){let r=typeof t.ossName==`string`?t.ossName:``,i=typeof e.title==`string`?e.title:``,a=n.length>0?n:i;if(r.length===0)return{tool:`paragraph`,data:{text:a}};let o=Cd(r),s=typeof t.display==`string`?t.display:`file`;if(s===`image`){let e={url:o},n=wd(t.format);return n!==null&&(e.alignment=n),{tool:`image`,data:e}}if(s===`video`)return{tool:`video`,data:{url:o}};if(s===`audio`){let e={url:o};return a.length>0&&(e.title=a,e.fileName=a),{tool:`audio`,data:e}}let c={url:o};return a.length>0&&(c.fileName=a),{tool:`file`,data:c}}function Cd(e){return`https://cdn2.buildin.ai/${e}`}function wd(e){return Nd(e)?e.contentGravity===`LEFT`?`left`:e.contentGravity===`RIGHT`?`right`:null:null}function Td(e,t){let n=Md(e.link);if(n===null)return{tool:`paragraph`,data:{text:t}};let r=Ed(n);if(r!==null)return r;let i={url:n},a=jd(e.linkInfo);return a.length>0&&(i.title=a),{tool:`bookmark`,data:i}}function Ed(e){let n=t.$n(e);return n===null?null:{tool:`embed`,data:{service:n.service,source:e,embed:n.embedUrl,kind:n.kind}}}var Dd=new Map(t.mr.map(e=>[e.name.toLowerCase(),e.id]));function Od(e){var n;return(n=Dd.get(String(e).toLowerCase()))==null?t.or:n}function kd(e){try{return JSON.parse(e)}catch(e){return null}}function Ad(e){return Array.isArray(e)?e.map(e=>Nd(e)&&typeof e.text==`string`?Pd(e.text):``).join(``):``}function jd(e){return Array.isArray(e)?e.map(e=>Nd(e)&&typeof e.text==`string`?e.text:``).join(``):``}function Md(...e){for(let t of e){let e=(typeof t==`string`?t:jd(t)).trim();if(/^https?:\/\//i.test(e))return e}return null}function Nd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pd(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}var Fd=class{constructor(e,t,n){this.Blok=e,this.toolRegistry=t,this.sanitizerBuilder=n}composePasteEvent(e,t){return new CustomEvent(e,{detail:t})}shouldReplaceCurrentBlock(e){let{BlockManager:t}=this.Blok,n=t.currentBlock;return n?e&&n.name===e?!0:!!n.tool.isDefault&&n.isEmpty:!1}redirectToTableParentIfNeeded(e,n){var r,i;let a=n.currentBlock,o=a==null||(r=a.holder)==null?void 0:r.closest(`[data-blok-table-cell-blocks]`),s=new Set(t.Ji()),c=e.some(e=>s.has(e.tool));if(!o||!c||a===void 0)return;let l=(i=a.holder.closest(`[data-blok-tool="table"]`))==null?void 0:i.closest(`[data-blok-element]`);l&&n.setCurrentBlockByChildNode(l)}async insertPasteData(e,t){var n=this;let{BlockManager:r,Caret:i}=n.Blok;if(!e.length)return;if(e.length>1){var a,o,s,c,l;n.redirectToTableParentIfNeeded(e,r);let u=r.currentBlock,d=(a=u==null||(o=u.holder)==null?void 0:o.querySelector(`[data-blok-toggle-children]`))==null?null:a,f=d!==null&&!d.contains((s=u==null?void 0:u.currentInput)==null?null:s)?(c=u==null?void 0:u.id)==null?null:c:(l=u==null?void 0:u.parentId)==null?null:l,p=[],m=r.operations,h={current:Promise.resolve()},g=()=>{h.current=(async()=>{for(let[o,s]of e.entries()){var a;m!==void 0&&(m.suppressStopCapturing=!0);let e=o===0&&t&&((a=r.currentBlock)==null?void 0:a.isEmpty)===!0?await r.paste(s.tool,s.event,!0):await r.paste(s.tool,s.event);i.setToBlock(e,i.positions.END),p.push(e),n.applyPastedBlockParent(e,s,p,r,f)}})()};typeof r.transactForTool==`function`?r.transactForTool(g):g(),await h.current,r.currentBlock&&i.setToBlock(r.currentBlock,i.positions.END);return}let[u]=e;if(u.isBlock){await n.processSingleBlock(u,t);return}await n.processInlinePaste(u,t)}applyPastedBlockParent(e,t,n,r,i){if(t.parentPasteIndex!==void 0){let i=n[t.parentPasteIndex];i&&r.setBlockParent(e,i.id)}else i===null?e.parentId!=null&&r.setBlockParent(e,null):r.setBlockParent(e,i)}async insertBlock(e,t=!1){let{BlockManager:n,Caret:r}=this.Blok,{currentBlock:i}=n;if(t&&i&&i.isEmpty){let t=await n.paste(e.tool,e.event,!0);r.setToBlock(t,r.positions.END);return}let a=await n.paste(e.tool,e.event);r.setToBlock(a,r.positions.END)}async processSingleBlock(e,n){var r=this;let{Caret:i,BlockManager:a}=r.Blok,{currentBlock:o}=a,s=t.Qi;if(!o||e.tool!==o.name||!s.containsOnlyInlineElements(e.content.innerHTML)){await r.insertBlock(e,n);return}i.insertContentAtCaretPosition(e.content.innerHTML)}async processInlinePaste(e,n){var r=this;let{BlockManager:i,Caret:a}=r.Blok,{content:o}=e,s=i.currentBlock;if(!s||!s.currentInput){await r.insertBlock(e,n);return}let c=s.tool.baseSanitizeConfig;a.insertContentAtCaretPosition(t.Ei(o.innerHTML,c))}},Id,Ld=class e{constructor(){this.scrollPosition=null}lock(){t.pa?this.lockHard():(document.body.classList.add(e.CSS.overflowHidden),document.body.setAttribute(e.DATA_ATTR.scrollLocked,`true`))}unlock(){t.pa?this.unlockHard():(document.body.classList.remove(e.CSS.overflowHidden),document.body.removeAttribute(e.DATA_ATTR.scrollLocked))}lockHard(){this.scrollPosition=window.pageYOffset,document.documentElement.style.setProperty(`--window-scroll-offset`,`${this.scrollPosition}px`),document.body.classList.add(e.CSS.overflowHidden,e.CSS.fixed,e.CSS.wFull),document.body.style.top=`calc(-1 * var(--window-scroll-offset))`,document.body.setAttribute(e.DATA_ATTR.scrollLockedHard,`true`)}unlockHard(){document.body.classList.remove(e.CSS.overflowHidden,e.CSS.fixed,e.CSS.wFull),document.body.style.top=``,document.body.removeAttribute(e.DATA_ATTR.scrollLockedHard),this.scrollPosition!==null&&window.scrollTo(0,this.scrollPosition),this.scrollPosition=null}};Id=Ld,Id.CSS={overflowHidden:`overflow-hidden`,fixed:`fixed`,wFull:`w-full`},Id.DATA_ATTR={scrollLocked:`data-blok-scroll-locked`,scrollLockedHard:`data-blok-scroll-locked-hard`};var Rd={root:`flex items-center mb-2 mt-1`,text:`text-lg font-semibold text-text-primary`,backButton:`border-0 bg-transparent w-9 h-9 text-text-primary cursor-pointer outline-hidden [&_svg]:block [&_svg]:w-7 [&_svg]:h-7`},zd=class{constructor({text:e,onBackButtonClick:n}){this.listeners=new t.qi,this.text=e,this.onBackButtonClick=n,this.nodes={root:t.Qi.make(`div`,[Rd.root],{"data-blok-testid":`popover-header`,[t.Ma.popoverHeader]:``}),backButton:t.Qi.make(`button`,[Rd.backButton],{"data-blok-testid":`popover-header-back-button`,[t.Ma.popoverHeaderBackButton]:``}),text:t.Qi.make(`div`,[Rd.text],{"data-blok-testid":`popover-header-text`,[t.Ma.popoverHeaderText]:``})},this.nodes.backButton.innerHTML=t.Y,this.nodes.root.appendChild(this.nodes.backButton),this.listeners.on(this.nodes.backButton,`click`,this.onBackButtonClick),this.nodes.text.innerText=this.text,this.nodes.root.appendChild(this.nodes.text)}getElement(){return this.nodes.root}destroy(){this.nodes.root.remove(),this.listeners.destroy()}},Bd=class{constructor(){this.history=[]}push(e){this.history.push(e)}pop(){return this.history.pop()}get currentTitle(){return this.history.length===0?``:this.history[this.history.length-1].title}get currentItems(){return this.history.length===0?[]:this.history[this.history.length-1].items}reset(){for(;this.history.length>1;)this.pop()}},Vd=class extends t.w{constructor(e){super(e,{[t.ki.Default]:{hint:{enabled:!1}},[t.ki.Html]:{hint:{enabled:!1}}}),this.scrollLocker=new Ld,this.history=new Bd,this.isHidden=!0,this.nodes.overlay=t.Qi.make(`div`,[t.D.popoverOverlay],{[t.Ma.popoverOverlay]:``,[t.Ma.overlayHidden]:``,"data-blok-testid":`popover-overlay`}),this.nodes.popover.insertBefore(this.nodes.overlay,this.nodes.popover.firstChild),this.listeners.on(this.nodes.overlay,`click`,()=>{this.hide()}),this.history.push({items:e.items}),this.nodes.popoverContainer.style.setProperty(`--offset`,`5px`),this.nodes.popoverContainer.className=r.n(t.D.popoverContainer,t.D.popoverContainerMobile)}show(){this.nodes.overlay.removeAttribute(t.Ma.overlayHidden),this.nodes.overlay.className=r.n(t.D.popoverOverlay,`fixed inset-0 block visible z-3 opacity-50`),super.show(),this.nodes.popoverContainer.className=r.n(t.D.popoverContainer,t.D.popoverContainerMobile,t.D.popoverContainerOpened,`max-h-none z-4`),this.scrollLocker.lock(),this.isHidden=!1}hide(){this.isHidden||(super.hide(),this.nodes.overlay.setAttribute(t.Ma.overlayHidden,``),this.nodes.overlay.className=t.D.popoverOverlay,this.nodes.popoverContainer.className=r.n(t.D.popoverContainer,t.D.popoverContainerMobile),this.scrollLocker.unlock(),this.history.reset(),this.isHidden=!0)}destroy(){super.destroy(),this.scrollLocker.unlock()}showNestedItems(e){this.updateItemsAndHeader(e.children,e.title),this.history.push({title:e.title,items:e.children})}updateItemsAndHeader(e,t){var n,r;this.header!==null&&this.header!==void 0&&(this.header.destroy(),this.header=null);let i=t!==void 0;i&&(this.header=new zd({text:t,onBackButtonClick:()=>{this.history.pop(),this.updateItemsAndHeader(this.history.currentItems,this.history.currentTitle)}}));let a=(n=(r=this.header)==null?void 0:r.getElement())==null?null:n;i&&a!==null&&this.nodes.popoverContainer.insertBefore(a,this.nodes.popoverContainer.firstChild),this.items.forEach(e=>{var t;return(t=e.getMountElement)==null||(t=t.call(e))==null?void 0:t.remove()}),this.items=this.buildItems(e),this.items.forEach(e=>{var t,n,r;let i=(t=(n=e.getMountElement)==null?void 0:n.call(e))==null?e.getElement():t;i!==null&&((r=this.nodes.items)==null||r.appendChild(i))})}},Hd={video:{icon:t.Gn,labelKey:`tools.linkPaste.embedVideo`},audio:{icon:t.ln,labelKey:`tools.linkPaste.embedAudio`},image:{icon:t.Lt,labelKey:`tools.linkPaste.embedImage`},social:{icon:t.an,labelKey:`tools.linkPaste.embedSocial`},document:{icon:t.xt,labelKey:`tools.linkPaste.embedDocument`},table:{icon:t.Fn,labelKey:`tools.linkPaste.embedTable`},form:{icon:t.Qt,labelKey:`tools.linkPaste.embedForm`},code:{icon:t.Q,labelKey:`tools.linkPaste.embedCode`},design:{icon:t.dn,labelKey:`tools.linkPaste.embedDesign`},chart:{icon:t.K,labelKey:`tools.linkPaste.embedChart`},map:{icon:t.tn,labelKey:`tools.linkPaste.embedMap`},calendar:{icon:t.H,labelKey:`tools.linkPaste.embedCalendar`}},Ud=e=>{switch(e){case`plain`:return{labelKey:`tools.linkPaste.plain`,icon:t.qt};case`bookmark`:return{labelKey:`tools.linkPaste.bookmark`,icon:t.V};case`embed`:return{labelKey:`tools.linkPaste.embed`,icon:t.Dt};case`mention`:return{labelKey:`tools.linkPaste.mention`,icon:t.qt}}};function Wd(e,n,r,i){return e.map(({type:e})=>{let{labelKey:a,icon:o}=Ud(e),s=e===`embed`&&i!==void 0?t.$n(i):null,c=s?Hd[s.type]:null;return{name:`paste-menu-${e}`,title:c&&s?n.t(c.labelKey).replace(`{provider}`,s.title):n.t(a),icon:c?c.icon:o,closeOnActivate:!0,onActivate:()=>{r(e)}}})}function Gd(e,n){if(n.hasSelection||!t.Qn(e))return[{type:`plain`}];let r=[];return(t.$n(e)||n.allowGenericEmbed===!0)&&r.push({type:`embed`}),r.push({type:`bookmark`},{type:`mention`},{type:`plain`}),r}var Kd=new Set([`plain`,`bookmark`,`embed`]),qd=class{constructor(e){this.i18n=e,this.popover=null}open(e){this.closeExisting();let r=Gd(e.url,{hasSelection:e.hasSelection,allowGenericEmbed:e.allowGenericEmbed===!0}).filter(e=>Kd.has(e.type)),i={picked:!1,closed:!1},a=new t.C(n.t(n.t({items:Wd(r,this.i18n,t=>{i.picked=!0,e.onSelect(t)},e.url),flippable:!0},e.trigger?{trigger:e.trigger}:{}),e.position?{position:e.position}:{}));this.popover=a;let o=e=>{e.key===`Escape`&&(e.stopImmediatePropagation(),a.hide())};window.addEventListener(`keydown`,o,!0),a.on(t.T.Closed,()=>{i.closed||(i.closed=!0,window.removeEventListener(`keydown`,o,!0),this.popover===a&&(this.popover=null),i.picked||e.onDismiss(),a.destroy())}),a.show()}closeExisting(){this.popover&&this.popover.hide()}},Jd,Yd=class e extends Fd{constructor(e,t,n,r,i){super(e,t,n),this.config=r,this.menu=i==null?new qd({t:t=>e.I18n.t(t)}):i}canHandle(t){if(typeof t!=`string`)return 0;let n=t;return!n||n.length>e.PATTERN_PROCESSING_MAX_LENGTH?0:this.toolRegistry.findToolForPattern(n)?60:0}async handle(e,n){var r=this;if(typeof e!=`string`)return!1;let i=r.toolRegistry.findToolForPattern(e);if(!i)return!1;if(t.Qn(e)&&!r.hasSelection())return r.openLinkPasteMenu(e),!0;let a=r.composePasteEvent(`pattern`,{key:i.key,data:e}),o={key:i.key,data:e,tool:i.tool.name,event:a};return await r.insertPatternBlock(o,n.canReplaceCurrentBlock),!0}async insertPatternBlock(e,t){let{BlockManager:n,Caret:r}=this.Blok,i=await n.paste(e.tool,e.event,t);r.setToBlock(i,r.positions.END)}hasSelection(){let e=window.getSelection();return e!==null&&!e.isCollapsed&&e.toString().length>0}getCaretRect(){var e;let t=window.getSelection();if(t&&t.rangeCount>0){let e=t.getRangeAt(0).getBoundingClientRect();if(e.width>0||e.height>0)return e}let n=(e=this.Blok.BlockManager.currentBlock)==null?void 0:e.holder;return n?n.getBoundingClientRect():null}openLinkPasteMenu(e){var t,r,i;let a=(t=this.Blok.BlockManager.currentBlock)==null?null:t,o=this.insertPlainLink(e,a);this.menu.open(n.t(n.t({url:e,hasSelection:this.hasSelection(),allowGenericEmbed:((r=this.config)==null||(r=r.linkPaste)==null?void 0:r.allowGenericEmbed)===!0,position:(i=this.getLinkEndRect(o))==null?this.getCaretRect():i},o!=null&&o.holder?{trigger:o.holder}:{}),{},{onSelect:t=>{this.applyMenuAction(t,e,o)},onDismiss:()=>{}}))}getLinkEndRect(e){var t;let n=e==null||(t=e.holder)==null?void 0:t.querySelector(`a`);if(!n)return null;let r=n.getClientRects(),i=r.length>0?r[r.length-1]:n.getBoundingClientRect();return i.width===0&&i.height===0?null:new DOMRect(i.right,i.top,0,i.height)}restoreTarget(e){e!=null&&e.holder&&this.Blok.BlockManager.setCurrentBlockByChildNode(e.holder)}async applyMenuAction(e,t,n){var r=this;switch(e){case`bookmark`:case`embed`:r.restoreTarget(n),await r.insertForcedPatternBlock(e,t,!0);break;case`plain`:break;case`mention`:break}}async insertForcedPatternBlock(e,t,n){var r=this;let i=r.composePasteEvent(`pattern`,{key:e,data:t});await r.insertPatternBlock({key:e,data:t,tool:e,event:i},n)}insertPlainLink(e,t){this.restoreTarget(t);let n=document.createElement(`a`);return n.href=e,n.target=`_blank`,n.rel=`nofollow`,n.textContent=e,this.Blok.BlockManager.insert({data:{text:n.outerHTML},replace:!0,needToFocus:!0})}};Jd=Yd,Jd.PATTERN_PROCESSING_MAX_LENGTH=450;var Xd=class extends Fd{constructor(e,t,n,r){super(e,t,n),this.config=r}canHandle(e){if(typeof e!=`string`)return 0;try{return JSON.parse(e),100}catch(e){return 0}}async handle(e,t){var n=this;if(typeof e!=`string`)return!1;let r=JSON.parse(e),i=n.toolRegistry.toolsPatterns.length>0,a=t.plainData;if(!i||!a)return n.insertBlokBlocks(r,t.canReplaceCurrentBlock),!0;let o=await n.tryPatternMatch(a);return o?(await n.insertPatternMatch(o,t.canReplaceCurrentBlock),!0):(n.insertBlokBlocks(r,t.canReplaceCurrentBlock),!0)}async tryPatternMatch(e){var t=this;if(t.patternHandler||(t.patternHandler=new Yd(t.Blok,t.toolRegistry,t.sanitizerBuilder)),e.length>Yd.PATTERN_PROCESSING_MAX_LENGTH)return;let n=t.toolRegistry.findToolForPattern(e);if(!n)return;let r=t.composePasteEvent(`pattern`,{key:n.key,data:e});return{key:n.key,data:e,tool:n.tool.name,event:r}}async insertPatternMatch(e,t){let{BlockManager:n,Caret:r}=this.Blok,i=await n.paste(e.tool,e.event,t);r.setToBlock(i,r.positions.END)}insertBlokBlocks(e,n){var r,i,a,o,s,c,l;let{BlockManager:u,Caret:d,Tools:f}=this.Blok,p=$d(e),m=t.Oi(p,e=>{var t,n;return(t=(n=f.blockTools.get(e))==null?void 0:n.sanitizeConfig)==null?{}:t},this.config.sanitizer),h=n&&!!((r=u.currentBlock)!=null&&r.tool.isDefault)&&!!((i=u.currentBlock)!=null&&i.isEmpty),g=u.currentBlock,_=(a=g==null||(o=g.holder)==null?void 0:o.querySelector(`[data-blok-toggle-children]`))==null?null:a,v=_!==null&&!_.contains((s=g==null?void 0:g.currentInput)==null?null:s)?(c=g==null?void 0:g.id)==null?null:c:(l=g==null?void 0:g.parentId)==null?null:l,y=new Set(p.filter(e=>e.tool===`table`&&e.id!==void 0).map(e=>e.id)),b=e=>e.parentId!==void 0&&e.parentId!==null&&y.has(e.parentId),x=[],ee=[];m.forEach((e,t)=>{let n=p[t];n!==void 0&&(b(n)?x:ee).push({sanitized:e,original:n})});let S=new Map,C=()=>{x.forEach(({sanitized:e,original:t})=>{let n=u.insert({tool:e.tool,data:e.data});S.set(t.id,{newBlock:n,original:t}),d.setToBlock(n,d.positions.END)});let e=new Map;for(let[t,{newBlock:n}]of S)e.set(t,n.id);ee.forEach(({sanitized:t,original:n},r)=>{let i=e.size>0?ef(t.data,e):t.data,a=u.insert({tool:t.tool,data:i,replace:r===0&&h&&x.length===0});v!==null&&(n.parentId===void 0||n.parentId===null)&&u.setBlockParent(a,v),S.set(n.id,{newBlock:a,original:n}),d.setToBlock(a,d.positions.END)});for(let[,{newBlock:e,original:t}]of S){if(t.parentId===void 0||t.parentId===null)continue;let n=S.get(t.parentId);n!==void 0&&u.setBlockParent(e,n.newBlock.id)}};typeof u.transactForTool==`function`?u.transactForTool(C):C()}};function Zd(e,t,n){typeof e!=`object`||!e||!Array.isArray(e.blocks)||e.blocks.forEach(e=>{typeof e==`string`&&!n.has(e)&&n.set(e,t)})}function Qd(e,t){if(e.tool!==`table`||e.id===void 0)return;let n=e.data,r=n==null?void 0:n.content;if(!Array.isArray(r))return;let i=e.id;r.forEach(e=>{Array.isArray(e)&&e.forEach(e=>Zd(e,i,t))})}function $d(e){let t=new Map;return e.forEach(e=>Qd(e,t)),t.size===0?e:e.map(e=>{if(e.id===void 0)return e;let r=t.get(e.id);return r===void 0||e.parentId!==void 0&&e.parentId!==null?e:n.t(n.t({},e),{},{parentId:r})})}function ef(e,t){if(typeof e==`string`){var n;return(n=t.get(e))==null?e:n}if(Array.isArray(e))return e.map(e=>ef(e,t));if(typeof e==`object`&&e){let n={};for(let[r,i]of Object.entries(e))n[r]=ef(i,t);return n}return e}var tf=e=>typeof e==`object`&&!!e&&`files`in e&&`types`in e&&`getData`in e&&`setData`in e,nf=class extends Fd{constructor(e,t,n){super(e,t,n)}canHandle(e){return tf(e)&&this.containsFiles(e)?80:0}async handle(e,t){var n=this;if(!tf(e)||!n.containsFiles(e))return!1;let r=n.extractFiles(e);return r.length===0?!1:(await n.processFiles(r),!0)}extractFiles(e){return e.files&&e.files.length>0?Array.from(e.files):this.extractFilesFromItems(e.items)}extractFilesFromItems(e){return e?Array.from(e).filter(e=>e.kind===`file`).map(e=>e.getAsFile()).filter(e=>e!==null):[]}containsFiles(e){var t;if(Array.from(e.types).includes(`Files`)||(t=e.files)!=null&&t.length||this.itemsContainFile(e.items))return!0;try{let t=e.types;if(typeof(t==null?void 0:t.contains)==`function`&&t.contains(`Files`))return!0}catch(e){}return!1}itemsContainFile(e){return e?Array.from(e).some(e=>e.kind===`file`):!1}async processFiles(e){var t=this,n;let{BlockManager:r}=t.Blok,i=(await Promise.all(Array.from(e).map(e=>t.processFile(e)))).filter(e=>e!=null);if(i.length===0)return;let a=t.shouldReplaceCurrentBlock((n=i[0])==null?void 0:n.type);for(let[e,t]of i.entries())await r.paste(t.type,t.event,e===0&&a)}async processFile(e){var t=this,n;let r=(n=t.Blok.BlockManager.currentBlock)==null?void 0:n.name,i=t.toolRegistry.findToolForFile(e,r);if(i)return{event:t.composePasteEvent(`file`,{file:e}),type:i}}},rf=class extends Fd{constructor(e,t,n){super(e,t,n)}canHandle(e){return typeof e!=`string`||!e.trim()||!t.Qi.isHTMLString(e)?0:40}async handle(e,t){var n=this;if(typeof e!=`string`)return!1;let r=n.processHTML(e);return r.length?(await n.insertPasteData(r,t.canReplaceCurrentBlock),!0):!1}processHTML(e){let{Tools:r}=this.Blok,i=t.Qi.make(`DIV`);i.innerHTML=e;let a=this.getNodes(i),o=[];for(let e of a){let t=e.nodeType===Node.ELEMENT_NODE&&e.tagName===`DETAILS`,n=e.nodeType===Node.ELEMENT_NODE&&e.tagName===`ASIDE`;if(!t&&!n){o.push({node:e});continue}let r=o.length;o.push({node:e});let i=Array.from(e.children).filter(e=>n||e.tagName!==`SUMMARY`);for(let e of i)o.push({node:e,parentExpandedIndex:r})}let s=o.map(({node:e,parentExpandedIndex:i},a)=>{let o=(()=>{switch(e.nodeType){case Node.DOCUMENT_FRAGMENT_NODE:{let n=t.Qi.make(`div`);return n.appendChild(e),{content:n,tool:r.defaultTool,isBlock:!1}}case Node.ELEMENT_NODE:{var n,i;let t=e,a=(n=this.toolRegistry.findToolForTag(t.tagName))==null?void 0:n;return{content:t,tool:(i=a==null?void 0:a.tool)==null?r.defaultTool:i,isBlock:!0}}default:return null}})();if(!o)return null;let{content:s,tool:c,isBlock:l}=o,u=this.buildToolTags(c),d=n.t(n.t(n.t(n.t({},this.sanitizerBuilder.getStructuralTagsConfig(s)),u),c.baseSanitizeConfig),{},{br:{}}),f=this.sanitizeContent(s,d);if(!f)return null;let p=this.composePasteEvent(`tag`,{data:f});return{data:{content:f,isBlock:l,tool:c.name,event:p,parentPasteIndex:i},originalIndex:a}}),c=new Map,l=[];for(let e of s){if(!e)continue;let{data:n,originalIndex:r}=e,i=t.Qi.isEmpty(n.content),a=t.Qi.isSingleTag(n.content);(!i||a)&&(c.set(r,l.length),l.push(n))}for(let e of l)e.parentPasteIndex!==void 0&&(e.parentPasteIndex=c.get(e.parentPasteIndex));return l}buildToolTags(e){var r;return e.pasteConfig===!1?{}:(((r=e.pasteConfig)==null?void 0:r.tags)||[]).reduce((e,r)=>{let i=Cu(r),a=n.t({},e);return i.forEach(e=>{let n=t.Sa(r)?r[e]:null;a[e.toLowerCase()]=n==null?{}:n}),a},{})}sanitizeContent(e,n){if(e.tagName.toLowerCase()!==`table`){let r=e.cloneNode(!0);return r.innerHTML=t.Ei(e.innerHTML,n),r}return this.sanitizerBuilder.sanitizeTable(e,n)}processElementNode(e,n,r){let i=Object.keys(this.toolRegistry.toolsTags),a=e,o=this.toolRegistry.findToolForTag(a.tagName),s=o==null?void 0:o.tool,c=s?this.toolRegistry.getToolTags(s.name):[],l=i.includes(a.tagName);if(l&&(a.tagName===`DETAILS`||a.tagName===`ASIDE`))return[...n,r,a];let u=t.Qi.blockElements.includes(a.tagName.toLowerCase()),d=Su.has(a.tagName.toLowerCase()),f=Array.from(a.children).some(({tagName:e})=>i.includes(e)&&!c.includes(e)),p=Array.from(a.children).some(({tagName:e})=>t.Qi.blockElements.includes(e.toLowerCase()));if(!u&&!l&&!f)return r.appendChild(a),[...n,r];if(l&&!f||u&&!p&&!f||d&&!f)return[...n,r,a]}getNodes(e){let n=Array.from(e.childNodes),r=(e,n)=>{if(t.Qi.isEmpty(n)&&!t.Qi.isSingleTag(n))return e;let i=e[e.length-1],{destNode:a,remainingNodes:o}=i!==void 0&&t.Qi.isFragment(i)?{destNode:i,remainingNodes:e.slice(0,-1)}:{destNode:new DocumentFragment,remainingNodes:e};if(n.nodeType===Node.TEXT_NODE)return a.appendChild(n),[...o,a];if(n.nodeType!==Node.ELEMENT_NODE)return[...o,a];let s=this.processElementNode(n,o,a);if(s)return s;let c=Array.from(n.childNodes).reduce(r,[]);return[...o,...c]};return n.reduce(r,[])}},af=[/^#{1,6}\s/m,/^```/m,/\|\s*---/,/^- \[[ x]\]/m,/\[.+?\]\(.+?\)/,/\*\*.+?\*\*/,/!\[/,/\$\$[\s\S]+?\$\$/,RegExp(`(?<!\\$)\\$(?!\\$)(?=\\S)[^$]+(?<=\\S)\\$(?!\\$)`,``)];function of(e){return e?af.some(t=>t.test(e)):!1}var sf=class extends Fd{constructor(e,t,n){super(e,t,n)}canHandle(e){return typeof e!=`string`||!e.trim()?0:of(e)?30:0}async handle(e,t){var n=this;if(typeof e!=`string`)return!1;let{markdownToBlocks:r}=await Promise.resolve().then(()=>require(`../markdown.cjs`)),i=await r(e);if(!i.length)return!1;let a=xt(i),{BlockManager:o,Caret:s}=n.Blok,c=o.currentBlock,l=t.canReplaceCurrentBlock&&c!==void 0&&c.isEmpty,u=l?o.currentBlockIndex:o.currentBlockIndex+1,d=a.map(({id:e,type:t,data:n,parent:r})=>o.composeBlock({id:e,tool:t,data:n,parentId:r}));o.insertMany(d,u),l&&c!==void 0&&await o.removeBlock(c,!1);let f=d[d.length-1];return f instanceof ne&&s.setToBlock(f,s.positions.END),!0}},cf=class extends Fd{constructor(e,t,n){super(e,t,n)}canHandle(e){return typeof e==`string`?t.b(e)===null?0:90:0}async handle(e,n){var r=this,i,a;if(typeof e!=`string`)return!1;let o=t.b(e);if(!o)return!1;let s=document.activeElement;if(s!=null&&s.closest(`[data-blok-table-cell]`)||!((i=n.currentBlock)==null||(i=i.holder)==null)&&i.closest(`[data-blok-table-cell-blocks]`)||(a=n.pasteTarget)!=null&&a.closest(`[data-blok-table-cell]`))return!1;let{BlockManager:c,Caret:l}=r.Blok,u={withHeadings:!1,withHeadingColumn:!1,content:o.cells.map(e=>e.map(e=>{let t=e.blocks.length===0?``:e.blocks.map(e=>typeof e.data.text==`string`?e.data.text:``).join(` `),n=e.color!==void 0,r=e.textColor!==void 0;if(!n&&!r)return t;let i={blocks:[],text:t};return n&&(i.color=e.color),r&&(i.textColor=e.textColor),i}))},d=n.canReplaceCurrentBlock,f=c.insert({tool:`table`,data:u,replace:d});return l.setToBlock(f,l.positions.END),!0}},lf=class extends Fd{constructor(e,t,n,r){super(e,t,n),this.config=r}canHandle(e){return typeof e==`string`&&e.length>0?10:0}async handle(e,t){var n=this;if(typeof e!=`string`)return!1;let r=n.processPlain(e);return r.length?(await n.insertPasteData(r,t.canReplaceCurrentBlock),!0):!1}processPlain(e){let{defaultBlock:n}=this.config;return!e||!n?[]:e.split(/\r?\n/).filter(e=>e.trim()).map(e=>{let r=t.Qi.make(`div`);return r.textContent=e,{content:r,tool:n,isBlock:!1,event:this.composePasteEvent(`tag`,{data:r})}})}},uf=class{constructor(e,t){this.tools=e,this.config=t}buildToolsTagsConfig(e){return Object.fromEntries(Object.keys(e).map(t=>{var n;return[t.toLowerCase(),(n=e[t].sanitizationConfig)==null?{}:n]}))}getStructuralTagsConfig(e){let t={},n=[e];for(;n.length>0;){let e=n.pop();if(!e)continue;let i=e.tagName.toLowerCase();if(Su.has(i)){var r;t[i]=(r=t[i])==null?{}:r}n.push(...Array.from(e.children))}return t}buildToolConfig(e){var n;if(e.pasteConfig===!1)return{};let r=((n=e.pasteConfig)==null?void 0:n.tags)||[],i={};return r.forEach(e=>{Cu(e).forEach(n=>{let r=t.Sa(e)?e[n]:null;i[n.toLowerCase()]=r==null?{}:r})}),i}composeConfigs(...e){return t.Di({},...e)}sanitizeTable(e,r){let i=n.t(n.t({},r),{},{img:{src:!0,alt:!0,width:!0,height:!0}}),a=t.Ei(e.outerHTML,i),o=document.createElement(`div`);o.innerHTML=a;let s=o.firstChild;return!s||!(s instanceof HTMLElement)?null:s}isStructuralTag(e){return Su.has(e.toLowerCase())}},df=class{constructor(e,n){this.tools=e,this.config=n,this.toolsTags={},this.tagsByTool={},this.toolsPatterns=[],this.toolsFiles={},this.exceptionList=[],this.processTool=e=>{try{if(e.pasteConfig===!1){this.exceptionList.push(e.name);return}if(!e.hasOnPasteHandler)return;this.getTagsConfig(e),this.getFilesConfig(e),this.getPatternsConfig(e)}catch(n){t.Ea(`Paste handling for «${e.name}» Tool hasn't been set up because of the error`,`warn`,n)}}}async processTools(){var e=this;let t=e.tools;await Array.from(t.values()).forEach(e.processTool)}getTagsConfig(e){if(e.pasteConfig===!1)return;let n=e.pasteConfig.tags||[],r=[];n.forEach(n=>{let i=Cu(n);r.push(...i),i.forEach(r=>{if(Object.prototype.hasOwnProperty.call(this.toolsTags,r)){t.Ea(`Paste handler for «${e.name}» Tool on «${r}» tag is skipped because it is already used by «${this.toolsTags[r].tool.name}» Tool.`,`warn`);return}let i=t.Sa(n)?n[r]:void 0;this.toolsTags[r.toUpperCase()]={tool:e,sanitizationConfig:i}})}),this.tagsByTool[e.name]=r.map(e=>e.toUpperCase())}getFilesConfig(e){if(e.pasteConfig===!1)return;let{files:n={}}=e.pasteConfig,{extensions:r,mimeTypes:i}=n;if(!r&&!i)return;let a=r==null?[]:Array.isArray(r)?r:(t.Ea(`«extensions» property of the paste config for «${e.name}» Tool should be an array`),[]),o=i==null?[]:Array.isArray(i)?i.filter(n=>t.ha(n)?!0:(t.Ea(`MIME type value «${n}» for the «${e.name}» Tool is not a valid MIME type`,`warn`),!1)):(t.Ea(`«mimeTypes» property of the paste config for «${e.name}» Tool should be an array`),[]);this.toolsFiles[e.name]={extensions:a,mimeTypes:o}}getPatternsConfig(e){if(e.pasteConfig===!1||!e.pasteConfig.patterns)return;let n=e.pasteConfig.patterns;Object.keys(n).length!==0&&Object.entries(n).forEach(([n,r])=>{r instanceof RegExp||t.Ea(`Pattern ${r} for «${e.name}» Tool is skipped because it should be a Regexp instance.`,`warn`),this.toolsPatterns.push({key:n,pattern:r,tool:e})})}findToolForTag(e){return this.toolsTags[e]}findToolForFile(e,t){var n,r;let i=(n=(r=e.name.split(`.`).pop())==null?void 0:r.toLowerCase())==null?``:n,a=t=>{let[n,r]=e.type.split(`/`),a=t.extensions.find(e=>e.toLowerCase()===i),o=t.mimeTypes.find(e=>{let[t,i]=e.split(`/`);return t===n&&(i===r||i===`*`)});return a!==void 0||o!==void 0};if(t!==void 0){let e=this.toolsFiles[t];if(e!==void 0&&a(e))return t}let o=Object.entries(this.toolsFiles).find(([,e])=>a(e));return o==null?void 0:o[0]}findToolForPattern(e){return this.toolsPatterns.find(t=>{let n=t.pattern.exec(e);return n?e===n.shift():!1})}getToolTags(e){var t;return(t=this.tagsByTool[e])==null?[]:t}isException(e){return this.exceptionList.includes(e)}},ff,pf=class extends s{constructor(...e){var t;super(...e),t=this,this.MIME_TYPE=`application/x-blok`,this.handlePasteEventWrapper=e=>{this.handlePasteEvent(e)},this.handleDropEventWrapper=e=>{this.handleDropEvent(e)},this.handleDragOverEventWrapper=e=>{this.handleDragOverEvent(e)},this.handleDragLeaveEventWrapper=e=>{this.handleDragLeaveEvent(e)},this.dropIndicatorHolder=null,this.handleDragOverEvent=e=>{let{dataTransfer:t}=e;this.dataTransferHasFiles(t)&&(e.preventDefault(),t&&(t.dropEffect=`copy`),this.updateDropIndicator(e))},this.handleDragLeaveEvent=e=>{let t=this.Blok.UI.nodes.holder,n=e.relatedTarget;n&&t.contains(n)||this.clearDropIndicator()},this.handleDropEvent=async e=>{var n;if(t.clearDropIndicator(),(n=t.Blok.DragManager)!=null&&n.isDragging||!t.dataTransferHasFiles(e.dataTransfer))return;e.preventDefault();let{BlockManager:r,Toolbar:i}=t.Blok,a=r.setCurrentBlockByChildNode(e.target);if(a&&!t.toolRegistry.isException(a.name)){if(e.dataTransfer){let n=e.target instanceof Element?e.target:void 0;await t.processDataTransfer(e.dataTransfer,n)}i.moveAndOpen()}},this.handlePasteEvent=async e=>{var n;if(e.defaultPrevented)return;if((n=t.Blok.DragManager)!=null&&n.isDragging){e.preventDefault();return}let{BlockManager:r,Toolbar:i}=t.Blok,a=r.setCurrentBlockByChildNode(e.target);if(!(!a||e.target&&t.isNativeBehaviour(e.target)&&e.clipboardData&&!e.clipboardData.types.includes(`Files`))&&!t.toolRegistry.isException(a.name)){if(e.preventDefault(),e.clipboardData){let n=e.target instanceof Element?e.target:void 0;await t.processDataTransfer(e.clipboardData,n)}i.moveAndOpen()}}}async prepare(){var e=this;let{Tools:t}=e.Blok;e.toolRegistry=new df(t.blockTools,e.config),e.sanitizerBuilder=new uf(t.blockTools,e.config),await e.toolRegistry.processTools(),e.handlers=[new Xd(e.Blok,e.toolRegistry,e.sanitizerBuilder,e.config),new cf(e.Blok,e.toolRegistry,e.sanitizerBuilder),new nf(e.Blok,e.toolRegistry,e.sanitizerBuilder),new Yd(e.Blok,e.toolRegistry,e.sanitizerBuilder,e.config),new rf(e.Blok,e.toolRegistry,e.sanitizerBuilder),new sf(e.Blok,e.toolRegistry,e.sanitizerBuilder),new lf(e.Blok,e.toolRegistry,e.sanitizerBuilder,e.config)]}async processText(e,t=!1){var n=this;let{BlockManager:r}=n.Blok,i=r.currentBlock,a=!!(i&&i.tool.isDefault&&i.isEmpty),o=t?n.handlers.find(e=>e instanceof rf):n.handlers.find(e=>e instanceof lf);if(!o)return;let s={canReplaceCurrentBlock:a,currentBlock:i==null?void 0:i};await o.handle(e,s)}toggleReadOnly(e){e?this.unsetCallback():this.setCallback()}async processDataTransfer(e,t){var n=this,r;let i=e.getData(`text/plain`),a=e.getData(`text/html`),o=a&&n.config.onBeforePaste?(r=n.config.onBeforePaste(a))==null?``:r:a,s=e.getData(n.MIME_TYPE)||n.readNotionBlocksV3(e)||n.readNextSpaceBlocks(e);await n.routeToHandlers(e,i,o,s,t)||await n.processAsText(i)}readNotionBlocksV3(e){let t=e.getData(Ou);if(!t)return``;let n=ku(t);return n===null||n.length===0?``:JSON.stringify(n)}readNextSpaceBlocks(e){for(let t of md){let n=e.getData(t);if(!n)continue;let r=hd(n);if(r!==null&&r.length>0)return JSON.stringify(r)}return``}async routeToHandlers(e,t,n,r,i){var a=this,o;let{BlockManager:s}=a.Blok,c=s.currentBlock,l={canReplaceCurrentBlock:!!(c&&c.tool.isDefault&&c.isEmpty&&!((o=c.holder)!=null&&o.closest(`[data-blok-table-cell-blocks]`))),currentBlock:c==null?void 0:c,plainData:t,pasteTarget:i};for(let i of a.handlers){let o=a.getDataForHandler(i,e,t,n,r);if(o!==void 0&&i.canHandle(o)!==0&&await i.handle(o,l))return!0}return!1}getDataForHandler(e,n,r,i,a){if(e instanceof Xd)return a;if(e instanceof cf)return i;if(e instanceof nf)return n;if(e instanceof Yd||e instanceof sf||e instanceof lf)return r;if(!(e instanceof rf))return;let o=this.sanitizerBuilder.buildToolsTagsConfig(this.toolRegistry.toolsTags),s=this.Blok.Tools.getAllInlineToolsSanitizeConfig(),c=Object.fromEntries([...Su].map(e=>[e,{}])),l=t.Di(this.config.sanitizer,c,o,s,{br:{}}),u=t.Ei(wu(t.Zr(i)),l),d=t.Qi.isHTMLString(u);return!u.trim()||u.trim()===r||!d?void 0:u}async processAsText(e){var t=this;let{BlockManager:n}=t.Blok;if(!e)return;let r=n.currentBlock,i=!!(r&&r.tool.isDefault&&r.isEmpty),a=t.handlers.find(e=>e instanceof lf);a&&await a.handle(e,{canReplaceCurrentBlock:i,currentBlock:r==null?void 0:r})}setCallback(){let e=this.Blok.UI.nodes.holder;this.listeners.on(e,`paste`,this.handlePasteEventWrapper),this.listeners.on(e,`drop`,this.handleDropEventWrapper),this.listeners.on(e,`dragover`,this.handleDragOverEventWrapper),this.listeners.on(e,`dragleave`,this.handleDragLeaveEventWrapper)}unsetCallback(){let e=this.Blok.UI.nodes.holder;this.listeners.off(e,`paste`,this.handlePasteEventWrapper),this.listeners.off(e,`drop`,this.handleDropEventWrapper),this.listeners.off(e,`dragover`,this.handleDragOverEventWrapper),this.listeners.off(e,`dragleave`,this.handleDragLeaveEventWrapper)}dataTransferHasFiles(e){var t,n;return e?Array.from((t=e.types)==null?[]:t).includes(`Files`)?!0:!!((n=e.files)!=null&&n.length):!1}updateDropIndicator(e){let t=e.target instanceof Element?e.target:null,n=t==null?void 0:t.closest(`[data-blok-element]`);if(!(n instanceof HTMLElement)){this.clearDropIndicator();return}let r=n.getBoundingClientRect(),i=e.clientY<r.top+r.height/2?`top`:`bottom`;this.dropIndicatorHolder&&this.dropIndicatorHolder!==n&&(this.dropIndicatorHolder.removeAttribute(`data-drop-indicator`),this.dropIndicatorHolder.style.removeProperty(`--drop-indicator-depth`)),n.setAttribute(`data-drop-indicator`,i),n.style.setProperty(`--drop-indicator-depth`,String(this.computeDropDepth(n))),this.dropIndicatorHolder=n}computeDropDepth(e){var t,n;let r=(t=e.parentElement)!=null&&t.closest(`[data-blok-element]`)?this.countAncestorBlocks(e):0,i=e.querySelector(`[data-list-depth]`),a=(n=i==null?void 0:i.getAttribute(`data-list-depth`))==null?`0`:n,o=Number.parseInt(a,10);return r+(Number.isNaN(o)?0:o)}countAncestorBlocks(e){var t;let n=(t=e.parentElement)==null?void 0:t.closest(`[data-blok-element]`);return n?1+this.countAncestorBlocks(n):0}clearDropIndicator(){this.dropIndicatorHolder&&(this.dropIndicatorHolder.removeAttribute(`data-drop-indicator`),this.dropIndicatorHolder.style.removeProperty(`--drop-indicator-depth`),this.dropIndicatorHolder=null)}isNativeBehaviour(e){return t.Qi.isNativeInput(e)||e instanceof HTMLElement&&(e.contentEditable===`plaintext-only`||e.getAttribute(`contenteditable`)===`plaintext-only`)}};ff=pf,ff.PATTERN_PROCESSING_MAX_LENGTH=450;var mf=class extends s{constructor(...e){super(...e),this.toolsDontSupportReadOnly=[],this.toolsDontSupportInPlaceToggle=[],this.readOnlyEnabled=!1,this.inPlaceToggleChecked=!1}get isEnabled(){return this.readOnlyEnabled}get supportsInPlaceToggle(){return this.inPlaceToggleChecked&&this.toolsDontSupportInPlaceToggle.length===0}async prepare(){var e=this;let{Tools:t}=e.Blok,{blockTools:n}=t,r=[];Array.from(n.entries()).forEach(([t,n])=>{n.isReadOnlySupported||r.push(t),n.supportsInPlaceReadOnly||e.toolsDontSupportInPlaceToggle.push(t)}),e.toolsDontSupportReadOnly=r,e.inPlaceToggleChecked=!0,e.config.readOnly===!0&&r.length>0&&e.throwCriticalError(),await e.toggle(e.config.readOnly,!0)}async toggle(e=!this.readOnlyEnabled,t=!1){var n=this;e&&n.toolsDontSupportReadOnly.length>0&&n.throwCriticalError();let r=n.readOnlyEnabled;n.readOnlyEnabled=e;for(let t of Object.values(n.Blok))t!=null&&typeof t.toggleReadOnly==`function`&&t.toggleReadOnly(e);if(r===e||t)return n.readOnlyEnabled;if(n.supportsInPlaceToggle){var i;n.Blok.ModificationsObserver.disable();let t=(i=n.Blok.BlockManager.blocks)==null?[]:i;for(let n of t)n.setReadOnly(e);return n.Blok.ModificationsObserver.enable(),n.readOnlyEnabled}n.Blok.ModificationsObserver.disable();let a=await n.Blok.Saver.save();if(a===void 0)return n.Blok.ModificationsObserver.enable(),n.readOnlyEnabled;let o=window.scrollY;n.Blok.Renderer.markRenderStart();try{await n.Blok.BlockManager.clear(),await n.Blok.Renderer.render(a.blocks)}finally{n.Blok.Renderer.markRenderEnd()}return window.scrollY!==o&&window.scrollTo(0,o),n.Blok.ModificationsObserver.enable(),n.readOnlyEnabled}async set(e){return this.toggle(e)}throwCriticalError(){throw new o(`To enable read-only mode all connected tools should support it. Tools ${this.toolsDontSupportReadOnly.join(`, `)} don't support read-only mode.`)}},hf=class extends s{constructor(...e){super(...e),this.isRectSelectionActivated=!1,this.SCROLL_SPEED=3,this.HEIGHT_OF_SCROLL_ZONE=40,this.BOTTOM_SCROLL_ZONE=1,this.TOP_SCROLL_ZONE=2,this.MAIN_MOUSE_BUTTON=0,this.mousedown=!1,this.mouseDownWithinBoundsFromContentEditable=!1,this.pendingToolbarClose=!1,this.isScrolling=!1,this.inScrollZone=null,this.startX=0,this.startY=0,this.mouseX=0,this.mouseY=0,this.stackOfSelected=[],this.rectCrossesBlocks=!1,this.anchorBlockIndex=null,this.overlayRectangle=null,this.listenerIds=[]}static get CSS(){return{overlay:``,overlayContainer:``,rect:``,topScrollZone:``,bottomScrollZone:``}}prepare(){this.enableModuleBindings()}startSelection(e,n,r=!1){let{UI:i}=this.Blok,a=i.nodes.redactor;if(!a)return;let o=a.getBoundingClientRect(),s=n-this.getScrollTop();if(!(s>=o.top&&s<=o.bottom))return;let c=this.getScrollLeft(),l=e-c,u=this.Blok.UI.contentRect,d=l>=u.left&&l<=u.right,f=document.elementFromPoint(e-c,s);f&&(!f.closest(t.Na(t.Ma.toolbar))&&!r&&(this.Blok.BlockSelection.allBlocksSelected=!1,this.Blok.BlockSelection.disableNavigationMode(),this.clearSelection(),this.stackOfSelected=[],this.anchorBlockIndex=null),![t.Na(t.Ma.elementContent),t.Na(t.Ma.settingsToggler),t.Na(t.Ma.popover),`[data-blok-interface=inline-toolbar]`].some(e=>!!f.closest(e))&&(d&&(this.pendingToolbarClose=!0),this.mousedown=!0,this.startX=e,this.startY=n))}endSelection(){this.mousedown=!1,this.mouseDownWithinBoundsFromContentEditable=!1,this.pendingToolbarClose=!1,this.startX=0,this.startY=0,this.anchorBlockIndex=null,this.stackOfSelected=[],this.overlayRectangle!==null&&(this.overlayRectangle.style.display=`none`)}isRectActivated(){return this.isRectSelectionActivated||this.mousedown}get isMouseDownWithinBounds(){return this.mouseDownWithinBoundsFromContentEditable}clearSelection(){this.isRectSelectionActivated=!1}cancelActiveSelection(){!this.mousedown&&!this.isRectSelectionActivated||(this.clearSelection(),this.endSelection())}enableModuleBindings(){this.genHTML(),this.listeners.on(document.body,`mousedown`,e=>{this.processMouseDown(e)},!1);let e=t.ya(e=>{e instanceof MouseEvent&&this.processMouseMove(e)},10);this.listeners.on(document.body,`mousemove`,e,{passive:!0}),this.listeners.on(document.body,`mouseleave`,()=>{this.processMouseLeave()});let n=t.ya(e=>{this.processScroll(e)},10);this.listeners.on(window,`scroll`,n,{passive:!0}),this.listeners.on(document,`mouseup`,()=>{this.processMouseUp()},!1)}processMouseDown(e){if(e.button!==this.MAIN_MOUSE_BUTTON)return;if(e.target.closest(t.Qi.allInputsSelector)===null){this.startSelection(e.pageX,e.pageY,e.shiftKey);return}let n=this.getScrollLeft(),r=e.pageX-n,i=this.Blok.UI.contentRect;r>=i.left&&r<=i.right&&(this.mouseDownWithinBoundsFromContentEditable=!0)}processMouseMove(e){this.mouseDownWithinBoundsFromContentEditable&&this.Blok.Toolbar.close(),this.pendingToolbarClose&&(this.pendingToolbarClose=!1,this.Blok.Toolbar.close()),this.changingRectangle(e),this.scrollByZones(e.clientY)}processMouseLeave(){this.clearSelection(),this.endSelection()}processScroll(e){this.changingRectangle(e)}processMouseUp(){this.Blok.BlockSelection.selectedBlocks.length>1&&this.Blok.Toolbar.moveAndOpenForMultipleBlocks(),this.clearSelection(),this.endSelection()}scrollByZones(e){if(this.inScrollZone=null,e<=this.HEIGHT_OF_SCROLL_ZONE&&(this.inScrollZone=this.TOP_SCROLL_ZONE),document.documentElement.clientHeight-e<=this.HEIGHT_OF_SCROLL_ZONE&&(this.inScrollZone=this.BOTTOM_SCROLL_ZONE),!this.inScrollZone){this.isScrolling=!1;return}this.isScrolling||(this.scrollVertical(this.inScrollZone===this.TOP_SCROLL_ZONE?-this.SCROLL_SPEED:this.SCROLL_SPEED),this.isScrolling=!0)}genHTML(){let{UI:e}=this.Blok,n=e.nodes.holder.querySelector(t.Na(t.Ma.editor)),r=t.Qi.make(`div`,[`fixed`,`inset-0`,`z-overlay`,`pointer-events-none`,`overflow-hidden`],{}),i=t.Qi.make(`div`,[`relative`,`pointer-events-auto`,`z-0`],{}),a=t.Qi.make(`div`,[`absolute`,`pointer-events-none`,`bg-selection-highlight`,`border`,`border-transparent`],{});if(r.setAttribute(t.Ma.overlay,``),i.setAttribute(t.Ma.overlayContainer,``),a.setAttribute(t.Ma.overlayRectangle,``),r.setAttribute(`data-blok-testid`,`overlay`),a.setAttribute(`data-blok-testid`,`overlay-rectangle`),!n)throw Error(`RectangleSelection: blok wrapper not found`);return i.appendChild(a),r.appendChild(i),n.appendChild(r),this.overlayRectangle=a,{container:n,overlay:r}}scrollVertical(e){if(!(this.inScrollZone&&this.mousedown))return;let t=this.getScrollTop();window.scrollBy(0,e),this.mouseY+=this.getScrollTop()-t,setTimeout(()=>{this.scrollVertical(e)},0)}changingRectangle(e){if(!this.mousedown)return;let n=this.overlayRectangle;if(n===null)return;e.pageY!==void 0&&(this.mouseX=e.pageX,this.mouseY=e.pageY),this.isRectSelectionActivated||(this.isRectSelectionActivated=!0,this.shrinkRectangleToPoint(),n.style.display=`block`);let{index:r}=this.genInfoForMouseSelection();this.rectCrossesBlocks=!1;let i=r===void 0?void 0:this.Blok.BlockManager.getBlockByIndex(r),a=i===void 0?void 0:this.Blok.BlockManager.resolveToRootBlock(i);if(a){let e=a.holder.getBoundingClientRect(),t=this.getScrollLeft(),n=Math.min(this.startX,this.mouseX),r=Math.max(this.startX,this.mouseX),i=e.left+t,o=e.right+t;this.rectCrossesBlocks=r>=i&&n<=o}if(this.updateRectangleSize(),this.Blok.Toolbar.close(),r===void 0)return;this.trySelectNextBlock(r),this.inverseSelection();let o=t.Ai.get();o&&o.removeAllRanges()}shrinkRectangleToPoint(){if(this.overlayRectangle===null)return;let e=this.getScrollLeft(),t=this.getScrollTop();this.overlayRectangle.style.left=`${this.startX-e}px`,this.overlayRectangle.style.top=`${this.startY-t}px`,this.overlayRectangle.style.bottom=`calc(100% - ${this.startY-t}px)`,this.overlayRectangle.style.right=`calc(100% - ${this.startX-e}px)`}inverseSelection(){if(this.stackOfSelected.length===0)return;let e=this.Blok.BlockManager.getBlockByIndex(this.stackOfSelected[0]);if(!e)return;let t=e.selected;if(this.rectCrossesBlocks&&!t)for(let e of this.stackOfSelected)this.Blok.BlockSelection.selectBlockByIndex(e);if(!this.rectCrossesBlocks&&t)for(let e of this.stackOfSelected)this.Blok.BlockSelection.unSelectBlockByIndex(e)}updateRectangleSize(){if(this.overlayRectangle===null)return;let e=this.getScrollLeft(),t=this.getScrollTop();this.mouseY>=this.startY?(this.overlayRectangle.style.top=`${this.startY-t}px`,this.overlayRectangle.style.bottom=`calc(100% - ${this.mouseY-t}px)`):(this.overlayRectangle.style.bottom=`calc(100% - ${this.startY-t}px)`,this.overlayRectangle.style.top=`${this.mouseY-t}px`),this.mouseX>=this.startX?(this.overlayRectangle.style.left=`${this.startX-e}px`,this.overlayRectangle.style.right=`calc(100% - ${this.mouseX-e}px)`):(this.overlayRectangle.style.right=`calc(100% - ${this.startX-e}px)`,this.overlayRectangle.style.left=`${this.mouseX-e}px`)}genInfoForMouseSelection(){let{UI:e}=this.Blok,t=e.nodes.redactor.getBoundingClientRect(),n=t.left+t.width/2,r=this.getScrollTop(),i=this.mouseY-r,a=document.elementFromPoint(n,i);if(!a)return{index:void 0};let o=this.Blok.BlockManager.getBlockByChildNode(a);return{index:o===void 0?void 0:this.Blok.BlockManager.blocks.indexOf(o)}}getScrollTop(){var e,t,n,r;return typeof window.scrollY==`number`?window.scrollY:(e=(t=(n=document.documentElement)==null?void 0:n.scrollTop)==null?(r=document.body)==null?void 0:r.scrollTop:t)==null?0:e}getScrollLeft(){var e,t,n,r;return typeof window.scrollX==`number`?window.scrollX:(e=(t=(n=document.documentElement)==null?void 0:n.scrollLeft)==null?(r=document.body)==null?void 0:r.scrollLeft:t)==null?0:e}addBlockInSelection(e){this.rectCrossesBlocks&&this.Blok.BlockSelection.selectBlockByIndex(e),this.stackOfSelected.push(e)}trySelectNextBlock(e){this.anchorBlockIndex===null&&(this.anchorBlockIndex=e);let t=this.Blok.BlockManager.blocks,n=t[this.anchorBlockIndex],r=t[e];if(!n||!r)return;let i=n.holder.getBoundingClientRect(),a=r.holder.getBoundingClientRect(),o=this.getScrollTop(),s=Math.min(this.startY,this.mouseY)-o,c=Math.max(this.startY,this.mouseY)-o,l=Math.max(Math.min(i.top,a.top),s),u=Math.min(Math.max(i.bottom,a.bottom),c),d=this.getScrollLeft(),f=Math.min(this.startX,this.mouseX)-d,p=Math.max(this.startX,this.mouseX)-d,m=new Set;t.forEach((e,t)=>{let n=e.holder.getBoundingClientRect(),r=e.holder.querySelector(`[data-blok-element-content]`),i=(r==null?e.holder:r).getBoundingClientRect(),a=f===p||i.right>f&&i.left<p;n.height>0&&n.bottom>l&&n.top<u&&a&&m.add(t)});let h=new Set(this.stackOfSelected);for(let e of h)!m.has(e)&&this.rectCrossesBlocks&&this.Blok.BlockSelection.unSelectBlockByIndex(e);for(let e of m)!h.has(e)&&this.rectCrossesBlocks&&this.Blok.BlockSelection.selectBlockByIndex(e);this.stackOfSelected=Array.from(m).sort((e,t)=>e-t)}},gf=[`color`,`background-color`],_f={color:`text`,"background-color":`bg`};function vf(e){e.querySelectorAll(`mark`).forEach(e=>{for(let n of gf){let r=e.style.getPropertyValue(n);if(!r||r===`transparent`||r.startsWith(`var(`))continue;if(n===`background-color`&&(t.ni(r)||t.ti(r))){e.style.removeProperty(n);continue}let i=t.$r(r,_f[n]);i!==null&&e.style.setProperty(n,t.ai(i,_f[n]))}})}var yf={delimiter:`divider`},bf=class extends s{constructor(...e){super(...e),this.detectedInputFormat=`flat`,this.pendingRender=null,this.pendingHashScroll=null,this.resolvePendingRender=null}markRenderStart(){this.pendingRender=new Promise(e=>{this.resolvePendingRender=e})}markRenderEnd(){this.resolvePendingRender!==null&&(this.resolvePendingRender(),this.resolvePendingRender=null),this.pendingRender=null}getDetectedInputFormat(){return this.detectedInputFormat}render(e){return new Promise(t=>{let n=this.insertRenderedBlocks(e);window.requestIdleCallback(()=>{this.eventsDispatcher.emit(p,{count:n}),t()},{timeout:2e3})})}insertRenderedBlocks(e){let{Tools:n,BlockManager:r}=this.Blok;if(e.length===0)return r.insert(),1;let i=this.config.dataModel||`auto`,a=Le(e);this.detectedInputFormat=a.format;let o=xt(Et(Dt(i,a.format)?$e(e):e)),s=new Set,c=o.map(e=>{let{tunes:i,parent:a,content:o,lastEditedAt:c,lastEditedBy:l}=e,u=e.id!==void 0&&s.has(e.id);u&&t.Da(`Duplicate block id «${e.id}» replaced with a generated id to ensure uniqueness`,`warn`);let d=u?t.aa():e.id;d!==void 0&&s.add(d);let f=e.type,p=(e=>typeof e==`object`&&!!e)(e.data)?e.data:{},m=(()=>{if(n.available.has(f))return{tool:f,data:p};let e=yf[f];return e!==void 0&&n.available.has(e)?{tool:e,data:p}:(t.Da(`Tool «${f}» is not found. Check 'tools' property at the Blok config.`,`warn`),{tool:n.stubTool,data:this.composeStubDataForTool(f,p,d)})})();return((e,s)=>{try{return r.composeBlock({id:d,tool:e,data:s,tunes:i,parentId:a,contentIds:o,lastEditedAt:c,lastEditedBy:l})}catch(u){t.Ea(`Block «${e}» skipped because of plugins error`,`error`,{data:s,error:u});let f=this.composeStubDataForTool(e,s,d);return r.composeBlock({id:d,tool:n.stubTool,data:f,tunes:i,parentId:a,contentIds:o,lastEditedAt:c,lastEditedBy:l})}})(m.tool,m.data)});return r.insertMany(c),vf(this.Blok.UI.nodes.redactor),c.length}composeStubDataForTool(e,t,n){let{Tools:r}=this.Blok,i=(()=>{if(!r.unavailable.has(e))return e;let t=r.unavailable.get(e).toolbox;return t!==void 0&&t[0].title!==void 0?t[0].title:e})();return{savedData:{id:n,type:e,data:t},title:i}}},xf=/<img\s+[^>]*src=["']([^"']+)["'][^>]*>/g,Sf=e=>{let r=new Map;for(let t of e)t.id!==void 0&&r.set(t.id,t);if(!e.some(e=>e.tool===`table`))return e;let i=new Map;for(let t of e){var a;if(t.tool!==`paragraph`||t.parentId===void 0||t.parentId===null)continue;let e=r.get(t.parentId);if(e===void 0||e.tool!==`table`)continue;let n=(a=t.data)==null?void 0:a.text;if(typeof n!=`string`)continue;let o=Array.from(n.matchAll(xf),e=>e[1]);if(o.length===0)continue;xf.lastIndex=0;let s=n.replace(xf,``);t.id!==void 0&&i.set(t.id,{parentTableId:t.parentId,imgSrcs:o,cleanedText:s})}if(i.size===0)return e;let o=new Map;for(let[e,n]of i){let r=[];for(let e of n.imgSrcs){let i={id:t.aa(),tool:`image`,data:{url:e},isValid:!0,parentId:n.parentTableId};r.push(i)}o.set(e,r)}let s=new Set;for(let e of i.values())s.add(e.parentTableId);let c=new Map;for(let e of s){let t=r.get(e);if(t===void 0)continue;let i=n.t({},t),a=t.data;if((a==null?void 0:a.content)!==void 0){let e=a.content.map(e=>e.map(e=>n.t(n.t({},e),{},{blocks:[...e.blocks]})));i.data=n.t(n.t({},t.data),{},{content:e})}i.contentIds=t.contentIds===void 0?[]:[...t.contentIds],c.set(e,i)}for(let[e,t]of o){let n=i.get(e);if(n===void 0)continue;let r=c.get(n.parentTableId);if(r===void 0)continue;let a=r.data;if((a==null?void 0:a.content)===void 0)continue;let o=t.map(e=>{var t;return(t=e.id)==null?``:t});a.content.flat().forEach(t=>{let n=t.blocks.indexOf(e);n!==-1&&t.blocks.splice(n,0,...o)}),r.contentIds!==void 0&&r.contentIds.push(...o)}let l=[];for(let t of e){if(t.id!==void 0&&c.has(t.id)){l.push(c.get(t.id));continue}if(t.id!==void 0&&i.has(t.id)){var u,d;l.push(...(u=o.get(t.id))==null?[]:u);let e=i.get(t.id),r=n.t(n.t({},t),{},{data:n.t(n.t({},t.data),{},{text:(d=e==null?void 0:e.cleanedText)==null?``:d})});l.push(r);continue}l.push(t)}return l},Cf=class extends s{constructor(...e){super(...e),this.pendingSave=null}async save(){var e=this;if(!e.isDestroyed){if(e.pendingSave!==null)return e.pendingSave;e.pendingSave=e.doSave();try{return await e.pendingSave}finally{e.pendingSave=null}}}async doSave(){var e=this,n;let r=(n=e.Blok.Renderer)==null?void 0:n.pendingRender;if(r!=null&&await r,e.isDestroyed)return;let{BlockManager:i,Tools:a}=e.Blok,o=i.blocks;if(o.length===1&&o[0].isEmpty&&o[0].tool.isDefault)return{time:+new Date,blocks:[],version:t.ka()};let s=new Set(o.map(e=>e.id));for(let e of o)e.parentId!==null&&!s.has(e.parentId)&&(t.Da(`Saver: cleared dangling parentId ${e.parentId} on block ${e.id}`,`warn`),e.parentId=null);let c=new Map;for(let e of o){if(e.parentId===null)continue;let t=c.get(e.parentId);t===void 0?c.set(e.parentId,[e.id]):t.push(e.id)}let l=o.map(t=>{var n;return e.getSavedData(t,(n=c.get(t.id))==null?[]:n)});e.lastSaveError=void 0;try{let t=await Promise.all(l),n=Sf(e.sanitizeExtractedData(t,e=>{var t;return(t=a.blockTools.get(e))==null?void 0:t.sanitizeConfig},e.config.sanitizer));return e.isDestroyed?void 0:e.makeOutput(n)}catch(n){e.lastSaveError=n,t.Da(`Saving failed due to the Error %o`,`error`,n instanceof Error?n:Error(String(n)));return}}async getSavedData(e,t){var r=this;let i=await e.save(),a=e.name,o=(i==null?void 0:i.data)===void 0?r.getPreservedSavedData(e):i;if(o===void 0)return{tool:a,isValid:!1};let s=await e.validate(o.data);return n.t(n.t({},o),{},{isValid:s,parentId:e.parentId,contentIds:t,lastEditedAt:e.lastEditedAt,lastEditedBy:e.lastEditedBy})}makeOutput(e){var r,i,a;let o=[];e.forEach(({id:e,tool:r,data:i,tunes:a,isValid:s,parentId:c,contentIds:l,lastEditedAt:u,lastEditedBy:d})=>{let f=c!=null;if(!s&&!f){t.Ea(`Block «${r}» skipped because saved data is invalid`);return}if(r===void 0||i===void 0){t.Ea(`Block skipped because saved data is missing required fields`);return}if(r===this.Blok.Tools.stubTool&&this.isStubSavedData(i)){o.push(i);return}if(r===this.Blok.Tools.stubTool){t.Ea(`Stub block data is malformed and was skipped`);return}let p=a===void 0||t.ba(a),m=l!==void 0&&l.length>0,h=u!==void 0,g=d!=null,_=n.t(n.t(n.t(n.t(n.t({id:e,type:r,data:i},!p&&{tunes:a}),f&&{parent:c}),m&&{content:l}),h&&{lastEditedAt:u}),g&&{lastEditedBy:d});o.push(_)});let s=Ot(this.config.dataModel||`auto`,(r=(i=this.Blok.Renderer)==null||(a=i.getDetectedInputFormat)==null?void 0:a.call(i))==null?`flat`:r)?ht(o):o,c=Xc(s);if(c.length>0){let e=`Saver produced output with hierarchy drift: ${c.map(e=>e.message).join(`; `)}`,n=typeof process<`u`?`production`:void 0;if(n===`test`||n===`development`)throw Error(e);t.Da(e,`error`)}return{time:+new Date,blocks:s,version:t.ka()}}sanitizeExtractedData(e,r,i){let a=[];if(e.forEach((e,t)=>{this.hasSanitizableData(e)&&a.push({index:t,data:e})}),a.length===0)return e;let o=t.Oi(a.map(({data:e})=>e),r,i),s=e.map(e=>n.t({},e));return a.forEach(({index:e},t)=>{let r=o[t];s[e]=n.t(n.t({},s[e]),{},{data:r.data})}),s}hasSanitizableData(e){return e.data!==void 0&&typeof e.tool==`string`}isStubSavedData(e){if(!t.Sa(e))return!1;let n=e;return typeof n.type==`string`&&n.data!==void 0}getLastSaveError(){return this.lastSaveError}getPreservedSavedData(e){let r=e.preservedData;if(t.ba(r))return;let i=e.preservedTunes;return n.t(n.t({id:e.id,tool:e.name,data:r},t.ba(i)?{}:{tunes:i}),{},{time:0})}},wf=class extends s{constructor(...e){super(...e),this.opened=!1,this.isOpening=!1,this.selection=new t.Ai,this.popover=null,this.flipperInstance=new t.mi({focusedItemClass:t.N.focused,allowedKeys:[t.Aa.TAB,t.Aa.UP,t.Aa.DOWN,t.Aa.ENTER,t.Aa.RIGHT,t.Aa.LEFT]}),this.flipperKeydownHandler=null,this.flipperKeydownSource=null,this.deleteKeyHandler=null,this.close=()=>{this.opened&&(this.opened=!1,this.isOpening=!1,t.Ai.isAtBlok||this.selection.restore(),this.selection.clearSaved(),this.detachDeleteKeyListener(),this.detachFlipperKeydownListener(),this.clearBlockSelectionOnClose(),this.eventsDispatcher.emit(this.events.closed),this.popover&&(this.popover.off(t.T.Closed,this.onPopoverClose),this.popover.destroy(),this.popover.getElement().remove(),this.popover=null))},this.onPopoverClose=()=>{this.close()}}get events(){return{opened:h,closed:m}}get CSS(){return{settings:``}}get flipper(){return this.flipperInstance}make(){this.nodes.wrapper=t.Qi.make(`div`),this.nodes.wrapper.setAttribute(`data-blok-testid`,`block-tunes-wrapper`),this.eventsDispatcher.on(g,this.close)}destroy(){this.detachFlipperKeydownListener(),this.removeAllNodes(),this.listeners.destroy(),this.eventsDispatcher.off(g,this.close)}async open(e,n,r){var i=this;let a=i.Blok.BlockSelection.selectedBlocks,o=a.length>1,s=o?a[0]:e==null?i.Blok.BlockManager.currentBlock:e;if(s!==void 0){i.isOpening=!0;try{var c;i.selection.save(),o||(i.Blok.BlockSelection.selectBlock(s),i.Blok.BlockSelection.clearCache());let{toolTunes:e,commonTunes:l}=s.getTunes(),u=await i.getTunesItems(s,l,e),d=o?void 0:await s.getActiveToolboxEntry(),f=o?i.Blok.I18n.t(`blockSettings.blocksSelected`,{count:a.length}):d?t.Ki(i.Blok.I18n,d,s.name):t.Gi(i.Blok.I18n,void 0,s.name),p=t.ma()?Vd:t.C,m={searchable:!0,trigger:n||i.nodes.wrapper,items:u,messages:{nothingFound:i.Blok.I18n.t(`popover.nothingFound`),search:i.Blok.I18n.t(`popover.search`)},autoFocusFirstItem:!1,minWidth:`220px`,placeLeftOfAnchor:(c=r==null?void 0:r.placeLeftOfAnchor)==null?!0:c,viewportMargin:50,contextLabel:f};p===t.C&&(m.flipper=i.flipperInstance),i.popover=new p(m),i.popover.getElement().setAttribute(`data-blok-testid`,`block-tunes-popover`),i.popover.on(t.T.Closed,i.onPopoverClose),i.attachDeleteKeyListener(u),i.opened=!0,i.isOpening=!1,i.popover.show(),i.attachFlipperKeydownListener(s),i.eventsDispatcher.emit(i.events.opened)}catch(e){i.isOpening=!1}}}getElement(){return this.nodes.wrapper}contains(e){var t,n;return!!((t=this.nodes.wrapper)!=null&&t.contains(e)||(n=this.popover)!=null&&n.hasNode(e))}async getTunesItems(e,n,r){var i=this;let a=[],o=i.Blok.BlockSelection.selectedBlocks,s=o.length>1,l=i.Blok.ReadOnly.isEnabled,u=Array.from(i.Blok.Tools.blockTools.values());if(l){let r=n.filter(e=>`name`in e&&e.name===`copy-link`);return a.push(...r),e.lastEditedAt!==void 0&&(a.push({type:t.ki.Separator}),a.push({type:t.ki.Html,element:i.createEditMetadataFooter(e),name:`edit-metadata`})),a}!s&&r!==void 0&&r.length>0&&(a.push(...r),a.push({type:t.ki.Separator}));let d=(s?await t.Vi(o.map(e=>new c(e)),u):await t.Bi(e,u)).reduce((n,r)=>(r.toolbox===void 0||r.toolbox.forEach(a=>{var c;let l=a.titleKey,u=l!=null&&l.includes(`.`)?l:`toolNames.${l}`,d=l?u:void 0,f=d?i.Blok.I18n.getEnglishTranslation(d):a.title;n.push({icon:a.icon,title:t.Ki(i.Blok.I18n,a,r.name),name:(c=a.name)==null?r.name:c,englishTitle:f,searchTerms:a.searchTerms,closeOnActivate:!0,onActivate:async()=>{let{Caret:t,Toolbar:n}=i.Blok,c=e.contentIds.length;if(c>0){let e=i.Blok.I18n.t(`blockSettings.convertWithChildrenWarning`,{count:c}),t=`This block has ${c} nested block${c===1?``:`s`}. Converting it will promote them to the top level. Continue?`;if(!window.confirm(e===`blockSettings.convertWithChildrenWarning`?t:e))return}let l=await i.convertBlock(e,o,s,r,a.data);n.close(),l&&t.setToBlock(l,t.positions.END)}})}),n),[]);if(s){let e=o.map(e=>e.id);d.push({icon:t.tt,title:i.Blok.I18n.t(`toolNames.columns`),name:`turn-into-columns`,closeOnActivate:!0,onActivate:()=>{let{Caret:t,Toolbar:n,BlockManager:r}=i.Blok,a=i.Blok.API.methods,o=Wl(a,e);if(o===null){n.close();return}let s=a.blocks.getChildren(o)[0],c=s===void 0?void 0:a.blocks.getChildren(s.id)[0],l=c===void 0?void 0:r.getBlockById(c.id);l!==void 0&&t.setToBlock(l,t.positions.START),n.close()}})}return d.length>0&&(a.push({icon:t.On,name:`convert-to`,title:i.Blok.I18n.t(`popover.convertTo`),children:{items:d,minWidth:`200px`}}),a.push({type:t.ki.Separator})),s?a.push({icon:t.Vn,title:i.Blok.I18n.t(`blockSettings.delete`),name:`delete`,isDestructive:!0,secondaryLabel:`Del`,closeOnActivate:!0,onActivate:()=>{let{BlockManager:e,Caret:t,Toolbar:n}=i.Blok,r=e.deleteSelectedBlocksAndInsertReplacement();r&&t.setToBlock(r,t.positions.END),n.close()}}):a.push(...n),e.lastEditedAt!==void 0&&(a.push({type:t.ki.Separator}),a.push({type:t.ki.Html,element:i.createEditMetadataFooter(e),name:`edit-metadata`})),a}createEditMetadataFooter(e){let t=document.createElement(`div`);t.classList.add(`px-3`,`py-2`,`text-xs`,`leading-snug`,`text-[color:var(--popover-text-secondary,_#888)]`,`select-none`);let n=document.createElement(`div`);if(n.setAttribute(`data-edit-meta-label`,``),n.textContent=this.Blok.I18n.t(`blockSettings.lastEdited`),e.lastEditedBy!=null&&this.config.resolveUser!=null&&Promise.resolve(this.config.resolveUser(e.lastEditedBy)).then(e=>{(e==null?void 0:e.name)!=null&&(n.textContent=this.Blok.I18n.t(`blockSettings.lastEditedBy`,{name:e.name}))}),t.appendChild(n),e.lastEditedAt!==void 0){let n=document.createElement(`div`);n.classList.add(`mt-1`);let r=this.Blok.I18n.getLocale(),i=new Date(e.lastEditedAt),a=new Intl.DateTimeFormat(r,{day:`numeric`,month:`long`,year:`numeric`}).formatToParts(i);for(;a.length>0&&a[a.length-1].type===`literal`&&a[a.length-1].value.includes(`.`);)a.pop();n.textContent=`${a.map(e=>e.value).join(``)}, ${new Intl.DateTimeFormat(r,{timeStyle:`short`}).format(i)}`,t.appendChild(n)}return t}clearBlockSelectionOnClose(){if(this.Blok.CrossBlockSelection.isCrossBlockSelectionStarted)return;if(this.Blok.BlockSelection.selectedBlocks.length>1){this.Blok.BlockSelection.allBlocksSelected=!1;return}let e=this.Blok.BlockManager.currentBlock;e&&this.Blok.BlockSelection.unselectBlock(e)}async convertBlock(e,t,n,r,i){var a=this;let{BlockManager:o}=a.Blok;if(n)return a.convertMultipleBlocks(t,r.name,i);let s=await a.getExplodableItems(e);return!a.canToolMergeMultipleItems(r)&&s!==null?a.convertMultiItemBlockToSeparateBlocks(e,r.name,i):o.convert(e,r.name,i)}async convertMultipleBlocks(e,n,r){var i=this;let{Tools:a}=i.Blok;if(e.length===0)return null;let o=new Set(e.map(e=>e.id)),s=e.filter(e=>{if(e.parentId!==null&&o.has(e.parentId))return!1;let n=a.blockTools.get(e.name);return n===void 0||t.Wi(n,`export`)});if(s.length===0)return null;let c=a.blockTools.get(n);return c&&i.canToolMergeMultipleItems(c)?i.convertBlocksToSingleMergedBlock(s,n,r):i.convertBlocksIndividually(s,n,r)}canToolMergeMultipleItems(e){let t=e.conversionConfig;if(!(t!=null&&t.import))return!1;try{let n=typeof t.import==`function`?t.import(`line1
11
+ `),c=i.innerHTML;r.setData(`text/plain`,s),r.setData(`text/html`,c);try{r.setData(n.Blok.Paste.MIME_TYPE,JSON.stringify(o))}catch(e){e instanceof Error&&console.warn(`Failed to set custom clipboard data:`,e.message)}}selectBlockByIndex(e){let{BlockManager:t}=this.Blok,n=t.getBlockByIndex(e);n!==void 0&&this.selectBlock(n)}selectBlock(e){this.selection.save();let n=t.Ai.get();n==null||n.removeAllRanges();let r=e;r.selected=!0,this.clearCache(),this.Blok.InlineToolbar.close()}unselectBlock(e){let t=e;t.selected=!1,this.clearCache()}clearCache(){this.anyBlockSelectedCache=null}enableNavigationMode(){let{BlockManager:e}=this.Blok;if(this._navigationModeEnabled)return;this._navigationModeEnabled=!0;let t=e.currentBlockIndex>=0?e.currentBlockIndex:0;this.setNavigationFocus(t)}disableNavigationMode(e=!1){if(!this._navigationModeEnabled)return;let t=this.navigationFocusedBlock;if(t&&t.holder.removeAttribute(`data-blok-navigation-focused`),this._navigationModeEnabled=!1,e&&t){let{Caret:e,BlockManager:n}=this.Blok;n.currentBlockIndex=this.navigationFocusIndex,e.setToBlock(t,e.positions.END)}this.navigationFocusIndex=-1}navigateNext(){if(!this._navigationModeEnabled)return!1;let{BlockManager:e}=this.Blok,t=this.navigationFocusIndex+1;return t>=e.blocks.length?!1:(this.setNavigationFocus(t),!0)}navigatePrevious(){if(!this._navigationModeEnabled)return!1;let e=this.navigationFocusIndex-1;return e<0?!1:(this.setNavigationFocus(e),!0)}setNavigationFocus(e){let{BlockManager:n}=this.Blok,r=n.getBlockByIndex(e);if(!r)return;let i=this.navigationFocusedBlock;i&&i.holder.removeAttribute(`data-blok-navigation-focused`),this.navigationFocusIndex=e,r.holder.setAttribute(`data-blok-navigation-focused`,`true`);let a=t.Ai.get();a==null||a.removeAllRanges(),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),r.holder.scrollIntoView({behavior:`smooth`,block:`nearest`})}destroy(){X.remove(this.Blok.UI.nodes.redactor,`CMD+A`)}handleCommandA(e){if(this.Blok.RectangleSelection.clearSelection(),t.Qi.isNativeInput(e.target)&&!this.readyToBlockSelection){this.readyToBlockSelection=!0;return}let n=this.Blok.BlockManager.getBlock(e.target);if(!n)return;let r=n.inputs;if(r.length>1&&!this.readyToBlockSelection){this.readyToBlockSelection=!0;return}if(r.length===1&&!this.needToSelectAll){this.needToSelectAll=!0;return}if(this.needToSelectAll){e.preventDefault(),this.selectAllBlocks(),this.needToSelectAll=!1,this.readyToBlockSelection=!1;return}this.readyToBlockSelection&&(e.preventDefault(),this.selectBlock(n),this.needToSelectAll=!0)}selectAllBlocks(){this.selection.save();let e=t.Ai.get();e==null||e.removeAllRanges(),this.allBlocksSelected=!0,this.Blok.InlineToolbar.close(),this.Blok.Toolbar.moveAndOpenForMultipleBlocks()}replaceSelectedBlocksWithPrintableKey(e){let{BlockManager:n,Caret:r}=this.Blok,i=n.deleteSelectedBlocksAndInsertReplacement();i&&r.setToBlock(i),t.va(()=>{let t=e.key;r.insertContentAtCaretPosition(t.length>1?``:t)},20)()}},Cl=127,wl=e=>{for(let t of e){if(t.trim().length===0)continue;if(t>=`0`&&t<=`9`||t.toLowerCase()!==t.toUpperCase())return!1;let e=t.codePointAt(0);if(typeof e==`number`&&e>Cl)return!1}return!0},Tl=e=>{var t;return e.nodeType===Node.TEXT_NODE?[e]:(t=e.hasChildNodes)!=null&&t.call(e)?Array.from(e.childNodes).flatMap(e=>Tl(e)):[]},El=e=>{var t,n;let r=Tl(e);if(r.length===0)return null;let i=r[r.length-1],a=(t=[...r].reverse().find(e=>{var t;return!wl((t=e.textContent)==null?``:t)}))==null?null:t;return a&&a!==i&&wl((n=i.textContent)==null?``:n)&&a.parentNode!==e?a:i},Dl=class e extends s{get positions(){return{START:`start`,END:`end`,DEFAULT:`default`}}static get DATA_ATTR(){return{shadowCaret:`data-blok-shadow-caret`}}setToBlock(e,n=this.positions.DEFAULT,r=0){let{BlockManager:i,BlockSelection:a}=this.Blok;if(a.clearSelection(),!e.focusable){var o;(o=window.getSelection())==null||o.removeAllRanges(),a.selectBlock(e),i.currentBlock=e;return}let s=n===this.positions.START?e.firstInput:n===this.positions.END?e.lastInput:e.currentInput;if(!s)return;let{node:c,offset:l}=(e=>{if(n===this.positions.START)return{node:t.Qi.getDeepestNode(e,!1),offset:0};if(n===this.positions.END)return this.resolveEndPositionNode(e);let{node:i,offset:a}=t.Qi.getNodeByOffset(e,r);return i?{node:i,offset:a}:{node:t.Qi.getDeepestNode(e,!1),offset:0}})(s);if(!c)return;this.set(c,l),i.setCurrentBlockByChildNode(e.holder);let u=i.currentBlock;u&&(u.currentInput=s)}resolveEndPositionNode(e){let n=t.Qi.getDeepestNode(e,!0);if(n instanceof HTMLElement&&t.Qi.isNativeInput(n))return{node:n,offset:t.Qi.getContentLength(n)};let r=El(e);return r?{node:r,offset:t.Qi.getContentLength(r)}:n?{node:n,offset:t.Qi.getContentLength(n)}:{node:null,offset:0}}setToInput(e,t=this.positions.DEFAULT,n=0){let{currentBlock:r}=this.Blok.BlockManager;this.setCaretToInputPosition(e,t,n),r&&(r.currentInput=e)}setToBlockAtXPosition(e,t,n){let{BlockManager:r,BlockSelection:i}=this.Blok;if(i.clearSelection(),!e.focusable){var a;(a=window.getSelection())==null||a.removeAllRanges(),i.selectBlock(e),r.currentBlock=e;return}let o=n?e.firstInput:e.lastInput;if(!o)return;if(t!==null)ec(o,t,n);else{let e=n?this.positions.START:this.positions.END;this.setCaretToInputPosition(o,e,0)}r.setCurrentBlockByChildNode(e.holder);let s=r.currentBlock;s&&(s.currentInput=o)}setToInputAtXPosition(e,t,n){let{currentBlock:r}=this.Blok.BlockManager;if(t!==null)ec(e,t,n);else{let t=n?this.positions.START:this.positions.END;this.setCaretToInputPosition(e,t,0)}r&&(r.currentInput=e)}setCaretToInputPosition(e,t,n){if(t===this.positions.START){this.setCaretToStart(e);return}if(t===this.positions.END){this.setCaretToEnd(e);return}this.setCaretToOffset(e,n)}setCaretToStart(e){let n=t.Qi.getDeepestNode(e,!1);n&&this.set(n,0)}setCaretToEnd(e){let n=t.Qi.getDeepestNode(e,!0);n&&this.set(n,t.Qi.getContentLength(n))}setCaretToOffset(e,n){let{node:r,offset:i}=t.Qi.getNodeByOffset(e,n);if(r){this.set(r,i);return}this.setCaretToEnd(e)}set(e,n=0){let{top:r,bottom:i}=t.Ai.setCursor(e,n),{innerHeight:a}=window;if(r<0){window.scrollBy(0,r-30);return}i>a&&window.scrollBy(0,i-a+30)}setToTheLastBlock(){let e=this.Blok.BlockManager.lastBlock;if(e)if(e.tool.isDefault&&e.isEmpty)this.setToBlock(e);else{let e=this.Blok.BlockManager.insertAtEnd();this.setToBlock(e)}}extractFragmentFromCaretPosition(){let e=t.Ai.get();if(!e||!e.rangeCount)return;let n=e.getRangeAt(0),r=this.Blok.BlockManager.currentBlock;if(!r)return;let i=r.currentInput;if(n.deleteContents(),!i)return;if(t.Qi.isNativeInput(i)){var a;let e=i,t=document.createDocumentFragment(),n=(a=e.selectionStart)==null?0:a,r=e.value.substring(0,n);return t.textContent=e.value.substring(n),e.value=r,t}let o=n.cloneRange();return o.selectNodeContents(i),o.setStart(n.endContainer,n.endOffset),o.extractContents()}navigateNext(e=!1){let{BlockManager:n}=this.Blok,{currentBlock:r,nextVisibleBlock:i}=n;if(r===void 0)return!1;let{nextInput:a,currentInput:o}=r,s=o===void 0?void 0:t.hi(o),c=e||s||!r.focusable;if(a&&c)return this.setToInput(a,this.positions.START),!0;let l=()=>{if(i===null||r.parentId===null||r.holder.parentElement!==null&&r.holder.parentElement===i.holder.parentElement)return i;let e=this.resolveContainerToExit(r.parentId);return this.shouldExitContainer(r,i,e)?this.findFirstBlockAfterParent(e):i},u=(()=>{let e=l();return e===null?r.tool.isDefault||!c?null:n.insertAtEnd():e})();return u!==null&&c?(this.setToBlock(u,this.positions.START),!0):!1}navigatePrevious(e=!1){let{currentBlock:n,previousVisibleBlock:r}=this.Blok.BlockManager;if(!n)return!1;let{previousInput:i,currentInput:a}=n,o=a===void 0?void 0:t.gi(a),s=e||o||!n.focusable;if(i&&s)return this.setToInput(i,this.positions.END),!0;let c=(()=>{if(r===null||n.parentId===null||n.holder.parentElement!==null&&n.holder.parentElement===r.holder.parentElement)return r;let e=this.resolveContainerToExit(n.parentId);return this.shouldExitContainer(n,r,e)?this.findFirstBlockBeforeParent(e):r})();return c!==null&&s?(this.setToBlock(c,this.positions.END),!0):!1}navigateToBlock(e,t){if(e===null)return!1;let{BlockManager:n,BlockSelection:r}=this.Blok;return r.clearSelection(),e.focusable?this.setToBlockAtXPosition(e,null,t):(r.selectBlock(e),n.currentBlock=e),!0}navigateVerticalNext(){let{BlockManager:e}=this.Blok,{currentBlock:n,nextVisibleBlock:r}=e;if(n===void 0)return!1;if(!n.focusable||n.isEmpty)return this.navigateToBlock(r,!0);let{currentInput:i}=n;if(!(i===void 0||Js(i)))return!1;let a=tc(),{nextInput:o}=n;if(o)return this.setToInputAtXPosition(o,a,!0),!0;if(r!==null&&n.parentId!==null&&n.holder.parentElement!==null&&n.holder.parentElement===r.holder.parentElement)return this.setToBlockAtXPosition(r,a,!0),!0;let s=n.parentId===null?null:this.resolveContainerToExit(n.parentId);if(s!==null&&this.shouldExitContainer(n,r,s)){let t=this.findFirstBlockAfterParent(s);if(t!==null)return this.setToBlockAtXPosition(t,a,!0),!0;let n=e.insertAtEnd();return this.setToBlock(n,this.positions.START),!0}if(r!==null)return this.setToBlockAtXPosition(r,a,!0),!0;let c=i===void 0?!0:t.hi(i);if(!n.tool.isDefault&&c){let t=e.insertAtEnd();return this.setToBlock(t,this.positions.START),!0}return!1}navigateVerticalPrevious(){let{BlockManager:e}=this.Blok,{currentBlock:t,previousVisibleBlock:n}=e;if(t===void 0)return!1;if(!t.focusable||t.isEmpty)return this.navigateToBlock(n,!1);let{currentInput:r}=t;if(!(r===void 0||qs(r)))return!1;let i=tc(),{previousInput:a}=t;if(a)return this.setToInputAtXPosition(a,i,!1),!0;if(n!==null&&t.parentId!==null&&t.holder.parentElement!==null&&t.holder.parentElement===n.holder.parentElement)return this.setToBlockAtXPosition(n,i,!1),!0;let o=t.parentId===null?null:this.resolveContainerToExit(t.parentId);if(o!==null&&this.shouldExitContainer(t,n,o)){let e=this.findFirstBlockBeforeParent(o);return e===null?!1:(this.setToBlockAtXPosition(e,i,!1),!0)}return n===null?!1:(this.setToBlockAtXPosition(n,i,!1),!0)}findFirstBlockBeforeParent(e){let{BlockManager:t}=this.Blok,n=t.blocks,r=n.findIndex(t=>t.id===e);return r<=0?null:n[r-1]}findFirstBlockAfterParent(e){var t;let{BlockManager:n}=this.Blok,r=n.blocks,i=r.findIndex(t=>t.id===e);return i===-1||(t=r.slice(i+1).find(t=>!this.isWithinContainer(t,e)))==null?null:t}resolveContainerToExit(e){var t;let n=(t=this.Blok.BlockManager.getBlockById)==null?void 0:t.bind(this.Blok.BlockManager);if(n===void 0)return e;let r=n(e);return r===void 0||r.parentId===null?e:this.resolveContainerToExit(r.parentId)}isWithinContainer(e,t){var n;let r=e.parentId;if(r===null)return!1;if(r===t)return!0;let i=(n=this.Blok.BlockManager.getBlockById)==null?void 0:n.bind(this.Blok.BlockManager);if(i===void 0)return!1;let a=i(r);return a===void 0?!1:this.isWithinContainer(a,t)}shouldExitContainer(e,t,n){return e.parentId===null?!1:t===null||t.id===n?!0:this.isWithinContainer(t,n)}createShadow(t){let n=document.createElement(`span`);n.setAttribute(e.DATA_ATTR.shadowCaret,``),n.setAttribute(`data-blok-testid`,`shadow-caret`),t.insertAdjacentElement(`beforeend`,n)}restoreCaret(e){let n=e.querySelector(`[data-blok-testid="shadow-caret"]`);if(!n)return;new t.Ai().expandToTag(n);let r=document.createRange();r.selectNode(n),r.extractContents()}insertContentAtCaretPosition(e){let n=document.createDocumentFragment(),r=document.createElement(`div`),i=t.Ai.get(),a=t.Ai.range;if(!i||!a)return;r.innerHTML=e,Array.from(r.childNodes).forEach(e=>n.appendChild(e)),n.childNodes.length===0&&n.appendChild(new Text);let o=n.lastChild;a.deleteContents(),a.insertNode(n);let s=document.createRange(),c=o.nodeType===Node.TEXT_NODE?o:o.firstChild;c!==null&&c.textContent!==null&&s.setStart(c,c.textContent.length),i.removeAllRanges(),i.addRange(s)}},Ol=class extends s{constructor(...e){super(...e),this.firstSelectedBlock=null,this.lastSelectedBlock=null,this.onMouseUp=()=>{this.listeners.off(document,`mouseover`,this.onMouseOver),this.listeners.off(document,`mouseup`,this.onMouseUp),this.isCrossBlockSelectionStarted&&(this.Blok.UI.disableHoverForCooldown(),this.Blok.UI.resetBlockHoverState(),this.Blok.Toolbar.moveAndOpenForMultipleBlocks())},this.onMouseOver=e=>{let n=e,{BlockManager:r,BlockSelection:i,DragManager:a}=this.Blok;if(a.isDragging||this.Blok.UI.someToolbarOpened||this.Blok.RectangleSelection.isRectActivated()||n.relatedTarget===null&&n.target===null)return;let o=r.getBlockByChildNode(n.relatedTarget)||this.lastSelectedBlock,s=r.getBlockByChildNode(n.target);if(!o||!s)return;let c=r.resolveToRootBlock(o),l=r.resolveToRootBlock(s);if(l!==c){if(this.firstSelectedBlock&&c===this.firstSelectedBlock){var u;(u=t.Ai.get())==null||u.removeAllRanges(),c.selected=!0,l.selected=!0,i.clearCache();return}if(this.firstSelectedBlock&&l===this.firstSelectedBlock){let e=r.blocks.indexOf(c),t=r.blocks.indexOf(l),n=Math.min(e,t),a=Math.max(e,t);for(let e of Array.from({length:a-n+1},(e,t)=>n+t))r.blocks[e].selected=!1;i.clearCache();return}this.Blok.InlineToolbar.close(),this.toggleBlocksSelectedState(c,l),this.lastSelectedBlock=l}}}async prepare(){var e=this;e.listeners.on(document,`mousedown`,t=>{e.enableCrossBlockSelection(t)})}watchSelection(e){if(e.button!==t.ja.LEFT)return;let{BlockManager:n}=this.Blok,r=n.getBlock(e.target);r&&(this.firstSelectedBlock=r,this.lastSelectedBlock=r,this.listeners.on(document,`mouseover`,this.onMouseOver),this.listeners.on(document,`mouseup`,this.onMouseUp))}get isCrossBlockSelectionStarted(){return!!this.firstSelectedBlock&&!!this.lastSelectedBlock&&this.firstSelectedBlock!==this.lastSelectedBlock}toggleBlockSelectedState(e=!0){let{BlockManager:n,BlockSelection:r}=this.Blok,i=n.currentBlock;if(!this.lastSelectedBlock&&!i)return;if(!this.lastSelectedBlock&&i&&(this.lastSelectedBlock=this.firstSelectedBlock=i),this.firstSelectedBlock===this.lastSelectedBlock&&this.firstSelectedBlock){var a;this.firstSelectedBlock.selected=!0,r.clearCache(),(a=t.Ai.get())==null||a.removeAllRanges(),this.Blok.Toolbar.close()}if(!this.lastSelectedBlock)return;let o=n.blocks.indexOf(this.lastSelectedBlock)+(e?1:-1),s=n.blocks[o];s&&(this.lastSelectedBlock.selected===s.selected?(this.lastSelectedBlock.selected=!1,r.clearCache(),this.Blok.Toolbar.close()):(s.selected=!0,r.clearCache(),this.Blok.Toolbar.close()),this.lastSelectedBlock=s,this.Blok.InlineToolbar.close(),s.holder.scrollIntoView({block:`nearest`}),this.isCrossBlockSelectionStarted&&this.Blok.Toolbar.moveAndOpenForMultipleBlocks())}clear(e){let{BlockManager:t,BlockSelection:n,Caret:r}=this.Blok;if(!this.firstSelectedBlock||!this.lastSelectedBlock)return;let i=t.blocks.indexOf(this.firstSelectedBlock),a=t.blocks.indexOf(this.lastSelectedBlock);if(!n.anyBlockSelected||i===-1||a===-1){this.firstSelectedBlock=this.lastSelectedBlock=null;return}if(e&&e instanceof KeyboardEvent)switch(e.key){case`ArrowDown`:case`ArrowRight`:r.setToBlock(t.blocks[Math.max(i,a)],r.positions.END);break;case`ArrowUp`:case`ArrowLeft`:r.setToBlock(t.blocks[Math.min(i,a)],r.positions.START);break;default:r.setToBlock(t.blocks[Math.max(i,a)],r.positions.END)}this.firstSelectedBlock=this.lastSelectedBlock=null}enableCrossBlockSelection(e){let{UI:n,Toolbar:r}=this.Blok;if(!n.nodes.redactor||this.Blok.RectangleSelection.isRectActivated())return;let i=r.nodes.wrapper;i&&i.contains(e.target)||(t.Ai.isCollapsed||this.Blok.BlockSelection.clearSelection(e),n.nodes.redactor.contains(e.target)?this.watchSelection(e):this.Blok.BlockSelection.clearSelection(e))}toggleBlocksSelectedState(e,t){let{BlockManager:n,BlockSelection:r}=this.Blok,i=n.blocks.indexOf(e),a=n.blocks.indexOf(t),o=e.selected!==t.selected,s=Math.min(i,a),c=Math.max(i,a);for(let i of Array.from({length:c-s+1},(e,t)=>s+t)){let a=n.blocks[i];a!==this.firstSelectedBlock&&a!==(o?e:t)&&(n.blocks[i].selected=!n.blocks[i].selected,r.clearCache())}this.Blok.Toolbar.close()}},kl=`cubic-bezier(0.2, 0, 0, 1)`,Al=350,jl=()=>{var e,t,n;return(e=(t=(n=window).matchMedia)==null?void 0:t.call(n,`(prefers-reduced-motion: reduce)`).matches)==null?!1:e},Ml=()=>{var e,t,n;return(e=(t=(n=window).matchMedia)==null?void 0:t.call(n,`(max-width: 650px)`).matches)==null?!1:e},Nl=new Set,Pl=(e,t)=>{let n={done:!1},r=()=>{n.done||(n.done=!0,clearTimeout(a),e.removeEventListener(`transitionend`,i),Nl.delete(r),t())},i=t=>{t.target===e&&r()},a=setTimeout(r,Al);e.addEventListener(`transitionend`,i),Nl.add(r)},Fl=()=>{for(let e of[...Nl])e()},Il=(e,t)=>{let n=e.reduce((e,t)=>e+t,0),r=t.reduce((e,t)=>e+t,0);return e.length!==t.length||n<=0||r<=0?[...t]:e.map(e=>e/n*r)},Ll=e=>{let{holders:t,startWidths:n,newColumnHolder:r}=e,i=n.reduce((e,t)=>e+t,0);if(t.length!==n.length||t.length===0||i<=0||jl()||Ml())return;let a=t.map(e=>Number(e.style.flexGrow)||1),o=Il(n,a),s=t[0].parentElement,c=r;t.forEach((e,t)=>{let n=e;n.style.flexGrow=String(o[t])}),c&&(c.style.opacity=`0`),t[0].offsetWidth;let l=`flex-grow 200ms ${kl}, opacity 200ms ${kl}`;t.forEach((e,t)=>{let n=e;n.style.transition=l,n.style.flexGrow=String(a[t])}),c&&(c.style.opacity=`1`),s==null||s.setAttribute(`data-blok-column-drop-animating`,``),Pl(t[0],()=>{t.forEach((e,t)=>{let n=e;n.style.removeProperty(`transition`),n.style.flexGrow=String(a[t])}),c==null||c.style.removeProperty(`opacity`),s==null||s.removeAttribute(`data-blok-column-drop-animating`)})},Rl=e=>{var t,n;let r=Array.from((t=(n=e.parentElement)==null?void 0:n.children)==null?[]:t),i=r.indexOf(e);return r.slice(i+1).filter(e=>e instanceof HTMLElement&&e.hasAttribute(`data-blok-element`)).map(e=>({element:e,top:e.getBoundingClientRect().top}))},zl=e=>{if(!jl())for(let{element:t,top:n}of e){if(!t.isConnected)continue;let e=n-t.getBoundingClientRect().top;Math.abs(e)<1||(t.style.transform=`translateY(${e}px)`,t.offsetWidth,t.style.transition=`transform 200ms ${kl}`,t.style.transform=``,Pl(t,()=>{t.style.removeProperty(`transition`),t.style.removeProperty(`transform`)}))}},Bl=e=>{let{preview:t,targetRect:n}=e;if(jl()){t.remove();return}t.style.transition=`left 200ms ${kl}, top 200ms ${kl}, opacity 200ms ${kl}`,t.style.left=`${n.left}px`,t.style.top=`${n.top}px`,t.style.opacity=`0`,Pl(t,()=>t.remove())},Vl=(e,n)=>{var r;let i=e.blocks.getChildren(n).map(e=>e.holder),a=(r=i[0])==null?void 0:r.closest(`[${t.oi}]`);a instanceof HTMLElement&&t.di(a,i,e.readOnly.isEnabled,e,n)},Hl=(e,t)=>{if(e.blocks.transact!==void 0){e.blocks.transact(t);return}t()},Ul=(e,n,r,i)=>{var a,o,s;if(r.length===0||r.includes(n))return null;let c=e.blocks.getBlockIndex(n);if(c===void 0)return null;for(let t of r)if(e.blocks.getBlockIndex(t)===void 0)return null;if(((a=e.blocks.getById(n))==null?void 0:a.parentId)!==null)return null;let l=(o=e.blocks.getById(n))==null?void 0:o.holder,u=(s=l==null?void 0:l.getBoundingClientRect().width)==null?0:s,d=l===void 0?null:Rl(l),f={listId:null,columnHolders:[],sourcesColumnHolder:null};return Hl(e,()=>{let a=e.blocks.insert(t.ci,{noSeed:!0},{},c,!1,!1);f.listId=a.id;let o=e.blocks.insert(t.ui,{noSeed:!0},{},c+1,!1,!1),s=e.blocks.insert(t.ui,{noSeed:!0},{},c+2,!1,!1);e.blocks.setBlockParent(o.id,a.id),e.blocks.setBlockParent(s.id,a.id);let l=i===`left`?s:o,u=i===`left`?o:s;f.columnHolders=[o.holder,s.holder],f.sourcesColumnHolder=u.holder,e.blocks.setBlockParent(n,l.id);for(let t of r)e.blocks.setBlockParent(t,u.id)}),l!==void 0&&f.columnHolders.length===2&&(Ll({holders:f.columnHolders,startWidths:i===`left`?[0,u]:[u,0],newColumnHolder:f.sourcesColumnHolder}),d!==null&&zl(d)),f.listId},Wl=(e,n)=>{let r=n.filter(t=>{var n;return e.blocks.getBlockIndex(t)===void 0?!1:((n=e.blocks.getById(t))==null?void 0:n.parentId)===null});if(r.length<2)return null;let i=e.blocks.getBlockIndex(r[0]);if(i===void 0)return null;let a={listId:null};return Hl(e,()=>{let n=e.blocks.insert(t.ci,{noSeed:!0},{},i,!1,!1);a.listId=n.id;let o=r.map((n,r)=>e.blocks.insert(t.ui,{noSeed:!0},{},i+1+r,!1,!1));for(let t of o)e.blocks.setBlockParent(t.id,n.id);r.forEach((t,n)=>{e.blocks.setBlockParent(t,o[n].id)}),t.fi(e,n.id),Vl(e,n.id)}),a.listId},Gl=(e,n,r,i)=>{var a;if(r.length===0)return null;let o=e.blocks.getBlockIndex(n);if(o===void 0)return null;for(let t of r)if(e.blocks.getBlockIndex(t)===void 0)return null;let s=e.blocks.getById(n),c=s==null?void 0:s.parentId;if(c==null)return null;let l=i===`left`?o:o+1,u=(a=e.blocks.getById(c))==null?void 0:a.holder,d=new Map(e.blocks.getChildren(c).map(e=>[e.holder,e.holder.getBoundingClientRect().width])),f=u===void 0?null:Rl(u),p={columnId:null};if(Hl(e,()=>{let n=e.blocks.insert(t.ui,{noSeed:!0},{},l,!1,!1);p.columnId=n.id,e.blocks.setBlockParent(n.id,c);for(let t of r)e.blocks.setBlockParent(t,n.id);t.fi(e,c),Vl(e,c)}),p.columnId!==null){var m,h;let t=e.blocks.getChildren(c);Ll({holders:t.map(e=>e.holder),startWidths:t.map(e=>{var t;return(t=d.get(e.holder))==null?0:t}),newColumnHolder:(m=(h=t.find(e=>e.id===p.columnId))==null?void 0:h.holder)==null?null:m}),f!==null&&zl(f)}return p.columnId},Z={previewOffsetX:10,previewOffsetY:0,dragThreshold:5,autoScrollZone:50,autoScrollSpeed:10,announcementThrottleMs:300,leftDropZone:50,sideZoneRatio:.25,sideZoneMin:48,sideBandRatio:.6},Kl={base:`fixed pointer-events-none z-10000 opacity-80 transition-none`,content:`relative mx-auto max-w-blok-content`},ql=(e,t,n,r,i=Z.dragThreshold)=>{let a=n-e,o=r-t;return Math.sqrt(a*a+o*o)>=i},Jl=class{constructor(e,t,n){this.lastAnnouncedDropIndex=null,this.pendingAnnouncementIndex=null,this.announcementTimeoutId=null,this.blockManager=e,this.i18n=t,this.announcer=n}announceDropPosition(e,t){if(t===`left`||t===`right`)return;let n=this.blockManager.getBlockIndex(e),r=t===`top`?n:n+1;this.lastAnnouncedDropIndex!==r&&(this.pendingAnnouncementIndex=r,this.announcementTimeoutId===null&&(this.announcementTimeoutId=setTimeout(()=>{if(this.pendingAnnouncementIndex===null)return;let e=this.pendingAnnouncementIndex;if(this.announcementTimeoutId=null,this.pendingAnnouncementIndex=null,this.lastAnnouncedDropIndex===e)return;this.lastAnnouncedDropIndex=e;let t=this.blockManager.blocks.length,n=this.i18n.t(`a11y.dropPosition`,{position:e+1,total:t});this.announcer.announce(n,{politeness:`polite`})},Z.announcementThrottleMs)))}announceDropComplete(e,t,n){let r=this.blockManager.getBlockIndex(e),i=this.blockManager.blocks.length;if(n){let e=this.i18n.t(`a11y.blocksMoved`,{count:t.length,position:r+1});this.announcer.announce(e,{politeness:`assertive`})}else{let e=this.i18n.t(`a11y.blockMoved`,{position:r+1,total:i});this.announcer.announce(e,{politeness:`assertive`})}}announceDuplicateComplete(e){let t=e[0];if(!t)return;let n=this.blockManager.getBlockIndex(t),r=e.length;if(r>1){let e=this.i18n.t(`a11y.blocksDuplicated`,{count:r,position:n+1});this.announcer.announce(e,{politeness:`assertive`})}else{let e=this.i18n.t(`a11y.blockDuplicated`,{position:n+1});this.announcer.announce(e,{politeness:`assertive`})}}reset(){this.announcementTimeoutId!==null&&(clearTimeout(this.announcementTimeoutId),this.announcementTimeoutId=null),this.lastAnnouncedDropIndex=null,this.pendingAnnouncementIndex=null}getLastAnnouncedIndex(){return this.lastAnnouncedDropIndex}},Yl=class{constructor(e,t,n){this.blockManager=e,this.yjsManager=t,this.blockSelection=n}moveBlocks(e,t,n){return this.blockManager.getBlockIndex(t)===-1||e.some(e=>this.blockManager.getBlockIndex(e)===-1)?{movedBlocks:[],targetIndex:-1}:e.length===1?this.moveSingleBlock(e[0],t,n):this.moveMultipleBlocks(e,t,n)}async prepareDuplicates(e,t,n){var r=this;if(r.blockManager.getBlockIndex(t)===-1||e.some(e=>r.blockManager.getBlockIndex(e)===-1))return{sortedBlocks:[],sourceIds:new Set,validResults:[],baseInsertIndex:-1,aborted:!0};let i=[...e].sort((e,t)=>r.blockManager.getBlockIndex(e)-r.blockManager.getBlockIndex(t)),a=await Promise.all(i.map(async e=>{let t=await e.save();return t?{saved:t,toolName:e.name}:null})),o=r.blockManager.getBlockIndex(t);if(o===-1)return{sortedBlocks:[],sourceIds:new Set,validResults:[],baseInsertIndex:-1,aborted:!0};let s=n===`top`?o:o+1,c=a.filter(e=>e!==null);return{sortedBlocks:i,sourceIds:new Set(i.map(e=>e.id)),validResults:c,baseInsertIndex:s,aborted:!1}}applyDuplicates(e){if(e.aborted||e.validResults.length===0)return{duplicatedBlocks:[],targetIndex:e.baseInsertIndex};let t=e.validResults.map(({saved:t,toolName:n},r)=>this.blockManager.insert({tool:n,data:structuredClone(t.data),tunes:structuredClone(t.tunes),index:e.baseInsertIndex+r,needToFocus:!1}));if(this.blockManager.setBlockParent!==void 0){let n=new Map;e.sortedBlocks.forEach((e,r)=>{n.set(e.id,t[r].id)}),e.sortedBlocks.forEach((r,i)=>{let a=r.parentId;if(a!==null&&e.sourceIds.has(a)){let e=n.get(a);e!==void 0&&this.blockManager.setBlockParent!==void 0&&this.blockManager.setBlockParent(t[i],e)}})}let n=this.blockSelection;return n&&(n.clearSelection(),t.forEach(e=>{n.selectBlock(e)})),{duplicatedBlocks:t,targetIndex:e.baseInsertIndex}}async duplicateBlocks(e,t,n){var r=this;let i=await r.prepareDuplicates(e,t,n);return r.applyDuplicates(i)}moveSingleBlock(e,t,n){let r=this.blockManager.getBlockIndex(e),i=this.blockManager.getBlockIndex(t),a=n===`top`?i:i+1,o=r<a?a-1:a;if(r===o)return{movedBlocks:[e],targetIndex:r};this.blockManager.move(o,r,!1);let s=this.blockManager.getBlockIndex(e);return this.blockSelection&&this.blockSelection.selectBlock(e),{movedBlocks:[e],targetIndex:s}}moveMultipleBlocks(e,t,n){var r;let i=[...e].sort((e,t)=>this.blockManager.getBlockIndex(e)-this.blockManager.getBlockIndex(t)),a=this.blockManager.getBlockIndex(t),o=n===`top`?a:a+1,s=new Set(e.map(e=>e.id)),c=i.filter(e=>e.parentId===null||!s.has(e.parentId)),l=(r=c[0])==null?i[0]:r,u=o>this.blockManager.getBlockIndex(l),d=i.length>1,f=()=>{u?this.moveBlocksDown(c,o):this.moveBlocksUp(c,o)};d&&this.yjsManager?this.yjsManager.transactMoves(f):f();let p=this.blockSelection;return p&&(p.clearSelection(),i.forEach(e=>{p.selectBlock(e)})),{movedBlocks:i,targetIndex:o}}moveBlocksDown(e,t){let n=new Map;e.forEach(e=>{n.set(e,this.blockManager.getBlockIndex(e))}),[...e].reverse().forEach((e,n)=>{let r=this.blockManager.getBlockIndex(e),i=t-1-n;this.blockManager.move(i,r,!1,!0)}),e.forEach(e=>{var t;e.call(T.MOVED,{fromIndex:(t=n.get(e))==null?0:t,toIndex:this.blockManager.getBlockIndex(e),isGroupMove:!0})})}moveBlocksUp(e,t){let n=new Map;e.forEach(e=>{n.set(e,this.blockManager.getBlockIndex(e))}),e.forEach((e,n)=>{let r=this.blockManager.getBlockIndex(e),i=t+n;r!==i&&this.blockManager.move(i,r,!1,!0)}),e.forEach(e=>{var t;e.call(T.MOVED,{fromIndex:(t=n.get(e))==null?0:t,toIndex:this.blockManager.getBlockIndex(e),isGroupMove:!0})})}},Xl=class{constructor(){this.element=null}createSingle(e,n,i){var a,o,s;let c=t.Qi.make(`div`,Kl.base);c.setAttribute(`data-blok-testid`,`drag-preview`);let l=e.cloneNode(!0);(a=l.querySelector(`[data-blok-toggle-children]`))==null||a.remove(),l.className=r.n(Kl.content,n?`max-w-none`:``);let u=e.getBoundingClientRect().width;u>0&&(l.style.width=`${u}px`);let d=l.firstElementChild;d&&(d.className=r.n(d.className,`m-0!`)),c.appendChild(l);let f=(o=i==null||(s=i.contentIds)==null?void 0:s.length)==null?0:o;if(f>0){let e=t.Qi.make(`span`,`absolute bottom-1 right-1 text-xs text-gray-400 bg-white/80 px-1 rounded`);e.setAttribute(`data-blok-children-badge`,``),e.textContent=`+${f}`,c.appendChild(e)}return this.element=c,c}createMulti(e){let n=t.Qi.make(`div`,Kl.base);n.setAttribute(`data-blok-testid`,`drag-preview`);let i=e.map(e=>{let t=e.holder.getBoundingClientRect(),n=e.holder.querySelector(`[data-blok-element-content]`);if(!n)return{width:0,height:0,element:null,holderHeight:0};let r=n.getBoundingClientRect();return{width:r.width,height:r.height,element:n,holderHeight:t.height}}),a=i.reduce((e,t,n)=>{if(n===0)e.push(0);else{let t=e[n-1],r=i[n-1].holderHeight;e.push(t+r)}return e},[]),o=Math.max(...i.map(e=>e.width),0),s=i.length-1,c=s>=0?a[s]+i[s].height:0;return e.forEach((t,o)=>{var s;let c=i[o];if(!c.element)return;let l=c.element.cloneNode(!0);(s=l.querySelector(`[data-blok-toggle-children]`))==null||s.remove(),l.className=r.n(Kl.content,t.stretched?`max-w-none`:``);let u=l.firstElementChild;u&&(u.className=r.n(u.className,`m-0!`)),l.style.position=`absolute`,l.style.top=`${a[o]}px`,l.style.left=`0`,l.style.zIndex=`${e.length-o}`,n.appendChild(l)}),n.style.width=`${o}px`,n.style.height=`${c}px`,this.element=n,n}updatePosition(e,t){this.element&&(this.element.style.left=`${e+Z.previewOffsetX}px`,this.element.style.top=`${t+Z.previewOffsetY}px`)}show(){this.element&&(this.element.style.display=`block`)}hide(){this.element&&(this.element.style.display=`none`)}getElement(){return this.element}exists(){return this.element!==null}release(){let e=this.element;return this.element=null,e}destroy(){this.element&&this.element.parentNode&&this.element.remove(),this.element=null}},Zl=e=>e.type===`tracking`||e.type===`dragging`,Q=e=>e.type===`dragging`||e.type===`dropped`,Ql=class{constructor(){this.state={type:`idle`}}getState(){return this.state}startTracking(e,t,n,r){if(this.state.type!==`idle`)throw Error(`Cannot start tracking from state "${this.state.type}", must be idle`);let i=t.length>1;return this.state={type:`tracking`,sourceBlock:e,sourceBlocks:t,isMultiBlockDrag:i,startX:n,startY:r},this.state}startDrag(){if(this.state.type!==`tracking`)throw Error(`Cannot start drag from state "${this.state.type}", must be tracking`);return this.state={type:`dragging`,sourceBlock:this.state.sourceBlock,sourceBlocks:this.state.sourceBlocks,isMultiBlockDrag:this.state.isMultiBlockDrag,targetBlock:null,targetEdge:null,targetParentId:null,startX:this.state.startX,startY:this.state.startY},this.state}updateTarget(e,t,r=null){if(this.state.type!==`dragging`)throw Error(`Cannot update target from state "${this.state.type}", must be dragging`);this.state=n.t(n.t({},this.state),{},{targetBlock:e,targetEdge:t,targetParentId:r})}drop(){if(this.state.type!==`dragging`)throw Error(`Cannot drop from state "${this.state.type}", must be dragging`);if(!this.state.targetBlock||!this.state.targetEdge)throw Error(`Cannot drop: no valid target`);return this.state={type:`dropped`,sourceBlock:this.state.sourceBlock,sourceBlocks:this.state.sourceBlocks,isMultiBlockDrag:this.state.isMultiBlockDrag,targetBlock:this.state.targetBlock,targetEdge:this.state.targetEdge,targetParentId:this.state.targetParentId},this.state}cancel(){if(this.state.type!==`tracking`&&this.state.type!==`dragging`)throw Error(`Cannot cancel from state "${this.state.type}", must be tracking or dragging`);return this.state={type:`cancelled`,sourceBlock:this.state.sourceBlock,sourceBlocks:this.state.sourceBlocks},this.state}reset(){return this.state={type:`idle`},this.state}getSourceBlocks(){switch(this.state.type){case`tracking`:case`dragging`:case`dropped`:case`cancelled`:return this.state.sourceBlocks;case`idle`:return null}}getSourceBlock(){switch(this.state.type){case`tracking`:case`dragging`:case`dropped`:case`cancelled`:return this.state.sourceBlock;case`idle`:return null}}isMultiBlockDrag(){switch(this.state.type){case`tracking`:case`dragging`:case`dropped`:return this.state.isMultiBlockDrag;case`cancelled`:case`idle`:return!1}}isSourceBlock(e){let t=this.getSourceBlocks();return t?t.includes(e):!1}},$l=e=>{let t=e.holder.getAttribute(`data-list-depth`);if(t!==null&&t!==``){let e=parseInt(t,10);return isNaN(e)?null:e}let n=e.holder.querySelector(`[data-list-depth]`);if(!n)return null;let r=n.getAttribute(`data-list-depth`);if(r&&r!==``){let e=parseInt(r,10);return isNaN(e)?0:e}return 0},eu=class{constructor(e){this.blockManager=e}getDepth(e){return $l(e)}calculateTargetDepth(e,t){var n,r;let i=this.blockManager.getBlockIndex(e),a=t===`top`?i:i+1;if(a===0)return 0;let o=this.blockManager.getBlockByIndex(a-1);if(!o)return 0;let s=(n=$l(o))==null?0:n,c=this.blockManager.getBlockByIndex(a),l=c?(r=$l(c))==null?0:r:0;return l>0&&l<=s+1?l:s>0?s:0}},tu=class{constructor(e,t){this.sourceBlocks=[],this.ui=e,this.blockManager=t,this.listItemDepth=new eu(t)}setSourceBlocks(e){this.sourceBlocks=e}findDropTargetBlock(e,n,r){let i=e.closest(`[data-blok-toggle-body-placeholder]`);if(i){let e=i.closest(t.Na(t.Ma.element));if(!(e instanceof HTMLElement))return{block:void 0,holder:null};let n=this.blockManager.blocks.find(t=>t.holder===e);if(n)return{block:n,holder:e}}let a=e.closest(t.Na(t.Ma.element));if(a instanceof HTMLElement)return{block:this.blockManager.blocks.find(e=>e.holder===a),holder:a};let o=this.findBlockInLeftDropZone(n,r);return o?{block:o,holder:o.holder}:{block:void 0,holder:null}}findBlockInLeftDropZone(e,t){let n=this.ui.contentRect.left-e;if(n<0||n>Z.leftDropZone)return null;for(let e of this.blockManager.blocks){if(this.sourceBlocks.includes(e))continue;let n=e.holder.getBoundingClientRect();if(t>=n.top&&t<=n.bottom)return e}return null}determineDropTarget(e,t,n,r){let i=this.determineColumnGapTarget(e,n);if(i&&i.block!==r)return i;let a=this.findDropTargetBlock(e,t,n);if(!a.holder||!a.block||a.block===r)return null;let{block:o,holder:s}=this.redirectColumnContainerTarget(a.block,a.holder);if(this.sourceBlocks.length>1&&this.sourceBlocks.includes(o))return null;let c=o.holder.closest(`[data-blok-table-cell-blocks]`),l=r.holder.closest(`[data-blok-table-cell-blocks]`);if(c!==null&&l!==c)return this.redirectToTableBlock(c,n);let u=this.determineHorizontalTarget(o,s,t,n);if(u)return u;let d=s.getBoundingClientRect(),f=n<d.top+d.height/2,p=this.blockManager.getBlockIndex(o),m=p>0?this.blockManager.getBlockByIndex(p-1):null,h=m&&!this.sourceBlocks.includes(m)&&m.parentId===o.parentId;if(f&&p>0&&h){let t=this.calculateTargetDepth(m,`bottom`,r);return this.resolveToggleNesting({block:m,edge:`bottom`,depth:t,parentId:null},e)}let g=f?`top`:`bottom`,_=this.calculateTargetDepth(o,g,r);return this.resolveToggleNesting({block:o,edge:g,depth:_,parentId:null},e)}determineHorizontalTarget(e,t,n,r){if(window.innerWidth<651)return null;if(e.name===`column_list`)return this.outerColumnListTarget(e,t,n,r);if(e.name===`column`)return null;let i=t.querySelector(`[data-blok-element-content]`),a=i instanceof HTMLElement?i.getBoundingClientRect():t.getBoundingClientRect();if(t.closest(`[data-blok-columns]`)instanceof HTMLElement){let t=a.height*(1-Z.sideBandRatio)/2;if(!(r>=a.top+t&&r<=a.bottom-t))return null;let i=Math.max(a.width*Z.sideZoneRatio,Z.sideZoneMin),o=n<=a.left+i,s=n>=a.right-i;return o&&this.isFirstColumnChild(e)?{block:e,edge:`left`,depth:0,parentId:this.findEnclosingColumnId(e)}:s&&this.isLastColumnChild(e)?{block:e,edge:`right`,depth:0,parentId:this.findEnclosingColumnId(e)}:null}let o=a.height*(1-Z.sideBandRatio)/2;if(!(r>=a.top+o&&r<=a.bottom-o))return null;let s=Math.max(a.width*Z.sideZoneRatio,Z.sideZoneMin),c=n<=a.left+s,l=n>=a.right-s;return!c&&!l?null:{block:e,edge:c?`left`:`right`,depth:0,parentId:this.findEnclosingColumnId(e)}}outerColumnListTarget(e,t,n,r){let i=t.querySelector(`[data-blok-element-content]`),a=i instanceof HTMLElement?i.getBoundingClientRect():t.getBoundingClientRect(),o=a.height*(1-Z.sideBandRatio)/2;if(!(r>=a.top+o&&r<=a.bottom-o))return null;let s=Math.max(a.width*Z.sideZoneRatio,Z.sideZoneMin),c=n<=a.left+s,l=n>=a.right-s;if(!c&&!l)return null;let u=c?`left`:`right`,d=this.blockManager.blocks.filter(t=>t.parentId===e.id),f=u===`left`?d[0]:d[d.length-1];if(f===void 0)return null;let p=this.blockManager.blocks.find(e=>e.parentId===f.id);return p===void 0?null:{block:p,edge:u,depth:0,parentId:f.id}}columnHolderOf(e){let n=e.holder.closest(`[data-blok-column]`);if(!(n instanceof HTMLElement))return null;let r=n.closest(t.Na(t.Ma.element));return r instanceof HTMLElement?r:null}isFirstColumnChild(e){let t=this.columnHolderOf(e);return t!==null&&this.previousColumnHolder(t)===null}isLastColumnChild(e){let t=this.columnHolderOf(e);return t!==null&&this.nextColumnHolder(t)===null}nextColumnHolder(e){let n=e.nextElementSibling;return n===null?null:n instanceof HTMLElement&&n.matches(t.Na(t.Ma.element))?n:this.nextColumnHolder(n)}previousColumnHolder(e){let n=e.previousElementSibling;return n===null?null:n instanceof HTMLElement&&n.matches(t.Na(t.Ma.element))?n:this.previousColumnHolder(n)}firstBlockInColumnHolder(e){let n=e.querySelector(t.Na(t.Ma.element));return n instanceof HTMLElement?this.blockManager.blocks.find(e=>e.holder===n):void 0}lastChildOfColumn(e){let t=this.blockManager.blocks.filter(t=>t.parentId===e.id);return t[t.length-1]}redirectColumnContainerTarget(e,t){if(e.name!==`column`)return{block:e,holder:t};let n=this.lastChildOfColumn(e);return n===void 0||this.sourceBlocks.includes(n)?{block:e,holder:t}:{block:n,holder:n.holder}}determineColumnGapTarget(e,t){if(window.innerWidth<651)return null;let n=e.closest(`[data-blok-column-resizer]`);if(!(n instanceof HTMLElement))return null;let r=this.stackIntoGapColumn(n,t);if(r!==null)return r;let i=this.nextColumnHolder(n),a=i===null?void 0:this.firstBlockInColumnHolder(i);return a===void 0?null:{block:a,edge:`left`,depth:0,parentId:this.findEnclosingColumnId(a)}}stackIntoGapColumn(e,t){let n=this.previousColumnHolder(e),r=this.nextColumnHolder(e);if(n===null||r===null)return null;let i=this.blockManager.blocks.find(e=>e.holder===n),a=this.blockManager.blocks.find(e=>e.holder===r);if(i===void 0||a===void 0)return null;let o=this.columnContentBottom(i),s=this.columnContentBottom(a);return o===null||s===null?null:t>o&&t<=s?this.stackIntoColumnTarget(i):t>s&&t<=o?this.stackIntoColumnTarget(a):null}columnContentBottom(e){let t=this.lastChildOfColumn(e);if(t===void 0)return null;let n=t.holder.querySelector(`[data-blok-element-content]`);return(n instanceof HTMLElement?n.getBoundingClientRect():t.holder.getBoundingClientRect()).bottom}stackIntoColumnTarget(e){let t=this.lastChildOfColumn(e);return t===void 0||this.sourceBlocks.includes(t)?null:{block:t,edge:`bottom`,depth:0,parentId:null}}findEnclosingColumnId(e){let t=e=>{if(e===null)return null;let n=this.blockManager.getBlockById(e);return n===void 0?null:n.name===`column`?n.id:t(n.parentId)};return t(e.parentId)}calculateTargetDepth(e,t,n){let r=this.blockManager.getBlockIndex(e),i=t===`top`?r:r+1;if(i===0)return 0;let a=this.blockManager.getBlockByIndex(i-1);if(!a)return 0;let o=this.listItemDepth.getDepth(a),s=o!==null,c=o==null?0:o,l=this.blockManager.getBlockByIndex(i),u=l?this.listItemDepth.getDepth(l):null,d=u!==null,f=u==null?0:u,p=n?this.listItemDepth.getDepth(n):null;return p===null?f>0&&f<=c+1?f:c>0?c:0:this.predictListItemDepth(p,c,s,f,d)}predictListItemDepth(e,t,n,r,i){let a=n?t+1:0;return e>a?a:i&&r>e&&r<=a?r:n&&!i&&t>e&&t<=a?t:e}isOpenToggle(e){return e.holder.querySelector(`[data-blok-toggle-open="true"]`)!==null}getToggleChildIndicatorDepth(e){return 0}resolveToggleNesting(e,t){let{block:r,edge:i}=e;if(i===`bottom`&&this.isOpenToggle(r)&&!(this.sourceBlocks.length>0&&this.sourceBlocks.every(e=>e.parentId===r.id))){let t=this.getToggleChildIndicatorDepth(r);return n.t(n.t({},e),{},{parentId:r.id,depth:t})}if(r.parentId!==null){let t=this.blockManager.getBlockById(r.parentId);if(t!==void 0&&this.isOpenToggle(t)){let r=this.getToggleChildIndicatorDepth(t);return n.t(n.t({},e),{},{parentId:t.id,depth:r})}}return n.t(n.t({},e),{},{parentId:null})}redirectToTableBlock(e,n){let r=e.closest(t.Na(t.Ma.element)),i=r?this.blockManager.blocks.find(e=>e.holder===r):void 0;if(!i)return null;let a=i.holder.getBoundingClientRect();return{block:i,edge:n<a.top+a.height/2?`top`:`bottom`,depth:0,parentId:null}}},nu=class{constructor(e){this.animationFrameId=null,this.scrollDirection=null,this.scrollContainer=e}start(e){let t=window.innerHeight,n=e<Z.autoScrollZone,r=e>t-Z.autoScrollZone;if(!n&&!r){this.stop();return}let i=n?`up`:`down`;this.scrollDirection!==i&&(this.stop(),this.scrollDirection=i),this.animationFrameId===null&&(this.animationFrameId=requestAnimationFrame(this.scroll.bind(this)))}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.scrollDirection=null}scroll(){if(this.scrollDirection===null)return;let e=(this.scrollDirection===`up`?-1:1)*Z.autoScrollSpeed;this.scrollContainer?this.scrollContainer.scrollTop+=e:window.scrollBy(0,e),this.animationFrameId=requestAnimationFrame(this.scroll.bind(this))}destroy(){this.stop()}},ru=500,iu=`data-blok-spring-loading`,au=`data-blok-spring-loaded`,ou=700;function su(e){return e.holder.querySelector(`[data-blok-toggle-open="false"]`)!==null}var cu=class{constructor(){this.timerId=null,this.currentBlock=null}update(e){if(e!==this.currentBlock){if(this.clearTimer(),e===null||!su(e)){this.currentBlock=null;return}this.currentBlock=e,e.holder.setAttribute(iu,``),this.timerId=setTimeout(()=>{if(this.timerId=null,this.currentBlock){this.currentBlock.holder.removeAttribute(iu),this.currentBlock.call(`expand`),this.currentBlock.holder.setAttribute(au,``);let e=this.currentBlock;setTimeout(()=>e.holder.removeAttribute(au),ou),this.currentBlock=null}},ru)}}cancel(){this.clearTimer(),this.currentBlock=null}clearTimer(){this.timerId!==null&&(clearTimeout(this.timerId),this.timerId=null),this.currentBlock&&(this.currentBlock.holder.removeAttribute(iu),this.currentBlock=null)}},lu=e=>{if(!e||e===document.body)return null;let t=e.parentElement;if(!t||t===document.body)return null;let n=window.getComputedStyle(t).overflowY,r=n===`auto`||n===`scroll`,i=t.scrollHeight>t.clientHeight;return r&&i?t:lu(t)},uu=class{constructor(e){this.blockManager=e}getDescendants(e){let t=$l(e);if(t===null)return[];let n=this.blockManager.getBlockIndex(e);return this.collectDescendants(n+1,t,[])}collectDescendants(e,t,n){if(e>=this.blockManager.blocks.length)return n;let r=this.blockManager.getBlockByIndex(e);if(!r)return n;let i=$l(r);return i===null||i<=t?n:this.collectDescendants(e+1,t,[...n,r])}},du=class extends s{constructor(...e){super(...e),this.stateMachine=new Ql,this.preview=new Xl,this.targetDetector=null,this.operations=null,this.a11y=null,this.autoScroll=null,this.springLoader=new cu,this.listItemDescendants=null,this.boundHandlers=null,this.dragHandleCleanups=new WeakMap,this.sourceBlockDestroyUnsubs=[]}get isDragging(){return Q(this.stateMachine.getState())}async prepare(){}lazyInit(){this.targetDetector&&this.operations&&this.a11y&&this.listItemDescendants||(this.targetDetector=new tu({contentRect:this.Blok.UI.contentRect},this.Blok.BlockManager),this.operations=new Yl(this.Blok.BlockManager,this.Blok.YjsManager,this.Blok.BlockSelection),this.a11y=new Jl(this.Blok.BlockManager,this.Blok.I18n,{announce:sl}),this.listItemDescendants=new uu(this.Blok.BlockManager))}cancelTracking(){Zl(this.stateMachine.getState())&&!Q(this.stateMachine.getState())&&this.cleanup(!1,!0)}onSourceBlockDestroyed(){Zl(this.stateMachine.getState())&&this.cleanup(!0,!0)}setupDragHandle(e,n){var r;(r=this.dragHandleCleanups.get(e))==null||r();let i=r=>{var i;if(r.button!==0||document.querySelector(`[${t.Ma.popoverOpened}]`)!==null)return;let a=e.closest(`[${t.Ma.id}]`),o=(i=a==null?void 0:a.getAttribute(t.Ma.id))==null?null:i;if(o!==null){let e=this.Blok.BlockManager.getBlockById(o);if(e===void 0)return;this.startDragTracking(r,e);return}this.startDragTracking(r,n)};e.addEventListener(`mousedown`,i);let a=()=>{e.removeEventListener(`mousedown`,i),this.dragHandleCleanups.get(e)===a&&this.dragHandleCleanups.delete(e)};return this.dragHandleCleanups.set(e,a),a}startDragTracking(e,t){var n;this.lazyInit();let r=t.holder.querySelector(`[data-blok-element-content]`);if(!r||!(r instanceof HTMLElement))return;let i=t.selected,a=i?this.Blok.BlockSelection.selectedBlocks:[t],o=!i&&this.listItemDescendants?this.listItemDescendants.getDescendants(t):[],s=!i&&((n=t.contentIds)==null?void 0:n.length)>0,c=o.length===0&&s?this.getHierarchyDescendants(t):[],l=o.length>0?o:c,u=l.length>0?[t,...l]:a,d=new Set(u.map(e=>e.id)),f=u.filter(e=>e.parentId===null||!d.has(e.parentId));f.length>1&&c.length===0?this.preview.createMulti(f):this.preview.createSingle(r,t.stretched,t),this.preview.hide();let p=this.preview.getElement();p&&document.body.appendChild(p),this.stateMachine.startTracking(t,u,e.clientX,e.clientY),this.sourceBlockDestroyUnsubs=u.filter(e=>typeof e.addDestroyCallback==`function`).map(e=>e.addDestroyCallback(()=>this.onSourceBlockDestroyed()));let m=lu(this.Blok.UI.nodes.wrapper);this.autoScroll=new nu(m),this.targetDetector&&this.targetDetector.setSourceBlocks(u),this.boundHandlers={onMouseMove:this.onMouseMove.bind(this),onMouseUp:this.onMouseUp.bind(this),onKeyDown:this.onKeyDown.bind(this),onKeyUp:this.onKeyUp.bind(this)},document.addEventListener(`mousemove`,this.boundHandlers.onMouseMove),document.addEventListener(`mouseup`,this.boundHandlers.onMouseUp),document.addEventListener(`keydown`,this.boundHandlers.onKeyDown),document.addEventListener(`keyup`,this.boundHandlers.onKeyUp)}onMouseMove(e){let t=this.stateMachine.getState(),n=this.stateMachine.getSourceBlock(),r=this.stateMachine.getSourceBlocks();if(!n||!r)return;let{startX:i,startY:a}=t;!Q(t)&&ql(i,a,e.clientX,e.clientY)&&this.startActualDrag(r.length),this.preview.updatePosition(e.clientX,e.clientY),this.updateDropTarget(e.clientX,e.clientY),this.autoScroll&&Q(t)&&this.autoScroll.start(e.clientY)}startActualDrag(e){Fl(),this.stateMachine.startDrag(),this.Blok.Toolbar.skipNextSettingsToggle(),this.preview.show();let n=this.Blok.UI.nodes.wrapper;n.setAttribute(t.Ma.dragging,`true`),e>1&&n.setAttribute(t.Ma.draggingMulti,`true`),e===1&&this.Blok.BlockSelection.clearSelection(),t.bi(),this.Blok.Toolbar.close({setExplicitlyClosed:!1});let r=e>1?`a11y.dragStartedMultiple`:`a11y.dragStarted`,i=e>1?{count:e}:void 0;sl(this.Blok.I18n.t(r,i),{politeness:`assertive`})}updateDropTarget(e,t){let n=this.stateMachine.getState(),r=this.stateMachine.getSourceBlock();if(!Q(n)||!r||!this.targetDetector)return;let i=this.stateMachine.getState();i.type===`dragging`&&i.targetBlock&&(i.targetBlock.holder.removeAttribute(`data-drop-indicator`),i.targetBlock.holder.style.removeProperty(`--drop-indicator-depth`),this.clearContentIndicatorOffsets(i.targetBlock)),this.preview.hide();let a=document.elementFromPoint(e,t);if(this.preview.show(),!a){this.stateMachine.updateTarget(null,null),this.springLoader.update(null);return}let o=this.targetDetector.determineDropTarget(a,e,t,r);if(!o){this.stateMachine.updateTarget(null,null),this.springLoader.update(null);return}this.stateMachine.updateTarget(o.block,o.edge,o.parentId),this.springLoader.update(o.block),o.block.holder.setAttribute(`data-drop-indicator`,o.edge),o.block.holder.style.setProperty(`--drop-indicator-depth`,String(o.depth)),this.applyContentIndicatorOffsets(o.block),this.applySideIndicatorHeight(o.block,o.edge),this.centerSideIndicatorInGutter(o.block,o.edge),this.a11y&&this.a11y.announceDropPosition(o.block,o.edge)}applyContentIndicatorOffsets(e){let t=e.holder.querySelector(`[data-blok-element-content]`);if(!(t instanceof HTMLElement))return;let n=e.holder.getBoundingClientRect(),r=t.getBoundingClientRect();e.holder.style.setProperty(`--drop-indicator-side-left`,`${r.left-n.left}px`),e.holder.style.setProperty(`--drop-indicator-side-right`,`${n.right-r.right}px`)}applySideIndicatorHeight(e,t){if(t!==`left`&&t!==`right`)return;let n=e.holder.closest(`[data-blok-columns]`);if(!(n instanceof HTMLElement))return;let r=e.holder.getBoundingClientRect(),i=n.getBoundingClientRect();e.holder.style.setProperty(`--drop-indicator-side-top`,`${i.top-r.top}px`),e.holder.style.setProperty(`--drop-indicator-side-bottom`,`${r.bottom-i.bottom}px`)}centerSideIndicatorInGutter(e,t){if(t!==`left`&&t!==`right`)return;let n=e.holder.closest(`[data-blok-column]`),r=n instanceof HTMLElement?n.closest(`[data-blok-element]`):null;if(!(r instanceof HTMLElement))return;let i=t===`left`?r.previousElementSibling:r.nextElementSibling;if(!(i instanceof HTMLElement)||!i.hasAttribute(`data-blok-column-resizer`))return;let a=e.holder.getBoundingClientRect(),o=i.getBoundingClientRect(),s=o.left+o.width/2,c=parseFloat(getComputedStyle(e.holder).getPropertyValue(`--blok-space-2`))||0;t===`left`?e.holder.style.setProperty(`--drop-indicator-side-left`,`${s-a.left+c}px`):e.holder.style.setProperty(`--drop-indicator-side-right`,`${a.right-s+c}px`)}clearContentIndicatorOffsets(e){e.holder.style.removeProperty(`--drop-indicator-side-left`),e.holder.style.removeProperty(`--drop-indicator-side-right`),e.holder.style.removeProperty(`--drop-indicator-side-top`),e.holder.style.removeProperty(`--drop-indicator-side-bottom`)}onMouseUp(e){let t=this.stateMachine.getState(),n=this.stateMachine.getSourceBlock(),r=this.stateMachine.getSourceBlocks();if(!n||!r||!Q(t)){this.cleanup();return}let{targetBlock:i,targetEdge:a,targetParentId:o}=t;if(!i||!a){this.cleanup();return}if(this.stateMachine.drop(),!this.operations){this.cleanup();return}if(a===`left`||a===`right`){this.handleColumnDrop(n,r,i,a,o),this.cleanup(!1,e.altKey);return}e.altKey?this.handleDuplicate(r,i,a):this.handleDrop(n,r,i,a),this.cleanup(!1,e.altKey)}handleColumnDrop(e,t,n,r,i){let a=this.Blok.API.methods,o=(t.length>0?t:[e]).filter(e=>e.id!==n.id),s=new Set(o.map(e=>e.id)),c=o.filter(e=>e.parentId===null||!s.has(e.parentId)).map(e=>e.id);if(c.length===0)return;let l=new Set(c.map(e=>{var t;return(t=this.Blok.BlockManager.getBlockById(e))==null?void 0:t.parentId}).filter(e=>e!=null)),u=i===null?Ul(a,n.id,c,r):Gl(a,i,c,r);this.reseedEmptiedColumns(l),u!==null&&this.settleDroppedPreview(c[0])}settleDroppedPreview(e){var t,n;let r=this.preview.release();if(r===null)return;let i=(t=this.Blok.BlockManager.getBlockById(e))==null?void 0:t.holder,a=(n=i==null?void 0:i.querySelector(`[data-blok-element-content]`))==null?i:n;if(a==null){r.remove();return}let o=a.getBoundingClientRect();Bl({preview:r,targetRect:{left:o.left,top:o.top}})}reseedEmptiedColumns(e){for(let t of e){let e=this.Blok.BlockManager.getBlockById(t);e!==void 0&&e.name===`column`&&e.contentIds.length===0&&e.call(`rendered`)}}handleDrop(e,t,n,r){let i=this.Blok.YjsManager;if(i!==void 0&&typeof i.transactMoves==`function`){i.transactMoves(()=>{this.handleDropImpl(e,t,n,r)});return}this.handleDropImpl(e,t,n,r)}handleDropImpl(e,t,n,r){let i=t.length>1;if(!this.operations)return;let a=new Map;for(let e of t)a.set(e.id,e.parentId);let o=this.operations.moveBlocks(t,n,r);if(o.movedBlocks.length===0)return;let s=this.resolveParentForDrop(n,r,t,a),c=new Set(o.movedBlocks.map(e=>e.id)),l=[],u=new Set;for(let e of o.movedBlocks){if(e.parentId!==null&&c.has(e.parentId)){this.Blok.BlockManager.setBlockParent(e,e.parentId);continue}if(e.parentId===s&&s!==null){this.Blok.BlockManager.setBlockParent(e,s);continue}let t=e.parentId;t!==null&&u.add(t),s!==null&&u.add(s),this.Blok.BlockManager.setBlockParent(e,s),l.push(e)}for(let e of u){let t=this.Blok.BlockManager.getBlockById(e);t!==void 0&&t.call(`rendered`)}s!==null&&l.length>0&&this.hideBlocksIfParentCollapsed(s,l);let d=this.Blok.BlockManager.getBlockByIndex(o.targetIndex);this.a11y&&d&&this.a11y.announceDropComplete(d,t,i),this.Blok.Toolbar.moveAndOpen(e)}resolveParentForDrop(e,t,n,r){return t===`bottom`&&this.isToggleableBlock(e)&&this.isOpenToggle(e)&&!(n.length>0&&n.every(t=>((r==null?void 0:r.has(t.id))===!0?r.get(t.id):t.parentId)===e.id))?e.id:e.parentId===null?null:e.parentId}isToggleableBlock(e){return e.holder.querySelector(`[data-blok-toggle-open]`)!==null}isOpenToggle(e){return e.holder.querySelector(`[data-blok-toggle-open="true"]`)!==null}hideBlocksIfParentCollapsed(e,t){if(t.length===0)return;let n=this.Blok.BlockManager.getBlockById(e);if(n===void 0)return;let r=n.holder.querySelector(`[data-blok-toggle-open]`);if((r==null?void 0:r.getAttribute(`data-blok-toggle-open`))===`false`)for(let e of t)e.holder.classList.add(`hidden`)}async handleDuplicate(e,t,n){var r=this;if(!r.operations)return;let i=await r.operations.prepareDuplicates(e,t,n);if(i.aborted)return;let a={current:{duplicatedBlocks:[],targetIndex:i.baseInsertIndex}},o=()=>{if(!r.operations||(a.current=r.operations.applyDuplicates(i),a.current.duplicatedBlocks.length===0))return;let o=r.resolveParentForDrop(t,n,e);for(let e of a.current.duplicatedBlocks)e.parentId!==o&&r.Blok.BlockManager.setBlockParent(e,o)};typeof r.Blok.BlockManager.transactForTool==`function`?r.Blok.BlockManager.transactForTool(o):o();let s=a.current;if(s.duplicatedBlocks.length===0)return;let c=r.resolveParentForDrop(t,n,e),l=new Set;for(let e of s.duplicatedBlocks)e.parentId===c&&c!==null&&l.add(c);for(let e of l){let t=r.Blok.BlockManager.getBlockById(e);t!==void 0&&t.call(`rendered`)}if(c!==null){let e=s.duplicatedBlocks.filter(e=>e.parentId===c);r.hideBlocksIfParentCollapsed(c,e)}r.a11y&&r.a11y.announceDuplicateComplete(s.duplicatedBlocks),r.Blok.Toolbar.moveAndOpen(s.duplicatedBlocks[0])}onKeyDown(e){if(e.key===`Escape`){this.cleanup(!0);return}e.key===`Alt`&&Q(this.stateMachine.getState())&&this.setDuplicationMode(!0)}onKeyUp(e){e.key===`Alt`&&Q(this.stateMachine.getState())&&this.setDuplicationMode(!1)}setDuplicationMode(e){let n=this.Blok.UI.nodes.wrapper;e?n.setAttribute(t.Ma.duplicating,`true`):n.removeAttribute(t.Ma.duplicating)}cleanup(e=!1,n=!1){if(e&&Q(this.stateMachine.getState())&&sl(this.Blok.I18n.t(`a11y.dropCancelled`),{politeness:`polite`}),e){var r,i,a,o;(r=(i=this.Blok.UI).resetBlockHoverState)==null||r.call(i),(a=(o=this.Blok.Toolbar).resetExplicitlyClosed)==null||a.call(o)}this.autoScroll&&(this.autoScroll.destroy(),this.autoScroll=null),this.a11y&&this.a11y.reset();let s=this.stateMachine.getState();(s.type===`dragging`||s.type===`dropped`)&&s.targetBlock&&(s.targetBlock.holder.removeAttribute(`data-drop-indicator`),s.targetBlock.holder.style.removeProperty(`--drop-indicator-depth`),this.clearContentIndicatorOffsets(s.targetBlock)),this.springLoader.cancel(),this.preview.destroy();let c=this.Blok.UI.nodes.wrapper;c.removeAttribute(t.Ma.dragging),c.removeAttribute(t.Ma.draggingMulti),c.removeAttribute(t.Ma.duplicating),this.boundHandlers&&(document.removeEventListener(`mousemove`,this.boundHandlers.onMouseMove),document.removeEventListener(`mouseup`,this.boundHandlers.onMouseUp),document.removeEventListener(`keydown`,this.boundHandlers.onKeyDown),document.removeEventListener(`keyup`,this.boundHandlers.onKeyUp),this.boundHandlers=null),this.sourceBlockDestroyUnsubs.forEach(e=>e()),this.sourceBlockDestroyUnsubs=[];let l=this.stateMachine.getSourceBlock();if(this.stateMachine.reset(),this.targetDetector&&this.targetDetector.setSourceBlocks([]),e||n)return;let u=l==null?this.Blok.BlockManager.currentBlock:l;u&&this.Blok.Toolbar.moveAndOpen(u)}getHierarchyDescendants(e){let t=[],n=e=>{for(let r of e.contentIds){let e=this.Blok.BlockManager.getBlockById(r);e!==void 0&&(t.push(e),n(e))}};return n(e),t}destroy(){Fl(),this.cleanup()}},fu=new Set([`ar`,`dv`,`fa`,`he`,`ku`,`ps`,`sd`,`ug`,`ur`,`yi`]),pu=e=>fu.has(e)?`rtl`:`ltr`,mu=(e,t)=>({dictionary:t,direction:pu(e)}),hu=`am.ar.az.bg.bn.bs.cs.da.de.dv.el.en.es.et.fa.fi.fil.fr.gu.he.hi.hr.hu.hy.id.it.ja.ka.km.kn.ko.ku.lo.lt.lv.mk.ml.mn.mr.ms.my.ne.nl.no.pa.pl.ps.pt.ro.ru.sd.si.sk.sl.sq.sr.sv.sw.ta.te.th.tr.ug.uk.ur.vi.yi.zh`.split(`.`),gu=mu(`en`,a.r),_u=new Map;_u.set(`en`,gu);var vu={am:()=>Promise.resolve().then(()=>require(`./messages-Dh79ToYM.cjs`)),ar:()=>Promise.resolve().then(()=>require(`./messages-DIeUb2w-.cjs`)),az:()=>Promise.resolve().then(()=>require(`./messages-BscUmD6D.cjs`)),bg:()=>Promise.resolve().then(()=>require(`./messages-D6y13edn.cjs`)),bn:()=>Promise.resolve().then(()=>require(`./messages-C8f4kUOB.cjs`)),bs:()=>Promise.resolve().then(()=>require(`./messages-JyzorVPx.cjs`)),cs:()=>Promise.resolve().then(()=>require(`./messages-DUbZA-w_.cjs`)),da:()=>Promise.resolve().then(()=>require(`./messages-B4ZVgIh5.cjs`)),de:()=>Promise.resolve().then(()=>require(`./messages-BLNieIb-.cjs`)),dv:()=>Promise.resolve().then(()=>require(`./messages-BEEGgtPo.cjs`)),el:()=>Promise.resolve().then(()=>require(`./messages-BRbGk1-Z.cjs`)),en:()=>Promise.resolve({default:a.r}),es:()=>Promise.resolve().then(()=>require(`./messages-C3SZsVB9.cjs`)),et:()=>Promise.resolve().then(()=>require(`./messages-JYea02IT.cjs`)),fa:()=>Promise.resolve().then(()=>require(`./messages-BL-E2Kw3.cjs`)),fi:()=>Promise.resolve().then(()=>require(`./messages-4Qka94cm.cjs`)),fil:()=>Promise.resolve().then(()=>require(`./messages-BX86v7Ev.cjs`)),fr:()=>Promise.resolve().then(()=>require(`./messages-Dh9psewW.cjs`)),gu:()=>Promise.resolve().then(()=>require(`./messages-CNMPtWiq.cjs`)),he:()=>Promise.resolve().then(()=>require(`./messages-Dv4oyF7T.cjs`)),hi:()=>Promise.resolve().then(()=>require(`./messages-Df6vXDrY.cjs`)),hr:()=>Promise.resolve().then(()=>require(`./messages-Vp8CpYh3.cjs`)),hu:()=>Promise.resolve().then(()=>require(`./messages-cSHh8Zgv.cjs`)),hy:()=>Promise.resolve().then(()=>require(`./messages-Br_qu_wR.cjs`)),id:()=>Promise.resolve().then(()=>require(`./messages-sTyGkmbu.cjs`)),it:()=>Promise.resolve().then(()=>require(`./messages-AtTKtjsQ.cjs`)),ja:()=>Promise.resolve().then(()=>require(`./messages-BJcc9h6p.cjs`)),ka:()=>Promise.resolve().then(()=>require(`./messages-BWh9I5Jv2.cjs`)),km:()=>Promise.resolve().then(()=>require(`./messages-PpRvDwOa2.cjs`)),kn:()=>Promise.resolve().then(()=>require(`./messages-DLYl6KdK2.cjs`)),ko:()=>Promise.resolve().then(()=>require(`./messages-9bK437Rh.cjs`)),ku:()=>Promise.resolve().then(()=>require(`./messages-z2DzBRgO.cjs`)),lo:()=>Promise.resolve().then(()=>require(`./messages-uOISsfmj.cjs`)),lt:()=>Promise.resolve().then(()=>require(`./messages-BwCw0TJ1.cjs`)),lv:()=>Promise.resolve().then(()=>require(`./messages-DVAU-8rH.cjs`)),mk:()=>Promise.resolve().then(()=>require(`./messages-CHEpECGv.cjs`)),ml:()=>Promise.resolve().then(()=>require(`./messages-7wDDggws.cjs`)),mn:()=>Promise.resolve().then(()=>require(`./messages-9VzB9Djh.cjs`)),mr:()=>Promise.resolve().then(()=>require(`./messages-CVerbLou.cjs`)),ms:()=>Promise.resolve().then(()=>require(`./messages-BYpvkG9S.cjs`)),my:()=>Promise.resolve().then(()=>require(`./messages-CbKOqXT6.cjs`)),ne:()=>Promise.resolve().then(()=>require(`./messages-LX9PuLsT.cjs`)),nl:()=>Promise.resolve().then(()=>require(`./messages-CcO-3_4k.cjs`)),no:()=>Promise.resolve().then(()=>require(`./messages-D1XTyTJz.cjs`)),pa:()=>Promise.resolve().then(()=>require(`./messages-CJC94Hci.cjs`)),pl:()=>Promise.resolve().then(()=>require(`./messages-D0th-I9S.cjs`)),ps:()=>Promise.resolve().then(()=>require(`./messages-CMP5dbqQ.cjs`)),pt:()=>Promise.resolve().then(()=>require(`./messages-CgFAGUJX.cjs`)),ro:()=>Promise.resolve().then(()=>require(`./messages-BDer7I67.cjs`)),ru:()=>Promise.resolve().then(()=>require(`./messages-DoA0Ecoi.cjs`)),sd:()=>Promise.resolve().then(()=>require(`./messages-CHP0nYRn.cjs`)),si:()=>Promise.resolve().then(()=>require(`./messages-CdEZ98_p.cjs`)),sk:()=>Promise.resolve().then(()=>require(`./messages-BhTlR4PP.cjs`)),sl:()=>Promise.resolve().then(()=>require(`./messages-D86p1eQY.cjs`)),sq:()=>Promise.resolve().then(()=>require(`./messages-C73dKqPT.cjs`)),sr:()=>Promise.resolve().then(()=>require(`./messages-CcTkC677.cjs`)),sv:()=>Promise.resolve().then(()=>require(`./messages-XqCqLy0k.cjs`)),sw:()=>Promise.resolve().then(()=>require(`./messages-DJ-RX5EJ.cjs`)),ta:()=>Promise.resolve().then(()=>require(`./messages-CxIknrw4.cjs`)),te:()=>Promise.resolve().then(()=>require(`./messages-Dln2T0zJ.cjs`)),th:()=>Promise.resolve().then(()=>require(`./messages-B5bSFRCa.cjs`)),tr:()=>Promise.resolve().then(()=>require(`./messages-CMm8FeOL.cjs`)),ug:()=>Promise.resolve().then(()=>require(`./messages-DC-yFRyF.cjs`)),uk:()=>Promise.resolve().then(()=>require(`./messages-lvo-9Be0.cjs`)),ur:()=>Promise.resolve().then(()=>require(`./messages-T8hCmys7.cjs`)),vi:()=>Promise.resolve().then(()=>require(`./messages-1jzEPeW5.cjs`)),yi:()=>Promise.resolve().then(()=>require(`./messages-DG9l5agQ.cjs`)),zh:()=>Promise.resolve().then(()=>require(`./messages-BeQVEC9q.cjs`))},yu=async e=>{let t=_u.get(e);if(t!==void 0)return t;let n=vu[e],r=mu(e,(await n()).default);return _u.set(e,r),r},bu=class extends s{constructor(...e){super(...e),this.i18nextWrapper=null,this.locale=`en`,this.defaultLocale=`en`,this.usingI18next=!1,this.lightweightI18n=new a.t}t(e,t){return this.usingI18next&&this.i18nextWrapper!==null?this.i18nextWrapper.t(e,t):this.lightweightI18n.t(e,t)}getEnglishTranslation(e){var t;return(t=a.r[e])==null?``:t}has(e){return this.usingI18next&&this.i18nextWrapper!==null?this.i18nextWrapper.has(e):this.lightweightI18n.has(e)}async setLocale(e){var t=this;try{if(e===`en`){t.locale=`en`,t.usingI18next=!1;return}let n=await yu(e);if(await t.ensureI18nextLoaded(e,n),t.i18nextWrapper===null)return;t.i18nextWrapper.instance.hasResourceBundle(e,`translation`)||t.i18nextWrapper.instance.addResourceBundle(e,`translation`,n.dictionary),await t.i18nextWrapper.changeLanguage(e),t.locale=e,t.usingI18next=!0}catch(n){console.warn(`Failed to load locale "${e}". Falling back to "${t.defaultLocale}".`,n),t.locale=t.defaultLocale,t.defaultLocale===`en`&&(t.usingI18next=!1)}}async detectAndSetLocale(){var e=this;let t=e.detectBrowserLocale();return await e.setLocale(t),e.locale}setDictionary(e){this.usingI18next&&this.i18nextWrapper!==null?this.i18nextWrapper.setDictionary(e):this.lightweightI18n.setDictionary(e)}getLocale(){return this.locale}getDirection(){return pu(this.locale)}getDirectionForLocale(e){return pu(e)}async prepare(){var e=this,t;let n=e.config.i18n;e.applyDefaultLocale(n==null?void 0:n.defaultLocale);let r=n==null?void 0:n.locale;r===void 0||r===`auto`?await e.detectAndSetLocale():await e.setLocale(r),(n==null?void 0:n.messages)!==void 0&&e.setDictionary(n.messages),e.updateConfigDirection((t=n==null?void 0:n.direction)==null?e.getDirection():t)}async ensureI18nextLoaded(e,t){var n=this;if(n.i18nextWrapper!==null)return;let{loadI18next:r}=await Promise.resolve().then(()=>require(`./i18next-loader-DVakgVCy.cjs`));n.i18nextWrapper=await r(e,t)}updateConfigDirection(e){this.config.i18n===void 0&&(this.config.i18n={}),this.config.i18n.direction=e}applyDefaultLocale(e){e!==void 0&&(this.defaultLocale=e)}isLocaleSupported(e){return hu.includes(e)}detectBrowserLocale(){var e;if(typeof navigator>`u`)return this.defaultLocale;let t=(e=navigator.languages)==null?[navigator.language]:e;for(let e of t){if(!e)continue;let t=this.matchLanguageTag(e);if(t!==null)return t}return this.defaultLocale}matchLanguageTag(e){let t=e.toLowerCase();if(this.isLocaleSupported(t))return t;let n=t.split(`-`)[0];return n!==void 0&&this.isLocaleSupported(n)?n:null}},xu=class extends s{constructor({config:e,eventsDispatcher:t}){super({config:e,eventsDispatcher:t}),this.disabled=!1,this.batchingTimeout=null,this.batchingOnChangeQueue=new Map,this.batchTime=400,this.destroyed=!1,this.mutationObserver=new MutationObserver(e=>{this.redactorChanged(e)}),this.eventsDispatcher.on(d,e=>{this.particularBlockChanged(e.event)}),this.eventsDispatcher.on(_,()=>{this.disable()}),this.eventsDispatcher.on(v,()=>{this.enable()})}enable(){this.mutationObserver.observe(this.Blok.UI.nodes.redactor,{childList:!0,subtree:!0,characterData:!0,attributes:!0}),this.disabled=!1}disable(){this.mutationObserver.disconnect(),this.disabled=!0}particularBlockChanged(e){this.disabled||!t.xa(this.config.onChange)&&!t.xa(this.config.onSave)||(this.batchingOnChangeQueue.set(`block:${e.detail.target.id}:event:${e.type}`,e),this.batchingTimeout&&clearTimeout(this.batchingTimeout),this.batchingTimeout=setTimeout(()=>{let e=Array.from(this.batchingOnChangeQueue.values());if(e.length===0)return;let n=e.length===1?e[0]:e;t.xa(this.config.onChange)&&this.config.onChange(this.Blok.API.methods,n),t.xa(this.config.onSave)&&this.emitOnSave(),this.batchingOnChangeQueue.clear()},this.batchTime))}emitOnSave(){this.Blok.Saver.save().then(e=>{if(this.destroyed||e===void 0)return;let{onSave:n}=this.config;t.xa(n)&&n(e,this.Blok.API.methods)}).catch(()=>{})}destroy(){this.disabled=!0,this.destroyed=!0,this.mutationObserver.disconnect(),this.batchingTimeout!==null&&(clearTimeout(this.batchingTimeout),this.batchingTimeout=null),this.batchingOnChangeQueue.clear()}redactorChanged(e){this.eventsDispatcher.emit(y,{mutations:e})}},Su=new Set([`table`,`thead`,`tbody`,`tfoot`,`tr`,`th`,`td`,`caption`,`colgroup`,`col`,`ul`,`ol`,`li`,`dl`,`dt`,`dd`,`details`,`summary`]),Cu=e=>typeof e==`string`?[e]:e&&typeof e==`object`?Object.keys(e):[];function wu(e){let t=document.createElement(`div`);return t.innerHTML=e,Eu(t)?(Du(t),t.innerHTML):e}var Tu=[`figure.callout`,`ul.to-do-list`,`ul.toggle`,`ol.numbered-list`,`ul.bulleted-list`,`.notion-text-equation-token`,`[class*="block-color-"]`,`figure.equation`].join(`, `);function Eu(e){return e.querySelector(Tu)!==null}function Du(e){e.querySelectorAll(`del, strike`).forEach(e=>{let t=document.createElement(`s`);t.innerHTML=e.innerHTML,e.replaceWith(t)})}var Ou=`text/_notion-blocks-v3-production`;function ku(e){let t=Nu(e);if(typeof t!=`object`||!t||Array.isArray(t))return null;let n=t.blocks;if(!Array.isArray(n))return null;let r=new Map;if(n.forEach(e=>{var t;let n=e==null||(t=e.blockSubtree)==null?void 0:t.block;n!=null&&Object.keys(n).forEach(e=>{var t;let i=(t=n[e])==null?void 0:t.value;typeof i==`object`&&i&&r.set(e,i)})}),r.size===0)return null;let i=n.map(e=>e==null?void 0:e.blockId).filter(e=>typeof e==`string`),a=[],o=new Set,s=(e,t)=>{if(o.has(e))return;let n=r.get(e);if(n===void 0)return;if(o.add(e),n.type===`table`){Au(n,t,r,o,a);return}let i=Mu(n,r),c=Array.isArray(n.content)?n.content:[];if(i===null){c.forEach(e=>s(e,t));return}let l={id:e,tool:i.tool,data:i.data};if(t!==null&&(l.parentId=t),a.push(l),n.type===`callout`){var u;let t=Ju((u=n.properties)==null?void 0:u.title,r);t.length>0&&a.push({id:`${e}:callout-body`,tool:`paragraph`,data:{text:t},parentId:e})}c.forEach(t=>s(t,e))};return i.forEach(e=>{if(!r.has(e)){a.push({id:e,tool:`bookmark`,data:{url:nd(e)}});return}s(e,null)}),a}function Au(e,t,n,r,i){var a;let o=e.id,s=(a=e.format)==null?{}:a,c=(Array.isArray(e.content)?e.content:[]).filter(e=>typeof e==`string`),l=ju(s.table_block_column_order,c,n),u=[],d=c.map(e=>{var t,i;r.add(e);let a=(t=(i=n.get(e))==null?void 0:i.properties)==null?{}:t;return l.map(t=>{let r=`${e}:${t}`;return u.push({id:r,tool:`paragraph`,data:{text:Ju(a[t],n)},parentId:o}),{blocks:[r]}})}),f={id:o,tool:`table`,data:{withHeadings:s.table_block_row_header===!0,withHeadingColumn:s.table_block_column_header===!0,content:d}};t!==null&&(f.parentId=t),i.push(f),u.forEach(e=>i.push(e))}function ju(e,t,n){if(Array.isArray(e)&&e.length>0)return e.filter(e=>typeof e==`string`);for(let e of t){var r;let t=(r=n.get(e))==null?void 0:r.properties,i=t==null?[]:Object.keys(t);if(i.length>0)return i}return[]}function Mu(e,r){var i;let a=(i=e.properties)==null?{}:i,o=Ju(a.title,r);switch(e.type){case`text`:return{tool:`paragraph`,data:{text:o}};case`header`:return Vu(o,1,e.format);case`sub_header`:return Vu(o,2,e.format);case`sub_sub_header`:return Vu(o,3,e.format);case`quote`:var s;return{tool:`quote`,data:((s=e.format)==null?void 0:s.quote_size)===`large`?{text:o,size:`large`}:{text:o}};case`divider`:return{tool:`divider`,data:{}};case`code`:return{tool:`code`,data:{code:$(a.title),language:qu(a.language),lineNumbers:!1}};case`to_do`:return{tool:`list`,data:{text:o,style:`checklist`,checked:Gu(a.checked)}};case`bulleted_list`:return{tool:`list`,data:{text:o,style:`unordered`}};case`numbered_list`:return{tool:`list`,data:{text:o,style:`ordered`}};case`toggle`:return{tool:`toggle`,data:{text:o,isOpen:!0}};case`column_list`:return{tool:`column_list`,data:{}};case`column`:{var c;let t=(c=e.format)==null?void 0:c.column_ratio;return{tool:`column`,data:typeof t==`number`&&t!==1?{widthRatio:t}:{}}}case`table_row`:return null;case`equation`:return{tool:`code`,data:{code:$(a.title),language:`latex`,lineNumbers:!1}};case`bookmark`:var l;return Pu(a,(l=e.format)==null?{}:l,o);case`image`:var u;return Fu(`image`,a,(u=e.format)==null?{}:u,o,e.id);case`file`:var d;return Fu(`file`,a,(d=e.format)==null?{}:d,o,e.id);case`video`:var f;return zu(a,(f=e.format)==null?{}:f,o,e.id);case`audio`:var p;return Hu(a,(p=e.format)==null?{}:p,o,e.id);case`pdf`:var m;return Fu(`file`,a,(m=e.format)==null?{}:m,o,e.id);case`drive`:case`embed`:case`tweet`:case`gist`:case`codepen`:case`figma`:case`maps`:case`miro`:case`loom`:case`typeform`:case`invision`:case`framer`:case`whimsical`:case`abstract`:var h;return Bu(a,(h=e.format)==null?{}:h,o);case`callout`:{var g;let n=(g=e.format)==null?{}:g,r=typeof n.page_icon==`string`&&n.page_icon.length>0?n.page_icon:t.Nr,{textColor:i,backgroundColor:a}=ld(n.block_color);return{tool:`callout`,data:{emoji:r,textColor:i,backgroundColor:a}}}case`page`:return{tool:`bookmark`,data:n.t({url:nd(e.id)},o.length>0?{title:o}:{})};case`tab`:return null;case`transclusion_container`:return null;case`transclusion_reference`:return null;case`table_of_contents`:case`breadcrumb`:case`copy_indicator`:case`link_to_page`:case`alias`:return null;default:return{tool:`paragraph`,data:{text:o}}}}function Nu(e){try{return JSON.parse(e)}catch(e){return null}}function Pu(e,t,n){let r=Wu(e.link);if(r===null)return{tool:`paragraph`,data:{text:n}};let i={url:r},a=$(e.title),o=$(e.description);return a.length>0&&(i.title=a),o.length>0&&(i.description=o),typeof t.bookmark_cover==`string`&&(i.image=t.bookmark_cover),typeof t.bookmark_icon==`string`&&(i.favicon=t.bookmark_icon),{tool:`bookmark`,data:i}}function Fu(e,t,n,r,i){let a=Wu(t.source,n.display_source);if(a===null)return rd(i,t,r);if(e===`image`){let e={url:a},r=Iu(n.block_alignment);r!==null&&(e.alignment=r),Object.assign(e,Lu(t.caption));let i=$(t.alt_text);i.length>0&&(e.alt=i);let o=Ru(n.image_edit_metadata);return o!==null&&(e.crop=o),{tool:`image`,data:e}}let o={url:a},s=$(t.title);return s.length>0&&(o.fileName=s),Object.assign(o,Lu(t.caption)),{tool:`file`,data:o}}function Iu(e){return e===`left`||e===`right`?e:null}function Lu(e){let t=$(e);return t.length>0?{caption:t,captionVisible:!0}:{}}function Ru(e){if(typeof e!=`object`||!e)return null;let t=e.crop;if(typeof t!=`object`||!t)return null;let{x:n,y:r,width:i,height:a,unit:o}=t;if(o!==`%`||typeof n!=`number`||typeof r!=`number`||typeof i!=`number`||typeof a!=`number`||n===0&&r===0&&i===100&&a===100)return null;let s={x:n,y:r,w:i,h:a},c=e.mask;return(c===`circle`||c===`ellipse`)&&(s.shape=c),s}function zu(e,t,n,r){let i=Wu(e.source,t.display_source);if(i===null)return rd(r,e,n);let a=Uu(i);if(a!==null)return a;let o={url:i},s=Iu(t.block_alignment);return s!==null&&(o.alignment=s),Object.assign(o,Lu(e.caption)),{tool:`video`,data:o}}function Bu(e,t,n){var r;let i=Wu(e.source,t.display_source);return i===null?{tool:`paragraph`,data:{text:n}}:(r=Uu(i))==null?{tool:`bookmark`,data:{url:i}}:r}function Vu(e,t,n){return(n==null?void 0:n.toggleable)===!0?{tool:`header`,data:{text:e,level:t,isToggleable:!0,isOpen:!0}}:{tool:`header`,data:{text:e,level:t}}}function Hu(e,t,n,r){let i=Wu(e.source,t.display_source);if(i===null)return rd(r,e,n);let a={url:i},o=$(e.title);return o.length>0&&(a.title=o,a.fileName=o),{tool:`audio`,data:a}}function Uu(e){let n=t.$n(e);return n===null?null:{tool:`embed`,data:{service:n.service,source:e,embed:n.embedUrl,kind:n.kind}}}function Wu(...e){for(let t of e){let e=(typeof t==`string`?t:$(t)).trim();if(/^https?:\/\//i.test(e))return e}return null}function Gu(e){return Array.isArray(e)&&Array.isArray(e[0])&&e[0][0]===`Yes`}var Ku=new Map(t.mr.map(e=>[e.name.toLowerCase(),e.id]));function qu(e){var n;return!Array.isArray(e)||!Array.isArray(e[0])||typeof e[0][0]!=`string`||(n=Ku.get(e[0][0].toLowerCase()))==null?t.or:n}function $(e){return Array.isArray(e)?e.map(e=>Array.isArray(e)&&typeof e[0]==`string`?e[0]:``).join(``):``}function Ju(e,t){return Array.isArray(e)?e.map(e=>Yu(e,t)).join(``):``}function Yu(e,t){if(!Array.isArray(e))return``;let n=typeof e[0]==`string`?e[0]:``,r=Array.isArray(e[1])?e[1]:[],i=[`e`,`p`,`d`,`u`],a=e=>Array.isArray(e)&&e[0]===`h`,o=e=>Array.isArray(e)&&i.includes(e[0]),s=r.filter(e=>!a(e)&&!o(e)).reduce((e,t)=>ud(t,e),Xu(n,r,t)),c=sd(r.filter(a));return c.length>0?`<mark style="${c}">${s}</mark>`:s}function Xu(e,t,n){let r=Zu(t,`e`);if(r!==null)return`<code>${fd(r)}</code>`;let i=Zu(t,`p`);if(i!==null)return ad(i,e,n);let a=$u(t);return a===null?Qu(t,`u`)||Qu(t,`d`)?``:fd(e):fd(td(a))}function Zu(e,t){for(let n of e)if(Array.isArray(n)&&n[0]===t&&typeof n[1]==`string`)return n[1];return null}function Qu(e,t){return e.some(e=>Array.isArray(e)&&e[0]===t)}function $u(e){for(let t of e)if(Array.isArray(t)&&t[0]===`d`&&ed(t[1]))return t[1];return null}function ed(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function td(e){let t=(t,n)=>{let r=typeof e[t]==`string`?e[t]:``,i=typeof e[n]==`string`?e[n]:``;return r.length===0?``:i.length>0?`${r} ${i}`:r};return[t(`start_date`,`start_time`),t(`end_date`,`end_time`)].filter(e=>e.length>0).join(` → `)}function nd(e){return`https://www.notion.so/${e.replace(/-/g,``)}`}function rd(e,t,n){let r=n.length>0?n:id(t.source),i={url:nd(e)};return r.length>0&&(i.title=r),{tool:`bookmark`,data:i}}function id(e){let t=Array.isArray(e)?e[0]:void 0,n=Array.isArray(t)?t[0]:void 0;if(typeof n!=`string`)return``;let r=/^attachment:[^:]+:(.+)$/.exec(n);if(r===null)return``;try{return decodeURIComponent(r[1])}catch(e){return r[1]}}function ad(e,t,n){var r;let i=$(n==null||(r=n.get(e))==null||(r=r.properties)==null?void 0:r.title),a=i.length>0?i:`Untitled`;return`<a href="${pd(nd(e))}">${fd(a)}</a>`}function od(e){if(typeof e!=`string`||e.length===0||e===`default`)return null;let t=e.endsWith(`_background`)?{mode:`bg`,name:e.slice(0,-11)}:{mode:`text`,name:e};return t.name===`default`?null:t}function sd(e){let n=e.map(e=>od(Array.isArray(e)?e[1]:void 0)).filter(e=>e!==null),r=n.find(e=>e.mode===`text`),i=n.find(e=>e.mode===`bg`),a=[];return r&&a.push(`color: ${t.ai(r.name,`text`)}`),i&&a.push(`background-color: ${t.ai(i.name,`bg`)}`),a.join(`; `)}var cd=new Set(t.ri.map(e=>e.name));function ld(e){let t=od(e);return t===null||!cd.has(t.name)?{textColor:null,backgroundColor:null}:t.mode===`text`?{textColor:t.name,backgroundColor:null}:{textColor:null,backgroundColor:t.name}}function ud(e,t){if(!Array.isArray(e))return t;switch(e[0]){case`b`:return`<b>${t}</b>`;case`i`:return`<i>${t}</i>`;case`s`:return`<s>${t}</s>`;case`c`:return`<code>${t}</code>`;case`_`:return`<u>${t}</u>`;case`a`:{let n=dd(e[1]);return n===null?t:`<a href="${pd(n)}">${t}</a>`}default:return t}}function dd(e){if(typeof e!=`string`)return null;let t=e.trim();return/^(?:https?:|mailto:|tel:|#|\/|\.\/|\.\.\/)/i.test(t)?t:null}function fd(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function pd(e){return fd(e).replace(/"/g,`&quot;`)}var md=[`text/next-space-blocks`,`text/next-space-content`];function hd(e){let t=kd(e);if(typeof t!=`object`||!t||Array.isArray(t))return null;let n=t.blocks;if(!Array.isArray(n)||n.length===0)return null;let r=new Map;if(n.forEach(e=>{let t=e==null?void 0:e.subTree;typeof t!=`object`||!t||Object.values(t).forEach(e=>{typeof e==`object`&&e&&typeof e.uuid==`string`&&r.set(e.uuid,e)})}),r.size===0)return null;let i=n.map(e=>e==null?void 0:e.id).filter(e=>typeof e==`string`),a=[],o=new Set,s=(e,t)=>{if(o.has(e))return;let n=r.get(e);if(n===void 0)return;if(o.add(e),n.type===27){gd(n,t,r,o,a);return}let i=_d(n);if(i===null)return;let c={id:e,tool:i.tool,data:i.data};if(t!==null&&(c.parentId=t),a.push(c),n.type===13){var l;let t=Ad(((l=n.data)==null?{}:l).segments);t.length>0&&a.push({id:`${e}:callout-body`,tool:`paragraph`,data:{text:t},parentId:e})}(Array.isArray(n.subNodes)?n.subNodes:[]).forEach(t=>s(t,e))};return i.forEach(e=>s(e,null)),a}function gd(e,t,n,r,i){var a;let o=e.uuid,s=(a=e.data)==null?{}:a,c=Nd(s.format)?s.format:{},l=(Array.isArray(e.subNodes)?e.subNodes:[]).filter(e=>typeof e==`string`),u=Array.isArray(c.tableBlockColumnOrder)?c.tableBlockColumnOrder.filter(e=>typeof e==`string`):[],d=[],f=l.map(e=>{var t,i;r.add(e);let a=(t=(i=n.get(e))==null?void 0:i.data)==null?{}:t,s=Nd(a.collectionProperties)?a.collectionProperties:{};return u.map(t=>{let n=`${e}:${t}`;return d.push({id:n,tool:`paragraph`,data:{text:Ad(s[t])},parentId:o}),{blocks:[n]}})}),p={id:o,tool:`table`,data:{withHeadings:c.tableBlockRowHeader===!0,withHeadingColumn:c.tableBlockColumnHeader===!0,content:f}};t!==null&&(p.parentId=t),i.push(p),d.forEach(e=>i.push(e))}function _d(e){var t;let n=(t=e.data)==null?{}:t,r=Ad(n.segments);switch(e.type){case 1:return{tool:`paragraph`,data:{text:r}};case 3:return{tool:`list`,data:{text:r,style:`checklist`,checked:n.checked===!0}};case 4:return{tool:`list`,data:{text:r,style:`unordered`}};case 5:return{tool:`list`,data:{text:r,style:`ordered`}};case 7:return{tool:`header`,data:{text:r,level:n.level}};case 38:return{tool:`header`,data:{text:r,level:n.level,isToggleable:!0,isOpen:!0}};case 6:return{tool:`toggle`,data:{text:r,isOpen:!0}};case 9:return{tool:`divider`,data:{}};case 12:return{tool:`quote`,data:{text:r}};case 13:return vd(e,n);case 25:return{tool:`code`,data:{code:jd(n.segments),language:Od(xd(n.format)),lineNumbers:!1}};case 23:return{tool:`code`,data:{code:jd(n.segments),language:`latex`,lineNumbers:!1}};case 10:return{tool:`column_list`,data:{}};case 11:{let e=n.columnRatio;return{tool:`column`,data:typeof e==`number`&&e!==1?{widthRatio:e}:{}}}case 14:return Sd(e,n,r);case 21:return Td(n,r);case 28:return null;default:return{tool:`paragraph`,data:{text:r}}}}function vd(e,n){let r=Nd(n.icon)?n.icon:{};return{tool:`callout`,data:{emoji:typeof r.value==`string`&&r.value.length>0?r.value:t.Nr,textColor:bd(e.textColor),backgroundColor:bd(e.backgroundColor)}}}var yd=new Set(t.ri.map(e=>e.name));function bd(e){if(typeof e!=`string`||e.length===0)return null;let t=e.toLowerCase()===`grey`?`gray`:e.toLowerCase();return yd.has(t)?t:null}function xd(e){return Nd(e)?e.language:void 0}function Sd(e,t,n){let r=typeof t.ossName==`string`?t.ossName:``,i=typeof e.title==`string`?e.title:``,a=n.length>0?n:i;if(r.length===0)return{tool:`paragraph`,data:{text:a}};let o=Cd(r),s=typeof t.display==`string`?t.display:`file`;if(s===`image`){let e={url:o},n=wd(t.format);return n!==null&&(e.alignment=n),{tool:`image`,data:e}}if(s===`video`)return{tool:`video`,data:{url:o}};if(s===`audio`){let e={url:o};return a.length>0&&(e.title=a,e.fileName=a),{tool:`audio`,data:e}}let c={url:o};return a.length>0&&(c.fileName=a),{tool:`file`,data:c}}function Cd(e){return`https://cdn2.buildin.ai/${e}`}function wd(e){return Nd(e)?e.contentGravity===`LEFT`?`left`:e.contentGravity===`RIGHT`?`right`:null:null}function Td(e,t){let n=Md(e.link);if(n===null)return{tool:`paragraph`,data:{text:t}};let r=Ed(n);if(r!==null)return r;let i={url:n},a=jd(e.linkInfo);return a.length>0&&(i.title=a),{tool:`bookmark`,data:i}}function Ed(e){let n=t.$n(e);return n===null?null:{tool:`embed`,data:{service:n.service,source:e,embed:n.embedUrl,kind:n.kind}}}var Dd=new Map(t.mr.map(e=>[e.name.toLowerCase(),e.id]));function Od(e){var n;return(n=Dd.get(String(e).toLowerCase()))==null?t.or:n}function kd(e){try{return JSON.parse(e)}catch(e){return null}}function Ad(e){return Array.isArray(e)?e.map(e=>Nd(e)&&typeof e.text==`string`?Pd(e.text):``).join(``):``}function jd(e){return Array.isArray(e)?e.map(e=>Nd(e)&&typeof e.text==`string`?e.text:``).join(``):``}function Md(...e){for(let t of e){let e=(typeof t==`string`?t:jd(t)).trim();if(/^https?:\/\//i.test(e))return e}return null}function Nd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pd(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}var Fd=class{constructor(e,t,n){this.Blok=e,this.toolRegistry=t,this.sanitizerBuilder=n}composePasteEvent(e,t){return new CustomEvent(e,{detail:t})}shouldReplaceCurrentBlock(e){let{BlockManager:t}=this.Blok,n=t.currentBlock;return n?e&&n.name===e?!0:!!n.tool.isDefault&&n.isEmpty:!1}redirectToTableParentIfNeeded(e,n){var r,i;let a=n.currentBlock,o=a==null||(r=a.holder)==null?void 0:r.closest(`[data-blok-table-cell-blocks]`),s=new Set(t.Ji()),c=e.some(e=>s.has(e.tool));if(!o||!c||a===void 0)return;let l=(i=a.holder.closest(`[data-blok-tool="table"]`))==null?void 0:i.closest(`[data-blok-element]`);l&&n.setCurrentBlockByChildNode(l)}async insertPasteData(e,t){var n=this;let{BlockManager:r,Caret:i}=n.Blok;if(!e.length)return;if(e.length>1){var a,o,s,c,l;n.redirectToTableParentIfNeeded(e,r);let u=r.currentBlock,d=(a=u==null||(o=u.holder)==null?void 0:o.querySelector(`[data-blok-toggle-children]`))==null?null:a,f=d!==null&&!d.contains((s=u==null?void 0:u.currentInput)==null?null:s)?(c=u==null?void 0:u.id)==null?null:c:(l=u==null?void 0:u.parentId)==null?null:l,p=[],m=r.operations,h={current:Promise.resolve()},g=()=>{h.current=(async()=>{for(let[o,s]of e.entries()){var a;m!==void 0&&(m.suppressStopCapturing=!0);let e=o===0&&t&&((a=r.currentBlock)==null?void 0:a.isEmpty)===!0?await r.paste(s.tool,s.event,!0):await r.paste(s.tool,s.event);i.setToBlock(e,i.positions.END),p.push(e),n.applyPastedBlockParent(e,s,p,r,f)}})()};typeof r.transactForTool==`function`?r.transactForTool(g):g(),await h.current,r.currentBlock&&i.setToBlock(r.currentBlock,i.positions.END);return}let[u]=e;if(u.isBlock){await n.processSingleBlock(u,t);return}await n.processInlinePaste(u,t)}applyPastedBlockParent(e,t,n,r,i){if(t.parentPasteIndex!==void 0){let i=n[t.parentPasteIndex];i&&r.setBlockParent(e,i.id)}else i===null?e.parentId!=null&&r.setBlockParent(e,null):r.setBlockParent(e,i)}async insertBlock(e,t=!1){let{BlockManager:n,Caret:r}=this.Blok,{currentBlock:i}=n;if(t&&i&&i.isEmpty){let t=await n.paste(e.tool,e.event,!0);r.setToBlock(t,r.positions.END);return}let a=await n.paste(e.tool,e.event);r.setToBlock(a,r.positions.END)}async processSingleBlock(e,n){var r=this;let{Caret:i,BlockManager:a}=r.Blok,{currentBlock:o}=a,s=t.Qi;if(!o||e.tool!==o.name||!s.containsOnlyInlineElements(e.content.innerHTML)){await r.insertBlock(e,n);return}i.insertContentAtCaretPosition(e.content.innerHTML)}async processInlinePaste(e,n){var r=this;let{BlockManager:i,Caret:a}=r.Blok,{content:o}=e,s=i.currentBlock;if(!s||!s.currentInput){await r.insertBlock(e,n);return}let c=s.tool.baseSanitizeConfig;a.insertContentAtCaretPosition(t.Ei(o.innerHTML,c))}},Id,Ld=class e{constructor(){this.scrollPosition=null}lock(){t.pa?this.lockHard():(document.body.classList.add(e.CSS.overflowHidden),document.body.setAttribute(e.DATA_ATTR.scrollLocked,`true`))}unlock(){t.pa?this.unlockHard():(document.body.classList.remove(e.CSS.overflowHidden),document.body.removeAttribute(e.DATA_ATTR.scrollLocked))}lockHard(){this.scrollPosition=window.pageYOffset,document.documentElement.style.setProperty(`--window-scroll-offset`,`${this.scrollPosition}px`),document.body.classList.add(e.CSS.overflowHidden,e.CSS.fixed,e.CSS.wFull),document.body.style.top=`calc(-1 * var(--window-scroll-offset))`,document.body.setAttribute(e.DATA_ATTR.scrollLockedHard,`true`)}unlockHard(){document.body.classList.remove(e.CSS.overflowHidden,e.CSS.fixed,e.CSS.wFull),document.body.style.top=``,document.body.removeAttribute(e.DATA_ATTR.scrollLockedHard),this.scrollPosition!==null&&window.scrollTo(0,this.scrollPosition),this.scrollPosition=null}};Id=Ld,Id.CSS={overflowHidden:`overflow-hidden`,fixed:`fixed`,wFull:`w-full`},Id.DATA_ATTR={scrollLocked:`data-blok-scroll-locked`,scrollLockedHard:`data-blok-scroll-locked-hard`};var Rd={root:`flex items-center mb-2 mt-1`,text:`text-lg font-semibold text-text-primary`,backButton:`border-0 bg-transparent w-9 h-9 text-text-primary cursor-pointer outline-hidden [&_svg]:block [&_svg]:w-7 [&_svg]:h-7`},zd=class{constructor({text:e,onBackButtonClick:n}){this.listeners=new t.qi,this.text=e,this.onBackButtonClick=n,this.nodes={root:t.Qi.make(`div`,[Rd.root],{"data-blok-testid":`popover-header`,[t.Ma.popoverHeader]:``}),backButton:t.Qi.make(`button`,[Rd.backButton],{"data-blok-testid":`popover-header-back-button`,[t.Ma.popoverHeaderBackButton]:``}),text:t.Qi.make(`div`,[Rd.text],{"data-blok-testid":`popover-header-text`,[t.Ma.popoverHeaderText]:``})},this.nodes.backButton.innerHTML=t.Y,this.nodes.root.appendChild(this.nodes.backButton),this.listeners.on(this.nodes.backButton,`click`,this.onBackButtonClick),this.nodes.text.innerText=this.text,this.nodes.root.appendChild(this.nodes.text)}getElement(){return this.nodes.root}destroy(){this.nodes.root.remove(),this.listeners.destroy()}},Bd=class{constructor(){this.history=[]}push(e){this.history.push(e)}pop(){return this.history.pop()}get currentTitle(){return this.history.length===0?``:this.history[this.history.length-1].title}get currentItems(){return this.history.length===0?[]:this.history[this.history.length-1].items}reset(){for(;this.history.length>1;)this.pop()}},Vd=class extends t.w{constructor(e){super(e,{[t.ki.Default]:{hint:{enabled:!1}},[t.ki.Html]:{hint:{enabled:!1}}}),this.scrollLocker=new Ld,this.history=new Bd,this.isHidden=!0,this.nodes.overlay=t.Qi.make(`div`,[t.D.popoverOverlay],{[t.Ma.popoverOverlay]:``,[t.Ma.overlayHidden]:``,"data-blok-testid":`popover-overlay`}),this.nodes.popover.insertBefore(this.nodes.overlay,this.nodes.popover.firstChild),this.listeners.on(this.nodes.overlay,`click`,()=>{this.hide()}),this.history.push({items:e.items}),this.nodes.popoverContainer.style.setProperty(`--offset`,`5px`),this.nodes.popoverContainer.className=r.n(t.D.popoverContainer,t.D.popoverContainerMobile)}show(){this.nodes.overlay.removeAttribute(t.Ma.overlayHidden),this.nodes.overlay.className=r.n(t.D.popoverOverlay,`fixed inset-0 block visible z-3 opacity-50`),super.show(),this.nodes.popoverContainer.className=r.n(t.D.popoverContainer,t.D.popoverContainerMobile,t.D.popoverContainerOpened,`max-h-none z-4`),this.scrollLocker.lock(),this.isHidden=!1}hide(){this.isHidden||(super.hide(),this.nodes.overlay.setAttribute(t.Ma.overlayHidden,``),this.nodes.overlay.className=t.D.popoverOverlay,this.nodes.popoverContainer.className=r.n(t.D.popoverContainer,t.D.popoverContainerMobile),this.scrollLocker.unlock(),this.history.reset(),this.isHidden=!0)}destroy(){super.destroy(),this.scrollLocker.unlock()}showNestedItems(e){this.updateItemsAndHeader(e.children,e.title),this.history.push({title:e.title,items:e.children})}updateItemsAndHeader(e,t){var n,r;this.header!==null&&this.header!==void 0&&(this.header.destroy(),this.header=null);let i=t!==void 0;i&&(this.header=new zd({text:t,onBackButtonClick:()=>{this.history.pop(),this.updateItemsAndHeader(this.history.currentItems,this.history.currentTitle)}}));let a=(n=(r=this.header)==null?void 0:r.getElement())==null?null:n;i&&a!==null&&this.nodes.popoverContainer.insertBefore(a,this.nodes.popoverContainer.firstChild),this.items.forEach(e=>{var t;return(t=e.getMountElement)==null||(t=t.call(e))==null?void 0:t.remove()}),this.items=this.buildItems(e),this.items.forEach(e=>{var t,n,r;let i=(t=(n=e.getMountElement)==null?void 0:n.call(e))==null?e.getElement():t;i!==null&&((r=this.nodes.items)==null||r.appendChild(i))})}},Hd={video:{icon:t.Gn,labelKey:`tools.linkPaste.embedVideo`},audio:{icon:t.ln,labelKey:`tools.linkPaste.embedAudio`},image:{icon:t.Lt,labelKey:`tools.linkPaste.embedImage`},social:{icon:t.an,labelKey:`tools.linkPaste.embedSocial`},document:{icon:t.xt,labelKey:`tools.linkPaste.embedDocument`},table:{icon:t.Fn,labelKey:`tools.linkPaste.embedTable`},form:{icon:t.Qt,labelKey:`tools.linkPaste.embedForm`},code:{icon:t.Q,labelKey:`tools.linkPaste.embedCode`},design:{icon:t.dn,labelKey:`tools.linkPaste.embedDesign`},chart:{icon:t.K,labelKey:`tools.linkPaste.embedChart`},map:{icon:t.tn,labelKey:`tools.linkPaste.embedMap`},calendar:{icon:t.H,labelKey:`tools.linkPaste.embedCalendar`}},Ud=e=>{switch(e){case`plain`:return{labelKey:`tools.linkPaste.plain`,icon:t.qt};case`bookmark`:return{labelKey:`tools.linkPaste.bookmark`,icon:t.V};case`embed`:return{labelKey:`tools.linkPaste.embed`,icon:t.Dt};case`mention`:return{labelKey:`tools.linkPaste.mention`,icon:t.qt}}};function Wd(e,n,r,i){return e.map(({type:e})=>{let{labelKey:a,icon:o}=Ud(e),s=e===`embed`&&i!==void 0?t.$n(i):null,c=s?Hd[s.type]:null;return{name:`paste-menu-${e}`,title:c&&s?n.t(c.labelKey).replace(`{provider}`,s.title):n.t(a),icon:c?c.icon:o,closeOnActivate:!0,onActivate:()=>{r(e)}}})}function Gd(e,n){if(n.hasSelection||!t.Qn(e))return[{type:`plain`}];let r=[];return(t.$n(e)||n.allowGenericEmbed===!0)&&r.push({type:`embed`}),r.push({type:`bookmark`},{type:`mention`},{type:`plain`}),r}var Kd=new Set([`plain`,`bookmark`,`embed`]),qd=class{constructor(e){this.i18n=e,this.popover=null}open(e){this.closeExisting();let r=Gd(e.url,{hasSelection:e.hasSelection,allowGenericEmbed:e.allowGenericEmbed===!0}).filter(e=>Kd.has(e.type)),i={picked:!1,closed:!1},a=new t.C(n.t(n.t({items:Wd(r,this.i18n,t=>{i.picked=!0,e.onSelect(t)},e.url),flippable:!0},e.trigger?{trigger:e.trigger}:{}),e.position?{position:e.position}:{}));this.popover=a;let o=e=>{e.key===`Escape`&&(e.stopImmediatePropagation(),a.hide())};window.addEventListener(`keydown`,o,!0),a.on(t.T.Closed,()=>{i.closed||(i.closed=!0,window.removeEventListener(`keydown`,o,!0),this.popover===a&&(this.popover=null),i.picked||e.onDismiss(),a.destroy())}),a.show()}closeExisting(){this.popover&&this.popover.hide()}},Jd,Yd=class e extends Fd{constructor(e,t,n,r,i){super(e,t,n),this.config=r,this.menu=i==null?new qd({t:t=>e.I18n.t(t)}):i}canHandle(t){if(typeof t!=`string`)return 0;let n=t;return!n||n.length>e.PATTERN_PROCESSING_MAX_LENGTH?0:this.toolRegistry.findToolForPattern(n)?60:0}async handle(e,n){var r=this;if(typeof e!=`string`)return!1;let i=r.toolRegistry.findToolForPattern(e);if(!i)return!1;if(t.Qn(e)&&!r.hasSelection())return r.openLinkPasteMenu(e),!0;let a=r.composePasteEvent(`pattern`,{key:i.key,data:e}),o={key:i.key,data:e,tool:i.tool.name,event:a};return await r.insertPatternBlock(o,n.canReplaceCurrentBlock),!0}async insertPatternBlock(e,t){let{BlockManager:n,Caret:r}=this.Blok,i=await n.paste(e.tool,e.event,t);r.setToBlock(i,r.positions.END)}hasSelection(){let e=window.getSelection();return e!==null&&!e.isCollapsed&&e.toString().length>0}getCaretRect(){var e;let t=window.getSelection();if(t&&t.rangeCount>0){let e=t.getRangeAt(0).getBoundingClientRect();if(e.width>0||e.height>0)return e}let n=(e=this.Blok.BlockManager.currentBlock)==null?void 0:e.holder;return n?n.getBoundingClientRect():null}openLinkPasteMenu(e){var t,r,i;let a=(t=this.Blok.BlockManager.currentBlock)==null?null:t,o=this.insertPlainLink(e,a);this.menu.open(n.t(n.t({url:e,hasSelection:this.hasSelection(),allowGenericEmbed:((r=this.config)==null||(r=r.linkPaste)==null?void 0:r.allowGenericEmbed)===!0,position:(i=this.getLinkEndRect(o))==null?this.getCaretRect():i},o!=null&&o.holder?{trigger:o.holder}:{}),{},{onSelect:t=>{this.applyMenuAction(t,e,o)},onDismiss:()=>{}}))}getLinkEndRect(e){var t;let n=e==null||(t=e.holder)==null?void 0:t.querySelector(`a`);if(!n)return null;let r=n.getClientRects(),i=r.length>0?r[r.length-1]:n.getBoundingClientRect();return i.width===0&&i.height===0?null:new DOMRect(i.right,i.top,0,i.height)}restoreTarget(e){e!=null&&e.holder&&this.Blok.BlockManager.setCurrentBlockByChildNode(e.holder)}async applyMenuAction(e,t,n){var r=this;switch(e){case`bookmark`:case`embed`:r.restoreTarget(n),await r.insertForcedPatternBlock(e,t,!0);break;case`plain`:break;case`mention`:break}}async insertForcedPatternBlock(e,t,n){var r=this;let i=r.composePasteEvent(`pattern`,{key:e,data:t});await r.insertPatternBlock({key:e,data:t,tool:e,event:i},n)}insertPlainLink(e,t){this.restoreTarget(t);let n=document.createElement(`a`);return n.href=e,n.target=`_blank`,n.rel=`nofollow`,n.textContent=e,this.Blok.BlockManager.insert({data:{text:n.outerHTML},replace:!0,needToFocus:!0})}};Jd=Yd,Jd.PATTERN_PROCESSING_MAX_LENGTH=450;var Xd=class extends Fd{constructor(e,t,n,r){super(e,t,n),this.config=r}canHandle(e){if(typeof e!=`string`)return 0;try{return JSON.parse(e),100}catch(e){return 0}}async handle(e,t){var n=this;if(typeof e!=`string`)return!1;let r=JSON.parse(e),i=n.toolRegistry.toolsPatterns.length>0,a=t.plainData;if(!i||!a)return n.insertBlokBlocks(r,t.canReplaceCurrentBlock),!0;let o=await n.tryPatternMatch(a);return o?(await n.insertPatternMatch(o,t.canReplaceCurrentBlock),!0):(n.insertBlokBlocks(r,t.canReplaceCurrentBlock),!0)}async tryPatternMatch(e){var t=this;if(t.patternHandler||(t.patternHandler=new Yd(t.Blok,t.toolRegistry,t.sanitizerBuilder)),e.length>Yd.PATTERN_PROCESSING_MAX_LENGTH)return;let n=t.toolRegistry.findToolForPattern(e);if(!n)return;let r=t.composePasteEvent(`pattern`,{key:n.key,data:e});return{key:n.key,data:e,tool:n.tool.name,event:r}}async insertPatternMatch(e,t){let{BlockManager:n,Caret:r}=this.Blok,i=await n.paste(e.tool,e.event,t);r.setToBlock(i,r.positions.END)}insertBlokBlocks(e,n){var r,i,a,o,s,c,l;let{BlockManager:u,Caret:d,Tools:f}=this.Blok,p=$d(e),m=t.Oi(p,e=>{var t,n;return(t=(n=f.blockTools.get(e))==null?void 0:n.sanitizeConfig)==null?{}:t},this.config.sanitizer),h=n&&!!((r=u.currentBlock)!=null&&r.tool.isDefault)&&!!((i=u.currentBlock)!=null&&i.isEmpty),g=u.currentBlock,_=(a=g==null||(o=g.holder)==null?void 0:o.querySelector(`[data-blok-toggle-children]`))==null?null:a,v=_!==null&&!_.contains((s=g==null?void 0:g.currentInput)==null?null:s)?(c=g==null?void 0:g.id)==null?null:c:(l=g==null?void 0:g.parentId)==null?null:l,y=new Set(p.filter(e=>e.tool===`table`&&e.id!==void 0).map(e=>e.id)),b=e=>e.parentId!==void 0&&e.parentId!==null&&y.has(e.parentId),x=[],ee=[];m.forEach((e,t)=>{let n=p[t];n!==void 0&&(b(n)?x:ee).push({sanitized:e,original:n})});let S=new Map,C=()=>{x.forEach(({sanitized:e,original:t})=>{let n=u.insert({tool:e.tool,data:e.data});S.set(t.id,{newBlock:n,original:t}),d.setToBlock(n,d.positions.END)});let e=new Map;for(let[t,{newBlock:n}]of S)e.set(t,n.id);ee.forEach(({sanitized:t,original:n},r)=>{let i=e.size>0?ef(t.data,e):t.data,a=u.insert({tool:t.tool,data:i,replace:r===0&&h&&x.length===0});v!==null&&(n.parentId===void 0||n.parentId===null)&&u.setBlockParent(a,v),S.set(n.id,{newBlock:a,original:n}),d.setToBlock(a,d.positions.END)});for(let[,{newBlock:e,original:t}]of S){if(t.parentId===void 0||t.parentId===null)continue;let n=S.get(t.parentId);n!==void 0&&u.setBlockParent(e,n.newBlock.id)}};typeof u.transactForTool==`function`?u.transactForTool(C):C()}};function Zd(e,t,n){typeof e!=`object`||!e||!Array.isArray(e.blocks)||e.blocks.forEach(e=>{typeof e==`string`&&!n.has(e)&&n.set(e,t)})}function Qd(e,t){if(e.tool!==`table`||e.id===void 0)return;let n=e.data,r=n==null?void 0:n.content;if(!Array.isArray(r))return;let i=e.id;r.forEach(e=>{Array.isArray(e)&&e.forEach(e=>Zd(e,i,t))})}function $d(e){let t=new Map;return e.forEach(e=>Qd(e,t)),t.size===0?e:e.map(e=>{if(e.id===void 0)return e;let r=t.get(e.id);return r===void 0||e.parentId!==void 0&&e.parentId!==null?e:n.t(n.t({},e),{},{parentId:r})})}function ef(e,t){if(typeof e==`string`){var n;return(n=t.get(e))==null?e:n}if(Array.isArray(e))return e.map(e=>ef(e,t));if(typeof e==`object`&&e){let n={};for(let[r,i]of Object.entries(e))n[r]=ef(i,t);return n}return e}var tf=e=>typeof e==`object`&&!!e&&`files`in e&&`types`in e&&`getData`in e&&`setData`in e,nf=class extends Fd{constructor(e,t,n){super(e,t,n)}canHandle(e){return tf(e)&&this.containsFiles(e)?80:0}async handle(e,t){var n=this;if(!tf(e)||!n.containsFiles(e))return!1;let r=n.extractFiles(e);return r.length===0?!1:(await n.processFiles(r),!0)}extractFiles(e){return e.files&&e.files.length>0?Array.from(e.files):this.extractFilesFromItems(e.items)}extractFilesFromItems(e){return e?Array.from(e).filter(e=>e.kind===`file`).map(e=>e.getAsFile()).filter(e=>e!==null):[]}containsFiles(e){var t;if(Array.from(e.types).includes(`Files`)||(t=e.files)!=null&&t.length||this.itemsContainFile(e.items))return!0;try{let t=e.types;if(typeof(t==null?void 0:t.contains)==`function`&&t.contains(`Files`))return!0}catch(e){}return!1}itemsContainFile(e){return e?Array.from(e).some(e=>e.kind===`file`):!1}async processFiles(e){var t=this,n;let{BlockManager:r}=t.Blok,i=(await Promise.all(Array.from(e).map(e=>t.processFile(e)))).filter(e=>e!=null);if(i.length===0)return;let a=t.shouldReplaceCurrentBlock((n=i[0])==null?void 0:n.type);for(let[e,t]of i.entries())await r.paste(t.type,t.event,e===0&&a)}async processFile(e){var t=this,n;let r=(n=t.Blok.BlockManager.currentBlock)==null?void 0:n.name,i=t.toolRegistry.findToolForFile(e,r);if(i)return{event:t.composePasteEvent(`file`,{file:e}),type:i}}},rf=class extends Fd{constructor(e,t,n){super(e,t,n)}canHandle(e){return typeof e!=`string`||!e.trim()||!t.Qi.isHTMLString(e)?0:40}async handle(e,t){var n=this;if(typeof e!=`string`)return!1;let r=n.processHTML(e);return r.length?(await n.insertPasteData(r,t.canReplaceCurrentBlock),!0):!1}processHTML(e){let{Tools:r}=this.Blok,i=t.Qi.make(`DIV`);i.innerHTML=e;let a=this.getNodes(i),o=[];for(let e of a){let t=e.nodeType===Node.ELEMENT_NODE&&e.tagName===`DETAILS`,n=e.nodeType===Node.ELEMENT_NODE&&e.tagName===`ASIDE`;if(!t&&!n){o.push({node:e});continue}let r=o.length;o.push({node:e});let i=Array.from(e.children).filter(e=>n||e.tagName!==`SUMMARY`);for(let e of i)o.push({node:e,parentExpandedIndex:r})}let s=o.map(({node:e,parentExpandedIndex:i},a)=>{let o=(()=>{switch(e.nodeType){case Node.DOCUMENT_FRAGMENT_NODE:{let n=t.Qi.make(`div`);return n.appendChild(e),{content:n,tool:r.defaultTool,isBlock:!1}}case Node.ELEMENT_NODE:{var n,i;let t=e,a=(n=this.toolRegistry.findToolForTag(t.tagName))==null?void 0:n;return{content:t,tool:(i=a==null?void 0:a.tool)==null?r.defaultTool:i,isBlock:!0}}default:return null}})();if(!o)return null;let{content:s,tool:c,isBlock:l}=o,u=this.buildToolTags(c),d=n.t(n.t(n.t(n.t({},this.sanitizerBuilder.getStructuralTagsConfig(s)),u),c.baseSanitizeConfig),{},{br:{}}),f=this.sanitizeContent(s,d);if(!f)return null;let p=this.composePasteEvent(`tag`,{data:f});return{data:{content:f,isBlock:l,tool:c.name,event:p,parentPasteIndex:i},originalIndex:a}}),c=new Map,l=[];for(let e of s){if(!e)continue;let{data:n,originalIndex:r}=e,i=t.Qi.isEmpty(n.content),a=t.Qi.isSingleTag(n.content);(!i||a)&&(c.set(r,l.length),l.push(n))}for(let e of l)e.parentPasteIndex!==void 0&&(e.parentPasteIndex=c.get(e.parentPasteIndex));return l}buildToolTags(e){var r;return e.pasteConfig===!1?{}:(((r=e.pasteConfig)==null?void 0:r.tags)||[]).reduce((e,r)=>{let i=Cu(r),a=n.t({},e);return i.forEach(e=>{let n=t.Sa(r)?r[e]:null;a[e.toLowerCase()]=n==null?{}:n}),a},{})}sanitizeContent(e,n){if(e.tagName.toLowerCase()!==`table`){let r=e.cloneNode(!0);return r.innerHTML=t.Ei(e.innerHTML,n),r}return this.sanitizerBuilder.sanitizeTable(e,n)}processElementNode(e,n,r){let i=Object.keys(this.toolRegistry.toolsTags),a=e,o=this.toolRegistry.findToolForTag(a.tagName),s=o==null?void 0:o.tool,c=s?this.toolRegistry.getToolTags(s.name):[],l=i.includes(a.tagName);if(l&&(a.tagName===`DETAILS`||a.tagName===`ASIDE`))return[...n,r,a];let u=t.Qi.blockElements.includes(a.tagName.toLowerCase()),d=Su.has(a.tagName.toLowerCase()),f=Array.from(a.children).some(({tagName:e})=>i.includes(e)&&!c.includes(e)),p=Array.from(a.children).some(({tagName:e})=>t.Qi.blockElements.includes(e.toLowerCase()));if(!u&&!l&&!f)return r.appendChild(a),[...n,r];if(l&&!f||u&&!p&&!f||d&&!f)return[...n,r,a]}getNodes(e){let n=Array.from(e.childNodes),r=(e,n)=>{if(t.Qi.isEmpty(n)&&!t.Qi.isSingleTag(n))return e;let i=e[e.length-1],{destNode:a,remainingNodes:o}=i!==void 0&&t.Qi.isFragment(i)?{destNode:i,remainingNodes:e.slice(0,-1)}:{destNode:new DocumentFragment,remainingNodes:e};if(n.nodeType===Node.TEXT_NODE)return a.appendChild(n),[...o,a];if(n.nodeType!==Node.ELEMENT_NODE)return[...o,a];let s=this.processElementNode(n,o,a);if(s)return s;let c=Array.from(n.childNodes).reduce(r,[]);return[...o,...c]};return n.reduce(r,[])}},af=[/^#{1,6}\s/m,/^```/m,/\|\s*---/,/^- \[[ x]\]/m,/\[.+?\]\(.+?\)/,/\*\*.+?\*\*/,/!\[/,/\$\$[\s\S]+?\$\$/,RegExp(`(?<!\\$)\\$(?!\\$)(?=\\S)[^$]+(?<=\\S)\\$(?!\\$)`,``)];function of(e){return e?af.some(t=>t.test(e)):!1}var sf=class extends Fd{constructor(e,t,n){super(e,t,n)}canHandle(e){return typeof e!=`string`||!e.trim()?0:of(e)?30:0}async handle(e,t){var n=this;if(typeof e!=`string`)return!1;let{markdownToBlocks:r}=await Promise.resolve().then(()=>require(`../markdown.cjs`)),i=await r(e);if(!i.length)return!1;let a=xt(i),{BlockManager:o,Caret:s}=n.Blok,c=o.currentBlock,l=t.canReplaceCurrentBlock&&c!==void 0&&c.isEmpty,u=l?o.currentBlockIndex:o.currentBlockIndex+1,d=a.map(({id:e,type:t,data:n,parent:r})=>o.composeBlock({id:e,tool:t,data:n,parentId:r}));o.insertMany(d,u),l&&c!==void 0&&await o.removeBlock(c,!1);let f=d[d.length-1];return f instanceof ne&&s.setToBlock(f,s.positions.END),!0}},cf=class extends Fd{constructor(e,t,n){super(e,t,n)}canHandle(e){return typeof e==`string`?t.b(e)===null?0:90:0}async handle(e,n){var r=this,i,a;if(typeof e!=`string`)return!1;let o=t.b(e);if(!o)return!1;let s=document.activeElement;if(s!=null&&s.closest(`[data-blok-table-cell]`)||!((i=n.currentBlock)==null||(i=i.holder)==null)&&i.closest(`[data-blok-table-cell-blocks]`)||(a=n.pasteTarget)!=null&&a.closest(`[data-blok-table-cell]`))return!1;let{BlockManager:c,Caret:l}=r.Blok,u={withHeadings:!1,withHeadingColumn:!1,content:o.cells.map(e=>e.map(e=>{let t=e.blocks.length===0?``:e.blocks.map(e=>typeof e.data.text==`string`?e.data.text:``).join(` `),n=e.color!==void 0,r=e.textColor!==void 0;if(!n&&!r)return t;let i={blocks:[],text:t};return n&&(i.color=e.color),r&&(i.textColor=e.textColor),i}))},d=n.canReplaceCurrentBlock,f=c.insert({tool:`table`,data:u,replace:d});return l.setToBlock(f,l.positions.END),!0}},lf=class extends Fd{constructor(e,t,n,r){super(e,t,n),this.config=r}canHandle(e){return typeof e==`string`&&e.length>0?10:0}async handle(e,t){var n=this;if(typeof e!=`string`)return!1;let r=n.processPlain(e);return r.length?(await n.insertPasteData(r,t.canReplaceCurrentBlock),!0):!1}processPlain(e){let{defaultBlock:n}=this.config;return!e||!n?[]:e.split(/\r?\n/).filter(e=>e.trim()).map(e=>{let r=t.Qi.make(`div`);return r.textContent=e,{content:r,tool:n,isBlock:!1,event:this.composePasteEvent(`tag`,{data:r})}})}},uf=class{constructor(e,t){this.tools=e,this.config=t}buildToolsTagsConfig(e){return Object.fromEntries(Object.keys(e).map(t=>{var n;return[t.toLowerCase(),(n=e[t].sanitizationConfig)==null?{}:n]}))}getStructuralTagsConfig(e){let t={},n=[e];for(;n.length>0;){let e=n.pop();if(!e)continue;let i=e.tagName.toLowerCase();if(Su.has(i)){var r;t[i]=(r=t[i])==null?{}:r}n.push(...Array.from(e.children))}return t}buildToolConfig(e){var n;if(e.pasteConfig===!1)return{};let r=((n=e.pasteConfig)==null?void 0:n.tags)||[],i={};return r.forEach(e=>{Cu(e).forEach(n=>{let r=t.Sa(e)?e[n]:null;i[n.toLowerCase()]=r==null?{}:r})}),i}composeConfigs(...e){return t.Di({},...e)}sanitizeTable(e,r){let i=n.t(n.t({},r),{},{img:{src:!0,alt:!0,width:!0,height:!0}}),a=t.Ei(e.outerHTML,i),o=document.createElement(`div`);o.innerHTML=a;let s=o.firstChild;return!s||!(s instanceof HTMLElement)?null:s}isStructuralTag(e){return Su.has(e.toLowerCase())}},df=class{constructor(e,n){this.tools=e,this.config=n,this.toolsTags={},this.tagsByTool={},this.toolsPatterns=[],this.toolsFiles={},this.exceptionList=[],this.processTool=e=>{try{if(e.pasteConfig===!1){this.exceptionList.push(e.name);return}if(!e.hasOnPasteHandler)return;this.getTagsConfig(e),this.getFilesConfig(e),this.getPatternsConfig(e)}catch(n){t.Ea(`Paste handling for «${e.name}» Tool hasn't been set up because of the error`,`warn`,n)}}}async processTools(){var e=this;let t=e.tools;await Array.from(t.values()).forEach(e.processTool)}getTagsConfig(e){if(e.pasteConfig===!1)return;let n=e.pasteConfig.tags||[],r=[];n.forEach(n=>{let i=Cu(n);r.push(...i),i.forEach(r=>{if(Object.prototype.hasOwnProperty.call(this.toolsTags,r)){t.Ea(`Paste handler for «${e.name}» Tool on «${r}» tag is skipped because it is already used by «${this.toolsTags[r].tool.name}» Tool.`,`warn`);return}let i=t.Sa(n)?n[r]:void 0;this.toolsTags[r.toUpperCase()]={tool:e,sanitizationConfig:i}})}),this.tagsByTool[e.name]=r.map(e=>e.toUpperCase())}getFilesConfig(e){if(e.pasteConfig===!1)return;let{files:n={}}=e.pasteConfig,{extensions:r,mimeTypes:i}=n;if(!r&&!i)return;let a=r==null?[]:Array.isArray(r)?r:(t.Ea(`«extensions» property of the paste config for «${e.name}» Tool should be an array`),[]),o=i==null?[]:Array.isArray(i)?i.filter(n=>t.ha(n)?!0:(t.Ea(`MIME type value «${n}» for the «${e.name}» Tool is not a valid MIME type`,`warn`),!1)):(t.Ea(`«mimeTypes» property of the paste config for «${e.name}» Tool should be an array`),[]);this.toolsFiles[e.name]={extensions:a,mimeTypes:o}}getPatternsConfig(e){if(e.pasteConfig===!1||!e.pasteConfig.patterns)return;let n=e.pasteConfig.patterns;Object.keys(n).length!==0&&Object.entries(n).forEach(([n,r])=>{r instanceof RegExp||t.Ea(`Pattern ${r} for «${e.name}» Tool is skipped because it should be a Regexp instance.`,`warn`),this.toolsPatterns.push({key:n,pattern:r,tool:e})})}findToolForTag(e){return this.toolsTags[e]}findToolForFile(e,t){var n,r;let i=(n=(r=e.name.split(`.`).pop())==null?void 0:r.toLowerCase())==null?``:n,a=t=>{let[n,r]=e.type.split(`/`),a=t.extensions.find(e=>e.toLowerCase()===i),o=t.mimeTypes.find(e=>{let[t,i]=e.split(`/`);return t===n&&(i===r||i===`*`)});return a!==void 0||o!==void 0};if(t!==void 0){let e=this.toolsFiles[t];if(e!==void 0&&a(e))return t}let o=Object.entries(this.toolsFiles).find(([,e])=>a(e));return o==null?void 0:o[0]}findToolForPattern(e){return this.toolsPatterns.find(t=>{let n=t.pattern.exec(e);return n?e===n.shift():!1})}getToolTags(e){var t;return(t=this.tagsByTool[e])==null?[]:t}isException(e){return this.exceptionList.includes(e)}},ff,pf=class extends s{constructor(...e){var t;super(...e),t=this,this.MIME_TYPE=`application/x-blok`,this.handlePasteEventWrapper=e=>{this.handlePasteEvent(e)},this.handleDropEventWrapper=e=>{this.handleDropEvent(e)},this.handleDragOverEventWrapper=e=>{this.handleDragOverEvent(e)},this.handleDragLeaveEventWrapper=e=>{this.handleDragLeaveEvent(e)},this.dropIndicatorHolder=null,this.handleDragOverEvent=e=>{let{dataTransfer:t}=e;this.dataTransferHasFiles(t)&&(e.preventDefault(),t&&(t.dropEffect=`copy`),this.updateDropIndicator(e))},this.handleDragLeaveEvent=e=>{let t=this.Blok.UI.nodes.holder,n=e.relatedTarget;n&&t.contains(n)||this.clearDropIndicator()},this.handleDropEvent=async e=>{var n;if(t.clearDropIndicator(),(n=t.Blok.DragManager)!=null&&n.isDragging||!t.dataTransferHasFiles(e.dataTransfer))return;e.preventDefault();let{BlockManager:r,Toolbar:i}=t.Blok,a=r.setCurrentBlockByChildNode(e.target);if(a&&!t.toolRegistry.isException(a.name)){if(e.dataTransfer){let n=e.target instanceof Element?e.target:void 0;await t.processDataTransfer(e.dataTransfer,n)}i.moveAndOpen()}},this.handlePasteEvent=async e=>{var n;if(e.defaultPrevented)return;if((n=t.Blok.DragManager)!=null&&n.isDragging){e.preventDefault();return}let{BlockManager:r,Toolbar:i}=t.Blok,a=r.setCurrentBlockByChildNode(e.target);if(!(!a||e.target&&t.isNativeBehaviour(e.target)&&e.clipboardData&&!e.clipboardData.types.includes(`Files`))&&!t.toolRegistry.isException(a.name)){if(e.preventDefault(),e.clipboardData){let n=e.target instanceof Element?e.target:void 0;await t.processDataTransfer(e.clipboardData,n)}i.moveAndOpen()}}}async prepare(){var e=this;let{Tools:t}=e.Blok;e.toolRegistry=new df(t.blockTools,e.config),e.sanitizerBuilder=new uf(t.blockTools,e.config),await e.toolRegistry.processTools(),e.handlers=[new Xd(e.Blok,e.toolRegistry,e.sanitizerBuilder,e.config),new cf(e.Blok,e.toolRegistry,e.sanitizerBuilder),new nf(e.Blok,e.toolRegistry,e.sanitizerBuilder),new Yd(e.Blok,e.toolRegistry,e.sanitizerBuilder,e.config),new rf(e.Blok,e.toolRegistry,e.sanitizerBuilder),new sf(e.Blok,e.toolRegistry,e.sanitizerBuilder),new lf(e.Blok,e.toolRegistry,e.sanitizerBuilder,e.config)]}async processText(e,t=!1){var n=this;let{BlockManager:r}=n.Blok,i=r.currentBlock,a=!!(i&&i.tool.isDefault&&i.isEmpty),o=t?n.handlers.find(e=>e instanceof rf):n.handlers.find(e=>e instanceof lf);if(!o)return;let s={canReplaceCurrentBlock:a,currentBlock:i==null?void 0:i};await o.handle(e,s)}toggleReadOnly(e){e?this.unsetCallback():this.setCallback()}async processDataTransfer(e,t){var n=this,r;let i=e.getData(`text/plain`),a=e.getData(`text/html`),o=a&&n.config.onBeforePaste?(r=n.config.onBeforePaste(a))==null?``:r:a,s=e.getData(n.MIME_TYPE)||n.readNotionBlocksV3(e)||n.readNextSpaceBlocks(e);await n.routeToHandlers(e,i,o,s,t)||await n.processAsText(i)}readNotionBlocksV3(e){let t=e.getData(Ou);if(!t)return``;let n=ku(t);return n===null||n.length===0?``:JSON.stringify(n)}readNextSpaceBlocks(e){for(let t of md){let n=e.getData(t);if(!n)continue;let r=hd(n);if(r!==null&&r.length>0)return JSON.stringify(r)}return``}async routeToHandlers(e,t,n,r,i){var a=this,o;let{BlockManager:s}=a.Blok,c=s.currentBlock,l={canReplaceCurrentBlock:!!(c&&c.tool.isDefault&&c.isEmpty&&!((o=c.holder)!=null&&o.closest(`[data-blok-table-cell-blocks]`))),currentBlock:c==null?void 0:c,plainData:t,pasteTarget:i};for(let i of a.handlers){let o=a.getDataForHandler(i,e,t,n,r);if(o!==void 0&&i.canHandle(o)!==0&&await i.handle(o,l))return!0}return!1}getDataForHandler(e,n,r,i,a){if(e instanceof Xd)return a;if(e instanceof cf)return i;if(e instanceof nf)return n;if(e instanceof Yd||e instanceof sf||e instanceof lf)return r;if(!(e instanceof rf))return;let o=this.sanitizerBuilder.buildToolsTagsConfig(this.toolRegistry.toolsTags),s=this.Blok.Tools.getAllInlineToolsSanitizeConfig(),c=Object.fromEntries([...Su].map(e=>[e,{}])),l=t.Di(this.config.sanitizer,c,o,s,{br:{}}),u=t.Ei(wu(t.Zr(i)),l),d=t.Qi.isHTMLString(u);return!u.trim()||u.trim()===r||!d?void 0:u}async processAsText(e){var t=this;let{BlockManager:n}=t.Blok;if(!e)return;let r=n.currentBlock,i=!!(r&&r.tool.isDefault&&r.isEmpty),a=t.handlers.find(e=>e instanceof lf);a&&await a.handle(e,{canReplaceCurrentBlock:i,currentBlock:r==null?void 0:r})}setCallback(){let e=this.Blok.UI.nodes.holder;this.listeners.on(e,`paste`,this.handlePasteEventWrapper),this.listeners.on(e,`drop`,this.handleDropEventWrapper),this.listeners.on(e,`dragover`,this.handleDragOverEventWrapper),this.listeners.on(e,`dragleave`,this.handleDragLeaveEventWrapper)}unsetCallback(){let e=this.Blok.UI.nodes.holder;this.listeners.off(e,`paste`,this.handlePasteEventWrapper),this.listeners.off(e,`drop`,this.handleDropEventWrapper),this.listeners.off(e,`dragover`,this.handleDragOverEventWrapper),this.listeners.off(e,`dragleave`,this.handleDragLeaveEventWrapper)}dataTransferHasFiles(e){var t,n;return e?Array.from((t=e.types)==null?[]:t).includes(`Files`)?!0:!!((n=e.files)!=null&&n.length):!1}updateDropIndicator(e){let t=e.target instanceof Element?e.target:null,n=t==null?void 0:t.closest(`[data-blok-element]`);if(!(n instanceof HTMLElement)){this.clearDropIndicator();return}let r=n.getBoundingClientRect(),i=e.clientY<r.top+r.height/2?`top`:`bottom`;this.dropIndicatorHolder&&this.dropIndicatorHolder!==n&&(this.dropIndicatorHolder.removeAttribute(`data-drop-indicator`),this.dropIndicatorHolder.style.removeProperty(`--drop-indicator-depth`)),n.setAttribute(`data-drop-indicator`,i),n.style.setProperty(`--drop-indicator-depth`,String(this.computeDropDepth(n))),this.dropIndicatorHolder=n}computeDropDepth(e){var t,n;let r=(t=e.parentElement)!=null&&t.closest(`[data-blok-element]`)?this.countAncestorBlocks(e):0,i=e.querySelector(`[data-list-depth]`),a=(n=i==null?void 0:i.getAttribute(`data-list-depth`))==null?`0`:n,o=Number.parseInt(a,10);return r+(Number.isNaN(o)?0:o)}countAncestorBlocks(e){var t;let n=(t=e.parentElement)==null?void 0:t.closest(`[data-blok-element]`);return n?1+this.countAncestorBlocks(n):0}clearDropIndicator(){this.dropIndicatorHolder&&(this.dropIndicatorHolder.removeAttribute(`data-drop-indicator`),this.dropIndicatorHolder.style.removeProperty(`--drop-indicator-depth`),this.dropIndicatorHolder=null)}isNativeBehaviour(e){return t.Qi.isNativeInput(e)||e instanceof HTMLElement&&(e.contentEditable===`plaintext-only`||e.getAttribute(`contenteditable`)===`plaintext-only`)}};ff=pf,ff.PATTERN_PROCESSING_MAX_LENGTH=450;var mf=class extends s{constructor(...e){super(...e),this.toolsDontSupportReadOnly=[],this.toolsDontSupportInPlaceToggle=[],this.readOnlyEnabled=!1,this.inPlaceToggleChecked=!1}get isEnabled(){return this.readOnlyEnabled}get supportsInPlaceToggle(){return this.inPlaceToggleChecked&&this.toolsDontSupportInPlaceToggle.length===0}async prepare(){var e=this;let{Tools:t}=e.Blok,{blockTools:n}=t,r=[];Array.from(n.entries()).forEach(([t,n])=>{n.isReadOnlySupported||r.push(t),n.supportsInPlaceReadOnly||e.toolsDontSupportInPlaceToggle.push(t)}),e.toolsDontSupportReadOnly=r,e.inPlaceToggleChecked=!0,e.config.readOnly===!0&&r.length>0&&e.throwCriticalError(),await e.toggle(e.config.readOnly,!0)}async toggle(e=!this.readOnlyEnabled,t=!1){var n=this;e&&n.toolsDontSupportReadOnly.length>0&&n.throwCriticalError();let r=n.readOnlyEnabled;n.readOnlyEnabled=e;for(let t of Object.values(n.Blok))t!=null&&typeof t.toggleReadOnly==`function`&&t.toggleReadOnly(e);if(r===e||t)return n.readOnlyEnabled;if(n.supportsInPlaceToggle){var i;n.Blok.ModificationsObserver.disable();let t=(i=n.Blok.BlockManager.blocks)==null?[]:i;for(let n of t)n.setReadOnly(e);return n.Blok.ModificationsObserver.enable(),n.readOnlyEnabled}n.Blok.ModificationsObserver.disable();let a=await n.Blok.Saver.save();if(a===void 0)return n.Blok.ModificationsObserver.enable(),n.readOnlyEnabled;let o=window.scrollY;n.Blok.Renderer.markRenderStart();try{await n.Blok.BlockManager.clear(),await n.Blok.Renderer.render(a.blocks)}finally{n.Blok.Renderer.markRenderEnd()}return window.scrollY!==o&&window.scrollTo(0,o),n.Blok.ModificationsObserver.enable(),n.readOnlyEnabled}async set(e){return this.toggle(e)}throwCriticalError(){throw new o(`To enable read-only mode all connected tools should support it. Tools ${this.toolsDontSupportReadOnly.join(`, `)} don't support read-only mode.`)}},hf=class extends s{constructor(...e){super(...e),this.isRectSelectionActivated=!1,this.SCROLL_SPEED=3,this.HEIGHT_OF_SCROLL_ZONE=40,this.BOTTOM_SCROLL_ZONE=1,this.TOP_SCROLL_ZONE=2,this.MAIN_MOUSE_BUTTON=0,this.mousedown=!1,this.mouseDownWithinBoundsFromContentEditable=!1,this.pendingToolbarClose=!1,this.isScrolling=!1,this.inScrollZone=null,this.startX=0,this.startY=0,this.mouseX=0,this.mouseY=0,this.stackOfSelected=[],this.rectCrossesBlocks=!1,this.anchorBlockIndex=null,this.overlayRectangle=null,this.listenerIds=[]}static get CSS(){return{overlay:``,overlayContainer:``,rect:``,topScrollZone:``,bottomScrollZone:``}}prepare(){this.enableModuleBindings()}startSelection(e,n,r=!1){let{UI:i}=this.Blok,a=i.nodes.redactor;if(!a)return;let o=a.getBoundingClientRect(),s=n-this.getScrollTop();if(!(s>=o.top&&s<=o.bottom))return;let c=this.getScrollLeft(),l=e-c,u=this.Blok.UI.contentRect,d=l>=u.left&&l<=u.right,f=document.elementFromPoint(e-c,s);f&&(!f.closest(t.Na(t.Ma.toolbar))&&!r&&(this.Blok.BlockSelection.allBlocksSelected=!1,this.Blok.BlockSelection.disableNavigationMode(),this.clearSelection(),this.stackOfSelected=[],this.anchorBlockIndex=null),![t.Na(t.Ma.elementContent),t.Na(t.Ma.settingsToggler),t.Na(t.Ma.popover),`[data-blok-interface=inline-toolbar]`].some(e=>!!f.closest(e))&&(d&&(this.pendingToolbarClose=!0),this.mousedown=!0,this.startX=e,this.startY=n))}endSelection(){this.mousedown=!1,this.mouseDownWithinBoundsFromContentEditable=!1,this.pendingToolbarClose=!1,this.startX=0,this.startY=0,this.anchorBlockIndex=null,this.stackOfSelected=[],this.overlayRectangle!==null&&(this.overlayRectangle.style.display=`none`)}isRectActivated(){return this.isRectSelectionActivated||this.mousedown}get isMouseDownWithinBounds(){return this.mouseDownWithinBoundsFromContentEditable}clearSelection(){this.isRectSelectionActivated=!1}cancelActiveSelection(){!this.mousedown&&!this.isRectSelectionActivated||(this.clearSelection(),this.endSelection())}enableModuleBindings(){this.genHTML(),this.listeners.on(document.body,`mousedown`,e=>{this.processMouseDown(e)},!1);let e=t.ya(e=>{e instanceof MouseEvent&&this.processMouseMove(e)},10);this.listeners.on(document.body,`mousemove`,e,{passive:!0}),this.listeners.on(document.body,`mouseleave`,()=>{this.processMouseLeave()});let n=t.ya(e=>{this.processScroll(e)},10);this.listeners.on(window,`scroll`,n,{passive:!0}),this.listeners.on(document,`mouseup`,()=>{this.processMouseUp()},!1)}processMouseDown(e){if(e.button!==this.MAIN_MOUSE_BUTTON)return;if(e.target.closest(t.Qi.allInputsSelector)===null){this.startSelection(e.pageX,e.pageY,e.shiftKey);return}let n=this.getScrollLeft(),r=e.pageX-n,i=this.Blok.UI.contentRect;r>=i.left&&r<=i.right&&(this.mouseDownWithinBoundsFromContentEditable=!0)}processMouseMove(e){this.mouseDownWithinBoundsFromContentEditable&&this.Blok.Toolbar.close(),this.pendingToolbarClose&&(this.pendingToolbarClose=!1,this.Blok.Toolbar.close()),this.changingRectangle(e),this.scrollByZones(e.clientY)}processMouseLeave(){this.clearSelection(),this.endSelection()}processScroll(e){this.changingRectangle(e)}processMouseUp(){this.Blok.BlockSelection.selectedBlocks.length>1&&this.Blok.Toolbar.moveAndOpenForMultipleBlocks(),this.clearSelection(),this.endSelection()}scrollByZones(e){if(this.inScrollZone=null,e<=this.HEIGHT_OF_SCROLL_ZONE&&(this.inScrollZone=this.TOP_SCROLL_ZONE),document.documentElement.clientHeight-e<=this.HEIGHT_OF_SCROLL_ZONE&&(this.inScrollZone=this.BOTTOM_SCROLL_ZONE),!this.inScrollZone){this.isScrolling=!1;return}this.isScrolling||(this.scrollVertical(this.inScrollZone===this.TOP_SCROLL_ZONE?-this.SCROLL_SPEED:this.SCROLL_SPEED),this.isScrolling=!0)}genHTML(){let{UI:e}=this.Blok,n=e.nodes.holder.querySelector(t.Na(t.Ma.editor)),r=t.Qi.make(`div`,[`fixed`,`inset-0`,`z-overlay`,`pointer-events-none`,`overflow-hidden`],{}),i=t.Qi.make(`div`,[`relative`,`pointer-events-auto`,`z-0`],{}),a=t.Qi.make(`div`,[`absolute`,`pointer-events-none`,`bg-selection-highlight`,`border`,`border-transparent`],{});if(r.setAttribute(t.Ma.overlay,``),i.setAttribute(t.Ma.overlayContainer,``),a.setAttribute(t.Ma.overlayRectangle,``),r.setAttribute(`data-blok-testid`,`overlay`),a.setAttribute(`data-blok-testid`,`overlay-rectangle`),!n)throw Error(`RectangleSelection: blok wrapper not found`);return i.appendChild(a),r.appendChild(i),n.appendChild(r),this.overlayRectangle=a,{container:n,overlay:r}}scrollVertical(e){if(!(this.inScrollZone&&this.mousedown))return;let t=this.getScrollTop();window.scrollBy(0,e),this.mouseY+=this.getScrollTop()-t,setTimeout(()=>{this.scrollVertical(e)},0)}changingRectangle(e){if(!this.mousedown)return;let n=this.overlayRectangle;if(n===null)return;e.pageY!==void 0&&(this.mouseX=e.pageX,this.mouseY=e.pageY),this.isRectSelectionActivated||(this.isRectSelectionActivated=!0,this.shrinkRectangleToPoint(),n.style.display=`block`);let{index:r}=this.genInfoForMouseSelection();this.rectCrossesBlocks=!1;let i=r===void 0?void 0:this.Blok.BlockManager.getBlockByIndex(r),a=i===void 0?void 0:this.Blok.BlockManager.resolveToRootBlock(i);if(a){let e=a.holder.getBoundingClientRect(),t=this.getScrollLeft(),n=Math.min(this.startX,this.mouseX),r=Math.max(this.startX,this.mouseX),i=e.left+t,o=e.right+t;this.rectCrossesBlocks=r>=i&&n<=o}if(this.updateRectangleSize(),this.Blok.Toolbar.close(),r===void 0)return;this.trySelectNextBlock(r),this.inverseSelection();let o=t.Ai.get();o&&o.removeAllRanges()}shrinkRectangleToPoint(){if(this.overlayRectangle===null)return;let e=this.getScrollLeft(),t=this.getScrollTop();this.overlayRectangle.style.left=`${this.startX-e}px`,this.overlayRectangle.style.top=`${this.startY-t}px`,this.overlayRectangle.style.bottom=`calc(100% - ${this.startY-t}px)`,this.overlayRectangle.style.right=`calc(100% - ${this.startX-e}px)`}inverseSelection(){if(this.stackOfSelected.length===0)return;let e=this.Blok.BlockManager.getBlockByIndex(this.stackOfSelected[0]);if(!e)return;let t=e.selected;if(this.rectCrossesBlocks&&!t)for(let e of this.stackOfSelected)this.Blok.BlockSelection.selectBlockByIndex(e);if(!this.rectCrossesBlocks&&t)for(let e of this.stackOfSelected)this.Blok.BlockSelection.unSelectBlockByIndex(e)}updateRectangleSize(){if(this.overlayRectangle===null)return;let e=this.getScrollLeft(),t=this.getScrollTop();this.mouseY>=this.startY?(this.overlayRectangle.style.top=`${this.startY-t}px`,this.overlayRectangle.style.bottom=`calc(100% - ${this.mouseY-t}px)`):(this.overlayRectangle.style.bottom=`calc(100% - ${this.startY-t}px)`,this.overlayRectangle.style.top=`${this.mouseY-t}px`),this.mouseX>=this.startX?(this.overlayRectangle.style.left=`${this.startX-e}px`,this.overlayRectangle.style.right=`calc(100% - ${this.mouseX-e}px)`):(this.overlayRectangle.style.right=`calc(100% - ${this.startX-e}px)`,this.overlayRectangle.style.left=`${this.mouseX-e}px`)}genInfoForMouseSelection(){let{UI:e}=this.Blok,t=e.nodes.redactor.getBoundingClientRect(),n=t.left+t.width/2,r=this.getScrollTop(),i=this.mouseY-r,a=document.elementFromPoint(n,i);if(!a)return{index:void 0};let o=this.Blok.BlockManager.getBlockByChildNode(a);return{index:o===void 0?void 0:this.Blok.BlockManager.blocks.indexOf(o)}}getScrollTop(){var e,t,n,r;return typeof window.scrollY==`number`?window.scrollY:(e=(t=(n=document.documentElement)==null?void 0:n.scrollTop)==null?(r=document.body)==null?void 0:r.scrollTop:t)==null?0:e}getScrollLeft(){var e,t,n,r;return typeof window.scrollX==`number`?window.scrollX:(e=(t=(n=document.documentElement)==null?void 0:n.scrollLeft)==null?(r=document.body)==null?void 0:r.scrollLeft:t)==null?0:e}addBlockInSelection(e){this.rectCrossesBlocks&&this.Blok.BlockSelection.selectBlockByIndex(e),this.stackOfSelected.push(e)}trySelectNextBlock(e){this.anchorBlockIndex===null&&(this.anchorBlockIndex=e);let t=this.Blok.BlockManager.blocks,n=t[this.anchorBlockIndex],r=t[e];if(!n||!r)return;let i=n.holder.getBoundingClientRect(),a=r.holder.getBoundingClientRect(),o=this.getScrollTop(),s=Math.min(this.startY,this.mouseY)-o,c=Math.max(this.startY,this.mouseY)-o,l=Math.max(Math.min(i.top,a.top),s),u=Math.min(Math.max(i.bottom,a.bottom),c),d=this.getScrollLeft(),f=Math.min(this.startX,this.mouseX)-d,p=Math.max(this.startX,this.mouseX)-d,m=new Set;t.forEach((e,t)=>{let n=e.holder.getBoundingClientRect(),r=e.holder.querySelector(`[data-blok-element-content]`),i=(r==null?e.holder:r).getBoundingClientRect(),a=f===p||i.right>f&&i.left<p;n.height>0&&n.bottom>l&&n.top<u&&a&&m.add(t)});let h=new Set(this.stackOfSelected);for(let e of h)!m.has(e)&&this.rectCrossesBlocks&&this.Blok.BlockSelection.unSelectBlockByIndex(e);for(let e of m)!h.has(e)&&this.rectCrossesBlocks&&this.Blok.BlockSelection.selectBlockByIndex(e);this.stackOfSelected=Array.from(m).sort((e,t)=>e-t)}},gf=[`color`,`background-color`],_f={color:`text`,"background-color":`bg`};function vf(e){e.querySelectorAll(`mark`).forEach(e=>{for(let n of gf){let r=e.style.getPropertyValue(n);if(!r||r===`transparent`||r.startsWith(`var(`))continue;if(n===`background-color`&&(t.ni(r)||t.ti(r))){e.style.removeProperty(n);continue}let i=t.$r(r,_f[n]);i!==null&&e.style.setProperty(n,t.ai(i,_f[n]))}})}var yf={delimiter:`divider`},bf=class extends s{constructor(...e){super(...e),this.detectedInputFormat=`flat`,this.pendingRender=null,this.pendingHashScroll=null,this.resolvePendingRender=null}markRenderStart(){this.pendingRender=new Promise(e=>{this.resolvePendingRender=e})}markRenderEnd(){this.resolvePendingRender!==null&&(this.resolvePendingRender(),this.resolvePendingRender=null),this.pendingRender=null}getDetectedInputFormat(){return this.detectedInputFormat}render(e){return new Promise(t=>{let n=this.insertRenderedBlocks(e);window.requestIdleCallback(()=>{this.eventsDispatcher.emit(p,{count:n}),t()},{timeout:2e3})})}insertRenderedBlocks(e){let{Tools:n,BlockManager:r}=this.Blok;if(e.length===0)return r.insert(),1;let i=this.config.dataModel||`auto`,a=Le(e);this.detectedInputFormat=a.format;let o=xt(Et(Dt(i,a.format)?$e(e):e)),s=new Set,c=o.map(e=>{let{tunes:i,parent:a,content:o,lastEditedAt:c,lastEditedBy:l}=e,u=e.id!==void 0&&s.has(e.id);u&&t.Da(`Duplicate block id «${e.id}» replaced with a generated id to ensure uniqueness`,`warn`);let d=u?t.aa():e.id;d!==void 0&&s.add(d);let f=e.type,p=(e=>typeof e==`object`&&!!e)(e.data)?e.data:{},m=(()=>{if(n.available.has(f))return{tool:f,data:p};let e=yf[f];return e!==void 0&&n.available.has(e)?{tool:e,data:p}:(t.Da(`Tool «${f}» is not found. Check 'tools' property at the Blok config.`,`warn`),{tool:n.stubTool,data:this.composeStubDataForTool(f,p,d)})})();return((e,s)=>{try{return r.composeBlock({id:d,tool:e,data:s,tunes:i,parentId:a,contentIds:o,lastEditedAt:c,lastEditedBy:l})}catch(u){t.Ea(`Block «${e}» skipped because of plugins error`,`error`,{data:s,error:u});let f=this.composeStubDataForTool(e,s,d);return r.composeBlock({id:d,tool:n.stubTool,data:f,tunes:i,parentId:a,contentIds:o,lastEditedAt:c,lastEditedBy:l})}})(m.tool,m.data)});return r.insertMany(c),vf(this.Blok.UI.nodes.redactor),c.length}composeStubDataForTool(e,t,n){let{Tools:r}=this.Blok,i=(()=>{if(!r.unavailable.has(e))return e;let t=r.unavailable.get(e).toolbox;return t!==void 0&&t[0].title!==void 0?t[0].title:e})();return{savedData:{id:n,type:e,data:t},title:i}}},xf=/<img\s+[^>]*src=["']([^"']+)["'][^>]*>/g,Sf=e=>{let r=new Map;for(let t of e)t.id!==void 0&&r.set(t.id,t);if(!e.some(e=>e.tool===`table`))return e;let i=new Map;for(let t of e){var a;if(t.tool!==`paragraph`||t.parentId===void 0||t.parentId===null)continue;let e=r.get(t.parentId);if(e===void 0||e.tool!==`table`)continue;let n=(a=t.data)==null?void 0:a.text;if(typeof n!=`string`)continue;let o=Array.from(n.matchAll(xf),e=>e[1]);if(o.length===0)continue;xf.lastIndex=0;let s=n.replace(xf,``);t.id!==void 0&&i.set(t.id,{parentTableId:t.parentId,imgSrcs:o,cleanedText:s})}if(i.size===0)return e;let o=new Map;for(let[e,n]of i){let r=[];for(let e of n.imgSrcs){let i={id:t.aa(),tool:`image`,data:{url:e},isValid:!0,parentId:n.parentTableId};r.push(i)}o.set(e,r)}let s=new Set;for(let e of i.values())s.add(e.parentTableId);let c=new Map;for(let e of s){let t=r.get(e);if(t===void 0)continue;let i=n.t({},t),a=t.data;if((a==null?void 0:a.content)!==void 0){let e=a.content.map(e=>e.map(e=>n.t(n.t({},e),{},{blocks:[...e.blocks]})));i.data=n.t(n.t({},t.data),{},{content:e})}i.contentIds=t.contentIds===void 0?[]:[...t.contentIds],c.set(e,i)}for(let[e,t]of o){let n=i.get(e);if(n===void 0)continue;let r=c.get(n.parentTableId);if(r===void 0)continue;let a=r.data;if((a==null?void 0:a.content)===void 0)continue;let o=t.map(e=>{var t;return(t=e.id)==null?``:t});a.content.flat().forEach(t=>{let n=t.blocks.indexOf(e);n!==-1&&t.blocks.splice(n,0,...o)}),r.contentIds!==void 0&&r.contentIds.push(...o)}let l=[];for(let t of e){if(t.id!==void 0&&c.has(t.id)){l.push(c.get(t.id));continue}if(t.id!==void 0&&i.has(t.id)){var u,d;l.push(...(u=o.get(t.id))==null?[]:u);let e=i.get(t.id),r=n.t(n.t({},t),{},{data:n.t(n.t({},t.data),{},{text:(d=e==null?void 0:e.cleanedText)==null?``:d})});l.push(r);continue}l.push(t)}return l},Cf=class extends s{constructor(...e){super(...e),this.pendingSave=null}async save(){var e=this;if(!e.isDestroyed){if(e.pendingSave!==null)return e.pendingSave;e.pendingSave=e.doSave();try{return await e.pendingSave}finally{e.pendingSave=null}}}async doSave(){var e=this,n;let r=(n=e.Blok.Renderer)==null?void 0:n.pendingRender;if(r!=null&&await r,e.isDestroyed)return;let{BlockManager:i,Tools:a}=e.Blok,o=i.blocks;if(o.length===1&&o[0].isEmpty&&o[0].tool.isDefault)return{time:+new Date,blocks:[],version:t.ka()};let s=new Set(o.map(e=>e.id));for(let e of o)e.parentId!==null&&!s.has(e.parentId)&&(t.Da(`Saver: cleared dangling parentId ${e.parentId} on block ${e.id}`,`warn`),e.parentId=null);let c=new Map;for(let e of o){if(e.parentId===null)continue;let t=c.get(e.parentId);t===void 0?c.set(e.parentId,[e.id]):t.push(e.id)}let l=o.map(t=>{var n;return e.getSavedData(t,(n=c.get(t.id))==null?[]:n)});e.lastSaveError=void 0;try{let t=await Promise.all(l),n=Sf(e.sanitizeExtractedData(t,e=>{var t;return(t=a.blockTools.get(e))==null?void 0:t.sanitizeConfig},e.config.sanitizer));return e.isDestroyed?void 0:e.makeOutput(n)}catch(n){e.lastSaveError=n,t.Da(`Saving failed due to the Error %o`,`error`,n instanceof Error?n:Error(String(n)));return}}async getSavedData(e,t){var r=this;let i=await e.save(),a=e.name,o=(i==null?void 0:i.data)===void 0?r.getPreservedSavedData(e):i;if(o===void 0)return{tool:a,isValid:!1};let s=await e.validate(o.data);return n.t(n.t({},o),{},{isValid:s,parentId:e.parentId,contentIds:t,lastEditedAt:e.lastEditedAt,lastEditedBy:e.lastEditedBy})}makeOutput(e){var r,i,a;let o=[];e.forEach(({id:e,tool:r,data:i,tunes:a,isValid:s,parentId:c,contentIds:l,lastEditedAt:u,lastEditedBy:d})=>{let f=c!=null;if(!s&&!f){t.Ea(`Block «${r}» skipped because saved data is invalid`);return}if(r===void 0||i===void 0){t.Ea(`Block skipped because saved data is missing required fields`);return}if(r===this.Blok.Tools.stubTool&&this.isStubSavedData(i)){o.push(i);return}if(r===this.Blok.Tools.stubTool){t.Ea(`Stub block data is malformed and was skipped`);return}let p=a===void 0||t.ba(a),m=l!==void 0&&l.length>0,h=u!==void 0,g=d!=null,_=n.t(n.t(n.t(n.t(n.t({id:e,type:r,data:i},!p&&{tunes:a}),f&&{parent:c}),m&&{content:l}),h&&{lastEditedAt:u}),g&&{lastEditedBy:d});o.push(_)});let s=Ot(this.config.dataModel||`auto`,(r=(i=this.Blok.Renderer)==null||(a=i.getDetectedInputFormat)==null?void 0:a.call(i))==null?`flat`:r)?ht(o):o,c=Xc(s);if(c.length>0){let e=`Saver produced output with hierarchy drift: ${c.map(e=>e.message).join(`; `)}`,n=typeof process<`u`?`production`:void 0;if(n===`test`||n===`development`)throw Error(e);t.Da(e,`error`)}return{time:+new Date,blocks:s,version:t.ka()}}sanitizeExtractedData(e,r,i){let a=[];if(e.forEach((e,t)=>{this.hasSanitizableData(e)&&a.push({index:t,data:e})}),a.length===0)return e;let o=t.Oi(a.map(({data:e})=>e),r,i),s=e.map(e=>n.t({},e));return a.forEach(({index:e},t)=>{let r=o[t];s[e]=n.t(n.t({},s[e]),{},{data:r.data})}),s}hasSanitizableData(e){return e.data!==void 0&&typeof e.tool==`string`}isStubSavedData(e){if(!t.Sa(e))return!1;let n=e;return typeof n.type==`string`&&n.data!==void 0}getLastSaveError(){return this.lastSaveError}getPreservedSavedData(e){let r=e.preservedData;if(t.ba(r))return;let i=e.preservedTunes;return n.t(n.t({id:e.id,tool:e.name,data:r},t.ba(i)?{}:{tunes:i}),{},{time:0})}},wf=class extends s{constructor(...e){super(...e),this.opened=!1,this.isOpening=!1,this.selection=new t.Ai,this.popover=null,this.flipperInstance=new t.mi({focusedItemClass:t.N.focused,allowedKeys:[t.Aa.TAB,t.Aa.UP,t.Aa.DOWN,t.Aa.ENTER,t.Aa.RIGHT,t.Aa.LEFT]}),this.flipperKeydownHandler=null,this.flipperKeydownSource=null,this.deleteKeyHandler=null,this.close=()=>{this.opened&&(this.opened=!1,this.isOpening=!1,t.Ai.isAtBlok||this.selection.restore(),this.selection.clearSaved(),this.detachDeleteKeyListener(),this.detachFlipperKeydownListener(),this.clearBlockSelectionOnClose(),this.eventsDispatcher.emit(this.events.closed),this.popover&&(this.popover.off(t.T.Closed,this.onPopoverClose),this.popover.destroy(),this.popover.getElement().remove(),this.popover=null))},this.onPopoverClose=()=>{this.close()}}get events(){return{opened:h,closed:m}}get CSS(){return{settings:``}}get flipper(){return this.flipperInstance}make(){this.nodes.wrapper=t.Qi.make(`div`),this.nodes.wrapper.setAttribute(`data-blok-testid`,`block-tunes-wrapper`),this.eventsDispatcher.on(g,this.close)}destroy(){this.detachFlipperKeydownListener(),this.removeAllNodes(),this.listeners.destroy(),this.eventsDispatcher.off(g,this.close)}async open(e,n,r){var i=this;let a=i.Blok.BlockSelection.selectedBlocks,o=a.length>1,s=o?a[0]:e==null?i.Blok.BlockManager.currentBlock:e;if(s!==void 0){i.isOpening=!0;try{var c;i.selection.save(),o||(i.Blok.BlockSelection.selectBlock(s),i.Blok.BlockSelection.clearCache());let{toolTunes:e,commonTunes:l}=s.getTunes(),u=await i.getTunesItems(s,l,e),d=o?void 0:await s.getActiveToolboxEntry(),f=o?i.Blok.I18n.t(`blockSettings.blocksSelected`,{count:a.length}):d?t.Ki(i.Blok.I18n,d,s.name):t.Gi(i.Blok.I18n,void 0,s.name),p=t.ma()?Vd:t.C,m={searchable:!0,trigger:n||i.nodes.wrapper,items:u,messages:{nothingFound:i.Blok.I18n.t(`popover.nothingFound`),search:i.Blok.I18n.t(`popover.search`)},autoFocusFirstItem:!1,minWidth:`220px`,placeLeftOfAnchor:(c=r==null?void 0:r.placeLeftOfAnchor)==null?!0:c,viewportMargin:50,contextLabel:f};p===t.C&&(m.flipper=i.flipperInstance),i.popover=new p(m),i.popover.getElement().setAttribute(`data-blok-testid`,`block-tunes-popover`),i.popover.on(t.T.Closed,i.onPopoverClose),i.attachDeleteKeyListener(u),i.opened=!0,i.isOpening=!1,i.popover.show(),i.attachFlipperKeydownListener(s),i.eventsDispatcher.emit(i.events.opened)}catch(e){i.isOpening=!1}}}getElement(){return this.nodes.wrapper}contains(e){var t,n;return!!((t=this.nodes.wrapper)!=null&&t.contains(e)||(n=this.popover)!=null&&n.hasNode(e))}async getTunesItems(e,n,r){var i=this;let a=[],o=i.Blok.BlockSelection.selectedBlocks,s=o.length>1,l=i.Blok.ReadOnly.isEnabled,u=Array.from(i.Blok.Tools.blockTools.values());if(l){let r=n.filter(e=>`name`in e&&e.name===`copy-link`);return a.push(...r),e.lastEditedAt!==void 0&&(a.push({type:t.ki.Separator}),a.push({type:t.ki.Html,element:i.createEditMetadataFooter(e),name:`edit-metadata`})),a}!s&&r!==void 0&&r.length>0&&(a.push(...r),a.push({type:t.ki.Separator}));let d=(s?await t.Vi(o.map(e=>new c(e)),u):await t.Bi(e,u)).reduce((n,r)=>(r.toolbox===void 0||r.toolbox.forEach(a=>{var c;let l=a.titleKey,u=l!=null&&l.includes(`.`)?l:`toolNames.${l}`,d=l?u:void 0,f=d?i.Blok.I18n.getEnglishTranslation(d):a.title;n.push({icon:a.icon,title:t.Ki(i.Blok.I18n,a,r.name),name:(c=a.name)==null?r.name:c,englishTitle:f,searchTerms:a.searchTerms,closeOnActivate:!0,onActivate:async()=>{let{Caret:t,Toolbar:n}=i.Blok,c=e.contentIds.length;if(c>0){let e=i.Blok.I18n.t(`blockSettings.convertWithChildrenWarning`,{count:c}),t=`This block has ${c} nested block${c===1?``:`s`}. Converting it will promote them to the top level. Continue?`;if(!window.confirm(e===`blockSettings.convertWithChildrenWarning`?t:e))return}let l=await i.convertBlock(e,o,s,r,a.data);n.close(),l&&t.setToBlock(l,t.positions.END)}})}),n),[]);if(s){let e=o.map(e=>e.id);d.push({icon:t.tt,title:i.Blok.I18n.t(`toolNames.columns`),name:`turn-into-columns`,closeOnActivate:!0,onActivate:()=>{let{Caret:t,Toolbar:n,BlockManager:r}=i.Blok,a=i.Blok.API.methods,o=Wl(a,e);if(o===null){n.close();return}let s=a.blocks.getChildren(o)[0],c=s===void 0?void 0:a.blocks.getChildren(s.id)[0],l=c===void 0?void 0:r.getBlockById(c.id);l!==void 0&&t.setToBlock(l,t.positions.START),n.close()}})}return d.length>0&&(a.push({icon:t.On,name:`convert-to`,title:i.Blok.I18n.t(`popover.convertTo`),children:{items:d,minWidth:`200px`}}),a.push({type:t.ki.Separator})),s?a.push({icon:t.Vn,title:i.Blok.I18n.t(`blockSettings.delete`),name:`delete`,isDestructive:!0,secondaryLabel:`Del`,closeOnActivate:!0,onActivate:()=>{let{BlockManager:e,Caret:t,Toolbar:n}=i.Blok,r=e.deleteSelectedBlocksAndInsertReplacement();r&&t.setToBlock(r,t.positions.END),n.close()}}):a.push(...n),e.lastEditedAt!==void 0&&(a.push({type:t.ki.Separator}),a.push({type:t.ki.Html,element:i.createEditMetadataFooter(e),name:`edit-metadata`})),a}createEditMetadataFooter(e){let t=document.createElement(`div`);t.classList.add(`px-3`,`py-2`,`text-xs`,`leading-snug`,`text-[color:var(--popover-text-secondary,_#888)]`,`select-none`);let n=document.createElement(`div`);if(n.setAttribute(`data-edit-meta-label`,``),n.textContent=this.Blok.I18n.t(`blockSettings.lastEdited`),e.lastEditedBy!=null&&this.config.resolveUser!=null&&Promise.resolve(this.config.resolveUser(e.lastEditedBy)).then(e=>{(e==null?void 0:e.name)!=null&&(n.textContent=this.Blok.I18n.t(`blockSettings.lastEditedBy`,{name:e.name}))}),t.appendChild(n),e.lastEditedAt!==void 0){let n=document.createElement(`div`);n.classList.add(`mt-1`);let r=this.Blok.I18n.getLocale(),i=new Date(e.lastEditedAt),a=new Intl.DateTimeFormat(r,{day:`numeric`,month:`long`,year:`numeric`}).formatToParts(i);for(;a.length>0&&a[a.length-1].type===`literal`&&a[a.length-1].value.includes(`.`);)a.pop();n.textContent=`${a.map(e=>e.value).join(``)}, ${new Intl.DateTimeFormat(r,{timeStyle:`short`}).format(i)}`,t.appendChild(n)}return t}clearBlockSelectionOnClose(){if(this.Blok.CrossBlockSelection.isCrossBlockSelectionStarted)return;if(this.Blok.BlockSelection.selectedBlocks.length>1){this.Blok.BlockSelection.allBlocksSelected=!1;return}let e=this.Blok.BlockManager.currentBlock;e&&this.Blok.BlockSelection.unselectBlock(e)}async convertBlock(e,t,n,r,i){var a=this;let{BlockManager:o}=a.Blok;if(n)return a.convertMultipleBlocks(t,r.name,i);let s=await a.getExplodableItems(e);return!a.canToolMergeMultipleItems(r)&&s!==null?a.convertMultiItemBlockToSeparateBlocks(e,r.name,i):o.convert(e,r.name,i)}async convertMultipleBlocks(e,n,r){var i=this;let{Tools:a}=i.Blok;if(e.length===0)return null;let o=new Set(e.map(e=>e.id)),s=e.filter(e=>{if(e.parentId!==null&&o.has(e.parentId))return!1;let n=a.blockTools.get(e.name);return n===void 0||t.Wi(n,`export`)});if(s.length===0)return null;let c=a.blockTools.get(n);return c&&i.canToolMergeMultipleItems(c)?i.convertBlocksToSingleMergedBlock(s,n,r):i.convertBlocksIndividually(s,n,r)}canToolMergeMultipleItems(e){let t=e.conversionConfig;if(!(t!=null&&t.import))return!1;try{let n=typeof t.import==`function`?t.import(`line1
12
12
  line2`,e.settings):{[t.import]:`line1
13
13
  line2`};return Array.isArray(n==null?void 0:n.items)&&n.items.length>1}catch(e){return!1}}async convertBlocksToSingleMergedBlock(e,t,n){var r=this,i,a;let{BlockManager:o}=r.Blok,s=[];for(let t of e)try{let e=await t.exportDataAsString();s.push(e)}catch(e){}if(s.length===0)return null;let c=e[0],l=s.join(`
14
14
  `),u=r.Blok.Tools.blockTools.get(t);if(!u)return null;let d=typeof((i=u.conversionConfig)==null?void 0:i.import)==`function`?u.conversionConfig.import(l,u.settings):{[(a=u.conversionConfig)==null?void 0:a.import]:l},f=n?Object.assign(d,n):d,p=o.replace(c,t,f),m=e.slice(1);for(let e of m)await o.removeBlock(e,!1);return p}async convertBlocksIndividually(e,t,n){var r=this;let{BlockManager:i}=r.Blok,a=[];for(let o of e){let e=await r.convertBlockSafely(i,o,t,n);e&&a.push(e)}return a.length>0?a[a.length-1]:null}async convertBlockSafely(e,t,n,r){try{return await e.convert(t,n,r)}catch(e){return console.warn(`Failed to convert block ${t.id}:`,e),null}}async getExplodableItems(e){try{let t=await e.data;if(!Array.isArray(t==null?void 0:t.items)||t.items.length<=1)return null;let n=e=>typeof e==`object`&&!!e,r=e=>{let t=[];for(let i of e)n(i)&&(i.content!==void 0&&i.content!==``&&t.push(i.content),Array.isArray(i.items)&&i.items.length>0&&t.push(...r(i.items)));return t};return r(t.items)}catch(e){return null}}async convertMultiItemBlockToSeparateBlocks(e,t,n){var r=this,i;let{BlockManager:a,Tools:o}=r.Blok,s=await r.getExplodableItems(e);if(!s||s.length===0)return null;let c=o.blockTools.get(t),l=c==null||(i=c.conversionConfig)==null?void 0:i.import;if(!l)return null;let u=a.getBlockIndex(e);await a.removeBlock(e,!1);let d=s.map((e,r)=>{let i=typeof l==`function`?l(e,c==null?void 0:c.settings):{[l]:e},o=n?Object.assign(i,n):i;return a.insert({tool:t,data:o,index:u+r,needToFocus:!1})});return d.length>0?d[d.length-1]:null}attachFlipperKeydownListener(e){this.detachFlipperKeydownListener();let t=e==null?void 0:e.pluginsContent;t instanceof HTMLElement&&(this.flipperInstance.setHandleContentEditableTargets(!0),this.flipperKeydownHandler=e=>{this.flipperInstance.handleExternalKeydown(e)},t.addEventListener(`keydown`,this.flipperKeydownHandler,!0),this.flipperKeydownSource=t)}detachFlipperKeydownListener(){this.flipperKeydownSource!==null&&this.flipperKeydownHandler!==null&&this.flipperKeydownSource.removeEventListener(`keydown`,this.flipperKeydownHandler,!0),this.flipperInstance.setHandleContentEditableTargets(!1),this.flipperKeydownSource=null,this.flipperKeydownHandler=null}attachDeleteKeyListener(e){if(this.detachDeleteKeyListener(),this.popover===null)return;let t=e.find(e=>`name`in e&&e.name===`delete`&&`onActivate`in e);t!==void 0&&(this.deleteKeyHandler=e=>{e.key===`Delete`&&(e.preventDefault(),t.onActivate(t),this.close())},this.popover.getElement().addEventListener(`keydown`,this.deleteKeyHandler))}detachDeleteKeyListener(){this.popover!==null&&this.deleteKeyHandler!==null&&this.popover.getElement().removeEventListener(`keydown`,this.deleteKeyHandler),this.deleteKeyHandler=null}},Tf=`block hovered`,Ef=function(e){return e.Opened=`toolbox-opened`,e.Closed=`toolbox-closed`,e.BlockAdded=`toolbox-block-added`,e}({}),Df=e=>{let{caretRect:t,caretRectIsDegenerate:n,blockRect:r,contentElement:i,slashSearchElement:a}=e;if(a!==null){let e=a.getBoundingClientRect();if(e.width>0||e.height>0)return new DOMRect(e.left,e.top,e.width,Math.max(0,e.height-2))}if(t!==void 0&&!n)return t;if(r===void 0)return;let o=i==null?void 0:i.getBoundingClientRect();return o===void 0?r:new DOMRect(o.left,r.top,o.width,r.height)},Of=class extends t.Ii{get isEmpty(){return this.toolsToBeDisplayed.length===0}static get CSS(){return{toolbox:``}}constructor({api:e,tools:n,i18nLabels:r,i18n:i,triggerElement:a,leftAlignElement:o}){super(),this.opened=!1,this.listeners=new t.qi,this.popover=null,this.currentBlockForSearch=null,this.currentContentEditable=null,this.isInsideTableCell=!1,this.openedWithSlash=!0,this.handleMobileLayoutToggle=()=>{this.destroyPopover(),this.initPopover()},this.onPopoverClose=()=>{this.opened&&(this.isInsideTableCell&&(this.toggleRestrictedToolsHidden(!1),this.isInsideTableCell=!1),this.stopListeningToBlockInput(),this.opened=!1,this.emit(Ef.Closed))},this.handleBlockInput=()=>{var e;if(this.currentContentEditable===null)return;let n=this.currentContentEditable.textContent||``;if(this.openedWithSlash&&n.lastIndexOf(`/`)===-1){this.close();return}let r=this.openedWithSlash?n.slice(n.lastIndexOf(`/`)+1):n;this.currentContentEditable instanceof HTMLElement&&this.currentContentEditable.setAttribute(t.Ma.slashSearch,r.length===0?this.i18nLabels.slashSearchPlaceholder:``),(e=this.popover)==null||e.filterItems(r)},this.api=e,this.tools=n,this.i18nLabels=r,this.i18n=i,this.triggerElement=a,this.leftAlignElement=o,this.enableShortcuts(),this.nodes={toolbox:t.Qi.make(`div`)},this.nodes.toolbox.setAttribute(`data-blok-testid`,`toolbox`),this.initPopover(),this.api.events.on(g,this.handleMobileLayoutToggle)}updateLeftAlignElement(e){this.leftAlignElement=e,this.popover!==null&&`setLeftAlignElement`in this.popover&&this.popover.setLeftAlignElement(e)}setCalloutBackground(e){var t;let n=(t=this.popover)==null?void 0:t.getElement();n&&(e?n.style.setProperty(`--blok-search-input-bg`,`light-dark(color-mix(in srgb, ${e} 70%, white), color-mix(in srgb, ${e} 85%, white))`):(n.style.removeProperty(`--blok-search-input-bg`),n.style.removeProperty(`--blok-search-input-border`)))}getElement(){return this.nodes.toolbox}contains(e){var t;return!!(this.nodes.toolbox.contains(e)||(t=this.popover)!=null&&t.getElement().contains(e))}hasFocus(){if(this.popover!==null)return`hasFocus`in this.popover?this.popover.hasFocus():void 0}destroy(){var e;super.destroy(),this.nodes&&this.nodes.toolbox&&this.nodes.toolbox.remove(),this.removeAllShortcuts(),(e=this.popover)==null||e.off(t.T.Closed,this.onPopoverClose),this.listeners.destroy(),this.api.events.off(g,this.handleMobileLayoutToggle)}async toolButtonActivated(e,t){await this.insertNewBlock(e,t)}open(e=!0){var n;if(this.isEmpty)return;let r=this.api.blocks.getCurrentBlockIndex();this.api.blocks.stopBlockMutationWatching(r);let i=this.api.blocks.getBlockByIndex(r);if(this.isInsideTableCell=i!==void 0&&i.holder.closest(`[data-blok-table-cell-blocks]`)!==null,this.isInsideTableCell&&this.toggleRestrictedToolsHidden(!0),this.startListeningToBlockInput(),this.popover instanceof t.C){var a,o;let n=i==null?void 0:i.holder.getBoundingClientRect(),r=e?t.Ai.rect:void 0,s=Df({caretRect:r,caretRectIsDegenerate:r!==void 0&&r.width===0&&r.height===0&&r.x===0&&r.y===0,blockRect:n,contentElement:(a=i==null?void 0:i.holder.querySelector(`[${t.Ma.elementContent}]`))==null?null:a,slashSearchElement:(o=i==null?void 0:i.holder.querySelector(`[${t.Ma.slashSearch}]`))==null?null:o});s!==void 0&&this.popover.updatePosition(s)}(n=this.popover)==null||n.show(),this.openedWithSlash=e,this.opened=!0,this.emit(Ef.Opened)}close(){var e;this.isInsideTableCell&&(this.toggleRestrictedToolsHidden(!1),this.isInsideTableCell=!1),this.stopListeningToBlockInput(),(e=this.popover)==null||e.hide(),this.opened&&(this.opened=!1,this.emit(Ef.Closed))}toggle(){this.opened?this.close():this.open()}initPopover(){let e=t.ma()?Vd:t.C;this.popover=new e({trigger:this.triggerElement||this.nodes.toolbox,leftAlignElement:this.leftAlignElement,messages:{nothingFound:this.i18nLabels.nothingFound,search:this.i18nLabels.filter},items:this.toolboxItemsToBeDisplayed,handleContentEditableNavigation:!0,minWidth:`220px`}),this.popover.on(t.T.Closed,this.onPopoverClose),this.popover.getElement().setAttribute(`data-blok-testid`,`toolbox-popover`)}destroyPopover(){this.popover!==null&&(this.popover.hide(),this.popover.off(t.T.Closed,this.onPopoverClose),this.popover.destroy(),this.popover=null),this.nodes.toolbox!==null&&(this.nodes.toolbox.innerHTML=``)}toggleRestrictedToolsHidden(e){let n=t.Ji();for(let t of this.toolsToBeDisplayed){if(!n.includes(t.name))continue;let a=t.toolbox;if(!a)continue;let o=Array.isArray(a)?a:[a];for(let n of o){var r,i;let a=(r=n.name)==null?t.name:r;(i=this.popover)==null||i.toggleItemHiddenByName(a,e)}}}get toolsToBeDisplayed(){if(this._toolsToBeDisplayed)return this._toolsToBeDisplayed;let e=[];return this.tools.forEach(t=>{t.toolbox&&e.push(t)}),this._toolsToBeDisplayed=e,e}get toolboxItemsToBeDisplayed(){if(this._toolboxItemsToBeDisplayed)return this._toolboxItemsToBeDisplayed;let e=(e,n,r=!0)=>{var i,a,o,s,c;let l=e.titleKey,u=l!=null&&l.includes(`.`)?l:`toolNames.${l}`,d=l?u:void 0,f=d?this.api.i18n.getEnglishTranslation(d):e.title,p=(i=e.searchTerms)==null?[]:i,m=(a=n.searchTerms)==null?[]:a,h=[...new Set([...p,...m])];for(let t of(o=e.searchTermKeys)==null?[]:o){let e=`searchTerms.${t}`;this.i18n.has(e)&&h.push(this.i18n.t(e))}let g=(s=e.shortcut)==null?r?n.shortcut:void 0:s;return{icon:e.icon,title:t.Ki(this.i18n,e,t.ua(n.name)),name:(c=e.name)==null?n.name:c,onActivate:()=>{this.toolButtonActivated(n.name,e.data)},secondaryLabel:g?t.la(g):``,englishTitle:f,searchTerms:h}},n=this.toolsToBeDisplayed.reduce((t,n)=>{let{toolbox:r}=n;return r===void 0||(Array.isArray(r)?r:[r]).forEach((r,i)=>{t.push(e(r,n,i===0))}),t},[]);return this._toolboxItemsToBeDisplayed=n,n}enableShortcuts(){this.toolsToBeDisplayed.forEach(e=>{let t=e.shortcut;t&&this.enableShortcutForTool(e.name,t)})}enableShortcutForTool(e,t){var n=this;X.add({name:t,on:this.api.ui.nodes.redactor,handler:async t=>{t.preventDefault();let r=n.api.blocks.getCurrentBlockIndex(),i=n.api.blocks.getBlockByIndex(r);if(i)try{let t=await n.api.blocks.convert(i.id,e);n.api.caret.setToBlock(t,`end`);return}catch(e){}await n.insertNewBlock(e)}})}removeAllShortcuts(){this.toolsToBeDisplayed.forEach(e=>{let t=e.shortcut;t&&X.remove(this.api.ui.nodes.redactor,t)})}async insertNewBlock(e,t){var n=this,r;let i=n.api.blocks.getCurrentBlockIndex(),a=n.api.blocks.getBlockByIndex(i);if(!a)return;let o=(r=a.parentId)==null?null:r,s=a.isEmpty||n.isBlockSlashSearchOnly(a.holder)||!n.openedWithSlash,c=s?i:i+1,l=t!==void 0&&Object.keys(t).length>0?Object.assign(await n.api.blocks.composeBlockData(e),t):void 0,u=n.insertWithTransaction(()=>{s&&o!==null&&n.api.blocks.setBlockParent(a.id,null);let t=n.api.blocks.insert(e,l,void 0,c,void 0,s);return o!==null&&n.api.blocks.setBlockParent(t.id,o),t},o);n.api.caret.setToBlock(c),n.emit(Ef.BlockAdded,{block:u}),n.api.toolbar.close({setExplicitlyClosed:!1})}insertWithTransaction(e,t){let n={block:void 0};return t!==null&&this.api.blocks.transact!==void 0?this.api.blocks.transact(()=>{n.block=e()}):n.block=e(),n.block}startListeningToBlockInput(){let e=this.api.blocks.getCurrentBlockIndex(),n=this.api.blocks.getBlockByIndex(e);if(!n)return;this.currentBlockForSearch=n.holder;let r=document.activeElement;this.currentContentEditable=r instanceof HTMLElement&&r.isContentEditable&&this.currentBlockForSearch.contains(r)?r:this.currentBlockForSearch.querySelector(`[contenteditable="true"]`),this.currentContentEditable instanceof HTMLElement&&this.currentContentEditable.setAttribute(t.Ma.slashSearch,this.i18nLabels.slashSearchPlaceholder),this.listeners.on(this.currentBlockForSearch,`input`,this.handleBlockInput)}stopListeningToBlockInput(){var e;this.currentBlockForSearch!==null&&(this.listeners.off(this.currentBlockForSearch,`input`,this.handleBlockInput),this.currentContentEditable instanceof HTMLElement&&this.currentContentEditable.removeAttribute(t.Ma.slashSearch),this.currentBlockForSearch=null,this.currentContentEditable=null),(e=this.popover)==null||e.filterItems(``)}isBlockSlashSearchOnly(e){var t;let n=e.querySelector(`[contenteditable="true"]`);return((n==null||(t=n.textContent)==null?void 0:t.trim())||``).startsWith(`/`)}},kf=class{constructor(){this.pendingMouseUpListeners=new Set}setup(e,t,n){let r={x:e.clientX,y:e.clientY},i=e=>{document.removeEventListener(`mouseup`,i,!0),this.pendingMouseUpListeners.delete(i),!(n!=null&&n.beforeCallback&&!n.beforeCallback())&&(Math.abs(e.clientX-r.x)>10||Math.abs(e.clientY-r.y)>10||t(e))};this.pendingMouseUpListeners.add(i),document.addEventListener(`mouseup`,i,!0)}cancelPending(){this.clearPendingListeners()}destroy(){this.clearPendingListeners()}clearPendingListeners(){for(let e of this.pendingMouseUpListeners)document.removeEventListener(`mouseup`,e,!0);this.pendingMouseUpListeners.clear()}};function Af(e,n,r){if(r===void 0)return 0;if(e.getAttribute(t.Ma.stretched)===`true`){let t=Mf(e);if(t!==null&&r.width>t)return(r.width-t)/2}return Math.max(0,n.left-r.left)}function jf(e,n,r){if(e.getAttribute(t.Ma.stretched)===`true`&&r!==void 0){let t=Mf(e);if(t!==null&&r.width>t)return t}return n.width}function Mf(e){let t=getComputedStyle(e).getPropertyValue(`--max-width-content`).trim(),n=parseFloat(t);return Number.isFinite(n)&&n>0?n:null}var Nf=class{constructor(e,t){this.hoveredBlockInternal=null,this.getBlok=e,this.getToolboxOpened=t.getToolboxOpened,this.openToolbox=t.openToolbox,this.openToolboxWithoutSlash=t.openToolboxWithoutSlash,this.closeToolbox=t.closeToolbox,this.moveAndOpenToolbar=t.moveAndOpenToolbar,this.onFocusBlockCaptured=t.onFocusBlockCaptured}get hoveredBlock(){return this.hoveredBlockInternal}setHoveredBlock(e){this.hoveredBlockInternal=e}make(e){let n=this.getBlok(),i=t.Qi.make(`div`,[r.t(`text-text-secondary cursor-pointer w-6 h-6 rounded-[5px] inline-flex justify-center items-center select-none`,`shrink-0`,`[&_svg]:h-[22px] [&_svg]:w-[22px]`,`can-hover:hover:bg-bg-light`,`group-data-[blok-toolbox-opened=true]:hidden`,`group-data-[blok-block-settings-opened=true]:hidden`,`mobile:bg-popover-bg mobile:border mobile:border-mobile-border mobile:shadow-overlay-pane mobile:rounded-[6px] mobile:z-2`,`mobile:w-toolbox-btn-mobile mobile:h-toolbox-btn-mobile`,`group-data-[blok-rtl=true]:right-[calc(-1*(var(--spacing-toolbox-btn)))] group-data-[blok-rtl=true]:left-auto`)],{innerHTML:t.Tn});i.setAttribute(t.Ma.testid,t.Fi.plusButton),e.plusButton=i;let a=t.da(),o=n.I18n.t(a.win?`toolbox.ctrlAddAbove`:`toolbox.optionAddAbove`);return t.xi(i,t.h([n.I18n.t(`toolbox.addBelow`),o]),{delay:500}),i}handleClick(e=!1){var n,r,i,a,o;let{BlockManager:s,BlockSettings:c,BlockSelection:l,Caret:u}=this.getBlok();if(c.opened&&c.close(),l.anyBlockSelected&&l.clearSelection(),(n=t.Ai.get())==null||n.removeAllRanges(),this.getToolboxOpened()){this.closeToolbox();return}let d=this.hoveredBlockInternal,f=(d==null?void 0:d.name)===`paragraph`&&((r=d.pluginsContent.textContent)==null?void 0:r.startsWith(`/`)),p=(i=s.currentBlock)==null?null:i,m=document.activeElement,h=m!==null&&m!==document.body?(a=s.getBlockByChildNode(m))==null?null:a:null,g=d!==null&&d.isEmpty,_=!g&&p!==null&&p!==d&&p.isEmpty&&d!==null&&d.holder.contains(p.holder),v=g&&d||_&&p||null,y=d===null?s.currentBlockIndex:s.getBlockIndex(d),b=e?y:y+1,x=s.blocks.slice(b),ee=e=>{var t;return((t=e.holder.parentElement)==null?void 0:t.closest(`[data-blok-testid="block-wrapper"]`))!==null},S=!e&&d&&x.length>0?x.findIndex(e=>!ee(e)):0,C=b+(S===-1?x.length:S),w=f?d:v==null?s.insertDefaultBlockAtIndex(C,!0):v;w!==d&&v===null&&ee(w)&&(d==null||d.holder.after(w.holder));let te=!f&&v===null?w:null;(o=this.onFocusBlockCaptured)==null||o.call(this,h,te),f?(u.setToBlock(w,u.positions.DEFAULT,1),this.moveAndOpenToolbar(w),this.openToolbox()):(u.setToBlock(w,u.positions.START),this.moveAndOpenToolbar(w),this.openToolboxWithoutSlash())}},Pf=class{constructor(){this.lastToolbarY=null,this.hoveredTarget=null,this.targetResizeObserver=null}get lastY(){return this.lastToolbarY}get target(){return this.hoveredTarget}setHoveredTarget(e){this.hoveredTarget=e}resetCachedPosition(){this.lastToolbarY=null}watchTargetResize(e,t){this.stopWatchingTargetResize(),!(typeof ResizeObserver>`u`)&&(this.targetResizeObserver=new ResizeObserver(()=>t()),this.targetResizeObserver.observe(e))}stopWatchingTargetResize(){var e;(e=this.targetResizeObserver)==null||e.disconnect(),this.targetResizeObserver=null}calculateToolbarY(e,t){var n,r,i,a;let{targetBlock:o,hoveredTarget:s,isMobile:c}=e;if(!o||!t)return null;let l=o.holder.getBoundingClientRect(),u=s==null?void 0:s.closest(`[role="listitem"]`),d=u==null?void 0:u.querySelector(`[contenteditable]`),f=o.pluginsContent,p=!d&&!u?o.getToolbarAnchorElement():void 0,m=!p&&!f.matches(`[contenteditable]`)?(n=f.querySelector(`[contenteditable]`))==null?null:n:null,h=(r=(i=(a=d==null?u:d)==null?p:a)==null?m:i)==null?f:r,g=h.getBoundingClientRect().top-l.top,_=window.getComputedStyle(h),v=parseInt(_.paddingTop,10)||0,y=parseFloat(_.lineHeight)||24,b=parseInt(window.getComputedStyle(t).height,10);return c?g-b:g+v+y/2-b/2}moveToY(e,t){let{wrapper:n}=e;if(!n)return null;let r=Math.floor(t);return this.lastToolbarY=r,n.style.top=`${r}px`,r}repositionToolbar(e,t,n){let{wrapper:r}=e;if(!r||!n)return!1;let i=this.calculateToolbarY(t,n);if(i===null)return!1;let a=this.lastToolbarY===null||Math.abs(i-this.lastToolbarY)>2;return a&&(this.lastToolbarY=i,r.style.top=`${i}px`),this.applyContentOffset(e,t.targetBlock),a}applyContentOffset(e,t){let{actions:n}=e;if(!n)return;if(!this.hoveredTarget){n.style.transform=``;return}let r=t.getContentOffset(this.hoveredTarget),i=r&&r.left>0;n.style.transform=i?`translateX(${r.left}px)`:``}},Ff=class{constructor(e,t,n){this.ignoreNextSettingsMouseUp=!1,this.settingsTogglerElement=null,this.hoveredBlockInternal=null,this.getBlok=e,this.clickDragHandler=t,this.setHoveredBlockCallback=n.setHoveredBlock,this.getToolboxOpened=n.getToolboxOpened,this.closeToolbox=n.closeToolbox}get hoveredBlock(){return this.hoveredBlockInternal}setHoveredBlock(e){this.hoveredBlockInternal=e}skipNextToggle(){this.ignoreNextSettingsMouseUp=!0}make(e){let n=this.getBlok(),i=t.Qi.make(`span`,[r.t(`text-text-secondary cursor-pointer w-[18px] h-6 rounded-[5px] inline-flex justify-center items-center select-none`,`[&_svg]:h-[22px] [&_svg]:w-[22px] [&_svg]:shrink-0`,`active:cursor-grabbing`,`can-hover:hover:bg-bg-light can-hover:hover:cursor-grab`,`group-data-[blok-toolbox-opened=true]:hidden`,`group-data-[blok-block-settings-opened=true]:hidden`,`mobile:bg-popover-bg mobile:border mobile:border-mobile-border mobile:shadow-overlay-pane mobile:rounded-[6px] mobile:z-2`,`mobile:w-toolbox-btn-mobile mobile:h-toolbox-btn-mobile`),`group-data-[blok-dragging=true]:cursor-grabbing`],{innerHTML:t.rn});i.setAttribute(t.Ma.settingsToggler,``),i.setAttribute(t.Ma.dragHandle,``),i.setAttribute(t.Ma.testid,t.Fi.settingsToggler),i.setAttribute(`role`,`button`),i.setAttribute(`tabindex`,`-1`),i.setAttribute(`aria-label`,n.I18n.t(`a11y.dragHandle`)),i.setAttribute(`aria-roledescription`,n.I18n.t(`a11y.dragHandleRole`)),e.settingsToggler=i,this.settingsTogglerElement=i;let a=t.da().win?n.I18n.t(`blockSettings.menuShortcutWin`):n.I18n.t(`blockSettings.menuShortcutMac`);return t.xi(i,t.h([n.I18n.t(`blockSettings.dragToMove`),[{text:`Click`,highlight:!0},{text:` or `,highlight:!1},{text:a,highlight:!0},{text:` to open menu`,highlight:!1}]]),{delay:500}),i}createMousedownHandler(){return e=>{e.preventDefault(),t.bi(),this.clickDragHandler.setup(e,()=>{this.handleClick(),this.getToolboxOpened()&&this.closeToolbox()},{beforeCallback:()=>this.ignoreNextSettingsMouseUp?(this.ignoreNextSettingsMouseUp=!1,!1):!0})}}handleClick(){var e;let t=this.getBlok();t.DragManager.cancelTracking();let n=(e=this.hoveredBlockInternal)==null?t.BlockManager.currentBlock:e;if(n)if(this.hoveredBlockInternal=n,t.BlockManager.currentBlock=n,t.BlockSettings.opened)t.BlockSettings.close();else{var r;t.BlockSettings.open(n,(r=this.settingsTogglerElement)==null?void 0:r)}}},If=()=>({toolbar:r.t(`absolute left-0 right-0 top-0 h-toolbox-btn transition-opacity duration-100 ease-linear will-change-[opacity,top]`,`pointer-events-none`),toolbarOpened:`block`,toolbarClosed:`hidden`,content:r.t(`relative mx-auto max-w-blok-content`),actions:r.t(`absolute flex opacity-0 pr-[5px]`,`right-full`,`mobile:right-auto`,`group-data-[blok-rtl=true]:right-auto group-data-[blok-rtl=true]:left-[calc(-1*(var(--spacing-toolbox-btn)))]`,`mobile:group-data-[blok-rtl=true]:ml-0 mobile:group-data-[blok-rtl=true]:mr-auto mobile:group-data-[blok-rtl=true]:pr-0 mobile:group-data-[blok-rtl=true]:pl-[10px]`),actionsOpened:`opacity-100`,plusButton:r.t(`text-dark cursor-pointer w-toolbox-btn h-toolbox-btn rounded-[7px] inline-flex justify-center items-center select-none`,`shrink-0`,`[&_svg]:h-6 [&_svg]:w-6`,`can-hover:hover:bg-bg-light`,`group-data-[blok-toolbox-opened=true]:bg-bg-light`,`mobile:bg-popover-bg mobile:border mobile:border-mobile-border mobile:shadow-overlay-pane mobile:rounded-[6px] mobile:z-2`,`mobile:w-toolbox-btn-mobile mobile:h-toolbox-btn-mobile`,`group-data-[blok-rtl=true]:right-[calc(-1*(var(--spacing-toolbox-btn)))] group-data-[blok-rtl=true]:left-auto`),plusButtonShortcutKey:`text-white`,settingsToggler:r.t(`text-dark cursor-pointer w-toolbox-btn h-toolbox-btn rounded-[7px] inline-flex justify-center items-center select-none`,`cursor-pointer select-none`,`[&_svg]:h-6 [&_svg]:w-6`,`active:cursor-grabbing`,`can-hover:hover:bg-bg-light can-hover:hover:cursor-grab`,`can-hover:hover:group-data-[blok-toolbox-opened=true]:cursor-pointer`,`group-data-[blok-block-settings-opened=true]:bg-bg-light`,`can-hover:hover:group-data-[blok-block-settings-opened=true]:cursor-pointer`,`mobile:bg-popover-bg mobile:border mobile:border-mobile-border mobile:shadow-overlay-pane mobile:rounded-[6px] mobile:z-2`,`mobile:w-toolbox-btn-mobile mobile:h-toolbox-btn-mobile`,`not-mobile:w-6`),settingsTogglerHidden:`hidden`}),Lf=class extends s{discardPlusContext(){this.preToolboxBlock=null,this.plusInsertedBlock=null}constructor({config:e,eventsDispatcher:n}){super({config:e,eventsDispatcher:n}),this.hoveredBlock=null,this.explicitlyClosed=!1,this.hoveredBlockIsFromTableCell=!1,this.toolboxInstance=null,this.preToolboxBlock=null,this.plusInsertedBlock=null,this.onBlockSettingsOpen=()=>{this.Blok.UI.nodes.wrapper.setAttribute(t.Ma.blockSettingsOpened,`true`)},this.onBlockSettingsClose=()=>{this.Blok.UI.nodes.wrapper.removeAttribute(t.Ma.blockSettingsOpened)},this.onBlockChanged=e=>{var t;!this.opened||!this.hoveredBlock||this.Blok.BlockSettings.opened||this.Blok.BlockSettings.isOpening||(t=this.toolboxInstance)!=null&&t.opened||e.event.detail.target.id===this.hoveredBlock.id&&this.repositionToolbar()},this.positioner=new Pf,this.clickDragHandler=new kf,this.plusButtonHandler=new Nf(()=>this.Blok,{getToolboxOpened:()=>{var e;return(e=this.toolbox.opened)==null?!1:e},openToolbox:()=>this.toolbox.open(),openToolboxWithoutSlash:()=>this.toolbox.openWithoutSlash(),closeToolbox:()=>this.toolbox.close(),moveAndOpenToolbar:(e,t)=>this.moveAndOpen(e,t),onFocusBlockCaptured:(e,t)=>{this.preToolboxBlock=e,this.plusInsertedBlock=t}}),this.settingsTogglerHandler=new Ff(()=>this.Blok,this.clickDragHandler,{setHoveredBlock:e=>{this.hoveredBlock=e},getToolboxOpened:()=>{var e;return(e=this.toolbox.opened)==null?!1:e},closeToolbox:()=>this.toolbox.close()})}get CSS(){return If()}get opened(){var e,t;return(e=(t=this.nodes.wrapper)==null?void 0:t.classList.contains(this.CSS.toolbarOpened))==null?!1:e}contains(e){var t,n;return!!((t=this.nodes.wrapper)!=null&&t.contains(e)||(n=this.toolboxInstance)!=null&&n.contains(e)||this.Blok.BlockSettings.contains(e))}get toolbox(){var e;return{opened:(e=this.toolboxInstance)==null?void 0:e.opened,close:()=>{var e;(e=this.toolboxInstance)==null||e.close()},openWithoutSlash:()=>{if(this.toolboxInstance===null){t.Ea(`toolbox.openWithoutSlash() called before initialization is finished`,`warn`);return}if(this.hoveredBlock&&!this.hoveredBlockIsFromTableCell){let e=this.Blok.BlockManager.currentBlock;e!==void 0&&e.holder.closest(`[data-blok-table-cell-blocks]`)!==null||(this.Blok.BlockManager.currentBlock=this.hoveredBlock)}this.toolboxInstance.open(!1)},open:()=>{if(this.toolboxInstance===null){t.Ea(`toolbox.open() called before initialization is finished`,`warn`);return}if(this.hoveredBlock&&!this.hoveredBlockIsFromTableCell){let e=this.Blok.BlockManager.currentBlock;e!==void 0&&e.holder.closest(`[data-blok-table-cell-blocks]`)!==null||(this.Blok.BlockManager.currentBlock=this.hoveredBlock)}this.toolboxInstance.open()},toggle:()=>{if(this.toolboxInstance===null){t.Ea(`toolbox.toggle() called before initialization is finished`,`warn`);return}this.toolboxInstance.toggle()},hasFocus:()=>{var e;return(e=this.toolboxInstance)==null?void 0:e.hasFocus()}}}get blockActions(){return{hide:()=>{var e,t;(e=this.nodes.actions)==null||e.classList.remove(this.CSS.actionsOpened),(t=this.nodes.actions)==null||t.removeAttribute(`data-blok-opened`),this.nodes.actions&&(this.nodes.actions.style.pointerEvents=`none`)},show:()=>{var e,t;if((e=this.nodes.actions)==null||e.classList.add(this.CSS.actionsOpened),(t=this.nodes.actions)==null||t.setAttribute(`data-blok-opened`,`true`),this.nodes.actions){this.nodes.actions.style.pointerEvents=`auto`;for(let e of Array.from(this.nodes.actions.querySelectorAll(`*`)))e.style.pointerEvents=``}}}}get blockTunesToggler(){return{hide:()=>{var e;return(e=this.nodes.settingsToggler)==null?void 0:e.classList.add(this.CSS.settingsTogglerHidden)},show:()=>{var e;return(e=this.nodes.settingsToggler)==null?void 0:e.classList.remove(this.CSS.settingsTogglerHidden)}}}toggleReadOnly(e){var t=this;if(this.nodes.wrapper===void 0){window.requestIdleCallback(async()=>{await t.drawUI(),t.enableModuleBindings(),t.applyReadOnlyToPlusButton(e)},{timeout:2e3});return}this.applyReadOnlyToPlusButton(e)}applyReadOnlyToPlusButton(e){let{plusButton:t}=this.nodes;t!==void 0&&(t.style.display=e?`none`:``)}moveAndOpen(e,n){if(this.toolboxInstance===null){t.Ea(`Can't open Toolbar since Blok initialization is not finished yet`,`warn`);return}this.explicitlyClosed=!1,this.toolboxInstance.opened&&this.toolboxInstance.close(),this.Blok.BlockSettings.opened&&this.Blok.BlockSettings.close();let r=e==null?this.Blok.BlockManager.currentBlock:e;if(!r)return;let i=n instanceof Element&&n.closest(`[data-blok-table-cell-blocks]`)!==null,a=r.holder.closest(`[data-blok-table-cell-blocks]`)!==null;this.hoveredBlockIsFromTableCell=i||a;let o=this.resolveTableCellBlock(r);this.hoveredBlock&&this.hoveredBlock!==o&&this.hoveredBlock.cleanupDraggable(),this.hoveredBlock=o,this.plusButtonHandler.setHoveredBlock(o),this.settingsTogglerHandler.setHoveredBlock(o),this.positioner.setHoveredTarget(n==null?null:n),this.positioner.resetCachedPosition();let{wrapper:s,plusButton:c,settingsToggler:l}=this.nodes;if(!s||!c)return;let u=this.isFirstChildOfCallout(o),d=u||this.Blok.ReadOnly.isEnabled;c.style.display=d?`none`:``,l&&(l.style.display=u?`none`:``);let f=o.name===`callout`,p=u||f?null:this.getCalloutBackgroundColor(o);p===null?s.style.removeProperty(`--blok-bg-light`):s.style.setProperty(`--blok-bg-light`,`light-dark(color-mix(in srgb, ${p} 70%, white), color-mix(in srgb, ${p} 85%, white))`);let m=o.holder,{isMobile:h}=this.Blok.UI,g=this.positioner.calculateToolbarY({targetBlock:o,hoveredTarget:n==null?null:n,isMobile:h},c);if(g===null)return;this.positioner.moveToY(this.nodes,g),m.appendChild(s),l&&!this.Blok.ReadOnly.isEnabled&&o.setupDraggable(l,this.Blok.DragManager);let _=m.querySelector(`[${t.Ma.elementContent}]`);_&&this.toolboxInstance.updateLeftAlignElement(_),this.positioner.applyContentOffset(this.nodes,o),this.positioner.watchTargetResize(m,()=>this.repositionToolbar());let v=o.getTunes(),y=v.toolTunes.length>0||v.commonTunes.length>0;this.Blok.BlockManager.blocks.length===1&&o.isEmpty&&!y?this.blockTunesToggler.hide():this.blockTunesToggler.show(),this.open();let b=o.name===`header`&&o.holder.querySelector(`[data-blok-toggle-arrow]`)!==null;if((o.name===`callout`||o.name===`toggle`||b)&&this.nodes.actions){this.nodes.actions.style.pointerEvents=`none`;for(let e of Array.from(this.nodes.actions.querySelectorAll(`*`)))e.style.pointerEvents=`none`;this.restoreSettingsTogglerForLeftEdgeBlock(o)}_&&this.syncContentToBlock(m,_)}syncContentToBlock(e,t){var n,r,i;if(this.nodes.content===void 0)return;let a=(n=this.nodes.wrapper)==null?void 0:n.getBoundingClientRect(),o=t.getBoundingClientRect(),s=Af(e,o,a),c=(r=(i=this.nodes.actions)==null?void 0:i.offsetWidth)==null?0:r,l=a?Math.max(0,a.left):0,u=Math.max(0,c-l),d=Math.max(s,u),f=jf(e,o,a);this.nodes.content.style.marginLeft=`${d}px`,this.nodes.content.style.maxWidth=`${f}px`}moveAndOpenForMultipleBlocks(e){if(this.Blok.BlockSettings.opened||this.Blok.BlockSettings.isOpening)return;let n=this.Blok.BlockSelection.selectedBlocks;if(n.length<2)return;if(this.toolboxInstance===null){t.Ea(`Can't open Toolbar since Blok initialization is not finished yet`,`warn`);return}this.toolboxInstance.opened&&this.toolboxInstance.close(),this.explicitlyClosed=!1;let r=e==null?n[0]:e;this.hoveredBlock&&this.hoveredBlock!==r&&this.hoveredBlock.cleanupDraggable(),this.hoveredBlock=r,this.plusButtonHandler.setHoveredBlock(r),this.settingsTogglerHandler.setHoveredBlock(r),this.positioner.setHoveredTarget(null),this.positioner.resetCachedPosition();let{wrapper:i,plusButton:a,settingsToggler:o}=this.nodes;if(!i||!a)return;a.style.display=this.Blok.ReadOnly.isEnabled?`none`:``,a.style.color=``,o&&(o.style.display=``,o.style.color=``);let s=r.holder,c=this.positioner.calculateToolbarY({targetBlock:r,hoveredTarget:null,isMobile:!1},a);if(c===null)return;this.positioner.moveToY(this.nodes,c),s.appendChild(i),o&&!this.Blok.ReadOnly.isEnabled&&r.setupDraggable(o,this.Blok.DragManager);let l=s.querySelector(`[${t.Ma.elementContent}]`);l&&this.toolboxInstance.updateLeftAlignElement(l),this.positioner.applyContentOffset(this.nodes,r),this.blockTunesToggler.show(),this.open(),l&&this.syncContentToBlock(s,l)}close(e){var t,n,r,i;(t=this.nodes.wrapper)==null||t.classList.remove(this.CSS.toolbarOpened),(n=this.nodes.wrapper)==null||n.classList.add(this.CSS.toolbarClosed),(r=this.nodes.wrapper)==null||r.removeAttribute(`data-blok-opened`),this.blockActions.hide(),(i=this.toolboxInstance)==null||i.close(),this.Blok.BlockSettings.close(),this.hoveredBlock=null,this.hoveredBlockIsFromTableCell=!1,(e==null?void 0:e.setExplicitlyClosed)!==!1&&(this.explicitlyClosed=!0,this.Blok.UI.resetBlockHoverState()),this.nodes.plusButton&&(this.nodes.plusButton.style.display=this.Blok.ReadOnly.isEnabled?`none`:``,this.nodes.plusButton.style.color=``),this.nodes.settingsToggler&&(this.nodes.settingsToggler.style.display=``,this.nodes.settingsToggler.style.color=``),this.nodes.actions&&(this.nodes.actions.style.transform=``),this.nodes.content&&(this.nodes.content.style.marginLeft=``,this.nodes.content.style.maxWidth=``),this.positioner.setHoveredTarget(null),this.positioner.stopWatchingTargetResize(),this.reset()}skipNextSettingsToggle(){this.settingsTogglerHandler.skipNextToggle()}hideBlockActions(){this.blockActions.hide()}resetExplicitlyClosed(){this.explicitlyClosed=!1}isFirstChildOfCallout(e){if(!e.parentId)return!1;let t=this.Blok.BlockManager.getBlockById(e.parentId);return!t||t.name!==`callout`?!1:t.contentIds[0]===e.id}getCalloutBackgroundColor(e){let t=this.resolveCalloutBlock(e);if(!t)return null;try{return t.pluginsContent.style.backgroundColor||null}catch(e){return null}}resolveCalloutBlock(e){if(e.name===`callout`)return e;if(!e.parentId)return null;let t=this.Blok.BlockManager.getBlockById(e.parentId);return!t||t.name!==`callout`?null:t}updateToolbarButtonsForCalloutFirstChild(){let{plusButton:e,settingsToggler:t}=this.nodes;if(!e)return;let n=this.hoveredBlock!==null&&this.isFirstChildOfCallout(this.hoveredBlock),r=n||this.Blok.ReadOnly.isEnabled;e.style.display=r?`none`:``,t&&(t.style.display=n?`none`:``)}restoreSettingsTogglerForLeftEdgeBlock(e){this.nodes.settingsToggler&&(this.nodes.settingsToggler.style.pointerEvents=`auto`)}resolveTableCellBlock(e){var t;let n=e.holder.closest(`[data-blok-table-cell-blocks]`);if(!n)return e;let r=n.closest(`[data-blok-testid="block-wrapper"]`);return r?(t=this.Blok.BlockManager.getBlockByChildNode(r))==null?e:t:e}reset(){this.positioner.resetCachedPosition(),this.nodes.wrapper&&(this.nodes.wrapper.style.top=`unset`,this.Blok.UI.nodes.wrapper.appendChild(this.nodes.wrapper))}open(e=!0){var t,n,r;(t=this.nodes.wrapper)==null||t.classList.remove(this.CSS.toolbarClosed),(n=this.nodes.wrapper)==null||n.classList.add(this.CSS.toolbarOpened),(r=this.nodes.wrapper)==null||r.setAttribute(`data-blok-opened`,`true`),e?this.blockActions.show():this.blockActions.hide()}async make(){var e=this;let n=t.Qi.make(`div`,[e.CSS.toolbar,e.CSS.toolbarClosed,`group-data-[blok-dragging=true]:pointer-events-none`]);e.nodes.wrapper=n,n.setAttribute(t.Ma.toolbar,``),n.setAttribute(`data-blok-testid`,`toolbar`);let r=t.Qi.make(`div`,e.CSS.content),i=t.Qi.make(`div`,[e.CSS.actions]);i.style.pointerEvents=`none`,e.nodes.content=r,e.nodes.actions=i,i.setAttribute(`data-blok-testid`,`toolbar-actions`),t.Qi.append(n,r),t.Qi.append(r,i);let a=e.plusButtonHandler.make(e.nodes);t.Qi.append(i,a);let o=e.settingsTogglerHandler.make(e.nodes);t.Qi.append(i,o),t.Qi.append(i,e.makeToolbox());let s=e.Blok.BlockSettings.getElement();if(!s)throw Error(`Block Settings element was not created`);t.Qi.append(i,s),t.Qi.append(e.Blok.UI.nodes.wrapper,n)}makeToolbox(){this.toolboxInstance=new Of({api:this.Blok.API.methods,tools:this.Blok.Tools.blockTools,i18nLabels:{filter:this.Blok.I18n.t(`popover.search`),nothingFound:this.Blok.I18n.t(`popover.nothingFound`),slashSearchPlaceholder:this.Blok.I18n.t(`toolbox.typeToSearch`)},i18n:this.Blok.I18n,triggerElement:this.nodes.plusButton}),this.toolboxInstance.on(Ef.Opened,()=>{var e;this.Blok.UI.nodes.wrapper.classList.add(this.CSS.openedToolboxHolderModifier),this.Blok.UI.nodes.wrapper.setAttribute(t.Ma.toolboxOpened,`true`);let n=this.hoveredBlock===null?null:this.getCalloutBackgroundColor(this.hoveredBlock);(e=this.toolboxInstance)==null||e.setCalloutBackground(n)}),this.toolboxInstance.on(Ef.Closed,()=>{if(this.Blok.UI.nodes.wrapper.classList.remove(this.CSS.openedToolboxHolderModifier),this.Blok.UI.nodes.wrapper.removeAttribute(t.Ma.toolboxOpened),this.preToolboxBlock!==null){let e=this.preToolboxBlock;this.preToolboxBlock=null,this.plusInsertedBlock=null,e.inputs.length>0&&this.Blok.Caret.setToBlock(e,this.Blok.Caret.positions.END);return}let e=this.Blok.BlockManager.currentBlock;if(e&&e.inputs.length>0){let t=document.activeElement;t instanceof Node&&e.holder.contains(t)||this.Blok.Caret.setToBlock(e,this.Blok.Caret.positions.END)}}),this.toolboxInstance.on(Ef.BlockAdded,({block:e})=>{this.preToolboxBlock=null,this.plusInsertedBlock=null;let{BlockManager:t,Caret:n}=this.Blok,r=t.getBlockById(e.id);if(!r||r.inputs.length!==0)return;if(r===t.lastBlock){t.insertAtEnd(),n.setToBlock(t.lastBlock);return}let i=t.nextBlock;i&&n.setToBlock(i)});let e=this.toolboxInstance.getElement();if(e===null)throw Error(`Toolbox element was not created`);return e}enableModuleBindings(){let e=this.nodes.plusButton;e&&this.readOnlyMutableListeners.on(e,`mousedown`,e=>{this.Blok.ReadOnly.isEnabled||(e.preventDefault(),t.bi(),this.clickDragHandler.setup(e,e=>{let n=t.da().win?e.ctrlKey:e.altKey;this.plusButtonHandler.handleClick(n)}))},!0);let n=this.nodes.settingsToggler;n&&this.readOnlyMutableListeners.on(n,`mousedown`,this.settingsTogglerHandler.createMousedownHandler(),!0),this.readOnlyMutableListeners.on(this.Blok.UI.nodes.wrapper,`focusin`,()=>{this.updateToolbarButtonsForCalloutFirstChild()}),t.ma()||this.eventsDispatcher.on(Tf,e=>{var t;if(this.Blok.DragManager.isDragging||this.Blok.RectangleSelection.isRectActivated()||this.Blok.RectangleSelection.isMouseDownWithinBounds)return;let n=e.block,r=e.target;if(!(n instanceof ne)||this.Blok.BlockSettings.opened||this.Blok.BlockSettings.isOpening||(t=this.toolboxInstance)!=null&&t.opened)return;if(this.explicitlyClosed){if(this.hoveredBlock!==null&&this.hoveredBlock===n)return;this.explicitlyClosed=!1}let i=this.Blok.BlockSelection.selectedBlocks,a=i.length>1,o=a&&i.some(e=>e===n);if(a&&o){this.moveAndOpenForMultipleBlocks(n);return}a||this.moveAndOpen(n,r)}),this.eventsDispatcher.on(h,this.onBlockSettingsOpen),this.eventsDispatcher.on(m,this.onBlockSettingsClose),this.eventsDispatcher.on(d,this.onBlockChanged)}disableModuleBindings(){this.readOnlyMutableListeners.clearAll(),this.eventsDispatcher.off(h,this.onBlockSettingsOpen),this.eventsDispatcher.off(m,this.onBlockSettingsClose),this.eventsDispatcher.off(d,this.onBlockChanged)}repositionToolbar(){!this.hoveredBlock||!this.nodes.plusButton||this.positioner.repositionToolbar(this.nodes,{targetBlock:this.hoveredBlock,hoveredTarget:this.positioner.target,isMobile:this.Blok.UI.isMobile},this.nodes.plusButton)}async drawUI(){var e=this;e.Blok.BlockSettings.make(),await e.make()}destroy(){this.removeAllNodes(),this.toolboxInstance&&this.toolboxInstance.destroy(),this.clickDragHandler.destroy()}},Rf=`38px`,zf=`46px`,Bf=class extends t.C{get hasNestedPopoverOpen(){return this.nestedPopover!==null&&this.nestedPopover!==void 0}closeNestedPopover(){this.destroyNestedPopoverIfExists()}constructor(e){var i;let a=!t.ma(),o=new t.mi({focusedItemClass:t.N.focused,allowedKeys:[t.Aa.TAB,t.Aa.UP,t.Aa.DOWN,t.Aa.ENTER]});super(n.t(n.t({},e),{},{flipper:o}),{[t.ki.Default]:{wrapperTag:`button`,hint:{position:`top`,alignment:`center`,enabled:a},iconWithGap:!1,isInline:!0},[t.ki.Html]:{hint:{position:`top`,alignment:`center`,enabled:a},isInline:!0},[t.ki.Separator]:{isInline:!0}}),this.hide=()=>{var e;this.setOpenTop(!1),this.setOpenLeft(!1),this.itemsDefault.forEach(e=>e.reset()),this.search!==void 0&&this.search.clear(),this.destroyNestedPopoverIfExists(),(e=this.flipper)==null||e.deactivate(),this.nodes.popover.className=r.n(t.O.popover),this.nodes.popoverContainer&&(this.nodes.popoverContainer.className=r.n(t.D.popoverContainer,t.O.popoverContainer),this.nodes.popoverContainer.style.height=``),t.A.instance.unregister(this),this.emit(t.T.Closed)},this.nodes.popover.className=r.n(t.O.popover),this.nodes.popoverContainer&&(this.nodes.popoverContainer.className=r.n(t.D.popoverContainer,t.O.popoverContainer)),this.nodes.items&&(this.nodes.items.className=r.n(t.D.items,`flex pb-0`)),this.nodes.popover.style.setProperty(`--height`,Rf),this.nodes.popover.style.setProperty(`--height-mobile`,zf),this.nodes.popover.setAttribute(t.Ma.popoverInline,``),(i=this.flipper)==null||i.setHandleContentEditableTargets(!0),this.items.forEach(e=>{!(e instanceof t.M)&&!(e instanceof t.j)||e.hasChildren&&e.isChildrenOpen&&this.showNestedItems(e)})}get offsetLeft(){return this.nodes.popoverContainer===null?0:this.nodes.popoverContainer.offsetLeft}show(){var e;if(super.show(),this.nodes.popover.className=r.n(t.O.popover,`inline-block`),this.nodes.popoverContainer){this.nodes.popoverContainer.className=r.n(t.D.popoverContainer,t.D.popoverContainerOpened,t.O.popoverContainer,t.O.popoverContainerOpened);let e=t.ma()?`var(--height-mobile)`:`var(--height)`;this.nodes.popoverContainer.style.height=e}let n=this.nestingLevel===0?(e=this.nodes.popoverContainer)==null?void 0:e.getBoundingClientRect():void 0;if(n!==void 0){let e=`${n.width}px`,r=`${n.height}px`;this.nodes.popover.style.setProperty(t.E.InlinePopoverWidth,e),this.nodes.popover.style.width=e,this.nodes.popover.style.height=r}queueMicrotask(()=>{var e,t;(e=this.flipper)==null||e.deactivate(),(t=this.flipper)==null||t.activate(this.flippableElements)})}handleHover(){}handleMouseLeave(){}setTriggerItemPosition(e,n){let r=n.getElement(),i=r?r.offsetLeft:0,a=this.offsetLeft+i;e.style.setProperty(t.E.TriggerItemLeft,a+`px`)}showNestedItems(e){if(this.nestedPopoverTriggerItem===e){this.destroyNestedPopoverIfExists(),this.nestedPopoverTriggerItem=null;return}super.showNestedItems(e)}showNestedPopoverForItem(e){var n;let i=super.showNestedPopoverForItem(e),a=i.getElement();(n=i.flipper)==null||n.setHandleContentEditableTargets(!0);let o=a.querySelector(`[${t.Ma.popoverContainer}]`);o&&(o.className=r.n(o.className,`h-fit p-1.5 flex-col`));let s=a.querySelector(`[${t.Ma.popoverItems}]`);if(s&&(s.className=r.n(s.className,`block w-full`)),a.setAttribute(t.Ma.nestedLevel,t.k(i.nestingLevel)),i.nestingLevel===1&&o instanceof HTMLElement){let n=e.getElement(),r=n?n.offsetLeft+this.offsetLeft:0,a=i.size.width,s=this.nodes.popoverContainer.offsetWidth,c=Math.max(0,s-a),l=Math.max(0,Math.min(r,c));o.style.left=`${l}px`;let u=t.ma()?`calc(var(--height-mobile) + 3px)`:`calc(var(--height) + 3px)`;o.style.top=u}return i}handleItemClick(e){if(e!==this.nestedPopoverTriggerItem){var t;(t=this.nestedPopoverTriggerItem)==null||t.handleClick(),super.destroyNestedPopoverIfExists()}super.handleItemClick(e)}},Vf=class{constructor(e,t){this.getPopover=e,this.closeToolbar=t}get hasFlipperFocus(){var e,t,n,r;let i=this.getPopover();if(i===null)return!1;let a=(e=(t=i.flipper)==null?void 0:t.hasFocus())==null?!1:e,o=i.nestedPopover,s=(n=o==null||(r=o.flipper)==null?void 0:r.hasFocus())==null?!1:n;return a||s}get hasNestedPopoverOpen(){let e=this.getPopover();return e===null?!1:e.hasNestedPopoverOpen}closeNestedPopover(){let e=this.getPopover();return e===null||!e.hasNestedPopoverOpen?!1:(e.closeNestedPopover(),!0)}handle(e,t){var n,r,i,a;let o=e.key===`ArrowDown`||e.key===`ArrowUp`,s=e.key===`ArrowLeft`||e.key===`ArrowRight`,c=this.getPopover(),l=(n=c==null||(r=c.flipper)==null?void 0:r.hasFocus())==null?!1:n,u=c===null?null:c.nestedPopover,d=u!=null,f=(i=u==null||(a=u.flipper)==null?void 0:a.hasFocus())==null?!1:i;if(o&&!e.shiftKey&&t&&!(l||d||f)){this.closeToolbar();return}if(s&&t&&l){e.preventDefault(),e.stopPropagation();return}}isShiftArrow(e){return e.shiftKey&&(e.key===`ArrowDown`||e.key===`ArrowUp`)}},Hf=class{constructor(e,t){this.initialized=!1,this.initializationScheduled=!1,this.getBlok=e,this.initialize=t}get isInitialized(){return this.initialized}markInitialized(){this.initialized=!0}get isScheduled(){return this.initializationScheduled}schedule(){if(this.initialized||this.initializationScheduled)return;this.initializationScheduled=!0;let e=()=>{this.initializationScheduled=!1,this.doInitialize()},t=()=>{typeof window<`u`?window.setTimeout(e,0):e()};typeof window<`u`&&`requestIdleCallback`in window?window.requestIdleCallback(()=>{t()},{timeout:2e3}):t()}doInitialize(){var e;if(this.initialized)return;let{UI:t}=this.getBlok();if((t==null||(e=t.nodes)==null?void 0:e.wrapper)===void 0){this.initializationScheduled=!1,this.schedule();return}this.initialize(),this.initialized=!0}},Uf=class{constructor(e,t){this.getBlok=e,this.getI18n=t}async build(e){var n=this;let r=[],i=Array.from(e.entries());for(let[e,[a,o]]of i.entries()){let i=await o.render(),{Tools:s}=n.getBlok(),c=s.inlineTools.get(a.name),l=c==null?void 0:c.shortcut,u=l===void 0?void 0:t.la(l),d=t.Gi(n.getI18n(),a.titleKey,a.title||t.ua(a.name)),f=Array.isArray(i)?i:[i],p=e===0;for(let e of f){let t=n.processPopoverItem(e,a.name,d,u,p);r.push(...t)}}return r}processPopoverItem(e,r,i,a,o){let s=[],c={name:r,hint:{title:i,description:a}};if(e instanceof HTMLElement)return s;if(e.type===t.ki.Html)return s.push(n.t(n.t(n.t({},c),e),{},{type:t.ki.Html})),s;if(e.type===t.ki.Separator)return s.push({type:t.ki.Separator}),s;let l=n.t(n.t(n.t({},c),e),{},{type:t.ki.Default});return s.push(l),`children`in l&&o&&s.push({type:t.ki.Separator}),s}},Wf=class{constructor(e){this.toolbarVerticalMargin=e?20:6}apply(e){let{wrapper:t,selectionRect:n,wrapperOffset:r,contentRect:i,popoverWidth:a}=e,o={x:n.x-r.x,y:n.y+n.height-r.top+this.toolbarVerticalMargin};o.x+a+r.x>i.right&&(o.x=i.right-a-r.x),t.style.left=Math.floor(o.x)+`px`,t.style.top=Math.floor(o.y)+`px`}},Gf=class{constructor(e){this.getBlok=e}canShow(){let e=[`IMG`,`INPUT`],n=this.resolveSelection(),r=t.Ai.text;if(!n||!n.anchorNode)return{allowed:!1,reason:`Selection is null or has no anchor node`};if(n.isCollapsed||r.length<1)return{allowed:!1,reason:`Selection is collapsed or empty`};let i=t.Qi.isElement(n.anchorNode)?n.anchorNode:n.anchorNode.parentElement;if(i===null)return{allowed:!1,reason:`Target element is null`};if(e.includes(i.tagName))return{allowed:!1,reason:`Target tag ${i.tagName} conflicts with selection`};let a=this.nodeToElement(n.focusNode);if(i.closest(`pre`)!==null||a!=null&&a.closest(`pre`))return{allowed:!1,reason:`Selection is inside a code block`};let o=t.Qi.isElement(n.anchorNode)?n.anchorNode:n.anchorNode.parentElement,{BlockManager:s}=this.getBlok(),c=o?s.getBlock(o):null,l=c==null?s.currentBlock:c;if(l==null)return{allowed:!1,reason:`Current block is null or undefined`};if(!this.getTools().some(e=>l.tool.inlineTools.has(e.name)))return{allowed:!1,reason:`No inline tools available for current block`};let u=`[contenteditable]`;if(i.closest(u)!==null)return{allowed:!0};let d=l.holder;if(d&&(d.matches(u)?d:d.closest(u)))return{allowed:!0};let{ReadOnly:f}=this.getBlok();return f.isEnabled?t.Ai.isSelectionAtBlok(n)?{allowed:!0}:{allowed:!1,reason:`Read-only mode and selection not at Blok`}:{allowed:!1,reason:`Target is not contenteditable`}}getTools(){var e;let{BlockManager:n,ReadOnly:r}=this.getBlok(),i=(e=n.currentBlock)==null?(()=>{let e=this.resolveSelection(),r=e==null?void 0:e.anchorNode;if(!r)return null;let i=t.Qi.isElement(r)?r:r.parentElement;return i?n.getBlock(i):null})():e;return i?Array.from(i.tool.inlineTools.values()).filter(e=>!(r.isEnabled&&!e.isReadOnlySupported)):[]}resolveSelection(){let e=t.Ai.selection;if(e!==void 0)return e;let n=t.Ai.instance;return n===void 0?t.Ai.get():n}nodeToElement(e){return e?t.Qi.isElement(e)?e:e.parentElement:null}},Kf=function(e){return e[e.Block=0]=`Block`,e[e.Inline=1]=`Inline`,e[e.Tune=2]=`Tune`,e}({}),qf=new Set([`class`,`inlineToolbar`,`tunes`,`shortcut`,`toolbox`,`config`,`isInternal`]),Jf=function(e){return e.Shortcut=`shortcut`,e.Toolbox=`toolbox`,e.EnabledInlineTools=`inlineToolbar`,e.EnabledBlockTunes=`tunes`,e.Config=`config`,e}({}),Yf=function(e){return e.Shortcut=`shortcut`,e.SanitizeConfig=`sanitize`,e}({}),Xf=function(e){return e.IsEnabledLineBreaks=`enableLineBreaks`,e.Toolbox=`toolbox`,e.ConversionConfig=`conversionConfig`,e.IsReadOnlySupported=`isReadOnlySupported`,e.PasteConfig=`pasteConfig`,e}({}),Zf=function(e){return e.IsInline=`isInline`,e}({}),Qf=function(e){return e.IsTune=`isTune`,e}({}),$f=class{constructor({name:e,constructable:t,config:n,api:r,isDefault:i,isInternal:a=!1,defaultPlaceholder:o}){this.api=r,this.name=e,this.constructable=t,this.config=n,this.isDefault=i,this.isInternal=a,this.defaultPlaceholder=o}setDefaultPlaceholder(e){this.defaultPlaceholder=e}get settings(){var e;let t=(e=this.config[Jf.Config])==null?{}:e,r={};for(let e of Object.keys(this.config))qf.has(e)||(r[e]=this.config[e]);let i=n.t(n.t({},t),r);return this.isDefault&&!(`placeholder`in i)&&this.defaultPlaceholder&&(i.placeholder=this.defaultPlaceholder),i}reset(){if(t.xa(this.constructable.reset))return this.constructable.reset()}prepare(){let e=this.constructable.prepare;if(!t.xa(e))return;let n={toolName:this.name,config:this.settings};return e.call(this.constructable,n)}get shortcut(){let e=this.constructable[Yf.Shortcut];return this.config[Jf.Shortcut]||e}get sanitizeConfig(){return this.constructable[Yf.SanitizeConfig]||{}}isInline(){return this.type===Kf.Inline}isBlock(){return this.type===Kf.Block}isTune(){return this.type===Kf.Tune}},ep=class{constructor(e,t){this.registeredShortcuts=new Map,this.shortcutsRegistered=!1,this.shortcutRegistrationScheduled=!1,this.getBlok=e,this.onShortcutPressed=t}tryRegisterShortcuts(){if(this.shortcutsRegistered)return;let{Tools:e}=this.getBlok();if(e===void 0){this.scheduleShortcutRegistration();return}this.registerInitialShortcuts()&&(this.shortcutsRegistered=!0)}getShortcut(e){let{Tools:t}=this.getBlok(),n=t.inlineTools.get(e),r=t.internal.inlineTools;if(Array.from(r.keys()).includes(e)){var i;return(i=this.inlineTools[e])==null?void 0:i[Yf.Shortcut]}return n==null?void 0:n.shortcut}hasShortcut(e){return this.registeredShortcuts.has(e)}destroy(){for(let[,e]of this.registeredShortcuts.entries())X.remove(document,e);this.registeredShortcuts.clear(),this.shortcutsRegistered=!1}registerInitialShortcuts(){let{Tools:e}=this.getBlok(),t=e==null?void 0:e.inlineTools;if(!t)return this.scheduleShortcutRegistration(),!1;let n=Array.from(t.keys());return n.length===0?(this.scheduleShortcutRegistration(),!1):(n.forEach(e=>{let t=this.getShortcut(e);this.tryEnableShortcut(e,t)}),!0)}tryEnableShortcut(e,t){if(t!==void 0)try{this.enableShortcuts(e,t)}catch(e){}}enableShortcuts(e,t){let n=this.registeredShortcuts.get(e);n!==t&&(this.isShortcutTakenByAnotherTool(e,t)||(n!==void 0&&(X.remove(document,n),this.registeredShortcuts.delete(e)),X.add({name:t,handler:t=>{var n,r;let{BlockManager:i}=this.getBlok(),a=(n=i.currentBlock)==null?i.getBlockByChildNode((r=window.getSelection())==null?void 0:r.anchorNode):n;a&&a.tool.enabledInlineTools!==!1&&(t.preventDefault(),this.onShortcutPressed(e))},on:document}),this.registeredShortcuts.set(e,t)))}isShortcutTakenByAnotherTool(e,t){return Array.from(this.registeredShortcuts.entries()).some(([n,r])=>n!==e&&r===t)}scheduleShortcutRegistration(){if(this.shortcutsRegistered||this.shortcutRegistrationScheduled)return;this.shortcutRegistrationScheduled=!0;let e=()=>{this.shortcutRegistrationScheduled=!1,this.tryRegisterShortcuts()};typeof window<`u`&&typeof window.setTimeout==`function`?window.setTimeout(e,0):e()}get inlineTools(){let{Tools:e}=this.getBlok(),t={};return Array.from(e.inlineTools.entries()).forEach(([e,n])=>{t[e]=n.create()}),t}},tp=class{constructor(e){this.getBlok=e}getAvailableTools(){let{ReadOnly:e}=this.getBlok(),t=this.getCurrentBlock();return t?Array.from(t.tool.inlineTools.values()).filter(t=>!(e.isEnabled&&!t.isReadOnlySupported)):[]}createInstances(e){let t=new Map;return e.forEach(e=>{let n=e.create();t.set(e,n)}),t}getToolShortcut(e){let{Tools:t}=this.getBlok(),n=t.inlineTools.get(e),r=t.internal.inlineTools;if(Array.from(r.keys()).includes(e)){var i;return(i=this.inlineTools[e])==null?void 0:i[Yf.Shortcut]}return n==null?void 0:n.shortcut}getCurrentBlock(){var e;let{BlockManager:n}=this.getBlok();return(e=n.currentBlock)==null?(()=>{let e=this.resolveSelection(),r=e==null?void 0:e.anchorNode;if(!r)return null;let i=t.Qi.isElement(r)?r:r.parentElement;return i?n.getBlock(i):null})():e}resolveSelection(){let e=t.Ai.selection;if(e!==void 0)return e;let n=t.Ai.instance;return n===void 0?t.Ai.get():n}get inlineTools(){let{Tools:e}=this.getBlok(),t={};return Array.from(e.inlineTools.entries()).forEach(([e,n])=>{t[e]=n.create()}),t}},np=class extends s{get hasNestedPopoverOpen(){return this.keyboardHandler.hasNestedPopoverOpen}closeNestedPopover(){return this.keyboardHandler.closeNestedPopover()}get hasFlipperFocus(){return this.keyboardHandler.hasFlipperFocus}constructor({config:e,eventsDispatcher:n}){super({config:e,eventsDispatcher:n}),this.opened=!1,this.popover=null,this.openingPromise=null,this.selection=new t.Ai,this.tools=new Map,this.positioner=new Wf(t.ma());let r=()=>this.Blok;this.shortcutManager=new ep(r,e=>this.activateToolByShortcut(e)),this.toolsManager=new tp(r),this.selectionValidator=new Gf(r),this.popoverBuilder=new Uf(r,()=>this.Blok.I18n),this.keyboardHandler=new Vf(()=>this.popover,()=>this.close()),this.lifecycleManager=new Hf(r,()=>this.initialize()),this.listeners.on(window,`keydown`,e=>{let t=e;this.keyboardHandler.handle(t,this.opened),this.keyboardHandler.isShiftArrow(t)&&this.tryToShow()},!0),this.lifecycleManager.schedule(),this.shortcutManager.tryRegisterShortcuts()}set state(e){super.state=e,this.shortcutManager.tryRegisterShortcuts()}initialize(){this.lifecycleManager.isInitialized||(this.make(),this.shortcutManager.tryRegisterShortcuts(),this.lifecycleManager.markInitialized())}async tryToShow(e=!1){var t=this;e&&t.close(),t.initialize();let{allowed:n}=t.selectionValidator.canShow();if(n){t.openingPromise=t.open();try{await t.openingPromise}catch(e){if(t.opened=!1,t.popover){var r,i,a,o;(r=(i=t.popover).hide)==null||r.call(i),(a=(o=t.popover).destroy)==null||a.call(o),t.popover=null}return}finally{t.openingPromise=null}t.Blok.Toolbar.hideBlockActions()}}close(){var e;if(!this.opened)return;if(this.tools=new Map,this.opened=!1,this.openingPromise=null,this.selection.clearFakeBackground(),this.popover){var t,n,r,i;(t=(n=this.popover).hide)==null||t.call(n),(r=(i=this.popover).destroy)==null||r.call(i),this.popover=null}this.nodes.wrapper&&(this.nodes.wrapper.innerHTML=``);let a=Bf.mock,o=a==null||(e=a.results)==null||(e=e.at(-1))==null?void 0:e.value;if(o){var s,c;(s=o.hide)==null||s.call(o),(c=o.destroy)==null||c.call(o)}}containsNode(e){return this.nodes.wrapper===void 0?!1:!!(this.nodes.wrapper.contains(e)||this.popover!==null&&this.popover.hasNode(e))}destroy(){if(this.popover){var e,t,n,r;(e=(t=this.popover).hide)==null||e.call(t),(n=(r=this.popover).destroy)==null||n.call(r),this.popover=null}this.shortcutManager.destroy(),this.removeAllNodes()}make(){this.nodes.wrapper=t.Qi.make(`div`,r.n(`absolute top-0 left-0 z-3 opacity-100 visible`,`transition-opacity duration-250 ease-out`,`will-change-[opacity,left,top]`,`**:[[hidden]]:hidden!`)),this.nodes.wrapper.setAttribute(t.Ma.interface,t.Ni),this.nodes.wrapper.setAttribute(`data-blok-testid`,`inline-toolbar`),t.Qi.append(this.Blok.UI.nodes.wrapper,this.nodes.wrapper)}async open(){var e=this,t,n,r,i,a,o,s,c,l,u,d,f;if(e.opened)return;if(e.initialize(),e.opened=!0,e.popover){var p,m,h,g;(p=(m=e.popover).hide)==null||p.call(m),(h=(g=e.popover).destroy)==null||h.call(g),e.popover=null}if(e.createToolsInstances(),!e.nodes.wrapper)return;e.nodes.wrapper.innerHTML=``,e.popover=new Bf({items:await e.buildPopoverItems(),messages:{nothingFound:e.Blok.I18n.t(`popover.nothingFound`),search:e.Blok.I18n.t(`popover.search`)}});let _=(t=(n=(r=e.popover).getMountElement)==null?void 0:n.call(r))==null?(i=(a=e.popover).getElement)==null?void 0:i.call(a):t,v=(o=(s=e.popover).getElement)==null?void 0:o.call(s),y=(c=(l=(u=e.popover.size)==null?void 0:u.width)==null?v==null?void 0:v.getBoundingClientRect().width:l)==null?0:c;e.applyPosition(y),_&&e.nodes.wrapper&&e.nodes.wrapper.appendChild(_),(d=(f=e.popover).show)==null||d.call(f)}async buildPopoverItems(){var e=this;return e.popoverBuilder.build(e.tools)}applyPosition(e){if(!this.nodes.wrapper)return;let n=this.Blok.UI.nodes.wrapper,r=this.nodes.wrapper.offsetParent===n?n.getBoundingClientRect():new DOMRect(0,0,0,0),i=this.Blok.UI.contentRect,a=t.Ai.rect;this.positioner.apply({wrapper:this.nodes.wrapper,selectionRect:a,wrapperOffset:r,contentRect:i,popoverWidth:e})}createToolsInstances(){let e=this.toolsManager.getAvailableTools();this.tools=this.toolsManager.createInstances(e)}async activateToolByShortcut(e){var t=this;if(t.opened||await t.tryToShow(),t.openingPromise!==null&&await t.openingPromise,t.popover){t.popover.activateItemByName(e);return}t.invokeToolActionDirectly(e)}invokeToolActionDirectly(e){let t=this.Blok.Tools.inlineTools.get(e);if(!t)return;let n=t.create().render(),r=Array.isArray(n)?n:[n];for(let e of r)if(`onActivate`in e&&typeof e.onActivate==`function`){e.onActivate(e);return}}},rp,ip=class{constructor({data:e,api:t}){this.api=t,this.title=e.title||this.api.i18n.t(`tools.stub.error`),this.subtitle=this.api.i18n.t(`tools.stub.blockCannotBeDisplayed`),this.savedData=e.savedData,this.wrapper=this.make()}render(){return this.wrapper}save(){return this.savedData}setReadOnly(e){}make(){let e=t.Qi.make(`div`,`flex items-center py-3 px-[18px] my-2.5 rounded-[10px] bg-bg-light border border-line-gray text-gray-text text-sm [&_svg]:size-icon`),n=t.qn,r=t.Qi.make(`div`,`ml-3.5`),i=t.Qi.make(`div`,`font-medium capitalize`,{textContent:this.title}),a=t.Qi.make(`div`,``,{textContent:this.subtitle});return e.setAttribute(t.Ma.tool,`stub`),e.setAttribute(t.Ma.stub,``),r.setAttribute(t.Ma.stubInfo,``),i.setAttribute(t.Ma.stubTitle,``),a.setAttribute(t.Ma.stubSubtitle,``),e.innerHTML=n,r.appendChild(i),r.appendChild(a),e.appendChild(r),e}};rp=ip,rp.isReadOnlySupported=!0;var ap,op=class{constructor({api:e,block:t}){this.api=e,this.block=t,this.onKeydown=e=>{e.metaKey&&e.ctrlKey&&e.code===`KeyL`&&this.block.selected&&this.handleClick()},document.addEventListener(`keydown`,this.onKeydown)}render(){return{icon:t.qt,title:this.api.i18n.t(`blockSettings.copyLink`),name:`copy-link`,secondaryLabel:`⌃⌘L`,onActivate:()=>this.handleClick()}}destroy(){document.removeEventListener(`keydown`,this.onKeydown)}async handleClick(){var e=this;let t=`${window.location.href.split(`#`)[0]}#${encodeURIComponent(e.block.id)}`;try{await navigator.clipboard.writeText(t),e.api.notifier.show({message:e.api.i18n.t(`blockSettings.copyLinkSuccess`),style:`success`,time:2e3})}catch(t){e.api.notifier.show({message:e.api.i18n.t(`blockSettings.copyLinkError`),style:`error`,time:3e3})}}};ap=op,ap.isTune=!0;var sp,cp=class{constructor({api:e}){this.api=e}render(){return{icon:t.Vn,title:this.api.i18n.t(`blockSettings.delete`),name:`delete`,isDestructive:!0,secondaryLabel:`Del`,onActivate:()=>this.handleClick()}}handleClick(){this.api.blocks.delete()}};sp=cp,sp.isTune=!0;var lp=class e extends Map{get blockTools(){return new e(Array.from(this.entries()).filter(([,e])=>e.isBlock()))}get inlineTools(){return new e(Array.from(this.entries()).filter(([,e])=>e.isInline()))}get blockTunes(){return new e(Array.from(this.entries()).filter(([,e])=>e.isTune()))}get internalTools(){return new e(Array.from(this.entries()).filter(([,e])=>e.isInternal))}get externalTools(){return new e(Array.from(this.entries()).filter(([,e])=>!e.isInternal))}},up=class extends $f{constructor(...e){super(...e),this.type=Kf.Block,this.inlineTools=new lp,this.tunes=new lp}create(e,t,n){return new this.constructable({data:e,block:t,readOnly:n,api:this.api,config:this.settings})}get isReadOnlySupported(){return this.constructable[Xf.IsReadOnlySupported]===!0}get supportsInPlaceReadOnly(){var e;let t=(e=this.constructable)==null?void 0:e.prototype;return typeof(t==null?void 0:t.setReadOnly)==`function`}get isLineBreaksEnabled(){var e;return(e=this.constructable[Xf.IsEnabledLineBreaks])==null?!1:e}get toolbox(){let e=this.constructable[Xf.Toolbox],n=this.config[Jf.Toolbox];if(!e||t.ba(e)||n===!1)return;let r=this.mergeToolboxSettings(e,n),i=this.filterToolboxEntriesByStyles(r);return this.filterToolboxEntriesByLevels(i)}mergeToolboxSettings(e,t){return t==null?Array.isArray(e)?e:[e]:!Array.isArray(t)&&Array.isArray(e)?[t]:Array.isArray(t)?Array.isArray(e)?t.map((t,r)=>{let i=e[r];return i?n.t(n.t({},i),t):t}):t:[n.t(n.t({},e),t)]}filterToolboxEntriesByStyles(e){let t=this.settings.toolboxStyles;return!t||!Array.isArray(t)||t.length===0?e:e.filter(e=>{let n=e.data;return!n||!n.style?!0:t.includes(n.style)})}filterToolboxEntriesByLevels(e){let t=this.settings.levels;return!t||!Array.isArray(t)||t.length===0?e:e.filter(e=>{let n=e.data;return!n||n.level===void 0?!0:t.includes(n.level)})}get conversionConfig(){return this.constructable[Xf.ConversionConfig]}get enabledInlineTools(){let e=this.config[Jf.EnabledInlineTools];return e===void 0?!0:e}get enabledBlockTunes(){return this.config[Jf.EnabledBlockTunes]}get searchTerms(){return this.config.searchTerms}get pasteConfig(){var e;return(e=this.constructable[Xf.PasteConfig])==null?{}:e}get hasOnPasteHandler(){var e;let t=(e=this.constructable)==null?void 0:e.prototype;return typeof(t==null?void 0:t.onPaste)==`function`}get sanitizeConfig(){if(this._sanitizeConfig)return this._sanitizeConfig;let e=super.sanitizeConfig,n=this.baseSanitizeConfig;if(t.ba(e))return this._sanitizeConfig=n,n;let r={};for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let a=e[i];t.Sa(a)?r[i]=Object.assign({},n,a):r[i]=a}return this._sanitizeConfig=r,r}get baseSanitizeConfig(){if(this._baseSanitizeConfig)return this._baseSanitizeConfig;let e={};return Array.from(this.inlineTools.values()).forEach(t=>Object.assign(e,t.sanitizeConfig)),Array.from(this.tunes.values()).forEach(t=>Object.assign(e,t.sanitizeConfig)),this._baseSanitizeConfig=e,e}},dp=class extends $f{constructor(...e){super(...e),this.type=Kf.Inline}getMissingMethods(e){let t=this.constructable,n=t==null?void 0:t.prototype;return n?e.filter(e=>typeof n[e]!=`function`):[...e]}create(){let e=this.constructable;return new e({api:this.api,config:this.settings})}get isReadOnlySupported(){var e;let t=this.constructable;return(e=t==null?void 0:t.isReadOnlySupported)==null?!1:e}get title(){return this.constructable.title||``}get titleKey(){return this.constructable.titleKey}},fp=class extends $f{constructor(...e){super(...e),this.type=Kf.Tune}create(e,t){let n=this.constructable;return new n({api:this.api,config:this.settings,block:t,data:e})}},pp=[`class`,`isInternal`],mp=class{constructor(e,t,n){this.api=n,this.config=e,this.blokConfig=t}updateConfig(e,t){let n=this.config[e];if(n===void 0)throw Error(`Tool "${e}" is not registered.`);n.config===void 0&&(n.config={}),Object.assign(n.config,t)}get(e){let t=this.config[e],{class:n,isInternal:r=!1}=t,i=ie(t,pp),a=n;if(a===void 0)throw Error(`Tool "${e}" does not provide a class.`);return new(this.getConstructor(a))({name:e,constructable:a,config:i,api:this.createToolApi(e),isDefault:e===this.blokConfig.defaultBlock,defaultPlaceholder:this.blokConfig.placeholder,isInternal:r})}createToolApi(e){let t=this.api.methods,r=`tools.${e}`;return n.t(n.t({},t),{},{i18n:{t:e=>{let n=`${r}.${e}`;return t.i18n.has(n)?t.i18n.t(n):t.i18n.t(e)},has:e=>{let n=`${r}.${e}`;return t.i18n.has(n)||t.i18n.has(e)},getEnglishTranslation:e=>t.i18n.getEnglishTranslation(e),getLocale:()=>t.i18n.getLocale()}})}getConstructor(e){let t=!!Reflect.get(e,Zf.IsInline),n=!!Reflect.get(e,Qf.IsTune);return t?dp:n?fp:up}},hp=class{constructor(){this.tail=Promise.resolve()}get completed(){return this.failure?Promise.reject(this.failure):this.tail}add(e){if(this.failure)return Promise.reject(this.failure);let t=this.tail.then(()=>e());return this.tail=t.catch(e=>{this.failure=e}),t}},gp,_p=e=>{if(!t.xa(e))throw Error(`Tool constructable must be a function`);return e},vp=class e extends s{constructor(...e){super(...e),this.stubTool=`stub`,this.factory=null,this.toolsAvailable=new lp,this.toolsUnavailable=new lp,this.inlineToolsSanitizeConfigCache=null}get available(){return this.toolsAvailable}get unavailable(){return this.toolsUnavailable}get inlineTools(){return this.available.inlineTools}get blockTools(){return this.available.blockTools}get blockTunes(){return this.available.blockTunes}get defaultTool(){let e=this.config.defaultBlock;if(!e)throw Error(`Default block tool name is not configured`);let t=this.blockTools.get(e);if(!t)throw Error(`Default block tool "${e}" not found in available block tools`);return t}get internal(){return this.available.internalTools}async prepare(){var e=this,n;let r=(n=e.config.tools)==null?{}:n;e.config.tools=e.expandToolGroups(t.sa({},e.internalTools,r)),e.validateTools();let i=e.config.tools;if(!i||Object.keys(i).length===0)throw Error(`Can't start without tools`);let a=e.prepareConfig(i);e.factory=new mp(a,e.config,e.Blok.API);let o=e.getListOfPrepareFunctions(a);if(o.length===0)return Promise.resolve();let s=t=>{e.isToolPrepareData(t)&&e.toolPrepareMethodSuccess({toolName:t.toolName})},c=t=>{e.isToolPrepareData(t)&&e.toolPrepareMethodFallback({toolName:t.toolName})},l=new hp;o.forEach(e=>{l.add(async()=>{let n=t.wa(e.data)?{}:e.data;try{await e.function(e.data),s(n)}catch(e){c(n)}})}),await l.completed,e.prepareBlockTools()}updateToolConfig(e,t){if(!this.available.has(e)&&!this.unavailable.has(e))throw Error(`Tool "${e}" is not registered.`);this.getFactory().updateConfig(e,t)}getAllInlineToolsSanitizeConfig(){if(this.inlineToolsSanitizeConfigCache)return this.inlineToolsSanitizeConfigCache;let e={};return Array.from(this.inlineTools.values()).forEach(t=>{Object.assign(e,t.sanitizeConfig)}),this.inlineToolsSanitizeConfigCache=e,e}destroy(){for(let e of this.available.values()){let n=(()=>{try{return e.reset()}catch(n){t.Ea(`Tool "${e.name}" reset failed`,`warn`,n);return}})();n instanceof Promise&&n.catch(n=>{t.Ea(`Tool "${e.name}" reset failed`,`warn`,n)})}}get internalTools(){return{stub:{class:_p(ip),isInternal:!0},delete:{class:_p(cp),isInternal:!0},copyLink:{class:_p(op),isInternal:!0},convertTo:{class:_p(t.m),isInternal:!0}}}expandToolGroups(e){let r={};for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let a=e[i],o=t.Sa(a)?a.class:a,s=o==null?void 0:o.provides;if(!s){r[i]=a;continue}let c=t.Sa(a)?Object.fromEntries(Object.entries(a).filter(([e])=>e!==`class`&&e!==`isInternal`)):{},l=Object.keys(c).length>0;Object.entries(s).forEach(([e,t])=>{e in r||(r[e]=l?n.t({class:t},c):t)})}return r}toolPrepareMethodSuccess(e){let n=this.getFactory().get(e.toolName);if(!n.isInline()){this.toolsAvailable.set(n.name,n);return}let r=n.getMissingMethods([`render`]);if(r.length){t.Ea(`Incorrect Inline Tool: ${n.name}. Some of required methods is not implemented %o`,`warn`,r),this.toolsUnavailable.set(n.name,n);return}this.toolsAvailable.set(n.name,n)}toolPrepareMethodFallback(e){let t=this.getFactory();this.toolsUnavailable.set(e.toolName,t.get(e.toolName))}getListOfPrepareFunctions(e){return Object.entries(e).map(([e,n])=>{let r={toolName:e,config:this.extractToolConfig(n)};return{function:async e=>{let i=n.class;if(!i||!t.xa(i.prepare))return;let a=e==null?r:e;return i.prepare.call(i,a)},data:r}})}extractToolConfig(t){var r;let i=(r=t.config)==null?{}:r,a={};for(let n of Object.keys(t))e.BLOK_SETTINGS_KEYS.has(n)||(a[n]=t[n]);return n.t(n.t({},i),a)}prepareBlockTools(){Array.from(this.blockTools.values()).forEach(e=>{this.assignInlineToolsToBlockTool(e),this.assignBlockTunesToBlockTool(e)})}assignInlineToolsToBlockTool(e){let t=e;if(this.config.inlineToolbar!==!1){if(t.enabledInlineTools===!0){t.inlineTools=Array.isArray(this.config.inlineToolbar)?this.createInlineToolsCollection(this.config.inlineToolbar):this.createInlineToolsCollection([`convertTo`,...this.inlineTools.keys()]);return}Array.isArray(t.enabledInlineTools)&&(t.inlineTools=this.createInlineToolsCollection([`convertTo`,...t.enabledInlineTools]))}}assignBlockTunesToBlockTool(e){let t=e;if(t.enabledBlockTunes!==!1){if(Array.isArray(t.enabledBlockTunes)){let e=this.createBlockTunesCollection(t.enabledBlockTunes);t.tunes=new lp([...Array.from(e.entries()),...Array.from(this.blockTunes.internalTools.entries())]);return}if(Array.isArray(this.config.tunes)){let e=this.createBlockTunesCollection(this.config.tunes);t.tunes=new lp([...Array.from(e.entries()),...Array.from(this.blockTunes.internalTools.entries())]);return}t.tunes=new lp(Array.from(this.blockTunes.internalTools.entries()))}}validateTools(){let e=this.config.tools;if(!e)return;let n=this.internalTools;for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r)||r in n)continue;let i=e[r],a=t.xa(i),s=t.xa(i.class);if(!a&&!s)throw new o(`Tool «${r}» must be a constructor function or an object with function in the «class» property`)}}prepareConfig(e){let n={};for(let r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let i=e[r];if(t.Sa(i)){n[r]=i;continue}n[r]={class:i}}return n}isToolPrepareData(e){let t=e;return typeof(t==null?void 0:t.toolName)==`string`}getFactory(){if(this.factory===null)throw Error(`Tools factory is not initialized`);return this.factory}createInlineToolsCollection(e){let n=[];for(let r of e){let e=this.inlineTools.get(r);if(!e){t.Ea(`Inline tool "${r}" is not available and will be skipped`,`warn`);continue}n.push([r,e])}return new lp(n)}createBlockTunesCollection(e){let n=[];for(let r of e){let e=this.blockTunes.get(r);if(!e){t.Ea(`Block tune "${r}" is not available and will be skipped`,`warn`);continue}n.push([r,e])}return new lp(n)}};gp=vp,gp.BLOK_SETTINGS_KEYS=new Set([`class`,`inlineToolbar`,`tunes`,`shortcut`,`toolbox`,`config`,`isInternal`]);var yp=`/*! tailwindcss v4.2.4 | MIT License | https://tailwindcss.com */