/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

import{watchedSignal as e,effect as t,namedSignals as n}from"@lexical/extension";import{$getSelection as i,$isRangeSelection as o,$isTextNode as s,defineExtension as r,safeCast as l,getEditorPropertyFromDOMNode as a,getActiveElementDeep as d,isLexicalEditor as u}from"lexical";const c={bold:"bold",italic:"italic",strikeThrough:"strikethrough",subscript:"subscript",superscript:"superscript",underline:"underline"},f=Symbol.for("@lexical/dragon/WindowState");function g(e=function(){return"undefined"!=typeof window?window:void 0}()){return e?p(e,Symbol("@lexical/dragon/globalInstall"),void 0):()=>{}}function p(e,t,n){const i=function(e){let t=e[f];return void 0===t&&(t={dispose:()=>{},editors:new Map,installs:new Set},e[f]=t),t}(e);if(0===i.installs.size){const t=x.bind(e);e.addEventListener("message",t,!0),i.dispose=()=>{e.removeEventListener("message",t,!0)}}if(i.installs.add(t),n){const e=i.editors.get(n)||new Set;e.add(t),i.editors.set(n,e)}return m.bind(null,e,i,t,n)}function m(e,t,n,i){if(i){const e=t.editors.get(i);e&&e.delete(n)&&0===e.size&&t.editors.delete(i)}t.installs.delete(n)&&0===t.installs.size&&(t.dispose(),delete e[f])}function y(e){return e&&e.ownerDocument.defaultView}function b(n){const i=e(()=>y(n.getRootElement()),e=>n.registerRootListener(t=>{e.value=y(t)}));return t(()=>{const e=i.value;if(e)return p(e,Symbol("@lexical/dragon/editorInstall"),n)})}function x(e){if(e.origin!==this.location.origin)return;const t=function(e){const t=e[f];if(void 0===t)return null;const n=a(d(e.document));return u(n)&&t.editors.has(n)?n:null}(this);if(null===t)return;const n=e.data;if("string"==typeof n){let r;try{r=JSON.parse(n)}catch(e){return}if(r&&"nuanria_messaging"===r.protocol&&"request"===r.type){const n=r.payload;if(n&&"makeChanges"===n.functionId){const r=n.args;if(Array.isArray(r)){const[n,l,a,d,u,f]=r;if(![n,l,d,u].every(Number.isFinite)||"string"!=typeof a&&-1!==a)return;t.update(()=>{const t=i();if(o(t)){const i=t.anchor;let o=i.getNode(),r=0,g=0;if(s(o)&&n>=0&&l>=0&&(r=n,g=n+l,t.setTextNodeRange(o,r,o,g)),"string"!=typeof a||r===g&&""===a||(t.insertRawText(a),o=i.getNode()),s(o)){const e=o.getTextContentSize();r=Math.min(Math.max(d,0),e),g=d<0||u<0?r:Math.min(d+u,e),t.setTextNodeRange(o,r,o,g)}if("string"==typeof f&&u>0&&!t.isCollapsed()){const e=c[f];void 0!==e&&t.formatText(e)}e.stopImmediatePropagation()}})}}}}}const h=/* @__PURE__ */r({build:(e,t,i)=>n(t),config:/* @__PURE__ */l({disabled:"undefined"==typeof window}),name:"@lexical/dragon",register:(e,n,i)=>t(()=>i.getOutput().disabled.value?void 0:b(e))});export{h as DragonExtension,g as installDragonSupport,b as registerDragonSupport};
