@lyfie/luthor-headless 2.6.3 → 2.6.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.
Files changed (2) hide show
  1. package/dist/index.js +5 -5
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import Yt,{createContext,createElement,useRef,useState,useEffect,useMemo,useCallback,useContext}from'react';import {LexicalComposer}from'@lexical/react/LexicalComposer';import {useLexicalComposerContext}from'@lexical/react/LexicalComposerContext';import {createCommand,$getSelection,$isNodeSelection,$getNodeByKey,$isRangeSelection,$createParagraphNode,$getRoot,COMMAND_PRIORITY_EDITOR,KEY_DELETE_COMMAND,KEY_BACKSPACE_COMMAND,PASTE_COMMAND,COMMAND_PRIORITY_NORMAL,DecoratorNode,$createTextNode,KEY_ENTER_COMMAND,$isTextNode,$isParagraphNode,$isRootOrShadowRoot,COMMAND_PRIORITY_LOW,$isElementNode,KEY_SPACE_COMMAND,INDENT_CONTENT_COMMAND,OUTDENT_CONTENT_COMMAND,KEY_TAB_COMMAND,$nodesOfType,INSERT_PARAGRAPH_COMMAND,ParagraphNode,FORMAT_ELEMENT_COMMAND,CAN_UNDO_COMMAND,CAN_REDO_COMMAND,CLEAR_HISTORY_COMMAND,REDO_COMMAND,UNDO_COMMAND,INSERT_LINE_BREAK_COMMAND,FORMAT_TEXT_COMMAND,$getNearestNodeFromDOMNode,$createNodeSelection,$setSelection,createEditor,TextNode,LineBreakNode,TabNode,ElementNode,IS_BOLD,IS_ITALIC,IS_STRIKETHROUGH,IS_CODE,IS_HIGHLIGHT,IS_UNDERLINE}from'lexical';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {$createLinkNode,TOGGLE_LINK_COMMAND,$isLinkNode,LinkNode,AutoLinkNode}from'@lexical/link';import {TRANSFORMERS,registerMarkdownShortcuts,$convertFromMarkdownString,$convertToMarkdownString}from'@lexical/markdown';import {ListNode,ListItemNode,$isListNode,INSERT_CHECK_LIST_COMMAND,INSERT_UNORDERED_LIST_COMMAND,INSERT_ORDERED_LIST_COMMAND,$isListItemNode,$getListDepth}from'@lexical/list';import {$isHeadingNode,$isQuoteNode,HeadingNode,QuoteNode,$createQuoteNode,$createHeadingNode}from'@lexical/rich-text';import {CodeNode,CodeHighlightNode,$createCodeNode,$isCodeNode,registerCodeHighlighting,PrismTokenizer,normalizeCodeLang,getCodeLanguageOptions,getCodeLanguages}from'@lexical/code';import {TableNode,TableRowNode,TableCellNode,$isTableNode,$isTableRowNode,$isTableCellNode,$isTableSelection,$deleteTableColumnAtSelection,$deleteTableRowAtSelection,$unmergeCell,$mergeCells,$getTableNodeFromLexicalNodeOrThrow,$getTableColumnIndexFromTableCellNode,TableCellHeaderStates,$getTableRowIndexFromTableCellNode,$insertTableColumnAtSelection,$insertTableRowAtSelection,$createTableNodeWithDimensions,$findCellNode}from'@lexical/table';import {HorizontalRuleNode,$createHorizontalRuleNode,$isHorizontalRuleNode,INSERT_HORIZONTAL_RULE_COMMAND}from'@lexical/react/LexicalHorizontalRuleNode';import {$generateNodesFromDOM,$generateHtmlFromNodes}from'@lexical/html';import {LinkPlugin}from'@lexical/react/LexicalLinkPlugin';import {AutoLinkPlugin}from'@lexical/react/LexicalAutoLinkPlugin';import {ClickableLinkPlugin}from'@lexical/react/LexicalClickableLinkPlugin';import {HorizontalRulePlugin}from'@lexical/react/LexicalHorizontalRulePlugin';import {$patchStyleText,$getSelectionStyleValueForProperty,$setBlocksType}from'@lexical/selection';import {createPortal}from'react-dom';import {TablePlugin}from'@lexical/react/LexicalTablePlugin';import {ListPlugin}from'@lexical/react/LexicalListPlugin';import {CheckListPlugin}from'@lexical/react/LexicalCheckListPlugin';import {HistoryPlugin}from'@lexical/react/LexicalHistoryPlugin';import {renderToStaticMarkup}from'react-dom/server';import {RichTextPlugin}from'@lexical/react/LexicalRichTextPlugin';import {ContentEditable}from'@lexical/react/LexicalContentEditable';var Ys=Object.defineProperty;var Qs=(i,t,e)=>t in i?Ys(i,t,{enumerable:true,configurable:true,writable:true,value:e}):i[t]=e;var C=(i,t,e)=>Qs(i,typeof t!="symbol"?t+"":t,e);var fr=["--luthor-bg","--luthor-fg","--luthor-border","--luthor-border-hover","--luthor-border-active","--luthor-accent","--luthor-accent-hover","--luthor-shadow","--luthor-muted","--luthor-muted-fg","--luthor-theme-transition","--luthor-drag-gutter-width","--luthor-line-height-ratio","--luthor-toolbar-bg","--luthor-toolbar-section-border","--luthor-toolbar-button-fg","--luthor-toolbar-button-hover-bg","--luthor-toolbar-button-hover-border","--luthor-toolbar-button-hover-shadow","--luthor-toolbar-button-press-shadow","--luthor-toolbar-button-active-bg","--luthor-toolbar-button-active-border","--luthor-toolbar-button-active-fg","--luthor-toolbar-button-active-shadow","--luthor-toolbar-button-overlay","--luthor-toolbar-button-active-overlay","--luthor-toolbar-color-indicator-border","--luthor-toolbar-highlight-bg","--luthor-quote-bg","--luthor-quote-fg","--luthor-quote-border","--luthor-text-bold-color","--luthor-link-color","--luthor-list-marker-color","--luthor-list-checkbox-color","--luthor-table-border-color","--luthor-table-header-bg","--luthor-hr-color","--luthor-placeholder-color","--luthor-codeblock-bg","--luthor-syntax-comment","--luthor-syntax-keyword","--luthor-syntax-string","--luthor-syntax-number","--luthor-syntax-function","--luthor-syntax-variable","--luthor-floating-bg","--luthor-floating-fg","--luthor-floating-border","--luthor-floating-shadow","--luthor-floating-muted","--luthor-floating-border-hover","--luthor-floating-border-active","--luthor-floating-accent","--luthor-floating-accent-fg","--luthor-preset-bg","--luthor-preset-fg","--luthor-preset-border","--luthor-preset-muted","--luthor-preset-muted-fg","--luthor-preset-accent","--luthor-preset-radius","--luthor-preset-shadow","--luthor-preset-content-padding","--luthor-preset-content-min-height"];function Vs(i){return typeof i=="string"&&i.trim().length>0}function Ws(i){if(!i)return;let t={};for(let e of fr){let n=i[e];Vs(n)&&(t[e]=n);}return Object.keys(t).length>0?t:void 0}var je={text:{bold:"luthor-text-bold",italic:"luthor-text-italic",underline:"luthor-text-underline",strikethrough:"luthor-text-strikethrough",code:"luthor-text-code"},list:{ul:"luthor-list-ul",ol:"luthor-list-ol",listitem:"luthor-list-li",listitemChecked:"luthor-list-item-checked",listitemUnchecked:"luthor-list-item-unchecked",nested:{list:"luthor-list-nested",listitem:"luthor-list-nested-item"}},quote:"luthor-quote",heading:{h1:"luthor-heading-h1",h2:"luthor-heading-h2",h3:"luthor-heading-h3",h4:"luthor-heading-h4",h5:"luthor-heading-h5",h6:"luthor-heading-h6"},paragraph:"luthor-paragraph",link:"luthor-link",image:"lexical-image",hr:"luthor-hr",table:"luthor-table",tableRow:"luthor-table-row",tableCell:"luthor-table-cell",tableCellHeader:"luthor-table-cell-header",code:"luthor-code-block hljs",codeHighlight:{atrule:"hljs-meta luthor-code-atrule",attr:"hljs-attribute luthor-code-attr",boolean:"hljs-literal luthor-code-boolean",builtin:"hljs-built_in luthor-code-builtin",cdata:"hljs-comment luthor-code-cdata",char:"hljs-string luthor-code-char",class:"hljs-type luthor-code-class","class-name":"hljs-title luthor-code-class-name",comment:"hljs-comment luthor-code-comment",constant:"hljs-variable luthor-code-constant",deleted:"hljs-deletion luthor-code-deleted",doctype:"hljs-meta luthor-code-doctype",entity:"hljs-symbol luthor-code-entity",function:"hljs-title luthor-code-function",important:"hljs-emphasis luthor-code-important",inserted:"hljs-addition luthor-code-inserted",keyword:"hljs-keyword luthor-code-keyword",namespace:"hljs-title luthor-code-namespace",number:"hljs-number luthor-code-number",operator:"hljs-operator luthor-code-operator",prolog:"hljs-meta luthor-code-prolog",property:"hljs-property luthor-code-property",punctuation:"hljs-punctuation luthor-code-punctuation",regex:"hljs-regexp luthor-code-regex",selector:"hljs-selector-tag luthor-code-selector",string:"hljs-string luthor-code-string",symbol:"hljs-symbol luthor-code-symbol",tag:"hljs-tag luthor-code-tag",url:"hljs-link luthor-code-url",variable:"hljs-variable luthor-code-variable"},toolbar:{button:"luthor-toolbar-button",buttonActive:"luthor-toolbar-button-active",buttonDisabled:"luthor-toolbar-button-disabled",group:"luthor-toolbar-group"},container:"luthor-editor-container",wrapper:"luthor-editor-wrapper",editor:"luthor-editor",contentEditable:"luthor-content-editable",contextMenu:{container:"luthor-context-menu",item:"luthor-context-menu-item",itemDisabled:"luthor-context-menu-item-disabled"},draggable:{handle:"luthor-draggable-handle",handleActive:"luthor-draggable-handle-active",handleHover:"luthor-draggable-handle-hover",handleDragging:"luthor-draggable-handle-dragging",blockDragging:"luthor-draggable-block-dragging opacity-50 transition-opacity duration-200",dropIndicator:"luthor-draggable-drop-indicator",upButton:"luthor-draggable-up-button",downButton:"luthor-draggable-down-button",blockIsDragging:"luthor-draggable-block-is-dragging",buttonStack:"luthor-draggable-button-stack"},floatingToolbar:{container:"luthor-floating-toolbar",button:"luthor-floating-toolbar-button",buttonActive:"luthor-floating-toolbar-button-active"},richText:{contentEditable:"luthor-content-editable",placeholder:"luthor-placeholder"}};function qs(i,t){return {...i,...t,text:{...i.text,...t.text},list:{...i.list,...t.list,nested:{...i.list?.nested,...t.list?.nested}},heading:{...i.heading,...t.heading},codeHighlight:{...i.codeHighlight,...t.codeHighlight},toolbar:{...i.toolbar,...t.toolbar},draggable:{...i.draggable,...t.draggable,styles:{...i.draggable?.styles,...t.draggable?.styles}},floatingToolbar:{...i.floatingToolbar,...t.floatingToolbar,styles:{...i.floatingToolbar?.styles,...t.floatingToolbar?.styles}},richText:{...i.richText,...t.richText},styles:{toolbar:{...i.styles?.toolbar,...t.styles?.toolbar},draggable:{...i.styles?.draggable,...t.styles?.draggable},floatingToolbar:{...i.styles?.floatingToolbar,...t.styles?.floatingToolbar},...t.styles}}}function Js(i){return i&&typeof i=="object"}var bt=createContext(null),uo=class{constructor(){C(this,"warnedMethods",new Set);}add(t){this.warn("add",t.name);}remove(t){this.warn("remove",t);}reorder(t){this.warn("reorder",t.join(", "));}warn(t,e){this.warnedMethods.has(t)||(this.warnedMethods.add(t),console.warn(`[luthor-headless] extensionsAPI.${t}("${e}") is not supported at runtime. Pass an updated \`extensions\` array to <Provider /> instead.`));}},ra=new uo;function br(){function i(){let n=useContext(bt);if(!n)throw new Error("useEditor must be used within Provider");return n}function t({children:n,config:o={},extensions:r}){let[s]=useLexicalComposerContext(),a=useMemo(()=>({formatText:(p,b)=>s?.dispatchCommand(FORMAT_TEXT_COMMAND,p)}),[s]),l=useMemo(()=>{if(!s)return {};let p={};for(let b of r)Object.assign(p,b.getCommands(s));return p},[r,s]),d=useMemo(()=>({...a,...l}),[a,l]),{plugins:c,pluginsBefore:u,pluginsAfter:m}=useMemo(()=>{let p=[],b=[];for(let f of r){let y=f.getPlugins?.()||[];(f.config?.position||"before")==="after"?b.push(...y):p.push(...y);}return {plugins:[...p,...b],pluginsBefore:p,pluginsAfter:b}},[r]);useEffect(()=>{if(!s)return;let b=[...r].sort((f,y)=>{let E=f.config?.initPriority??0;return (y.config?.initPriority??0)-E}).map(f=>f.register(s));return ()=>b.forEach(f=>f&&f())},[s,r]);let g=useMemo(()=>{if(!s)return {};let p={};for(let b of r)b.getStateQueries&&Object.assign(p,b.getStateQueries(s));return p},[r,s]),[h,T]=useState(()=>{let p={};return Object.keys(g).forEach(b=>p[b]=false),p});useEffect(()=>{let p=Object.keys(g);T(b=>{let f={};for(let E of p){let N=b[E];f[E]=N??false;}if(Object.keys(b).length!==p.length)return f;for(let E of p)if(b[E]!==f[E])return f;return b});},[g]),useEffect(()=>{if(!s)return;let p=true,b=0,f=async()=>{let N=++b,x=Object.entries(g).map(async([A,V])=>{try{let U=await V();return [A,U]}catch{return [A,false]}}),L=await Promise.all(x);if(!p||N!==b)return;let O=Object.fromEntries(L);T(A=>{let V=A,U=O,G=Object.keys(V),B=Object.keys(U);if(G.length!==B.length)return O;for(let $ of B)if(V[$]!==U[$])return O;return A});};f();let y=s.registerUpdateListener(()=>{f();}),E=r.map(N=>{let v=N;if(typeof v.onStateChange=="function")return v.onStateChange(()=>{f();})}).filter(N=>typeof N=="function");return ()=>{p=false,y(),E.forEach(N=>N());}},[s,g,r]);let w={editor:s,config:o,extensions:r,commands:d,activeStates:h,stateQueries:g,listeners:{registerUpdate:p=>s?.registerUpdateListener(p)||(()=>{}),registerPaste:p=>s?.registerCommand(PASTE_COMMAND,p,COMMAND_PRIORITY_EDITOR)||(()=>{})},export:{toJSON:()=>s?.getEditorState().toJSON()},import:{fromJSON:p=>{if(s&&(typeof p=="string"||typeof p=="object"&&p!==null)){s.setEditorState(s.parseEditorState(p));let b=d;typeof b.rehydrateListStyles=="function"&&queueMicrotask(()=>{b.rehydrateListStyles?.();});}}},lexical:s,extensionsAPI:ra,plugins:c,hasExtension:p=>r.some(b=>b.name===p)};return jsxs(bt.Provider,{value:w,children:[u,n,m]})}function e(n){let o=useMemo(()=>n.extensions.flatMap(a=>a.getNodes?.()||[]),[n.extensions]),r=useMemo(()=>({namespace:"modern-editor",theme:n.config?.theme||je,onError:s=>{console.error("Lexical error:",s);},nodes:o}),[n.config?.theme,o]);return jsx(LexicalComposer,{initialConfig:r,children:jsx(t,{...n})})}return {Provider:e,useEditor:i}}var ia=br(),sa=ia.Provider,Ie=()=>{let i=useContext(bt);if(!i)throw new Error("useBaseEditor must be used within Provider");return i};var la=(o=>(o.Toolbar="toolbar",o.Sidebar="sidebar",o.ContextMenu="contextmenu",o.Floating="floating",o))(la||{});var k=class{constructor(t,e=["toolbar"]){C(this,"name");C(this,"category",["toolbar"]);C(this,"config",{});C(this,"supportedFormats",[]);C(this,"nodeOverrides",{});this.name=t,this.category=e;}configure(t){return this.config={...this.config,...t},this}getNodes(){return []}overrideUI(t){return this}overrideNodeRender(t){return this.nodeOverrides={...this.nodeOverrides,...t},this}getPlugins(){return []}getCommands(t){return {}}getStateQueries(t){return {}}getToolbarItems(t){return []}};function ca(i){return new class extends k{constructor(){super(i.name,i.category||["toolbar"]);C(this,"_plugins",[]);C(this,"_nodes",[]);C(this,"_initialize");i.config&&(this.config={...this.config,...i.config}),this._initialize=i.initialize,i.supportedFormats&&(this.supportedFormats=i.supportedFormats),i.nodes&&(this._nodes=i.nodes),i.plugins&&(this._plugins=i.plugins);}register(e){let n=this._initialize?.(e);return ()=>{typeof n=="function"&&n();}}getNodes(){return this._nodes}getPlugins(){return this._plugins}getCommands(e){return i.commands?i.commands(e):{}}getStateQueries(e){return i.stateQueries?i.stateQueries(e):{}}}}function ua(i){i.update(()=>{$setSelection(null);});}function ma(i,t){let e=t.getAttribute("data-lexical-node-key")?.trim();if(e)return e;let n=null;return i.read(()=>{let o=$getNearestNodeFromDOMNode(t);if($isLinkNode(o)){n=o.getKey();return}let r=t.firstChild;if(!r)return;let s=$getNearestNodeFromDOMNode(r);if($isLinkNode(s)){n=s.getKey();return}let a=s?.getParent();a&&$isLinkNode(a)&&(n=a.getKey());}),n}var ie=class extends k{constructor(t){super(t,["toolbar"]),this.supportedFormats=[t];}register(t){let e=t.registerCommand(INSERT_PARAGRAPH_COMMAND,()=>(t.getEditorState().read(()=>{let o=$getSelection();$isRangeSelection(o)&&o.hasFormat(this.name)&&t.dispatchCommand(FORMAT_TEXT_COMMAND,this.name);}),false),1),n=t.registerCommand(INSERT_LINE_BREAK_COMMAND,()=>false,1);return ()=>{e(),n();}}getCommands(t){return {[`toggle${this.name.charAt(0).toUpperCase()+this.name.slice(1)}`]:()=>t.dispatchCommand(FORMAT_TEXT_COMMAND,this.name)}}getStateQueries(t){return {[this.name]:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();$isRangeSelection(n)?e(n.hasFormat(this.name)):e(false);});})}}};var Fe=class{static importDOM(){return {img:()=>({conversion:t=>{try{if(!t||!(t instanceof HTMLImageElement)||!t.src)return null;let e=t,n=e.closest("figure"),o=this.resolveAlignment(e,n),r;if(n){let c=n.querySelector("figcaption");c&&(r=c.textContent||void 0);}let s=e.getAttribute("width"),a=e.getAttribute("height"),l=s?Number(s):void 0,d=a?Number(a):void 0;try{return {node:Ue(e.src,e.alt||"",r,o,e.className||void 0,this.extractStyleObject(e),Number.isFinite(l)?l:void 0,Number.isFinite(d)?d:void 0)}}catch{return null}}catch{return null}},priority:0}),figure:()=>({conversion:t=>{try{if(!t||!(t instanceof HTMLElement)||t.tagName!=="FIGURE")return null;let e=t,n=e.querySelector("img");if(!n||!n.src)return null;let r=e.querySelector("figcaption")?.textContent||void 0,s=this.resolveAlignment(n,e),a=n.getAttribute("width"),l=n.getAttribute("height"),d=a?Number(a):void 0,c=l?Number(l):void 0;try{return {node:Ue(n.src,n.alt||"",r,s,n.className||void 0,this.extractStyleObject(n),Number.isFinite(d)?d:void 0,Number.isFinite(c)?c:void 0)}}catch{return null}}catch{return null}},priority:1})}}static exportDOM(t){let{element:e,after:n}=this.createImageElement(t);return {element:e,after:n}}static exportJSON(t){return {type:"image",version:1,src:t.__src,alt:t.__alt,caption:t.__caption,alignment:t.__alignment,className:t.__className,style:t.__style?this.styleObjectToRecord(t.__style):void 0,width:t.__width,height:t.__height,uploading:t.__uploading}}static importJSON(t){let{src:e,alt:n,caption:o,alignment:r,className:s,style:a,width:l,height:d,uploading:c}=t;if(!e||e.length===0)throw new Error("Cannot import ImageNode with empty src");return Ue(e,n,o,r,s,a?this.recordToStyleObject(a):void 0,l,d,c)}static createImageElement(t){let e=document.createElement("figure"),n=document.createElement("img");switch(n.src=t.__src,n.alt=t.__alt,t.__width&&(n.width=t.__width),t.__height&&(n.height=t.__height),t.__className&&(n.className=t.__className),t.__style&&Object.assign(n.style,t.__style),e.className=`lexical-image align-${t.__alignment}`,t.__alignment){case "left":e.style.textAlign="left";break;case "center":e.style.textAlign="center";break;case "right":e.style.textAlign="right";break;default:e.style.textAlign="left";}if(e.style.margin="1rem 0",e.style.display="block",e.appendChild(n),t.__caption){let o=document.createElement("figcaption");o.textContent=t.__caption,o.style.fontSize="0.9em",o.style.color="#666",o.style.fontStyle="italic",o.style.marginTop="0.5rem",o.style.textAlign="center",e.appendChild(o);}return {element:e,after:o=>o}}static extractStyleObject(t){if(!t||!(t instanceof HTMLElement)||!t.style||!t.style.length)return;let e={};try{for(let n=0;n<t.style.length;n++){let o=t.style.item(n);o&&(e[o]=t.style.getPropertyValue(o));}return Object.keys(e).length>0?e:void 0}catch{return}}static resolveAlignment(t,e){let n=[t,e].filter(Boolean);for(let r of n){if(r.classList.contains("align-left"))return "left";if(r.classList.contains("align-center"))return "center";if(r.classList.contains("align-right"))return "right"}let o=e?.getAttribute("data-align");if(o==="left"||o==="center"||o==="right")return o;for(let r of n){if(r.style.textAlign==="left")return "left";if(r.style.textAlign==="center")return "center";if(r.style.textAlign==="right")return "right";if(r.style.float==="left")return "left";if(r.style.float==="right")return "right"}return "none"}static styleObjectToRecord(t){let e={};for(let[n,o]of Object.entries(t))e[n]=String(o);return e}static recordToStyleObject(t){return {...t}}},{importDOM:tf,exportDOM:nf,importJSON:of,exportJSON:rf}=Fe;var Tr=createCommand("insert-image"),Pr=Ta,fo=true,po=false,Lr=50,wr=50,Rr=2400,kr=2400;function Jt(i,t,e){return Math.min(e,Math.max(t,Math.round(i)))}function va(i,t,e,n){return i&&n&&t&&!e}function Ta({src:i,alt:t,caption:e,alignment:n="none",className:o="",style:r,nodeKey:s,width:a,height:l,resizable:d=true,scaleByRatio:c=false,uploading:u=false}){let[m]=useLexicalComposerContext(),g=useRef(null),h=useRef(null),T=useRef(null),w=useRef(0),p=useRef(0),[b,f]=useState(false),[y,E]=useState(false),[N,v]=useState(()=>m.isEditable()),[x,L]=useState(a||"auto"),[O,A]=useState(l||"auto");useEffect(()=>()=>{i&&i.startsWith("blob:")&&URL.revokeObjectURL(i);},[i]),useEffect(()=>{L(a||"auto"),A(l||"auto"),w.current=typeof a=="number"?a:0,p.current=typeof l=="number"?l:0;},[a,l]),useEffect(()=>()=>{T.current!=null&&window.cancelAnimationFrame(T.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>m.registerEditableListener(I=>{v(I);}),[m]),useEffect(()=>{if(s)return m.registerUpdateListener(({editorState:I})=>{I.read(()=>{let K=$getSelection();if($isNodeSelection(K)){let X=K.getNodes();f(X.some(se=>se.getKey()===s));}else f(false);});})},[m,s]);let V=I=>{N&&(I.preventDefault(),I.stopPropagation(),s&&m.update(()=>{let K=$createNodeSelection();K.add(s),$setSelection(K);}));},U=I=>K=>{if(!N||!g.current||!s)return;K.preventDefault(),K.stopPropagation(),E(true),document.body.style.userSelect="none",document.body.style.cursor=I==="width"?"ew-resize":"ns-resize";let X=K.clientX,se=K.clientY,j=g.current.clientWidth||(typeof x=="number"?x:100),te=g.current.clientHeight||(typeof O=="number"?O:100),Ce=Number.isFinite(j)&&Number.isFinite(te)&&j>0&&te>0?j/te:null;w.current=j,p.current=te;let De=()=>{T.current=null,h.current&&(h.current.style.width=`${w.current}px`),g.current&&(g.current.style.height=`${p.current}px`);},He=Se=>{let we=!!Ce&&(c?!Se.shiftKey:Se.shiftKey),fe=I==="width"?Jt(j+(Se.clientX-X),Lr,Rr):w.current,tt=I==="height"?Jt(te+(Se.clientY-se),wr,kr):p.current;we&&Ce&&(I==="width"?tt=Jt(fe/Ce,wr,kr):fe=Jt(tt*Ce,Lr,Rr)),w.current=fe,p.current=tt,T.current==null&&(T.current=window.requestAnimationFrame(De));},ge=()=>{T.current!=null&&(window.cancelAnimationFrame(T.current),T.current=null),E(false),L(w.current),A(p.current),m.update(()=>{let Se=$getNodeByKey(s);Se instanceof z&&Se.setWidthAndHeight(w.current,p.current);}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",He),document.removeEventListener("mouseup",ge);};document.addEventListener("mousemove",He),document.addEventListener("mouseup",ge);},G={margin:0,display:"block",position:"relative",...r},B={maxWidth:"100%",display:"block",borderRadius:"4px",width:typeof x=="number"?"100%":"auto",height:typeof O=="number"?`${O}px`:O,margin:0},$={fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"},Y=va(N,b,y,d);return jsxs("figure",{className:`lexical-image align-${n} ${o} ${b?"selected":""} ${y?"resizing":""} ${u?"uploading":""}`,style:G,children:[jsxs("div",{ref:h,className:`luthor-media-embed-shell${b?" is-selected":""}${y?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{position:"relative",display:"inline-block",width:x,maxWidth:"100%",cursor:N?"pointer":"default"},onClick:N?V:void 0,children:[jsx("img",{ref:g,src:i,alt:t,style:B}),d?jsxs(Fragment,{children:[jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize image width","aria-hidden":!Y,tabIndex:Y?0:-1,style:{opacity:Y?1:0,pointerEvents:Y?"auto":"none"},onMouseDown:U("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize image height","aria-hidden":!Y,tabIndex:Y?0:-1,style:{opacity:Y?1:0,pointerEvents:Y?"auto":"none"},onMouseDown:U("height")})]}):null]}),e&&jsx("figcaption",{style:$,children:e}),jsx("div",{style:{clear:"both",height:0,fontSize:0}})]})}var z=class i extends DecoratorNode{constructor(e="",n="",o,r="none",s,a,l,d,c,u){super(u);C(this,"__src");C(this,"__alt");C(this,"__caption");C(this,"__alignment");C(this,"__className");C(this,"__style");C(this,"__width");C(this,"__height");C(this,"__uploading");this.__src=e&&e.length>0?e:"",this.__alt=n,this.__caption=o,this.__alignment=r,this.__className=s,this.__style=a,this.__width=l,this.__height=d,this.__uploading=c;}static getType(){return "image"}static clone(e){return new i(e.__src,e.__alt,e.__caption,e.__alignment,e.__className,e.__style,e.__width,e.__height,e.__uploading,e.__key)}static importDOM(){return Fe.importDOM()}static importJSON(e){return Fe.importJSON(e)}createDOM(e){let n=document.createElement("div"),o=e.theme?.image||"",r=this.__alignment;return n.className=`${o} lexical-image-container align-${r}`.trim(),n.style.display=r==="center"?"block":"inline-block",n.style.float=r==="left"?"left":r==="right"?"right":"none",n.style.margin=r==="center"?"1rem auto":r==="left"?"0 1rem 1rem 0":r==="right"?"0 0 1rem 1rem":"1rem 0",n.style.textAlign=r==="center"?"center":"inherit",n.style.position="relative",n}updateDOM(e,n,o){let r=this.__alignment;if(r!==e.__alignment){let s=o.theme?.image||"";n.className=`${s} lexical-image-container align-${r}`.trim();}return n.style.display=r==="center"?"block":"inline-block",n.style.float=r==="left"?"left":r==="right"?"right":"none",n.style.margin=r==="center"?"1rem auto":r==="left"?"0 1rem 1rem 0":r==="right"?"0 0 1rem 1rem":"1rem 0",n.style.textAlign=r==="center"?"center":"inherit",n.style.position="relative",false}exportDOM(){return Fe.exportDOM(this)}exportJSON(){return Fe.exportJSON(this)}setSrc(e){if(!e||e.length===0){console.warn("Attempted to set empty src on ImageNode");return}let n=this.getWritable();n.__src=e;}setAlt(e){let n=this.getWritable();n.__alt=e;}setCaption(e){let n=this.getWritable();n.__caption=e;}setAlignment(e){let n=this.getWritable();n.__alignment=e;}setClassName(e){let n=this.getWritable();n.__className=e;}setStyle(e){let n=this.getWritable();n.__style=e;}getWidth(){return this.__width}getHeight(){return this.__height}setWidthAndHeight(e,n){let o=this.getWritable();o.__width=e,o.__height=n;}isInline(){return false}isBlockElement(){return true}canBeEmpty(){return false}decorate(){if(!this.__src||this.__src.length===0)return console.error("\u274C No src provided to ImageNode"),jsx("div",{style:{color:"red",border:"1px solid red",padding:"10px",backgroundColor:"#ffe6e6"},children:"Image Error: No source URL provided"});try{return jsx(Pr,{src:this.__src,alt:this.__alt,caption:this.__caption,alignment:this.__alignment,className:this.__className,style:this.__style,nodeKey:this.getKey(),width:this.__width,height:this.__height,resizable:fo,scaleByRatio:po,uploading:this.__uploading})}catch(e){return console.error("\u274C Error rendering ImageNode:",e),jsxs("div",{style:{color:"red",border:"1px solid red",padding:"10px",backgroundColor:"#ffe6e6"},children:["Image Error: ",String(e)]})}}};function Ue(i,t,e,n="none",o,r,s,a,l){if(!i||i.length===0)throw new Error("Cannot create ImageNode with empty src");return new z(i,t,e,n,o,r,s,a,l)}var Gt=class extends k{constructor(){super("image",["toolbar"]);C(this,"recentImages",new Set);C(this,"lastSelectedImageNodeKey",null);this.config={...this.config,resizable:true,scaleByRatio:false,pasteListener:{insert:true,replace:true},debug:false,forceUpload:false},fo=true,po=false;}configure(e){e.customRenderer&&(Pr=e.customRenderer),e.uploadHandler&&(this.config.uploadHandler=e.uploadHandler),e.defaultAlignment&&(this.config.defaultAlignment=e.defaultAlignment),e.classNames&&(this.config.classNames=e.classNames),e.styles&&(this.config.styles=e.styles),this.config.pasteListener={insert:e.pasteListener?.insert??this.config.pasteListener?.insert??true,replace:e.pasteListener?.replace??this.config.pasteListener?.replace??true},this.config.debug=e.debug??this.config.debug??false;let n={...this.config,...e,resizable:e.resizable??this.config.resizable??true,scaleByRatio:e.scaleByRatio??this.config.scaleByRatio??false};return this.config=n,fo=n.resizable??true,po=n.scaleByRatio??false,this}register(e){let n=e.registerUpdateListener(({editorState:l})=>{l.read(()=>{let d=$getSelection();if(!$isNodeSelection(d))return;let c=d.getNodes().find(u=>u instanceof z);c&&(this.lastSelectedImageNodeKey=c.getKey());});}),o=e.registerCommand(Tr,l=>(e.update(()=>{try{let d=l.src||(l.file?URL.createObjectURL(l.file):"");if(!d)throw new Error("No src for image");if(this.recentImages.has(d))return !0;this.recentImages.add(d),setTimeout(()=>this.recentImages.delete(d),1e3);let c=!1;l.file&&this.config.uploadHandler&&this.config.forceUpload&&(c=!0,this.config.uploadHandler(l.file).then(g=>{e.update(()=>{let h=$getNodeByKey(u.getKey());h instanceof z&&(h.setSrc(g),h.__uploading=!1);});}).catch(g=>{console.error("Upload failed:",g),e.update(()=>{let h=$getNodeByKey(u.getKey());h instanceof z&&(h.__uploading=!1);});}));let u=Ue(d,l.alt,l.caption,l.alignment||this.config.defaultAlignment||"none",l.className,l.style,void 0,void 0,c),m=$getSelection();if($isRangeSelection(m))m.insertNodes([u]);else {let g=$createParagraphNode();g.append(u),$getRoot().append(g);}}catch(d){console.error("\u274C Insertion error:",d);}}),true),COMMAND_PRIORITY_EDITOR),r=e.registerCommand(KEY_DELETE_COMMAND,()=>{let l=$getSelection();if($isNodeSelection(l)){let d=l.getNodes();if(d.some(c=>c instanceof z))return e.update(()=>{d.forEach(c=>c.remove());}),true}return false},COMMAND_PRIORITY_EDITOR),s=e.registerCommand(KEY_BACKSPACE_COMMAND,()=>{let l=$getSelection();if($isNodeSelection(l)){let d=l.getNodes();if(d.some(c=>c instanceof z))return e.update(()=>{d.forEach(c=>c.remove());}),true}return false},COMMAND_PRIORITY_EDITOR),a=()=>{};if(this.config.pasteListener?.insert||this.config.pasteListener?.replace){let l=this.config.debug?console.log:()=>{};a=e.registerCommand(PASTE_COMMAND,d=>{let c=d.clipboardData?.items;if(!c)return false;let u=false,m=Array.from(c).some(g=>g.type==="text/html");for(let g of c)if(g.type.startsWith("image/")){if(m)continue;d.preventDefault();let h=g.getAsFile();if(!h)continue;l("\u{1F4CB} Pasting image:",h.name),(this.config.uploadHandler&&this.config.forceUpload?this.config.uploadHandler(h).catch(w=>(console.error("Upload failed:",w),URL.createObjectURL(h))):Promise.resolve(URL.createObjectURL(h))).then(w=>{if(this.recentImages.has(w)){l("\u{1F6AB} Duplicate paste image src detected, skipping:",w);return}this.recentImages.add(w),setTimeout(()=>this.recentImages.delete(w),1e3);let p=false,b;this.config.uploadHandler&&this.config.forceUpload&&h&&(p=true,this.config.uploadHandler(h).then(f=>{e.update(()=>{let y=$getNodeByKey(b.getKey());y instanceof z&&(y.setSrc(f),y.__uploading=false);});}).catch(f=>{console.error("Upload failed:",f),e.update(()=>{let y=$getNodeByKey(b.getKey());y instanceof z&&(y.__uploading=false);});})),e.update(()=>{let f=$getSelection(),y=h.name||"Pasted image";if($isNodeSelection(f)&&this.config.pasteListener?.replace){let N=f.getNodes().find(v=>v instanceof z);if(N){l("\u{1F504} Replacing selected image src"),N.setSrc(w),N.__uploading=p,u=true;return}}this.config.pasteListener?.insert&&(l("\u2795 Inserting new pasted image"),b=Ue(w,y,void 0,"none",void 0,void 0,void 0,void 0,p),$isRangeSelection(f)?f.insertNodes([b]):$getRoot().append($createParagraphNode().append(b)),u=true);});});break}return u},COMMAND_PRIORITY_NORMAL);}return ()=>{n(),o(),r(),s(),a();}}getNodes(){return [z]}getCommands(e){return {insertImage:n=>{e.dispatchCommand(Tr,n);},setImageAlignment:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof z&&s.setAlignment(n);}});},setImageCaption:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof z&&s.setCaption(n);return}if(this.lastSelectedImageNodeKey){let r=$getNodeByKey(this.lastSelectedImageNodeKey);r instanceof z?r.setCaption(n):this.lastSelectedImageNodeKey=null;}});},getImageCaption:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes().find(s=>s instanceof z);if(r){n(r.__caption??"");return}}if(this.lastSelectedImageNodeKey){let r=$getNodeByKey(this.lastSelectedImageNodeKey);if(r instanceof z){n(r.__caption??"");return}}n("");});}),setImageClassName:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof z&&s.setClassName(n);}});},setImageStyle:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof z&&s.setStyle(n);}});}}}getStateQueries(e){return {imageSelected:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();n(r.length===1&&r[0]instanceof z);}else n(false);});}),isImageAlignedLeft:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();if(r.length===1&&r[0]instanceof z){n(r[0].__alignment==="left");return}}n(false);});}),isImageAlignedCenter:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();if(r.length===1&&r[0]instanceof z){n(r[0].__alignment==="center");return}}n(false);});}),isImageAlignedRight:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();if(r.length===1&&r[0]instanceof z){n(r[0].__alignment==="right");return}}n(false);});}),isImageAlignedNone:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();if(r.length===1&&r[0]instanceof z){n(r[0].__alignment==="none");return}}n(false);});})}}},La=new Gt,Mr={dependencies:[z],export:i=>{if(!wa(i))return null;let t=i,e=t.__src||"",n=t.__alt||"",o=t.__caption||"",r=t.__alignment||"none";if(!e)return null;let s=`![${n}](${e}`;return o&&(s+=` "${o}"`),s+=")",r!=="none"&&(s+=` <!-- align:${r} -->`),s},regExp:/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)(?:\s*<!--\s*align:(left|center|right)\s*-->)?\s*$/,replace:(i,t,e,n)=>{let[,o,r,s,a]=e;if(!r)return;let l=Ue(r,o||"",s||void 0,a||"none",void 0,void 0,void 0,void 0,false);i.replace(l);},type:"element"};function wa(i){return i instanceof z}function ho(i,t,e){return i&&t&&!e}function bo(i,t,e){return i?t&&!e?"auto":"none":"auto"}function Da(i){let t=i.trim();return /^https?:\/\//i.test(t)?t:`https://${t}`}function Ir(i){try{let t=new URL(Da(i.trim()));return t.protocol!=="http:"&&t.protocol!=="https:"||!t.hostname?null:t}catch{return null}}function ke(i,t,e){return Math.min(e,Math.max(t,Math.round(i)))}function Ha(i){return i==="center"?{margin:"1rem auto",width:"fit-content",maxWidth:"100%"}:i==="left"?{margin:"1rem auto 1rem 0",width:"fit-content",maxWidth:"100%"}:{margin:"1rem 0 1rem auto",width:"fit-content",maxWidth:"100%"}}var vt=240,Tt=140,Lt=1600,wt=1200,J=class i extends DecoratorNode{constructor(e,n){super(n);C(this,"__payload");this.__payload=e;}static getType(){return "iframe-embed"}static clone(e){return new i(e.__payload,e.__key)}static importJSON(e){return new i({src:e.src,width:ke(e.width,vt,Lt),height:ke(e.height,Tt,wt),alignment:e.alignment,title:e.title,caption:e.caption??""})}static importDOM(){let e=n=>{let o=n.querySelector("iframe");if(!o)return {node:null};let r=o.getAttribute("src")??"",s=Number(o.getAttribute("width")??"640"),a=Number(o.getAttribute("height")??"360"),l=n.getAttribute("data-align")??"center",c=n.querySelector("figcaption")?.textContent??n.getAttribute("data-caption")??"";return {node:new i({src:r,width:ke(s,vt,Lt),height:ke(a,Tt,wt),alignment:l,title:o.getAttribute("title")??void 0,caption:c})}};return {div:n=>n.hasAttribute("data-lexical-iframe-embed")||n.hasAttribute("data-iframe-embed")?{conversion:e,priority:4}:null,figure:n=>n.hasAttribute("data-lexical-iframe-embed")||n.hasAttribute("data-iframe-embed")?{conversion:e,priority:4}:null}}createDOM(){let e=document.createElement("div");return e.setAttribute("data-lexical-iframe-embed","true"),e}updateDOM(){return false}exportJSON(){return {type:"iframe-embed",version:1,src:this.__payload.src,width:this.__payload.width,height:this.__payload.height,alignment:this.__payload.alignment,title:this.__payload.title,caption:this.__payload.caption}}exportDOM(){let e=document.createElement("figure");e.setAttribute("data-lexical-iframe-embed","true"),e.setAttribute("data-iframe-embed",""),e.setAttribute("data-align",this.__payload.alignment),e.setAttribute("data-caption",this.__payload.caption??""),e.style.margin="1rem 0";let n=document.createElement("iframe");if(n.setAttribute("src",this.__payload.src),n.setAttribute("width",String(this.__payload.width)),n.setAttribute("height",String(this.__payload.height)),n.setAttribute("title",this.__payload.title??"Embedded content"),n.setAttribute("loading","lazy"),n.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),n.setAttribute("allowfullscreen","true"),n.style.border="0",e.appendChild(n),this.__payload.caption){let o=document.createElement("figcaption");o.textContent=this.__payload.caption,e.appendChild(o);}return {element:e}}getPayload(){return this.getLatest().__payload}setPayload(e){let n=this.getWritable();n.__payload={...n.__payload,...e};}decorate(){return jsx(Fa,{nodeKey:this.__key,payload:this.__payload})}isInline(){return false}isKeyboardSelectable(){return true}};function Fa({nodeKey:i,payload:t}){let[e]=useLexicalComposerContext(),[n,o]=useState(()=>e.isEditable()),[r,s]=useState(false),[a,l]=useState(false),[d,c]=useState(t.width),[u,m]=useState(t.height),g=useRef(t.width),h=useRef(t.height),T=useRef(null),w=useRef(null),p=useRef(null);useEffect(()=>{c(t.width),m(t.height),g.current=t.width,h.current=t.height;},[t.width,t.height]),useEffect(()=>()=>{p.current!=null&&window.cancelAnimationFrame(p.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>e.registerEditableListener(x=>{o(x);}),[e]),useEffect(()=>e.registerUpdateListener(({editorState:x})=>{x.read(()=>{let L=$getSelection();if(!$isNodeSelection(L)){s(false);return}let O=L.getNodes().some(A=>A.getKey()===i);s(O);});}),[e,i]);let b=x=>{e.update(()=>{let L=$getNodeByKey(i);L instanceof J&&L.setPayload(x);});},f=x=>{x.preventDefault(),x.stopPropagation(),e.update(()=>{let L=$createNodeSelection();L.add(i),$setSelection(L);});},y=x=>L=>{if(L.preventDefault(),L.stopPropagation(),!T.current)return;let A=L.clientX,V=L.clientY,U=d,G=u;document.body.style.userSelect="none",document.body.style.cursor=x==="width"?"ew-resize":"ns-resize",l(true);let B=()=>{p.current=null,T.current&&(T.current.style.width=`${g.current}px`),w.current&&(w.current.style.height=`${h.current}px`);},$=I=>{let K=x==="width"?ke(U+(I.clientX-A),vt,Lt):g.current,X=x==="height"?ke(G+(I.clientY-V),Tt,wt):h.current;g.current=K,h.current=X,p.current==null&&(p.current=window.requestAnimationFrame(B));},Y=()=>{p.current!=null&&(window.cancelAnimationFrame(p.current),p.current=null),l(false),c(g.current),m(h.current),b({width:g.current,height:h.current}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",$),document.removeEventListener("mouseup",Y);};document.addEventListener("mousemove",$),document.addEventListener("mouseup",Y);},E=useMemo(()=>Ha(t.alignment),[t.alignment]),N=useMemo(()=>({marginTop:"0.5rem",textAlign:"center",color:"#666",fontSize:"0.9em",fontStyle:"italic"}),[]),v=ho(n,r,a);return jsxs("div",{style:E,children:[jsxs("div",{ref:T,className:`luthor-media-embed-shell${r?" is-selected":""}${a?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{width:d,maxWidth:"100%"},onClick:n?f:void 0,children:[jsx("iframe",{ref:w,src:t.src,title:t.title??"Embedded content",loading:"lazy",referrerPolicy:"strict-origin-when-cross-origin",allowFullScreen:true,style:{width:"100%",height:`${u}px`,border:"0",display:"block",pointerEvents:bo(n,r,a)}}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize iframe width","aria-hidden":!v,tabIndex:v?0:-1,style:{opacity:v?1:0,pointerEvents:v?"auto":"none"},onMouseDown:y("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize iframe height","aria-hidden":!v,tabIndex:v?0:-1,style:{opacity:v?1:0,pointerEvents:v?"auto":"none"},onMouseDown:y("height")})]}),t.caption?jsx("figcaption",{style:N,children:t.caption}):null]})}var en=class extends k{constructor(t){super("iframeEmbed",["toolbar"]),this.config={defaultWidth:640,defaultHeight:360,defaultAlignment:"center",...t};}register(t){return ()=>{}}getNodes(){return [J]}getPlugins(){return []}getCommands(t){return {insertIframeEmbed:(e,n,o,r)=>{let s=Ir(e);s&&t.update(()=>{let a=new J({src:s.toString(),width:ke(n??this.config.defaultWidth??640,vt,Lt),height:ke(o??this.config.defaultHeight??360,Tt,wt),alignment:this.config.defaultAlignment??"center",title:r,caption:""}),l=$getSelection();$isRangeSelection(l)?l.insertNodes([a]):$getRoot().append(a);});},setIframeEmbedAlignment:e=>{t.update(()=>{let n=$getSelection();$isNodeSelection(n)&&n.getNodes().forEach(o=>{o instanceof J&&o.setPayload({alignment:e});});});},resizeIframeEmbed:(e,n)=>{t.update(()=>{let o=$getSelection();$isNodeSelection(o)&&o.getNodes().forEach(r=>{r instanceof J&&r.setPayload({width:ke(e,vt,Lt),height:ke(n,Tt,wt)});});});},setIframeEmbedCaption:e=>{t.update(()=>{let n=$getSelection();$isNodeSelection(n)&&n.getNodes().forEach(o=>{o instanceof J&&o.setPayload({caption:e});});});},getIframeEmbedCaption:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isNodeSelection(n)){e("");return}let o=n.getNodes().find(r=>r instanceof J);e(o?.getPayload().caption??"");});}),updateIframeEmbedUrl:e=>{let n=Ir(e);if(!n)return false;let o=false;return t.update(()=>{let r=$getSelection();$isNodeSelection(r)&&r.getNodes().forEach(s=>{s instanceof J&&(s.setPayload({src:n.toString()}),o=true);});}),o},getIframeEmbedUrl:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isNodeSelection(n)){e("");return}let o=n.getNodes().find(r=>r instanceof J);e(o?.getPayload().src??"");});})}}getStateQueries(t){return {isIframeEmbedSelected:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isNodeSelection(n)){e(false);return}e(n.getNodes().some(o=>o instanceof J));});}),isIframeEmbedAlignedLeft:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isNodeSelection(n)){e(false);return}let o=n.getNodes().find(r=>r instanceof J);e(o?.getPayload().alignment==="left");});}),isIframeEmbedAlignedCenter:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isNodeSelection(n)){e(false);return}let o=n.getNodes().find(r=>r instanceof J);e(o?.getPayload().alignment==="center");});}),isIframeEmbedAlignedRight:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isNodeSelection(n)){e(false);return}let o=n.getNodes().find(r=>r instanceof J);e(o?.getPayload().alignment==="right");});})}}},Ba=new en;var ot=240,rt=140,it=1600,st=1200;function be(i,t,e){return Math.min(e,Math.max(t,Math.round(i)))}function Qa(i){return i==="center"?{margin:"1rem auto",width:"fit-content",maxWidth:"100%"}:i==="left"?{margin:"1rem auto 1rem 0",width:"fit-content",maxWidth:"100%"}:{margin:"1rem 0 1rem auto",width:"fit-content",maxWidth:"100%"}}function Va(i){let t=i.trim();return /^https?:\/\//i.test(t)?t:`https://${t}`}function yo(i){try{return new URL(Va(i))}catch{return null}}function Fr(i){return /^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/.*)?$/i.test(i)}function ve(i){return typeof i=="string"&&/^[A-Za-z0-9_-]{3,}$/.test(i)}function Br(i){let t=i.hostname.toLowerCase(),e=i.pathname;if(t==="youtu.be"){let r=e.split("/").filter(Boolean)[0];return ve(r)?{videoId:r}:null}if(e==="/playlist"){let r=i.searchParams.get("list");return ve(r)?{playlistId:r}:null}if(e.startsWith("/shorts/")){let r=e.split("/")[2];return ve(r)?{videoId:r}:null}if(e.startsWith("/embed/")){let r=e.split("/")[2];if(!r)return null;if(r==="videoseries"){let s=i.searchParams.get("list");return ve(s)?{playlistId:s}:null}return ve(r)?{videoId:r}:null}if(e==="/watch"){let r=i.searchParams.get("list"),s=i.searchParams.get("v"),a={};return ve(s)&&(a.videoId=s),ve(r)&&(a.playlistId=r),a.videoId||a.playlistId?a:null}let n=i.searchParams.get("v"),o=i.searchParams.get("list");return ve(n)||ve(o)?{videoId:ve(n)?n:void 0,playlistId:ve(o)?o:void 0}:null}function Wa(i,t){if(!Fr(i))return null;let e=yo(i);if(!e)return null;if(e.pathname.includes("/embed/"))return e.toString();let n=Br(e);if(!n)return null;let o=t.nocookie?"https://www.youtube-nocookie.com/embed/":"https://www.youtube.com/embed/",r="";if(n.playlistId&&!n.videoId?r=`${o}videoseries?list=${encodeURIComponent(n.playlistId)}`:n.videoId&&(r=`${o}${encodeURIComponent(n.videoId)}`),!r)return null;let s=[];if(t.allowFullscreen||s.push("fs=0"),t.autoplay&&s.push("autoplay=1"),t.controls||s.push("controls=0"),t.rel!==1&&s.push(`rel=${t.rel}`),t.start>0&&s.push(`start=${Math.max(0,Math.floor(t.start))}`),s.length===0)return r;let a=r.includes("?")?"&":"?";return `${r}${a}${s.join("&")}`}function Dr(i,t){let e=yo(i);if(!e||!Fr(t))return null;let n=yo(t);if(!n)return null;let o=Br(n);if(!o||!o.videoId&&!o.playlistId)return null;let r=new URLSearchParams(e.search);r.delete("v"),r.delete("list"),r.delete("index"),o.playlistId&&r.set("list",o.playlistId);let a=e.hostname.toLowerCase().includes("youtube-nocookie.com")?"https://www.youtube-nocookie.com":"https://www.youtube.com",l=o.videoId?`/embed/${encodeURIComponent(o.videoId)}`:"/embed/videoseries",d=new URL(`${a}${l}`);return d.search=r.toString(),d.toString()}var Q=class i extends DecoratorNode{constructor(e,n){super(n);C(this,"__payload");this.__payload=e;}static getType(){return "youtube-embed"}static clone(e){return new i(e.__payload,e.__key)}static importJSON(e){return new i({src:e.src,width:be(e.width,ot,it),height:be(e.height,rt,st),alignment:e.alignment,caption:e.caption??"",start:e.start})}static importDOM(){return {div:e=>e.hasAttribute("data-lexical-youtube-embed")||e.hasAttribute("data-youtube-video")?{conversion:o=>{let r=o.querySelector("iframe");if(!r)return {node:null};let s=r.getAttribute("src")??"",a=Number(r.getAttribute("width")??"640"),l=Number(r.getAttribute("height")??"480"),d=o.getAttribute("data-align")??"center",u=o.querySelector("figcaption")?.textContent??o.getAttribute("data-caption")??"",m=Number(r.getAttribute("data-start")??"0");return {node:new i({src:s,width:be(a,ot,it),height:be(l,rt,st),alignment:d,caption:u,start:Number.isFinite(m)?m:0})}},priority:4}:null,figure:e=>e.hasAttribute("data-lexical-youtube-embed")||e.hasAttribute("data-youtube-video")?{conversion:o=>{let r=o.querySelector("iframe");if(!r)return {node:null};let s=r.getAttribute("src")??"",a=Number(r.getAttribute("width")??"640"),l=Number(r.getAttribute("height")??"480"),d=o.getAttribute("data-align")??"center",u=o.querySelector("figcaption")?.textContent??o.getAttribute("data-caption")??"",m=Number(r.getAttribute("data-start")??"0");return {node:new i({src:s,width:be(a,ot,it),height:be(l,rt,st),alignment:d,caption:u,start:Number.isFinite(m)?m:0})}},priority:4}:null}}createDOM(){let e=document.createElement("div");return e.setAttribute("data-lexical-youtube-embed","true"),e}updateDOM(){return false}exportJSON(){return {type:"youtube-embed",version:1,src:this.__payload.src,width:this.__payload.width,height:this.__payload.height,alignment:this.__payload.alignment,caption:this.__payload.caption,start:this.__payload.start}}exportDOM(){let e=document.createElement("figure");e.setAttribute("data-lexical-youtube-embed","true"),e.setAttribute("data-youtube-video",""),e.setAttribute("data-align",this.__payload.alignment),e.setAttribute("data-caption",this.__payload.caption??"");let n=document.createElement("iframe");if(n.setAttribute("src",this.__payload.src),n.setAttribute("width",String(this.__payload.width)),n.setAttribute("height",String(this.__payload.height)),n.setAttribute("title","YouTube video player"),n.setAttribute("loading","lazy"),n.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),n.setAttribute("allow","accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"),n.setAttribute("allowfullscreen","true"),n.style.border="0",this.__payload.start&&this.__payload.start>0&&n.setAttribute("data-start",String(this.__payload.start)),e.appendChild(n),this.__payload.caption){let o=document.createElement("figcaption");o.textContent=this.__payload.caption,e.appendChild(o);}return {element:e}}getPayload(){return this.getLatest().__payload}setPayload(e){let n=this.getWritable();n.__payload={...n.__payload,...e};}decorate(){return jsx(qa,{nodeKey:this.__key,payload:this.__payload})}isInline(){return false}isKeyboardSelectable(){return true}};function qa({nodeKey:i,payload:t}){let[e]=useLexicalComposerContext(),[n,o]=useState(()=>e.isEditable()),[r,s]=useState(false),[a,l]=useState(false),[d,c]=useState(t.width),[u,m]=useState(t.height),g=useRef(t.width),h=useRef(t.height),T=useRef(null),w=useRef(null),p=useRef(null);useEffect(()=>{c(t.width),m(t.height),g.current=t.width,h.current=t.height;},[t.width,t.height]),useEffect(()=>()=>{p.current!=null&&window.cancelAnimationFrame(p.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>e.registerEditableListener(x=>{o(x);}),[e]),useEffect(()=>e.registerUpdateListener(({editorState:x})=>{x.read(()=>{let L=$getSelection();if(!$isNodeSelection(L)){s(false);return}let O=L.getNodes().some(A=>A.getKey()===i);s(O);});}),[e,i]);let b=x=>{e.update(()=>{let L=$getNodeByKey(i);L instanceof Q&&L.setPayload(x);});},f=x=>{x.preventDefault(),x.stopPropagation(),e.update(()=>{let L=$createNodeSelection();L.add(i),$setSelection(L);});},y=x=>L=>{if(L.preventDefault(),L.stopPropagation(),!T.current)return;let A=L.clientX,V=L.clientY,U=d,G=u;document.body.style.userSelect="none",document.body.style.cursor=x==="width"?"ew-resize":"ns-resize",l(true);let B=()=>{p.current=null,T.current&&(T.current.style.width=`${g.current}px`),w.current&&(w.current.style.height=`${h.current}px`);},$=I=>{let K=x==="width"?be(U+(I.clientX-A),ot,it):g.current,X=x==="height"?be(G+(I.clientY-V),rt,st):h.current;g.current=K,h.current=X,p.current==null&&(p.current=window.requestAnimationFrame(B));},Y=()=>{p.current!=null&&(window.cancelAnimationFrame(p.current),p.current=null),l(false),c(g.current),m(h.current),b({width:g.current,height:h.current}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",$),document.removeEventListener("mouseup",Y);};document.addEventListener("mousemove",$),document.addEventListener("mouseup",Y);},E=useMemo(()=>Qa(t.alignment),[t.alignment]),N=ho(n,r,a),v=useMemo(()=>({fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"}),[]);return jsxs("div",{style:E,children:[jsxs("div",{ref:T,className:`luthor-media-embed-shell${r?" is-selected":""}${a?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{width:d,maxWidth:"100%"},onClick:n?f:void 0,children:[jsx("iframe",{ref:w,src:t.src,title:"YouTube video player",loading:"lazy",referrerPolicy:"strict-origin-when-cross-origin",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share",allowFullScreen:true,style:{width:"100%",height:`${u}px`,border:"0",display:"block",pointerEvents:bo(n,r,a)}}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize YouTube embed width","aria-hidden":!N,tabIndex:N?0:-1,style:{opacity:N?1:0,pointerEvents:N?"auto":"none"},onMouseDown:y("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize YouTube embed height","aria-hidden":!N,tabIndex:N?0:-1,style:{opacity:N?1:0,pointerEvents:N?"auto":"none"},onMouseDown:y("height")})]}),t.caption?jsx("figcaption",{style:v,children:t.caption}):null]})}var nn=class extends k{constructor(e){super("youtubeEmbed",["toolbar"]);C(this,"lastSelectedYouTubeNodeKey",null);this.config={defaultWidth:640,defaultHeight:480,defaultAlignment:"center",allowFullscreen:true,autoplay:false,controls:true,nocookie:true,rel:1,...e};}register(e){return e.registerUpdateListener(({editorState:n})=>{n.read(()=>{let o=$getSelection();if(!$isNodeSelection(o))return;let r=o.getNodes().find(s=>s instanceof Q);r&&(this.lastSelectedYouTubeNodeKey=r.getKey());});})}getNodes(){return [Q]}getPlugins(){return []}getCommands(e){return {insertYouTubeEmbed:(n,o,r,s)=>{let a=Wa(n,{allowFullscreen:this.config.allowFullscreen??true,autoplay:this.config.autoplay??false,controls:this.config.controls??true,nocookie:this.config.nocookie??true,rel:this.config.rel??1,start:Math.max(0,Math.floor(s??0))});a&&e.update(()=>{let l=new Q({src:a,width:be(o??this.config.defaultWidth??640,ot,it),height:be(r??this.config.defaultHeight??480,rt,st),alignment:this.config.defaultAlignment??"center",caption:"",start:s}),d=$getSelection();$isRangeSelection(d)?d.insertNodes([l]):$getRoot().append(l);});},setYouTubeEmbedAlignment:n=>{e.update(()=>{let o=$getSelection();$isNodeSelection(o)&&o.getNodes().forEach(r=>{r instanceof Q&&r.setPayload({alignment:n});});});},resizeYouTubeEmbed:(n,o)=>{e.update(()=>{let r=$getSelection();$isNodeSelection(r)&&r.getNodes().forEach(s=>{s instanceof Q&&s.setPayload({width:be(n,ot,it),height:be(o,rt,st)});});});},setYouTubeEmbedCaption:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){o.getNodes().forEach(r=>{r instanceof Q&&r.setPayload({caption:n});});return}if(this.lastSelectedYouTubeNodeKey){let r=$getNodeByKey(this.lastSelectedYouTubeNodeKey);r instanceof Q?r.setPayload({caption:n}):this.lastSelectedYouTubeNodeKey=null;}});},getYouTubeEmbedCaption:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes().find(s=>s instanceof Q);if(r){n(r.getPayload().caption??"");return}}if(this.lastSelectedYouTubeNodeKey){let r=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(r instanceof Q){n(r.getPayload().caption??"");return}}n("");});}),updateYouTubeEmbedUrl:n=>{let o=false;return e.update(()=>{let r=$getSelection();if($isNodeSelection(r)){r.getNodes().forEach(s=>{if(s instanceof Q){let a=Dr(s.getPayload().src,n);if(!a)return;s.setPayload({src:a}),o=true;}});return}if(this.lastSelectedYouTubeNodeKey){let s=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(s instanceof Q){let a=Dr(s.getPayload().src,n);a&&(s.setPayload({src:a}),o=true);}else this.lastSelectedYouTubeNodeKey=null;}}),o},getYouTubeEmbedUrl:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes().find(s=>s instanceof Q);if(r){n(r.getPayload().src??"");return}}if(this.lastSelectedYouTubeNodeKey){let r=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(r instanceof Q){n(r.getPayload().src??"");return}}n("");});})}}getStateQueries(e){return {isYouTubeEmbedSelected:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){n(false);return}n(o.getNodes().some(r=>r instanceof Q));});}),isYouTubeEmbedAlignedLeft:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){n(false);return}let r=o.getNodes().find(s=>s instanceof Q);n(r?.getPayload().alignment==="left");});}),isYouTubeEmbedAlignedCenter:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){n(false);return}let r=o.getNodes().find(s=>s instanceof Q);n(r?.getPayload().alignment==="center");});}),isYouTubeEmbedAlignedRight:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){n(false);return}let r=o.getNodes().find(s=>s instanceof Q);n(r?.getPayload().alignment==="right");});})}}},Ja=new nn;var Xa="luthor:meta";var Ga=/<!--\s*luthor:meta\s+v(\d+)\s+({[\s\S]*?})\s*-->/g;function Pe(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function at(i){return i===void 0?i:JSON.parse(JSON.stringify(i))}function xo(i){return {type:"text",version:1,text:i,detail:0,format:0,mode:"normal",style:""}}function Eo(i){return {type:"paragraph",version:1,format:"",indent:0,direction:null,children:[xo(i)]}}function Za(i){return {type:"listitem",version:1,value:1,checked:null,indent:0,direction:null,format:"",children:[xo(i)]}}function el(i,t){return `[Unsupported ${t} preserved in ${i} metadata]`}function zr(i,t,e){let n=t.length>0?t.join("."):"root";return `${i}:${n}:${e}`}function tl(i,t){return i==="root"||i==="quote"?Eo(t):i==="list"?Za(t):i==="paragraph"||i==="heading"||i==="listitem"||i==="link"||i==="autolink"||i==="code"||i==="code-highlight"?xo(t):Eo(t)}function $r(i,t,e,n,o,r){let s=[];for(let[a,l]of i.entries()){if(!Pe(l))continue;let d=[...e,a],c=typeof l.type=="string"?l.type:"";if(!o.has(c)){let m=el(n,c||"node"),g={id:zr(c||"node",d,r.length+1),type:c||"node",path:d,node:at(l),fallback:m};r.push(g),s.push(tl(t,m));continue}let u={...l};Array.isArray(l.children)&&(u.children=$r(l.children,c,d,n,o,r)),s.push(u);}return s}function nl(){return {type:"root",version:1,format:"",indent:0,direction:null,children:[Eo("")]}}function jr(i){let t=typeof i=="string"?JSON.parse(i):i;if(!Pe(t)||!Pe(t.root))return {root:nl()};let e=t.root,n=Array.isArray(e.children)?e.children:[];return {root:{...e,type:"root",children:n}}}function ol(i,t,e){if(t.length===0)return false;let n=i;for(let r of t.slice(0,-1)){if(!Array.isArray(n.children)||r<0||r>=n.children.length)return false;let s=n.children[r];if(!Pe(s))return false;n=s;}let o=t[t.length-1];return typeof o!="number"||!Array.isArray(n.children)||o<0?false:o<n.children.length?(n.children[o]=at(e),true):o===n.children.length?(n.children.push(at(e)),true):false}function rl(i,t){if(t.length===0)return i;let e=i;for(let n of t){if(!Array.isArray(e.children)||n<0||n>=e.children.length)return null;let o=e.children[n];if(!Pe(o))return null;e=o;}return e}function Kr(i,t){for(let[e,n]of Object.entries(t)){if(e==="__luthorTextFormatExtra"){let o=typeof n=="number"?n:Number(n);if(!Number.isFinite(o)||o===0)continue;let r=typeof i.format=="number"?i.format:Number(i.format??0);i.format=Number.isFinite(r)?r|o:o;continue}if(Pe(n)&&Pe(i[e])){Kr(i[e],n);continue}i[e]=at(n);}}function il(i,t,e){let n=rl(i,t);return n?(Kr(n,e),true):false}function Ot(i,t){let e=jr(i),n=Array.isArray(e.root.children)?e.root.children:[],o=[],r=$r(n,"root",[],t.mode,t.supportedNodeTypes,o);return {document:{root:{...e.root,type:"root",children:r}},envelopes:o}}function It(i,t){if(t.length===0)return i;let n=t.map(o=>{let r=JSON.stringify(o);return `<!-- ${Xa} v1 ${r} -->`}).join(`
1
+ import Vt,{createContext,createElement,useRef,useState,useEffect,useMemo,useCallback,useContext}from'react';import {LexicalComposer}from'@lexical/react/LexicalComposer';import {useLexicalComposerContext}from'@lexical/react/LexicalComposerContext';import {createCommand,$getSelection,$isNodeSelection,$getNodeByKey,$isRangeSelection,$createParagraphNode,$getRoot,COMMAND_PRIORITY_EDITOR,KEY_DELETE_COMMAND,KEY_BACKSPACE_COMMAND,PASTE_COMMAND,COMMAND_PRIORITY_NORMAL,DecoratorNode,$createTextNode,KEY_ENTER_COMMAND,$isTextNode,$isParagraphNode,$isRootOrShadowRoot,COMMAND_PRIORITY_LOW,$isElementNode,KEY_SPACE_COMMAND,INDENT_CONTENT_COMMAND,OUTDENT_CONTENT_COMMAND,KEY_TAB_COMMAND,$nodesOfType,INSERT_PARAGRAPH_COMMAND,ParagraphNode,FORMAT_ELEMENT_COMMAND,CAN_UNDO_COMMAND,CAN_REDO_COMMAND,CLEAR_HISTORY_COMMAND,REDO_COMMAND,UNDO_COMMAND,INSERT_LINE_BREAK_COMMAND,FORMAT_TEXT_COMMAND,$getNearestNodeFromDOMNode,$createNodeSelection,$setSelection,createEditor,TextNode,LineBreakNode,TabNode,ElementNode,IS_BOLD,IS_ITALIC,IS_STRIKETHROUGH,IS_CODE,IS_HIGHLIGHT,IS_UNDERLINE}from'lexical';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {$createLinkNode,TOGGLE_LINK_COMMAND,$isLinkNode,LinkNode,AutoLinkNode}from'@lexical/link';import {TRANSFORMERS,registerMarkdownShortcuts,$convertFromMarkdownString,$convertToMarkdownString}from'@lexical/markdown';import {ListNode,ListItemNode,$isListNode,INSERT_CHECK_LIST_COMMAND,INSERT_UNORDERED_LIST_COMMAND,INSERT_ORDERED_LIST_COMMAND,$isListItemNode,$getListDepth}from'@lexical/list';import {$isHeadingNode,$isQuoteNode,HeadingNode,QuoteNode,$createQuoteNode,$createHeadingNode}from'@lexical/rich-text';import {CodeNode,CodeHighlightNode,$createCodeNode,$isCodeNode,registerCodeHighlighting,PrismTokenizer,normalizeCodeLang,getCodeLanguageOptions,getCodeLanguages}from'@lexical/code';import {TableNode,TableRowNode,TableCellNode,$isTableNode,$isTableRowNode,$isTableCellNode,$isTableSelection,$deleteTableColumnAtSelection,$deleteTableRowAtSelection,$unmergeCell,$mergeCells,$getTableNodeFromLexicalNodeOrThrow,$getTableColumnIndexFromTableCellNode,TableCellHeaderStates,$getTableRowIndexFromTableCellNode,$insertTableColumnAtSelection,$insertTableRowAtSelection,$createTableNodeWithDimensions,$findCellNode}from'@lexical/table';import {HorizontalRuleNode,$createHorizontalRuleNode,$isHorizontalRuleNode,INSERT_HORIZONTAL_RULE_COMMAND}from'@lexical/react/LexicalHorizontalRuleNode';import {$generateNodesFromDOM,$generateHtmlFromNodes}from'@lexical/html';import {LinkPlugin}from'@lexical/react/LexicalLinkPlugin';import {AutoLinkPlugin}from'@lexical/react/LexicalAutoLinkPlugin';import {ClickableLinkPlugin}from'@lexical/react/LexicalClickableLinkPlugin';import {HorizontalRulePlugin}from'@lexical/react/LexicalHorizontalRulePlugin';import {$patchStyleText,$getSelectionStyleValueForProperty,$setBlocksType}from'@lexical/selection';import {createPortal}from'react-dom';import {TablePlugin}from'@lexical/react/LexicalTablePlugin';import {ListPlugin}from'@lexical/react/LexicalListPlugin';import {CheckListPlugin}from'@lexical/react/LexicalCheckListPlugin';import {HistoryPlugin}from'@lexical/react/LexicalHistoryPlugin';import {renderToStaticMarkup}from'react-dom/server';import {RichTextPlugin}from'@lexical/react/LexicalRichTextPlugin';import {ContentEditable}from'@lexical/react/LexicalContentEditable';var Qs=Object.defineProperty;var Vs=(i,t,e)=>t in i?Qs(i,t,{enumerable:true,configurable:true,writable:true,value:e}):i[t]=e;var x=(i,t,e)=>Vs(i,typeof t!="symbol"?t+"":t,e);var br=["--luthor-bg","--luthor-fg","--luthor-border","--luthor-border-hover","--luthor-border-active","--luthor-accent","--luthor-accent-hover","--luthor-shadow","--luthor-muted","--luthor-muted-fg","--luthor-theme-transition","--luthor-drag-gutter-width","--luthor-line-height-ratio","--luthor-toolbar-bg","--luthor-toolbar-section-border","--luthor-toolbar-button-fg","--luthor-toolbar-button-hover-bg","--luthor-toolbar-button-hover-border","--luthor-toolbar-button-hover-shadow","--luthor-toolbar-button-press-shadow","--luthor-toolbar-button-active-bg","--luthor-toolbar-button-active-border","--luthor-toolbar-button-active-fg","--luthor-toolbar-button-active-shadow","--luthor-toolbar-button-overlay","--luthor-toolbar-button-active-overlay","--luthor-toolbar-color-indicator-border","--luthor-toolbar-highlight-bg","--luthor-quote-bg","--luthor-quote-fg","--luthor-quote-border","--luthor-text-bold-color","--luthor-link-color","--luthor-list-marker-color","--luthor-list-checkbox-color","--luthor-table-border-color","--luthor-table-header-bg","--luthor-hr-color","--luthor-placeholder-color","--luthor-codeblock-bg","--luthor-syntax-comment","--luthor-syntax-keyword","--luthor-syntax-string","--luthor-syntax-number","--luthor-syntax-function","--luthor-syntax-variable","--luthor-floating-bg","--luthor-floating-fg","--luthor-floating-border","--luthor-floating-shadow","--luthor-floating-muted","--luthor-floating-border-hover","--luthor-floating-border-active","--luthor-floating-accent","--luthor-floating-accent-fg","--luthor-preset-bg","--luthor-preset-fg","--luthor-preset-border","--luthor-preset-muted","--luthor-preset-muted-fg","--luthor-preset-accent","--luthor-preset-radius","--luthor-preset-shadow","--luthor-preset-content-padding","--luthor-preset-content-min-height"];function Ws(i){return typeof i=="string"&&i.trim().length>0}function qs(i){if(!i)return;let t={};for(let e of br){let n=i[e];Ws(n)&&(t[e]=n);}return Object.keys(t).length>0?t:void 0}var Ue={text:{bold:"luthor-text-bold",italic:"luthor-text-italic",underline:"luthor-text-underline",strikethrough:"luthor-text-strikethrough",code:"luthor-text-code"},list:{ul:"luthor-list-ul",ol:"luthor-list-ol",listitem:"luthor-list-li",listitemChecked:"luthor-list-item-checked",listitemUnchecked:"luthor-list-item-unchecked",nested:{list:"luthor-list-nested",listitem:"luthor-list-nested-item"}},quote:"luthor-quote",heading:{h1:"luthor-heading-h1",h2:"luthor-heading-h2",h3:"luthor-heading-h3",h4:"luthor-heading-h4",h5:"luthor-heading-h5",h6:"luthor-heading-h6"},paragraph:"luthor-paragraph",link:"luthor-link",image:"lexical-image",hr:"luthor-hr",table:"luthor-table",tableRow:"luthor-table-row",tableCell:"luthor-table-cell",tableCellHeader:"luthor-table-cell-header",code:"luthor-code-block hljs",codeHighlight:{atrule:"hljs-meta luthor-code-atrule",attr:"hljs-attribute luthor-code-attr",boolean:"hljs-literal luthor-code-boolean",builtin:"hljs-built_in luthor-code-builtin",cdata:"hljs-comment luthor-code-cdata",char:"hljs-string luthor-code-char",class:"hljs-type luthor-code-class","class-name":"hljs-title luthor-code-class-name",comment:"hljs-comment luthor-code-comment",constant:"hljs-variable luthor-code-constant",deleted:"hljs-deletion luthor-code-deleted",doctype:"hljs-meta luthor-code-doctype",entity:"hljs-symbol luthor-code-entity",function:"hljs-title luthor-code-function",important:"hljs-emphasis luthor-code-important",inserted:"hljs-addition luthor-code-inserted",keyword:"hljs-keyword luthor-code-keyword",namespace:"hljs-title luthor-code-namespace",number:"hljs-number luthor-code-number",operator:"hljs-operator luthor-code-operator",prolog:"hljs-meta luthor-code-prolog",property:"hljs-property luthor-code-property",punctuation:"hljs-punctuation luthor-code-punctuation",regex:"hljs-regexp luthor-code-regex",selector:"hljs-selector-tag luthor-code-selector",string:"hljs-string luthor-code-string",symbol:"hljs-symbol luthor-code-symbol",tag:"hljs-tag luthor-code-tag",url:"hljs-link luthor-code-url",variable:"hljs-variable luthor-code-variable"},toolbar:{button:"luthor-toolbar-button",buttonActive:"luthor-toolbar-button-active",buttonDisabled:"luthor-toolbar-button-disabled",group:"luthor-toolbar-group"},container:"luthor-editor-container",wrapper:"luthor-editor-wrapper",editor:"luthor-editor",contentEditable:"luthor-content-editable",contextMenu:{container:"luthor-context-menu",item:"luthor-context-menu-item",itemDisabled:"luthor-context-menu-item-disabled"},draggable:{handle:"luthor-draggable-handle",handleActive:"luthor-draggable-handle-active",handleHover:"luthor-draggable-handle-hover",handleDragging:"luthor-draggable-handle-dragging",blockDragging:"luthor-draggable-block-dragging opacity-50 transition-opacity duration-200",dropIndicator:"luthor-draggable-drop-indicator",upButton:"luthor-draggable-up-button",downButton:"luthor-draggable-down-button",blockIsDragging:"luthor-draggable-block-is-dragging",buttonStack:"luthor-draggable-button-stack"},floatingToolbar:{container:"luthor-floating-toolbar",button:"luthor-floating-toolbar-button",buttonActive:"luthor-floating-toolbar-button-active"},richText:{contentEditable:"luthor-content-editable",placeholder:"luthor-placeholder"}};function Js(i,t){return {...i,...t,text:{...i.text,...t.text},list:{...i.list,...t.list,nested:{...i.list?.nested,...t.list?.nested}},heading:{...i.heading,...t.heading},codeHighlight:{...i.codeHighlight,...t.codeHighlight},toolbar:{...i.toolbar,...t.toolbar},draggable:{...i.draggable,...t.draggable,styles:{...i.draggable?.styles,...t.draggable?.styles}},floatingToolbar:{...i.floatingToolbar,...t.floatingToolbar,styles:{...i.floatingToolbar?.styles,...t.floatingToolbar?.styles}},richText:{...i.richText,...t.richText},styles:{toolbar:{...i.styles?.toolbar,...t.styles?.toolbar},draggable:{...i.styles?.draggable,...t.styles?.draggable},floatingToolbar:{...i.styles?.floatingToolbar,...t.styles?.floatingToolbar},...t.styles}}}function Xs(i){return i&&typeof i=="object"}var Et=createContext(null),po=class{constructor(){x(this,"warnedMethods",new Set);}add(t){this.warn("add",t.name);}remove(t){this.warn("remove",t);}reorder(t){this.warn("reorder",t.join(", "));}warn(t,e){this.warnedMethods.has(t)||(this.warnedMethods.add(t),console.warn(`[luthor-headless] extensionsAPI.${t}("${e}") is not supported at runtime. Pass an updated \`extensions\` array to <Provider /> instead.`));}},ia=new po;function xr(){function i(){let n=useContext(Et);if(!n)throw new Error("useEditor must be used within Provider");return n}function t({children:n,config:o={},extensions:r}){let[s]=useLexicalComposerContext(),a=useMemo(()=>({formatText:(b,h)=>s?.dispatchCommand(FORMAT_TEXT_COMMAND,b)}),[s]),l=useMemo(()=>{if(!s)return {};let b={};for(let h of r)Object.assign(b,h.getCommands(s));return b},[r,s]),c=useMemo(()=>({...a,...l}),[a,l]),{plugins:d,pluginsBefore:u,pluginsAfter:m}=useMemo(()=>{let b=[],h=[];for(let N of r){let f=N.getPlugins?.()||[];(N.config?.position||"before")==="after"?h.push(...f):b.push(...f);}return {plugins:[...b,...h],pluginsBefore:b,pluginsAfter:h}},[r]);useEffect(()=>{if(!s)return;let h=[...r].sort((N,f)=>{let y=N.config?.initPriority??0;return (f.config?.initPriority??0)-y}).map(N=>N.register(s));return ()=>h.forEach(N=>N&&N())},[s,r]);let g=useMemo(()=>{if(!s)return {};let b={};for(let h of r)h.getStateQueries&&Object.assign(b,h.getStateQueries(s));return b},[r,s]),[p,T]=useState(()=>{let b={};return Object.keys(g).forEach(h=>b[h]=false),b});useEffect(()=>{let b=Object.keys(g);T(h=>{let N={};for(let y of b){let S=h[y];N[y]=S??false;}if(Object.keys(h).length!==b.length)return N;for(let y of b)if(h[y]!==N[y])return N;return h});},[g]),useEffect(()=>{if(!s)return;let b=true,h=0,N=async()=>{let S=++h,E=Object.entries(g).map(async([A,F])=>{try{let Q=await F();return [A,Q]}catch{return [A,false]}}),v=await Promise.all(E);if(!b||S!==h)return;let M=Object.fromEntries(v);T(A=>{let F=A,Q=M,te=Object.keys(F),B=Object.keys(Q);if(te.length!==B.length)return M;for(let z of B)if(F[z]!==Q[z])return M;return A});};N();let f=s.registerUpdateListener(()=>{N();}),y=r.map(S=>{let L=S;if(typeof L.onStateChange=="function")return L.onStateChange(()=>{N();})}).filter(S=>typeof S=="function");return ()=>{b=false,f(),y.forEach(S=>S());}},[s,g,r]);let w={editor:s,config:o,extensions:r,commands:c,activeStates:p,stateQueries:g,listeners:{registerUpdate:b=>s?.registerUpdateListener(b)||(()=>{}),registerPaste:b=>s?.registerCommand(PASTE_COMMAND,b,COMMAND_PRIORITY_EDITOR)||(()=>{})},export:{toJSON:()=>s?.getEditorState().toJSON()},import:{fromJSON:b=>{if(s&&(typeof b=="string"||typeof b=="object"&&b!==null)){s.setEditorState(s.parseEditorState(b));let h=c;typeof h.rehydrateListStyles=="function"&&queueMicrotask(()=>{h.rehydrateListStyles?.();});}}},lexical:s,extensionsAPI:ia,plugins:d,hasExtension:b=>r.some(h=>h.name===b)};return jsxs(Et.Provider,{value:w,children:[u,n,m]})}function e(n){let o=useMemo(()=>n.extensions.flatMap(a=>a.getNodes?.()||[]),[n.extensions]),r=useMemo(()=>({namespace:"modern-editor",theme:n.config?.theme||Ue,onError:s=>{console.error("Lexical error:",s);},nodes:o}),[n.config?.theme,o]);return jsx(LexicalComposer,{initialConfig:r,children:jsx(t,{...n})})}return {Provider:e,useEditor:i}}var sa=xr(),aa=sa.Provider,Ae=()=>{let i=useContext(Et);if(!i)throw new Error("useBaseEditor must be used within Provider");return i};var ca=(o=>(o.Toolbar="toolbar",o.Sidebar="sidebar",o.ContextMenu="contextmenu",o.Floating="floating",o))(ca||{});var k=class{constructor(t,e=["toolbar"]){x(this,"name");x(this,"category",["toolbar"]);x(this,"config",{});x(this,"supportedFormats",[]);x(this,"nodeOverrides",{});this.name=t,this.category=e;}configure(t){return this.config={...this.config,...t},this}getNodes(){return []}overrideUI(t){return this}overrideNodeRender(t){return this.nodeOverrides={...this.nodeOverrides,...t},this}getPlugins(){return []}getCommands(t){return {}}getStateQueries(t){return {}}getToolbarItems(t){return []}};function da(i){return new class extends k{constructor(){super(i.name,i.category||["toolbar"]);x(this,"_plugins",[]);x(this,"_nodes",[]);x(this,"_initialize");i.config&&(this.config={...this.config,...i.config}),this._initialize=i.initialize,i.supportedFormats&&(this.supportedFormats=i.supportedFormats),i.nodes&&(this._nodes=i.nodes),i.plugins&&(this._plugins=i.plugins);}register(e){let n=this._initialize?.(e);return ()=>{typeof n=="function"&&n();}}getNodes(){return this._nodes}getPlugins(){return this._plugins}getCommands(e){return i.commands?i.commands(e):{}}getStateQueries(e){return i.stateQueries?i.stateQueries(e):{}}}}function ma(i){i.update(()=>{$setSelection(null);});}function ga(i,t){let e=t.getAttribute("data-lexical-node-key")?.trim();if(e)return e;let n=null;return i.read(()=>{let o=$getNearestNodeFromDOMNode(t);if($isLinkNode(o)){n=o.getKey();return}let r=t.firstChild;if(!r)return;let s=$getNearestNodeFromDOMNode(r);if($isLinkNode(s)){n=s.getKey();return}let a=s?.getParent();a&&$isLinkNode(a)&&(n=a.getKey());}),n}var ie=class extends k{constructor(t){super(t,["toolbar"]),this.supportedFormats=[t];}register(t){let e=t.registerCommand(INSERT_PARAGRAPH_COMMAND,()=>(t.getEditorState().read(()=>{let o=$getSelection();$isRangeSelection(o)&&o.hasFormat(this.name)&&t.dispatchCommand(FORMAT_TEXT_COMMAND,this.name);}),false),1),n=t.registerCommand(INSERT_LINE_BREAK_COMMAND,()=>false,1);return ()=>{e(),n();}}getCommands(t){return {[`toggle${this.name.charAt(0).toUpperCase()+this.name.slice(1)}`]:()=>t.dispatchCommand(FORMAT_TEXT_COMMAND,this.name)}}getStateQueries(t){return {[this.name]:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();$isRangeSelection(n)?e(n.hasFormat(this.name)):e(false);});})}}};var Be=class{static importDOM(){return {img:()=>({conversion:t=>{try{if(!t||!(t instanceof HTMLImageElement)||!t.src)return null;let e=t,n=e.closest("figure"),o=this.resolveAlignment(e,n),r;if(n){let d=n.querySelector("figcaption");d&&(r=d.textContent||void 0);}let s=e.getAttribute("width"),a=e.getAttribute("height"),l=s?Number(s):void 0,c=a?Number(a):void 0;try{return {node:Qe(e.src,e.alt||"",r,o,e.className||void 0,this.extractStyleObject(e),Number.isFinite(l)?l:void 0,Number.isFinite(c)?c:void 0)}}catch{return null}}catch{return null}},priority:0}),figure:()=>({conversion:t=>{try{if(!t||!(t instanceof HTMLElement)||t.tagName!=="FIGURE")return null;let e=t,n=e.querySelector("img");if(!n||!n.src)return null;let r=e.querySelector("figcaption")?.textContent||void 0,s=this.resolveAlignment(n,e),a=n.getAttribute("width"),l=n.getAttribute("height"),c=a?Number(a):void 0,d=l?Number(l):void 0;try{return {node:Qe(n.src,n.alt||"",r,s,n.className||void 0,this.extractStyleObject(n),Number.isFinite(c)?c:void 0,Number.isFinite(d)?d:void 0)}}catch{return null}}catch{return null}},priority:1})}}static exportDOM(t){let{element:e,after:n}=this.createImageElement(t);return {element:e,after:n}}static exportJSON(t){return {type:"image",version:1,src:t.__src,alt:t.__alt,caption:t.__caption,alignment:t.__alignment,className:t.__className,style:t.__style?this.styleObjectToRecord(t.__style):void 0,width:t.__width,height:t.__height,uploading:t.__uploading}}static importJSON(t){let{src:e,alt:n,caption:o,alignment:r,className:s,style:a,width:l,height:c,uploading:d}=t;if(!e||e.length===0)throw new Error("Cannot import ImageNode with empty src");return Qe(e,n,o,r,s,a?this.recordToStyleObject(a):void 0,l,c,d)}static createImageElement(t){let e=document.createElement("figure"),n=document.createElement("img");switch(n.src=t.__src,n.alt=t.__alt,t.__width&&(n.width=t.__width),t.__height&&(n.height=t.__height),t.__className&&(n.className=t.__className),t.__style&&Object.assign(n.style,t.__style),e.className=`lexical-image align-${t.__alignment}`,t.__alignment){case "left":e.style.textAlign="left";break;case "center":e.style.textAlign="center";break;case "right":e.style.textAlign="right";break;default:e.style.textAlign="left";}if(e.style.margin="1rem 0",e.style.display="block",e.appendChild(n),t.__caption){let o=document.createElement("figcaption");o.textContent=t.__caption,o.style.fontSize="0.9em",o.style.color="#666",o.style.fontStyle="italic",o.style.marginTop="0.5rem",o.style.textAlign="center",e.appendChild(o);}return {element:e,after:o=>o}}static extractStyleObject(t){if(!t||!(t instanceof HTMLElement)||!t.style||!t.style.length)return;let e={};try{for(let n=0;n<t.style.length;n++){let o=t.style.item(n);o&&(e[o]=t.style.getPropertyValue(o));}return Object.keys(e).length>0?e:void 0}catch{return}}static resolveAlignment(t,e){let n=[t,e].filter(Boolean);for(let r of n){if(r.classList.contains("align-left"))return "left";if(r.classList.contains("align-center"))return "center";if(r.classList.contains("align-right"))return "right"}let o=e?.getAttribute("data-align");if(o==="left"||o==="center"||o==="right")return o;for(let r of n){if(r.style.textAlign==="left")return "left";if(r.style.textAlign==="center")return "center";if(r.style.textAlign==="right")return "right";if(r.style.float==="left")return "left";if(r.style.float==="right")return "right"}return "none"}static styleObjectToRecord(t){let e={};for(let[n,o]of Object.entries(t))e[n]=String(o);return e}static recordToStyleObject(t){return {...t}}},{importDOM:tf,exportDOM:nf,importJSON:of,exportJSON:rf}=Be;var Rr=createCommand("insert-image"),Ir=La,yo=true,Eo=false,kr=50,Mr=50,Pr=2400,Or=2400;function Zt(i,t,e){return Math.min(e,Math.max(t,Math.round(i)))}function Ta(i,t,e,n){return i&&n&&t&&!e}function La({src:i,alt:t,caption:e,alignment:n="none",className:o="",style:r,nodeKey:s,width:a,height:l,resizable:c=true,scaleByRatio:d=false,uploading:u=false}){let[m]=useLexicalComposerContext(),g=useRef(null),p=useRef(null),T=useRef(null),w=useRef(0),b=useRef(0),[h,N]=useState(false),[f,y]=useState(false),[S,L]=useState(()=>m.isEditable()),[E,v]=useState(a||"auto"),[M,A]=useState(l||"auto");useEffect(()=>()=>{i&&i.startsWith("blob:")&&URL.revokeObjectURL(i);},[i]),useEffect(()=>{v(a||"auto"),A(l||"auto"),w.current=typeof a=="number"?a:0,b.current=typeof l=="number"?l:0;},[a,l]),useEffect(()=>()=>{T.current!=null&&window.cancelAnimationFrame(T.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>m.registerEditableListener(I=>{L(I);}),[m]),useEffect(()=>{if(s)return m.registerUpdateListener(({editorState:I})=>{I.read(()=>{let j=$getSelection();if($isNodeSelection(j)){let Y=j.getNodes();N(Y.some(le=>le.getKey()===s));}else N(false);});})},[m,s]);let F=I=>{S&&(I.preventDefault(),I.stopPropagation(),s&&m.update(()=>{let j=$createNodeSelection();j.add(s),$setSelection(j);}));},Q=I=>j=>{if(!S||!g.current||!s)return;j.preventDefault(),j.stopPropagation(),y(true),document.body.style.userSelect="none",document.body.style.cursor=I==="width"?"ew-resize":"ns-resize";let Y=j.clientX,le=j.clientY,J=g.current.clientWidth||(typeof E=="number"?E:100),X=g.current.clientHeight||(typeof M=="number"?M:100),Se=Number.isFinite(J)&&Number.isFinite(X)&&J>0&&X>0?J/X:null;w.current=J,b.current=X;let Oe=()=>{T.current=null,p.current&&(p.current.style.width=`${w.current}px`),g.current&&(g.current.style.height=`${b.current}px`);},Ie=me=>{let pe=!!Se&&(d?!me.shiftKey:me.shiftKey),ue=I==="width"?Zt(J+(me.clientX-Y),kr,Pr):w.current,Ke=I==="height"?Zt(X+(me.clientY-le),Mr,Or):b.current;pe&&Se&&(I==="width"?Ke=Zt(ue/Se,Mr,Or):ue=Zt(Ke*Se,kr,Pr)),w.current=ue,b.current=Ke,T.current==null&&(T.current=window.requestAnimationFrame(Oe));},_e=()=>{T.current!=null&&(window.cancelAnimationFrame(T.current),T.current=null),y(false),v(w.current),A(b.current),m.update(()=>{let me=$getNodeByKey(s);me instanceof U&&me.setWidthAndHeight(w.current,b.current);}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",Ie),document.removeEventListener("mouseup",_e);};document.addEventListener("mousemove",Ie),document.addEventListener("mouseup",_e);},te={margin:0,display:"block",position:"relative",...r},B={maxWidth:"100%",display:"block",borderRadius:"4px",width:typeof E=="number"?"100%":"auto",height:typeof M=="number"?`${M}px`:M,margin:0},z={fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"},K=Ta(S,h,f,c);return jsxs("figure",{className:`lexical-image align-${n} ${o} ${h?"selected":""} ${f?"resizing":""} ${u?"uploading":""}`,style:te,children:[jsxs("div",{ref:p,className:`luthor-media-embed-shell${h?" is-selected":""}${f?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{position:"relative",display:"inline-block",width:E,maxWidth:"100%",cursor:S?"pointer":"default"},onClick:S?F:void 0,children:[jsx("img",{ref:g,src:i,alt:t,style:B}),c?jsxs(Fragment,{children:[jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize image width","aria-hidden":!K,tabIndex:K?0:-1,style:{opacity:K?1:0,pointerEvents:K?"auto":"none"},onMouseDown:Q("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize image height","aria-hidden":!K,tabIndex:K?0:-1,style:{opacity:K?1:0,pointerEvents:K?"auto":"none"},onMouseDown:Q("height")})]}):null]}),e&&jsx("figcaption",{style:z,children:e}),jsx("div",{style:{clear:"both",height:0,fontSize:0}})]})}var U=class i extends DecoratorNode{constructor(e="",n="",o,r="none",s,a,l,c,d,u){super(u);x(this,"__src");x(this,"__alt");x(this,"__caption");x(this,"__alignment");x(this,"__className");x(this,"__style");x(this,"__width");x(this,"__height");x(this,"__uploading");this.__src=e&&e.length>0?e:"",this.__alt=n,this.__caption=o,this.__alignment=r,this.__className=s,this.__style=a,this.__width=l,this.__height=c,this.__uploading=d;}static getType(){return "image"}static clone(e){return new i(e.__src,e.__alt,e.__caption,e.__alignment,e.__className,e.__style,e.__width,e.__height,e.__uploading,e.__key)}static importDOM(){return Be.importDOM()}static importJSON(e){return Be.importJSON(e)}createDOM(e){let n=document.createElement("div"),o=e.theme?.image||"",r=this.__alignment;return n.className=`${o} lexical-image-container align-${r}`.trim(),n.style.display=r==="center"?"block":"inline-block",n.style.float=r==="left"?"left":r==="right"?"right":"none",n.style.margin=r==="center"?"1rem auto":r==="left"?"0 1rem 1rem 0":r==="right"?"0 0 1rem 1rem":"1rem 0",n.style.textAlign=r==="center"?"center":"inherit",n.style.position="relative",n}updateDOM(e,n,o){let r=this.__alignment;if(r!==e.__alignment){let s=o.theme?.image||"";n.className=`${s} lexical-image-container align-${r}`.trim();}return n.style.display=r==="center"?"block":"inline-block",n.style.float=r==="left"?"left":r==="right"?"right":"none",n.style.margin=r==="center"?"1rem auto":r==="left"?"0 1rem 1rem 0":r==="right"?"0 0 1rem 1rem":"1rem 0",n.style.textAlign=r==="center"?"center":"inherit",n.style.position="relative",false}exportDOM(){return Be.exportDOM(this)}exportJSON(){return Be.exportJSON(this)}setSrc(e){if(!e||e.length===0){console.warn("Attempted to set empty src on ImageNode");return}let n=this.getWritable();n.__src=e;}setAlt(e){let n=this.getWritable();n.__alt=e;}setCaption(e){let n=this.getWritable();n.__caption=e;}setAlignment(e){let n=this.getWritable();n.__alignment=e;}setClassName(e){let n=this.getWritable();n.__className=e;}setStyle(e){let n=this.getWritable();n.__style=e;}getWidth(){return this.__width}getHeight(){return this.__height}setWidthAndHeight(e,n){let o=this.getWritable();o.__width=e,o.__height=n;}isInline(){return false}isBlockElement(){return true}canBeEmpty(){return false}decorate(){if(!this.__src||this.__src.length===0)return console.error("\u274C No src provided to ImageNode"),jsx("div",{style:{color:"red",border:"1px solid red",padding:"10px",backgroundColor:"#ffe6e6"},children:"Image Error: No source URL provided"});try{return jsx(Ir,{src:this.__src,alt:this.__alt,caption:this.__caption,alignment:this.__alignment,className:this.__className,style:this.__style,nodeKey:this.getKey(),width:this.__width,height:this.__height,resizable:yo,scaleByRatio:Eo,uploading:this.__uploading})}catch(e){return console.error("\u274C Error rendering ImageNode:",e),jsxs("div",{style:{color:"red",border:"1px solid red",padding:"10px",backgroundColor:"#ffe6e6"},children:["Image Error: ",String(e)]})}}};function Qe(i,t,e,n="none",o,r,s,a,l){if(!i||i.length===0)throw new Error("Cannot create ImageNode with empty src");return new U(i,t,e,n,o,r,s,a,l)}var tn=class extends k{constructor(){super("image",["toolbar"]);x(this,"recentImages",new Set);x(this,"lastSelectedImageNodeKey",null);this.config={...this.config,resizable:true,scaleByRatio:false,pasteListener:{insert:true,replace:true},debug:false,forceUpload:false},yo=true,Eo=false;}configure(e){e.customRenderer&&(Ir=e.customRenderer),e.uploadHandler&&(this.config.uploadHandler=e.uploadHandler),e.defaultAlignment&&(this.config.defaultAlignment=e.defaultAlignment),e.classNames&&(this.config.classNames=e.classNames),e.styles&&(this.config.styles=e.styles),this.config.pasteListener={insert:e.pasteListener?.insert??this.config.pasteListener?.insert??true,replace:e.pasteListener?.replace??this.config.pasteListener?.replace??true},this.config.debug=e.debug??this.config.debug??false;let n={...this.config,...e,resizable:e.resizable??this.config.resizable??true,scaleByRatio:e.scaleByRatio??this.config.scaleByRatio??false};return this.config=n,yo=n.resizable??true,Eo=n.scaleByRatio??false,this}register(e){let n=e.registerUpdateListener(({editorState:l})=>{l.read(()=>{let c=$getSelection();if(!$isNodeSelection(c))return;let d=c.getNodes().find(u=>u instanceof U);d&&(this.lastSelectedImageNodeKey=d.getKey());});}),o=e.registerCommand(Rr,l=>(e.update(()=>{try{let c=l.src||(l.file?URL.createObjectURL(l.file):"");if(!c)throw new Error("No src for image");if(this.recentImages.has(c))return !0;this.recentImages.add(c),setTimeout(()=>this.recentImages.delete(c),1e3);let d=!1;l.file&&this.config.uploadHandler&&this.config.forceUpload&&(d=!0,this.config.uploadHandler(l.file).then(g=>{e.update(()=>{let p=$getNodeByKey(u.getKey());p instanceof U&&(p.setSrc(g),p.__uploading=!1);});}).catch(g=>{console.error("Upload failed:",g),e.update(()=>{let p=$getNodeByKey(u.getKey());p instanceof U&&(p.__uploading=!1);});}));let u=Qe(c,l.alt,l.caption,l.alignment||this.config.defaultAlignment||"none",l.className,l.style,void 0,void 0,d),m=$getSelection();if($isRangeSelection(m))m.insertNodes([u]);else {let g=$createParagraphNode();g.append(u),$getRoot().append(g);}}catch(c){console.error("\u274C Insertion error:",c);}}),true),COMMAND_PRIORITY_EDITOR),r=e.registerCommand(KEY_DELETE_COMMAND,()=>{let l=$getSelection();if($isNodeSelection(l)){let c=l.getNodes();if(c.some(d=>d instanceof U))return e.update(()=>{c.forEach(d=>d.remove());}),true}return false},COMMAND_PRIORITY_EDITOR),s=e.registerCommand(KEY_BACKSPACE_COMMAND,()=>{let l=$getSelection();if($isNodeSelection(l)){let c=l.getNodes();if(c.some(d=>d instanceof U))return e.update(()=>{c.forEach(d=>d.remove());}),true}return false},COMMAND_PRIORITY_EDITOR),a=()=>{};if(this.config.pasteListener?.insert||this.config.pasteListener?.replace){let l=this.config.debug?console.log:()=>{};a=e.registerCommand(PASTE_COMMAND,c=>{let d=c.clipboardData?.items;if(!d)return false;let u=false,m=Array.from(d).some(g=>g.type==="text/html");for(let g of d)if(g.type.startsWith("image/")){if(m)continue;c.preventDefault();let p=g.getAsFile();if(!p)continue;l("\u{1F4CB} Pasting image:",p.name),(this.config.uploadHandler&&this.config.forceUpload?this.config.uploadHandler(p).catch(w=>(console.error("Upload failed:",w),URL.createObjectURL(p))):Promise.resolve(URL.createObjectURL(p))).then(w=>{if(this.recentImages.has(w)){l("\u{1F6AB} Duplicate paste image src detected, skipping:",w);return}this.recentImages.add(w),setTimeout(()=>this.recentImages.delete(w),1e3);let b=false,h;this.config.uploadHandler&&this.config.forceUpload&&p&&(b=true,this.config.uploadHandler(p).then(N=>{e.update(()=>{let f=$getNodeByKey(h.getKey());f instanceof U&&(f.setSrc(N),f.__uploading=false);});}).catch(N=>{console.error("Upload failed:",N),e.update(()=>{let f=$getNodeByKey(h.getKey());f instanceof U&&(f.__uploading=false);});})),e.update(()=>{let N=$getSelection(),f=p.name||"Pasted image";if($isNodeSelection(N)&&this.config.pasteListener?.replace){let S=N.getNodes().find(L=>L instanceof U);if(S){l("\u{1F504} Replacing selected image src"),S.setSrc(w),S.__uploading=b,u=true;return}}this.config.pasteListener?.insert&&(l("\u2795 Inserting new pasted image"),h=Qe(w,f,void 0,"none",void 0,void 0,void 0,void 0,b),$isRangeSelection(N)?N.insertNodes([h]):$getRoot().append($createParagraphNode().append(h)),u=true);});});break}return u},COMMAND_PRIORITY_NORMAL);}return ()=>{n(),o(),r(),s(),a();}}getNodes(){return [U]}getCommands(e){return {insertImage:n=>{e.dispatchCommand(Rr,n);},setImageAlignment:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof U&&s.setAlignment(n);}});},setImageCaption:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof U&&s.setCaption(n);return}if(this.lastSelectedImageNodeKey){let r=$getNodeByKey(this.lastSelectedImageNodeKey);r instanceof U?r.setCaption(n):this.lastSelectedImageNodeKey=null;}});},getImageCaption:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes().find(s=>s instanceof U);if(r){n(r.__caption??"");return}}if(this.lastSelectedImageNodeKey){let r=$getNodeByKey(this.lastSelectedImageNodeKey);if(r instanceof U){n(r.__caption??"");return}}n("");});}),setImageClassName:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof U&&s.setClassName(n);}});},setImageStyle:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof U&&s.setStyle(n);}});}}}getStateQueries(e){return {imageSelected:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();n(r.length===1&&r[0]instanceof U);}else n(false);});}),isImageAlignedLeft:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();if(r.length===1&&r[0]instanceof U){n(r[0].__alignment==="left");return}}n(false);});}),isImageAlignedCenter:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();if(r.length===1&&r[0]instanceof U){n(r[0].__alignment==="center");return}}n(false);});}),isImageAlignedRight:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();if(r.length===1&&r[0]instanceof U){n(r[0].__alignment==="right");return}}n(false);});}),isImageAlignedNone:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();if(r.length===1&&r[0]instanceof U){n(r[0].__alignment==="none");return}}n(false);});})}}},wa=new tn,_r={dependencies:[U],export:i=>{if(!Ra(i))return null;let t=i,e=t.__src||"",n=t.__alt||"",o=t.__caption||"",r=t.__alignment||"none";if(!e)return null;let s=`![${n}](${e}`;return o&&(s+=` "${o}"`),s+=")",r!=="none"&&(s+=` <!-- align:${r} -->`),s},regExp:/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)(?:\s*<!--\s*align:(left|center|right)\s*-->)?\s*$/,replace:(i,t,e,n)=>{let[,o,r,s,a]=e;if(!r)return;let l=Qe(r,o||"",s||void 0,a||"none",void 0,void 0,void 0,void 0,false);i.replace(l);},type:"element"};function Ra(i){return i instanceof U}function xo(i,t,e){return i&&t&&!e}function Co(i,t,e){return i?t&&!e?"auto":"none":"auto"}function Ha(i){let t=i.trim();return /^https?:\/\//i.test(t)?t:`https://${t}`}function Dr(i){try{let t=new URL(Ha(i.trim()));return t.protocol!=="http:"&&t.protocol!=="https:"||!t.hostname?null:t}catch{return null}}function Re(i,t,e){return Math.min(e,Math.max(t,Math.round(i)))}function Fa(i){return i==="center"?{margin:"1rem auto",width:"fit-content",maxWidth:"100%"}:i==="left"?{margin:"1rem auto 1rem 0",width:"fit-content",maxWidth:"100%"}:{margin:"1rem 0 1rem auto",width:"fit-content",maxWidth:"100%"}}var Lt=240,wt=140,Rt=1600,kt=1200,G=class i extends DecoratorNode{constructor(e,n){super(n);x(this,"__payload");this.__payload=e;}static getType(){return "iframe-embed"}static clone(e){return new i(e.__payload,e.__key)}static importJSON(e){return new i({src:e.src,width:Re(e.width,Lt,Rt),height:Re(e.height,wt,kt),alignment:e.alignment,title:e.title,caption:e.caption??""})}static importDOM(){let e=n=>{let o=n.querySelector("iframe");if(!o)return {node:null};let r=o.getAttribute("src")??"",s=Number(o.getAttribute("width")??"640"),a=Number(o.getAttribute("height")??"360"),l=n.getAttribute("data-align")??"center",d=n.querySelector("figcaption")?.textContent??n.getAttribute("data-caption")??"";return {node:new i({src:r,width:Re(s,Lt,Rt),height:Re(a,wt,kt),alignment:l,title:o.getAttribute("title")??void 0,caption:d})}};return {div:n=>n.hasAttribute("data-lexical-iframe-embed")||n.hasAttribute("data-iframe-embed")?{conversion:e,priority:4}:null,figure:n=>n.hasAttribute("data-lexical-iframe-embed")||n.hasAttribute("data-iframe-embed")?{conversion:e,priority:4}:null}}createDOM(){let e=document.createElement("div");return e.setAttribute("data-lexical-iframe-embed","true"),e}updateDOM(){return false}exportJSON(){return {type:"iframe-embed",version:1,src:this.__payload.src,width:this.__payload.width,height:this.__payload.height,alignment:this.__payload.alignment,title:this.__payload.title,caption:this.__payload.caption}}exportDOM(){let e=document.createElement("figure");e.setAttribute("data-lexical-iframe-embed","true"),e.setAttribute("data-iframe-embed",""),e.setAttribute("data-align",this.__payload.alignment),e.setAttribute("data-caption",this.__payload.caption??""),e.style.margin="1rem 0";let n=document.createElement("iframe");if(n.setAttribute("src",this.__payload.src),n.setAttribute("width",String(this.__payload.width)),n.setAttribute("height",String(this.__payload.height)),n.setAttribute("title",this.__payload.title??"Embedded content"),n.setAttribute("loading","lazy"),n.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),n.setAttribute("allowfullscreen","true"),n.style.border="0",e.appendChild(n),this.__payload.caption){let o=document.createElement("figcaption");o.textContent=this.__payload.caption,e.appendChild(o);}return {element:e}}getPayload(){return this.getLatest().__payload}setPayload(e){let n=this.getWritable();n.__payload={...n.__payload,...e};}decorate(){return jsx(Ba,{nodeKey:this.__key,payload:this.__payload})}isInline(){return false}isKeyboardSelectable(){return true}};function Ba({nodeKey:i,payload:t}){let[e]=useLexicalComposerContext(),[n,o]=useState(()=>e.isEditable()),[r,s]=useState(false),[a,l]=useState(false),[c,d]=useState(t.width),[u,m]=useState(t.height),g=useRef(t.width),p=useRef(t.height),T=useRef(null),w=useRef(null),b=useRef(null);useEffect(()=>{d(t.width),m(t.height),g.current=t.width,p.current=t.height;},[t.width,t.height]),useEffect(()=>()=>{b.current!=null&&window.cancelAnimationFrame(b.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>e.registerEditableListener(E=>{o(E);}),[e]),useEffect(()=>e.registerUpdateListener(({editorState:E})=>{E.read(()=>{let v=$getSelection();if(!$isNodeSelection(v)){s(false);return}let M=v.getNodes().some(A=>A.getKey()===i);s(M);});}),[e,i]);let h=E=>{e.update(()=>{let v=$getNodeByKey(i);v instanceof G&&v.setPayload(E);});},N=E=>{E.preventDefault(),E.stopPropagation(),e.update(()=>{let v=$createNodeSelection();v.add(i),$setSelection(v);});},f=E=>v=>{if(v.preventDefault(),v.stopPropagation(),!T.current)return;let A=v.clientX,F=v.clientY,Q=c,te=u;document.body.style.userSelect="none",document.body.style.cursor=E==="width"?"ew-resize":"ns-resize",l(true);let B=()=>{b.current=null,T.current&&(T.current.style.width=`${g.current}px`),w.current&&(w.current.style.height=`${p.current}px`);},z=I=>{let j=E==="width"?Re(Q+(I.clientX-A),Lt,Rt):g.current,Y=E==="height"?Re(te+(I.clientY-F),wt,kt):p.current;g.current=j,p.current=Y,b.current==null&&(b.current=window.requestAnimationFrame(B));},K=()=>{b.current!=null&&(window.cancelAnimationFrame(b.current),b.current=null),l(false),d(g.current),m(p.current),h({width:g.current,height:p.current}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",z),document.removeEventListener("mouseup",K);};document.addEventListener("mousemove",z),document.addEventListener("mouseup",K);},y=useMemo(()=>Fa(t.alignment),[t.alignment]),S=useMemo(()=>({marginTop:"0.5rem",textAlign:"center",color:"#666",fontSize:"0.9em",fontStyle:"italic"}),[]),L=xo(n,r,a);return jsxs("div",{style:y,children:[jsxs("div",{ref:T,className:`luthor-media-embed-shell${r?" is-selected":""}${a?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{width:c,maxWidth:"100%"},onClick:n?N:void 0,children:[jsx("iframe",{ref:w,src:t.src,title:t.title??"Embedded content",loading:"lazy",referrerPolicy:"strict-origin-when-cross-origin",allowFullScreen:true,style:{width:"100%",height:`${u}px`,border:"0",display:"block",pointerEvents:Co(n,r,a)}}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize iframe width","aria-hidden":!L,tabIndex:L?0:-1,style:{opacity:L?1:0,pointerEvents:L?"auto":"none"},onMouseDown:f("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize iframe height","aria-hidden":!L,tabIndex:L?0:-1,style:{opacity:L?1:0,pointerEvents:L?"auto":"none"},onMouseDown:f("height")})]}),t.caption?jsx("figcaption",{style:S,children:t.caption}):null]})}var on=class extends k{constructor(t){super("iframeEmbed",["toolbar"]),this.config={defaultWidth:640,defaultHeight:360,defaultAlignment:"center",...t};}register(t){return ()=>{}}getNodes(){return [G]}getPlugins(){return []}getCommands(t){return {insertIframeEmbed:(e,n,o,r)=>{let s=Dr(e);s&&t.update(()=>{let a=new G({src:s.toString(),width:Re(n??this.config.defaultWidth??640,Lt,Rt),height:Re(o??this.config.defaultHeight??360,wt,kt),alignment:this.config.defaultAlignment??"center",title:r,caption:""}),l=$getSelection();$isRangeSelection(l)?l.insertNodes([a]):$getRoot().append(a);});},setIframeEmbedAlignment:e=>{t.update(()=>{let n=$getSelection();$isNodeSelection(n)&&n.getNodes().forEach(o=>{o instanceof G&&o.setPayload({alignment:e});});});},resizeIframeEmbed:(e,n)=>{t.update(()=>{let o=$getSelection();$isNodeSelection(o)&&o.getNodes().forEach(r=>{r instanceof G&&r.setPayload({width:Re(e,Lt,Rt),height:Re(n,wt,kt)});});});},setIframeEmbedCaption:e=>{t.update(()=>{let n=$getSelection();$isNodeSelection(n)&&n.getNodes().forEach(o=>{o instanceof G&&o.setPayload({caption:e});});});},getIframeEmbedCaption:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isNodeSelection(n)){e("");return}let o=n.getNodes().find(r=>r instanceof G);e(o?.getPayload().caption??"");});}),updateIframeEmbedUrl:e=>{let n=Dr(e);if(!n)return false;let o=false;return t.update(()=>{let r=$getSelection();$isNodeSelection(r)&&r.getNodes().forEach(s=>{s instanceof G&&(s.setPayload({src:n.toString()}),o=true);});}),o},getIframeEmbedUrl:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isNodeSelection(n)){e("");return}let o=n.getNodes().find(r=>r instanceof G);e(o?.getPayload().src??"");});})}}getStateQueries(t){return {isIframeEmbedSelected:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isNodeSelection(n)){e(false);return}e(n.getNodes().some(o=>o instanceof G));});}),isIframeEmbedAlignedLeft:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isNodeSelection(n)){e(false);return}let o=n.getNodes().find(r=>r instanceof G);e(o?.getPayload().alignment==="left");});}),isIframeEmbedAlignedCenter:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isNodeSelection(n)){e(false);return}let o=n.getNodes().find(r=>r instanceof G);e(o?.getPayload().alignment==="center");});}),isIframeEmbedAlignedRight:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isNodeSelection(n)){e(false);return}let o=n.getNodes().find(r=>r instanceof G);e(o?.getPayload().alignment==="right");});})}}},za=new on;var rt=240,it=140,st=1600,at=1200;function ye(i,t,e){return Math.min(e,Math.max(t,Math.round(i)))}function Va(i){return i==="center"?{margin:"1rem auto",width:"fit-content",maxWidth:"100%"}:i==="left"?{margin:"1rem auto 1rem 0",width:"fit-content",maxWidth:"100%"}:{margin:"1rem 0 1rem auto",width:"fit-content",maxWidth:"100%"}}function Wa(i){let t=i.trim();return /^https?:\/\//i.test(t)?t:`https://${t}`}function So(i){try{return new URL(Wa(i))}catch{return null}}function $r(i){return /^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/.*)?$/i.test(i)}function ve(i){return typeof i=="string"&&/^[A-Za-z0-9_-]{3,}$/.test(i)}function jr(i){let t=i.hostname.toLowerCase(),e=i.pathname;if(t==="youtu.be"){let r=e.split("/").filter(Boolean)[0];return ve(r)?{videoId:r}:null}if(e==="/playlist"){let r=i.searchParams.get("list");return ve(r)?{playlistId:r}:null}if(e.startsWith("/shorts/")){let r=e.split("/")[2];return ve(r)?{videoId:r}:null}if(e.startsWith("/embed/")){let r=e.split("/")[2];if(!r)return null;if(r==="videoseries"){let s=i.searchParams.get("list");return ve(s)?{playlistId:s}:null}return ve(r)?{videoId:r}:null}if(e==="/watch"){let r=i.searchParams.get("list"),s=i.searchParams.get("v"),a={};return ve(s)&&(a.videoId=s),ve(r)&&(a.playlistId=r),a.videoId||a.playlistId?a:null}let n=i.searchParams.get("v"),o=i.searchParams.get("list");return ve(n)||ve(o)?{videoId:ve(n)?n:void 0,playlistId:ve(o)?o:void 0}:null}function qa(i,t){if(!$r(i))return null;let e=So(i);if(!e)return null;if(e.pathname.includes("/embed/"))return e.toString();let n=jr(e);if(!n)return null;let o=t.nocookie?"https://www.youtube-nocookie.com/embed/":"https://www.youtube.com/embed/",r="";if(n.playlistId&&!n.videoId?r=`${o}videoseries?list=${encodeURIComponent(n.playlistId)}`:n.videoId&&(r=`${o}${encodeURIComponent(n.videoId)}`),!r)return null;let s=[];if(t.allowFullscreen||s.push("fs=0"),t.autoplay&&s.push("autoplay=1"),t.controls||s.push("controls=0"),t.rel!==1&&s.push(`rel=${t.rel}`),t.start>0&&s.push(`start=${Math.max(0,Math.floor(t.start))}`),s.length===0)return r;let a=r.includes("?")?"&":"?";return `${r}${a}${s.join("&")}`}function Br(i,t){let e=So(i);if(!e||!$r(t))return null;let n=So(t);if(!n)return null;let o=jr(n);if(!o||!o.videoId&&!o.playlistId)return null;let r=new URLSearchParams(e.search);r.delete("v"),r.delete("list"),r.delete("index"),o.playlistId&&r.set("list",o.playlistId);let a=e.hostname.toLowerCase().includes("youtube-nocookie.com")?"https://www.youtube-nocookie.com":"https://www.youtube.com",l=o.videoId?`/embed/${encodeURIComponent(o.videoId)}`:"/embed/videoseries",c=new URL(`${a}${l}`);return c.search=r.toString(),c.toString()}var V=class i extends DecoratorNode{constructor(e,n){super(n);x(this,"__payload");this.__payload=e;}static getType(){return "youtube-embed"}static clone(e){return new i(e.__payload,e.__key)}static importJSON(e){return new i({src:e.src,width:ye(e.width,rt,st),height:ye(e.height,it,at),alignment:e.alignment,caption:e.caption??"",start:e.start})}static importDOM(){return {div:e=>e.hasAttribute("data-lexical-youtube-embed")||e.hasAttribute("data-youtube-video")?{conversion:o=>{let r=o.querySelector("iframe");if(!r)return {node:null};let s=r.getAttribute("src")??"",a=Number(r.getAttribute("width")??"640"),l=Number(r.getAttribute("height")??"480"),c=o.getAttribute("data-align")??"center",u=o.querySelector("figcaption")?.textContent??o.getAttribute("data-caption")??"",m=Number(r.getAttribute("data-start")??"0");return {node:new i({src:s,width:ye(a,rt,st),height:ye(l,it,at),alignment:c,caption:u,start:Number.isFinite(m)?m:0})}},priority:4}:null,figure:e=>e.hasAttribute("data-lexical-youtube-embed")||e.hasAttribute("data-youtube-video")?{conversion:o=>{let r=o.querySelector("iframe");if(!r)return {node:null};let s=r.getAttribute("src")??"",a=Number(r.getAttribute("width")??"640"),l=Number(r.getAttribute("height")??"480"),c=o.getAttribute("data-align")??"center",u=o.querySelector("figcaption")?.textContent??o.getAttribute("data-caption")??"",m=Number(r.getAttribute("data-start")??"0");return {node:new i({src:s,width:ye(a,rt,st),height:ye(l,it,at),alignment:c,caption:u,start:Number.isFinite(m)?m:0})}},priority:4}:null}}createDOM(){let e=document.createElement("div");return e.setAttribute("data-lexical-youtube-embed","true"),e}updateDOM(){return false}exportJSON(){return {type:"youtube-embed",version:1,src:this.__payload.src,width:this.__payload.width,height:this.__payload.height,alignment:this.__payload.alignment,caption:this.__payload.caption,start:this.__payload.start}}exportDOM(){let e=document.createElement("figure");e.setAttribute("data-lexical-youtube-embed","true"),e.setAttribute("data-youtube-video",""),e.setAttribute("data-align",this.__payload.alignment),e.setAttribute("data-caption",this.__payload.caption??"");let n=document.createElement("iframe");if(n.setAttribute("src",this.__payload.src),n.setAttribute("width",String(this.__payload.width)),n.setAttribute("height",String(this.__payload.height)),n.setAttribute("title","YouTube video player"),n.setAttribute("loading","lazy"),n.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),n.setAttribute("allow","accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"),n.setAttribute("allowfullscreen","true"),n.style.border="0",this.__payload.start&&this.__payload.start>0&&n.setAttribute("data-start",String(this.__payload.start)),e.appendChild(n),this.__payload.caption){let o=document.createElement("figcaption");o.textContent=this.__payload.caption,e.appendChild(o);}return {element:e}}getPayload(){return this.getLatest().__payload}setPayload(e){let n=this.getWritable();n.__payload={...n.__payload,...e};}decorate(){return jsx(Ja,{nodeKey:this.__key,payload:this.__payload})}isInline(){return false}isKeyboardSelectable(){return true}};function Ja({nodeKey:i,payload:t}){let[e]=useLexicalComposerContext(),[n,o]=useState(()=>e.isEditable()),[r,s]=useState(false),[a,l]=useState(false),[c,d]=useState(t.width),[u,m]=useState(t.height),g=useRef(t.width),p=useRef(t.height),T=useRef(null),w=useRef(null),b=useRef(null);useEffect(()=>{d(t.width),m(t.height),g.current=t.width,p.current=t.height;},[t.width,t.height]),useEffect(()=>()=>{b.current!=null&&window.cancelAnimationFrame(b.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>e.registerEditableListener(E=>{o(E);}),[e]),useEffect(()=>e.registerUpdateListener(({editorState:E})=>{E.read(()=>{let v=$getSelection();if(!$isNodeSelection(v)){s(false);return}let M=v.getNodes().some(A=>A.getKey()===i);s(M);});}),[e,i]);let h=E=>{e.update(()=>{let v=$getNodeByKey(i);v instanceof V&&v.setPayload(E);});},N=E=>{E.preventDefault(),E.stopPropagation(),e.update(()=>{let v=$createNodeSelection();v.add(i),$setSelection(v);});},f=E=>v=>{if(v.preventDefault(),v.stopPropagation(),!T.current)return;let A=v.clientX,F=v.clientY,Q=c,te=u;document.body.style.userSelect="none",document.body.style.cursor=E==="width"?"ew-resize":"ns-resize",l(true);let B=()=>{b.current=null,T.current&&(T.current.style.width=`${g.current}px`),w.current&&(w.current.style.height=`${p.current}px`);},z=I=>{let j=E==="width"?ye(Q+(I.clientX-A),rt,st):g.current,Y=E==="height"?ye(te+(I.clientY-F),it,at):p.current;g.current=j,p.current=Y,b.current==null&&(b.current=window.requestAnimationFrame(B));},K=()=>{b.current!=null&&(window.cancelAnimationFrame(b.current),b.current=null),l(false),d(g.current),m(p.current),h({width:g.current,height:p.current}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",z),document.removeEventListener("mouseup",K);};document.addEventListener("mousemove",z),document.addEventListener("mouseup",K);},y=useMemo(()=>Va(t.alignment),[t.alignment]),S=xo(n,r,a),L=useMemo(()=>({fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"}),[]);return jsxs("div",{style:y,children:[jsxs("div",{ref:T,className:`luthor-media-embed-shell${r?" is-selected":""}${a?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{width:c,maxWidth:"100%"},onClick:n?N:void 0,children:[jsx("iframe",{ref:w,src:t.src,title:"YouTube video player",loading:"lazy",referrerPolicy:"strict-origin-when-cross-origin",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share",allowFullScreen:true,style:{width:"100%",height:`${u}px`,border:"0",display:"block",pointerEvents:Co(n,r,a)}}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize YouTube embed width","aria-hidden":!S,tabIndex:S?0:-1,style:{opacity:S?1:0,pointerEvents:S?"auto":"none"},onMouseDown:f("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize YouTube embed height","aria-hidden":!S,tabIndex:S?0:-1,style:{opacity:S?1:0,pointerEvents:S?"auto":"none"},onMouseDown:f("height")})]}),t.caption?jsx("figcaption",{style:L,children:t.caption}):null]})}var sn=class extends k{constructor(e){super("youtubeEmbed",["toolbar"]);x(this,"lastSelectedYouTubeNodeKey",null);this.config={defaultWidth:640,defaultHeight:480,defaultAlignment:"center",allowFullscreen:true,autoplay:false,controls:true,nocookie:true,rel:1,...e};}register(e){return e.registerUpdateListener(({editorState:n})=>{n.read(()=>{let o=$getSelection();if(!$isNodeSelection(o))return;let r=o.getNodes().find(s=>s instanceof V);r&&(this.lastSelectedYouTubeNodeKey=r.getKey());});})}getNodes(){return [V]}getPlugins(){return []}getCommands(e){return {insertYouTubeEmbed:(n,o,r,s)=>{let a=qa(n,{allowFullscreen:this.config.allowFullscreen??true,autoplay:this.config.autoplay??false,controls:this.config.controls??true,nocookie:this.config.nocookie??true,rel:this.config.rel??1,start:Math.max(0,Math.floor(s??0))});a&&e.update(()=>{let l=new V({src:a,width:ye(o??this.config.defaultWidth??640,rt,st),height:ye(r??this.config.defaultHeight??480,it,at),alignment:this.config.defaultAlignment??"center",caption:"",start:s}),c=$getSelection();$isRangeSelection(c)?c.insertNodes([l]):$getRoot().append(l);});},setYouTubeEmbedAlignment:n=>{e.update(()=>{let o=$getSelection();$isNodeSelection(o)&&o.getNodes().forEach(r=>{r instanceof V&&r.setPayload({alignment:n});});});},resizeYouTubeEmbed:(n,o)=>{e.update(()=>{let r=$getSelection();$isNodeSelection(r)&&r.getNodes().forEach(s=>{s instanceof V&&s.setPayload({width:ye(n,rt,st),height:ye(o,it,at)});});});},setYouTubeEmbedCaption:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){o.getNodes().forEach(r=>{r instanceof V&&r.setPayload({caption:n});});return}if(this.lastSelectedYouTubeNodeKey){let r=$getNodeByKey(this.lastSelectedYouTubeNodeKey);r instanceof V?r.setPayload({caption:n}):this.lastSelectedYouTubeNodeKey=null;}});},getYouTubeEmbedCaption:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes().find(s=>s instanceof V);if(r){n(r.getPayload().caption??"");return}}if(this.lastSelectedYouTubeNodeKey){let r=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(r instanceof V){n(r.getPayload().caption??"");return}}n("");});}),updateYouTubeEmbedUrl:n=>{let o=false;return e.update(()=>{let r=$getSelection();if($isNodeSelection(r)){r.getNodes().forEach(s=>{if(s instanceof V){let a=Br(s.getPayload().src,n);if(!a)return;s.setPayload({src:a}),o=true;}});return}if(this.lastSelectedYouTubeNodeKey){let s=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(s instanceof V){let a=Br(s.getPayload().src,n);a&&(s.setPayload({src:a}),o=true);}else this.lastSelectedYouTubeNodeKey=null;}}),o},getYouTubeEmbedUrl:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes().find(s=>s instanceof V);if(r){n(r.getPayload().src??"");return}}if(this.lastSelectedYouTubeNodeKey){let r=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(r instanceof V){n(r.getPayload().src??"");return}}n("");});})}}getStateQueries(e){return {isYouTubeEmbedSelected:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){n(false);return}n(o.getNodes().some(r=>r instanceof V));});}),isYouTubeEmbedAlignedLeft:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){n(false);return}let r=o.getNodes().find(s=>s instanceof V);n(r?.getPayload().alignment==="left");});}),isYouTubeEmbedAlignedCenter:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){n(false);return}let r=o.getNodes().find(s=>s instanceof V);n(r?.getPayload().alignment==="center");});}),isYouTubeEmbedAlignedRight:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){n(false);return}let r=o.getNodes().find(s=>s instanceof V);n(r?.getPayload().alignment==="right");});})}}},Xa=new sn;var Ga="luthor:meta";var Za=/<!--\s*luthor:meta\s+v(\d+)\s+({[\s\S]*?})\s*-->/g;function ke(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function lt(i){return i===void 0?i:JSON.parse(JSON.stringify(i))}function vo(i){return {type:"text",version:1,text:i,detail:0,format:0,mode:"normal",style:""}}function No(i){return {type:"paragraph",version:1,format:"",indent:0,direction:null,children:[vo(i)]}}function el(i){return {type:"listitem",version:1,value:1,checked:null,indent:0,direction:null,format:"",children:[vo(i)]}}function tl(i,t){return `[Unsupported ${t} preserved in ${i} metadata]`}function Kr(i,t,e){let n=t.length>0?t.join("."):"root";return `${i}:${n}:${e}`}function nl(i,t){return i==="root"||i==="quote"?No(t):i==="list"?el(t):i==="paragraph"||i==="heading"||i==="listitem"||i==="link"||i==="autolink"||i==="code"||i==="code-highlight"?vo(t):No(t)}function Ur(i,t,e,n,o,r){let s=[];for(let[a,l]of i.entries()){if(!ke(l))continue;let c=[...e,a],d=typeof l.type=="string"?l.type:"";if(!o.has(d)){let m=tl(n,d||"node"),g={id:Kr(d||"node",c,r.length+1),type:d||"node",path:c,node:lt(l),fallback:m};r.push(g),s.push(nl(t,m));continue}let u={...l};Array.isArray(l.children)&&(u.children=Ur(l.children,d,c,n,o,r)),s.push(u);}return s}function ol(){return {type:"root",version:1,format:"",indent:0,direction:null,children:[No("")]}}function Yr(i){let t=typeof i=="string"?JSON.parse(i):i;if(!ke(t)||!ke(t.root))return {root:ol()};let e=t.root,n=Array.isArray(e.children)?e.children:[];return {root:{...e,type:"root",children:n}}}function rl(i,t,e){if(t.length===0)return false;let n=i;for(let r of t.slice(0,-1)){if(!Array.isArray(n.children)||r<0||r>=n.children.length)return false;let s=n.children[r];if(!ke(s))return false;n=s;}let o=t[t.length-1];return typeof o!="number"||!Array.isArray(n.children)||o<0?false:o<n.children.length?(n.children[o]=lt(e),true):o===n.children.length?(n.children.push(lt(e)),true):false}function il(i,t){if(t.length===0)return i;let e=i;for(let n of t){if(!Array.isArray(e.children)||n<0||n>=e.children.length)return null;let o=e.children[n];if(!ke(o))return null;e=o;}return e}function Qr(i,t){for(let[e,n]of Object.entries(t)){if(e==="__luthorTextFormatExtra"){let o=typeof n=="number"?n:Number(n);if(!Number.isFinite(o)||o===0)continue;let r=typeof i.format=="number"?i.format:Number(i.format??0);i.format=Number.isFinite(r)?r|o:o;continue}if(ke(n)&&ke(i[e])){Qr(i[e],n);continue}i[e]=lt(n);}}function sl(i,t,e){let n=il(i,t);return n?(Qr(n,e),true):false}function _t(i,t){let e=Yr(i),n=Array.isArray(e.root.children)?e.root.children:[],o=[],r=Ur(n,"root",[],t.mode,t.supportedNodeTypes,o);return {document:{root:{...e.root,type:"root",children:r}},envelopes:o}}function At(i,t){if(t.length===0)return i;let n=t.map(o=>{let r=JSON.stringify(o);return `<!-- ${Ga} v1 ${r} -->`}).join(`
2
2
  `);return i?`${i}${i.endsWith(`
3
3
  `)?"":`
4
- `}${n}`:n}function _t(i){let t=[],e=[],n=new RegExp(Ga.source,"g");for(let o of i.matchAll(n)){if(Number.parseInt(o[1]??"",10)!==1){e.push(`Ignoring metadata envelope version v${o[1]??"unknown"}.`);continue}try{let s=JSON.parse(o[2]??"");if(!Pe(s)){e.push("Ignoring metadata envelope with non-object payload.");continue}let a=typeof s.type=="string"?s.type:"",l=typeof s.id=="string"?s.id:"",d=typeof s.fallback=="string"?s.fallback:"",c=s.strategy==="merge"||s.strategy==="replace"?s.strategy:void 0,m=(Array.isArray(s.path)?s.path:[]).filter(h=>Number.isInteger(h)&&h>=0).map(h=>Number(h)),g=Pe(s.node)?s.node:null;if(!l||!a||!g){e.push("Ignoring metadata envelope with missing required fields.");continue}t.push({id:l,type:a,path:m,node:g,fallback:d,strategy:c});}catch{e.push("Ignoring malformed metadata envelope payload.");}}return {content:i.replace(n,"").trimEnd(),envelopes:t,warnings:e}}function At(i,t){if(t.length===0)return i;let e=at(i.root);for(let n of t){if(n.strategy==="merge"){il(e,n.path,n.node);continue}if(ol(e,n.path,n.node))continue;Array.isArray(e.children)||(e.children=[]),e.children.push(at(n.node));}return {...i,root:e}}function sl(i){return Object.keys(i).length>0}function on(i,t){let e=jr(i),n=Array.isArray(e.root.children)?e.root.children:[],o=[],r=(s,a)=>{for(let[l,d]of s.entries()){if(!Pe(d))continue;let c=[...a,l],u=typeof d.type=="string"?d.type:"";if(!u||!t.supportedNodeTypes.has(u))continue;let m=t.extractPatch({mode:t.mode,type:u,path:c,node:d});m&&sl(m)&&o.push({id:zr(u,c,o.length+1),type:u,path:c,node:m,fallback:"",strategy:"merge"}),Array.isArray(d.children)&&r(d.children,c);}};return r(n,[]),o}var Al={dependencies:[HorizontalRuleNode],export:i=>$isHorizontalRuleNode(i)?"---":null,regExp:/^(?:---|___)\s*$/,replace:(i,t,e)=>{i.replace($createHorizontalRuleNode());},type:"element"},Dl={format:["underline"],tag:"++",type:"text-format"};function Jr(i){return i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Xr(i){return i.replace(/\\(["\\])/g,"$1")}function Gr(i){try{let t=JSON.parse(i);if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}catch{return null}return null}var Hl={dependencies:[J],export:i=>{if(!(i instanceof J))return null;let t=i.getPayload(),e=t.caption??"",n=e?` "${Jr(e)}"`:"";return `[iframe](${t.src}${n})`},regExp:/^\[iframe\]\(([^)\s]+)(?:\s+"((?:[^"\\]|\\.)*)")?\)\s*(?:<!--\s*luthor:iframe\s+({[\s\S]*?})\s*-->)?\s*$/,replace:(i,t,e)=>{let[,n,o,r]=e;if(!n)return;let s=typeof o=="string"?Xr(o):"",a=640,l=360,d="center",c;if(typeof r=="string"&&r.length>0){let u=Gr(r);if(u){let m=Number(u.width);Number.isFinite(m)&&(a=m);let g=Number(u.height);Number.isFinite(g)&&(l=g),(u.alignment==="left"||u.alignment==="center"||u.alignment==="right")&&(d=u.alignment),typeof u.title=="string"&&(c=u.title);}}i.replace(new J({src:n,width:a,height:l,alignment:d,title:c,caption:s}));},type:"element"},Fl={dependencies:[Q],export:i=>{if(!(i instanceof Q))return null;let t=i.getPayload(),e=t.caption??"",n=e?` "${Jr(e)}"`:"";return `[youtube](${t.src}${n})`},regExp:/^\[youtube\]\(([^)\s]+)(?:\s+"((?:[^"\\]|\\.)*)")?\)\s*(?:<!--\s*luthor:youtube\s+({[\s\S]*?})\s*-->)?\s*$/,replace:(i,t,e)=>{let[,n,o,r]=e;if(!n)return;let s=typeof o=="string"?Xr(o):"",a=640,l=360,d="center",c=0;if(typeof r=="string"&&r.length>0){let u=Gr(r);if(u){let m=Number(u.width);Number.isFinite(m)&&(a=m);let g=Number(u.height);Number.isFinite(g)&&(l=g),(u.alignment==="left"||u.alignment==="center"||u.alignment==="right")&&(d=u.alignment);let h=Number(u.start);Number.isFinite(h)&&(c=h);}}i.replace(new Q({src:n,width:a,height:l,alignment:d,caption:s,start:c}));},type:"element"},Bl={dependencies:[TableNode,TableRowNode,TableCellNode],export:i=>{if(!$isTableNode(i))return null;let t=i.getChildren();if(t.length===0)return null;let e=[];if(t.forEach(r=>{if(!$isTableRowNode(r))return;let s=[];r.getChildren().forEach(a=>{$isTableCellNode(a)&&s.push(a.getTextContent().trim());}),s.length>0&&e.push(s);}),e.length===0||!e[0])return null;let n=[];n.push(`| ${e[0].join(" | ")} |`);let o=e[0].length||1;n.push(`| ${Array(o).fill("---").join(" | ")} |`);for(let r=1;r<e.length;r+=1){let a=[...e[r]??[]];for(;a.length<o;)a.push("");n.push(`| ${a.join(" | ")} |`);}return n.join(`
5
- `)},regExpStart:/^\|.*\|$/,regExpEnd:{optional:true,regExp:/^$/},replace:(i,t,e,n,o,r)=>{let s=e[0];if(!s)return;let l=[s,...o??[]].filter(g=>typeof g=="string").filter(g=>{let h=g.trim();return h.length>0&&h.includes("|")&&h.split("|").length>1});if(l.length<2)return;let d=[];if(l.forEach(g=>{let h=g.split("|").slice(1,-1).map(T=>T.trim());h.length>0&&d.push(h);}),d.length===0||!d[0])return;let c=d.filter(g=>!g.every(h=>/^:?-+:?$/.test(h)));if(c.length===0)return;let u=$createTableNodeWithDimensions(c.length,Math.max(...c.map(g=>g.length)),false),m=u.getChildren();c.forEach((g,h)=>{let T=m[h];if(!$isTableRowNode(T))return;let w=T.getChildren();g.forEach((p,b)=>{let f=w[b];if(!$isTableCellNode(f))return;f.clear();let y=$createParagraphNode();p&&y.append($createTextNode(p)),f.append(y);});}),i.append(u);},type:"multiline-element"},Zr=[...TRANSFORMERS,Dl,Al,Bl,Mr,Hl,Fl],ei=new Set(["root","paragraph","text","linebreak","tab","heading","quote","list","listitem","link","autolink","code","code-highlight","horizontalrule","image","iframe-embed","youtube-embed","table","tablerow","tablecell"]),zl=IS_BOLD|IS_ITALIC|IS_STRIKETHROUGH|IS_CODE|IS_HIGHLIGHT|IS_UNDERLINE,$l={root:new Set(["type","version","children"]),paragraph:new Set(["type","version","children"]),text:new Set(["type","version","text","format"]),linebreak:new Set(["type","version"]),tab:new Set(["type","version"]),heading:new Set(["type","version","tag","children"]),quote:new Set(["type","version","children"]),list:new Set(["type","version","listType","start","children"]),listitem:new Set(["type","version","value","checked","children"]),link:new Set(["type","version","url","title","children"]),autolink:new Set(["type","version","url","title","children"]),code:new Set(["type","version","language","children"]),"code-highlight":new Set(["type","version","text","highlightType"]),horizontalrule:new Set(["type","version"]),image:new Set(["type","version","src","alt","caption","alignment"]),"iframe-embed":new Set(["type","version","src","caption"]),"youtube-embed":new Set(["type","version","src","caption"]),table:new Set(["type","version","children"]),tablerow:new Set(["type","version","children"]),tablecell:new Set(["type","version","children"])};function jl(i){return i===void 0?i:JSON.parse(JSON.stringify(i))}function Kl(i){return Object.keys(i).length>0}function Ul(i,t){switch(i){case "textFormat":return t===0;case "textStyle":return t==="";case "format":return t===""||t===0;case "indent":return t===0;case "direction":return t===null;case "detail":return t===0;case "mode":return t==="normal";case "style":return t===""||t===null;case "headerState":return t===0;case "colSpan":case "rowSpan":return t===1;case "width":case "height":return t==null;case "backgroundColor":return t===null||t==="";case "verticalAlign":return t==null||t==="";case "rowStriping":return t===false;case "frozenColumnCount":case "frozenRowCount":return t===0;case "colWidths":return Array.isArray(t)&&t.length===0;case "uploading":return t===false||t===void 0;case "title":return t===""||t===null||t===void 0;default:return false}}function Yl(i,t,e){if(Ul(t,e))return true;if(i==="iframe-embed"){if(t==="width")return e===640;if(t==="height")return e===360;if(t==="alignment")return e==="center"}if(i==="youtube-embed"){if(t==="width")return e===640;if(t==="height")return e===360;if(t==="alignment")return e==="center";if(t==="start")return e===0}return false}function Ql(i,t){let e=$l[t];if(!e)return null;let n={};for(let[o,r]of Object.entries(i))if(!(o==="children"||o==="type")){if(t==="text"&&o==="format"&&typeof r=="number"){let s=r&~zl;s!==0&&(n.__luthorTextFormatExtra=s);continue}e.has(o)||r!==void 0&&(Yl(t,o,r)||(n[o]=jl(r)));}return Kl(n)?n:null}function Vl(i){return on(i,{mode:"markdown",supportedNodeTypes:ei,extractPatch:({node:t,type:e})=>Ql(t,e)})}function ti(){return createEditor({namespace:"luthor-markdown-converter",onError:i=>{throw i},nodes:[ParagraphNode,TextNode,LineBreakNode,TabNode,HeadingNode,QuoteNode,ListNode,ListItemNode,LinkNode,AutoLinkNode,CodeNode,CodeHighlightNode,HorizontalRuleNode,z,J,Q,TableNode,TableRowNode,TableCellNode]})}function Wl(i,t){let e=typeof t=="string"?t:JSON.stringify(t??{});return i.parseEditorState(e)}function ql(i){let{content:t,envelopes:e,warnings:n}=_t(i);for(let s of n)console.warn(`[luthor-headless] ${s}`);let o=ti();o.update(()=>{$convertFromMarkdownString(t,Zr);},{discrete:true});let r=o.getEditorState().toJSON();return At(r,e)}function Jl(i){let t=Ot(i,{mode:"markdown",supportedNodeTypes:ei}),e=Vl(i),n=ti(),o=Wl(n,t.document);n.setEditorState(o,{tag:"history-merge"});let r=o.read(()=>$convertToMarkdownString(Zr));return It(r,[...t.envelopes,...e])}var ri=new Set(["root","paragraph","text","linebreak","tab","heading","quote","list","listitem","link","autolink","code","code-highlight","horizontalrule","image","iframe-embed","youtube-embed","table","tablerow","tablecell"]),bc={root:new Set(["type","version","format","indent","direction","children"]),paragraph:new Set(["type","version","format","indent","direction","children"]),text:new Set(["type","version","text","detail","format","mode","style"]),linebreak:new Set(["type","version"]),tab:new Set(["type","version"]),heading:new Set(["type","version","tag","format","indent","direction","children"]),quote:new Set(["type","version","format","indent","direction","children"]),list:new Set(["type","version","listType","start","tag","format","indent","direction","style","children"]),listitem:new Set(["type","version","value","checked","format","indent","direction","style","children"]),link:new Set(["type","version","url","target","rel","title","children"]),autolink:new Set(["type","version","url","target","rel","title","isUnlinked","children"]),code:new Set(["type","version","language","format","indent","direction","children"]),"code-highlight":new Set(["type","version","text","highlightType"]),horizontalrule:new Set(["type","version"]),image:new Set(["type","version","src","alt","caption","alignment","className","style","width","height"]),"iframe-embed":new Set(["type","version","src","width","height","alignment","title","caption"]),"youtube-embed":new Set(["type","version","src","width","height","alignment","caption","start"]),table:new Set(["type","version","format","indent","direction","children","rowStriping","frozenColumnCount","frozenRowCount","colWidths","style"]),tablerow:new Set(["type","version","height","children"]),tablecell:new Set(["type","version","headerState","colSpan","rowSpan","width","backgroundColor","verticalAlign","children"])};function yc(i){return i===void 0?i:JSON.parse(JSON.stringify(i))}function Ec(i){return Object.keys(i).length>0}function xc(i,t){switch(i){case "textFormat":return t===0;case "textStyle":return t==="";case "format":return t===""||t===0;case "indent":return t===0;case "direction":return t===null;case "detail":return t===0;case "mode":return t==="normal";case "style":return t===""||t===null;case "uploading":return t===false||t===void 0;default:return false}}function Cc(i,t){let e=bc[t];if(!e)return null;let n={};for(let[o,r]of Object.entries(i))o==="children"||o==="type"||e.has(o)||r!==void 0&&(xc(o,r)||(n[o]=yc(r)));return Ec(n)?n:null}function Sc(i){return on(i,{mode:"html",supportedNodeTypes:ri,extractPatch:({node:t,type:e})=>Cc(t,e)})}var Nc=new Set(["pre","script","style","textarea"]);function ii(){return createEditor({namespace:"luthor-html-converter",onError:i=>{throw i},nodes:[ParagraphNode,TextNode,LineBreakNode,TabNode,HeadingNode,QuoteNode,ListNode,ListItemNode,LinkNode,AutoLinkNode,CodeNode,CodeHighlightNode,HorizontalRuleNode,z,J,Q,TableNode,TableRowNode,TableCellNode]})}function vc(i,t){let e=typeof t=="string"?t:JSON.stringify(t??{});return i.parseEditorState(e)}function si(){if(typeof document>"u"||typeof window>"u"||typeof DOMParser>"u")throw new Error("HTML conversion requires browser DOM APIs (document/window/DOMParser).")}function ni(i){if(!i)return false;let t=i.getAttribute("style");return t?/\bwhite-space\s*:\s*(pre|pre-wrap|pre-line)\b/i.test(t):false}function Tc(i){let t=i.parentElement;for(;t;){if(Nc.has(t.tagName.toLowerCase()))return true;t=t.parentElement;}return false}function oi(i,t){let e=t==="previous"?i.previousSibling:i.nextSibling;for(;e;){if(e.nodeType!==Node.TEXT_NODE||(e.textContent??"").trim().length>0)return e;e=t==="previous"?e.previousSibling:e.nextSibling;}return null}function Lc(i,t){if(!i||!t||/\s$/.test(i)||/^\s/.test(t))return false;let e=i.at(-1)??"",n=t[0]??"";return !(!e||!n||/^[,.;:!?)]$/.test(n)||/^[([{"']$/.test(e))}function wc(i){let t=Array.from(i.querySelectorAll("[style]"));for(let r of t){if(!ni(r)||r.childNodes.length!==1||r.firstChild?.nodeType!==Node.TEXT_NODE)continue;let s=r.firstChild;/[\r\n]/.test(s.data)&&(s.data=s.data.replace(/^\s*\r?\n\s*/,"").replace(/\r?\n\s*$/,""));}let e=i.createTreeWalker(i.body,NodeFilter.SHOW_TEXT),n=[],o=e.nextNode();for(;o;){let r=o,s=r.data,a=r.parentElement;if(!/^[\s\r\n\t]+$/.test(s)||!/[\r\n]/.test(s)||Tc(r)||ni(a)){o=e.nextNode();continue}let l=oi(r,"previous"),d=oi(r,"next"),c=l?.textContent??"",u=d?.textContent??"";Lc(c,u)?n.push({node:r,replacement:" "}):n.push({node:r,replacement:null}),o=e.nextNode();}for(let r of n)if(r.node.parentNode){if(r.replacement===null){r.node.parentNode.removeChild(r.node);continue}r.node.data=r.replacement;}}function Rc(i){si();let{content:t,envelopes:e,warnings:n}=_t(i);for(let s of n)console.warn(`[luthor-headless] ${s}`);let o=ii();o.update(()=>{let s=new DOMParser().parseFromString(t,"text/html");wc(s);let a=$generateNodesFromDOM(o,s),l=$getRoot();l.clear(),l.append(...a);},{discrete:true});let r=o.getEditorState().toJSON();return At(r,e)}function kc(i){si();let t=Ot(i,{mode:"html",supportedNodeTypes:ri}),e=Sc(i),n=ii(),o=vc(n,t.document);n.setEditorState(o,{tag:"history-merge"});let r=o.read(()=>$generateHtmlFromNodes(n,null));return It(r,[...t.envelopes,...e])}var rn=class extends ie{constructor(){super("bold");}},Pc=new rn;var sn=class extends ie{constructor(){super("italic");}},Mc=new sn;var Oc={format:["underline"],tag:"++",type:"text-format"},an=class extends ie{constructor(){super("underline");}getMarkdownTransformers(){return [Oc]}},Ic=new an;var ln=class extends ie{constructor(){super("strikethrough");}},_c=new ln;var cn=class extends k{constructor(){super("link",["toolbar"]);C(this,"lastSelectedLinkNodeKey",null);this.config={autoLinkText:false,clickableLinks:true,openLinksInNewTab:true,linkSelectedTextOnPaste:true,validateUrl:e=>{try{return new URL(e),!0}catch{return false}}};}register(e){let n=e.registerCommand(PASTE_COMMAND,r=>{let s=r.clipboardData;if(!s)return false;let a=s.getData("text/plain");return a&&this.config.validateUrl(a)&&this.config.autoLinkUrls?(r.preventDefault(),e.update(()=>{let l=$getSelection();if($isRangeSelection(l))if(l.isCollapsed()){let d=$createLinkNode(a);d.append($createTextNode(a)),l.insertNodes([d]);}else if(this.config.linkSelectedTextOnPaste)e.dispatchCommand(TOGGLE_LINK_COMMAND,a);else {l.insertText(a);let d=$getSelection();d&&$isRangeSelection(d)&&d.getNodes()[0]&&e.dispatchCommand(TOGGLE_LINK_COMMAND,a);}}),true):false},3),o=e.registerUpdateListener(({editorState:r})=>{r.read(()=>{let s=this.getSelectedLinkNode();if(s){this.lastSelectedLinkNodeKey=s.getKey();return}if(this.lastSelectedLinkNodeKey){let a=$getNodeByKey(this.lastSelectedLinkNodeKey);$isLinkNode(a)||(this.lastSelectedLinkNodeKey=null);}});});return ()=>{n(),o();}}getNodes(){let e=[LinkNode];return this.config.autoLinkText&&e.push(AutoLinkNode),e}getPlugins(){let e=[];if(e.push(jsx(LinkPlugin,{validateUrl:this.config.validateUrl},"link-plugin")),this.config.clickableLinks!==false&&e.push(jsx(ClickableLinkPlugin,{newTab:this.config.openLinksInNewTab!==false},"clickable-link")),this.config.autoLinkText){let n=o=>{let s=/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_.+~#?&//=]*)/g.exec(o);return s&&this.config.validateUrl(s[0])?{text:s[0],url:s[0],index:s.index,length:s[0].length}:null};e.push(jsx(AutoLinkPlugin,{matchers:[n]},"auto-link"));}return e}getCommands(e){let n=s=>s.trim(),o=s=>s.length>0&&!!this.config.validateUrl?.(s),r=(s,a,l,d)=>{s.setURL(a),typeof l<"u"&&s.setRel(l.trim()||null),typeof d<"u"&&s.setTarget(d.trim()||null);};return {insertLink:(s,a)=>{if(s){let l=n(s);if(!o(l))return;a&&e.update(()=>{let d=$getSelection();d&&d.insertText(a);}),e.dispatchCommand(TOGGLE_LINK_COMMAND,l);}else {let l=prompt("Enter URL:");if(l){let d=n(l);if(!o(d))return;e.dispatchCommand(TOGGLE_LINK_COMMAND,d);}}},updateLink:(s,a,l)=>{let d=n(s);if(!o(d))return false;let c=false;return e.update(()=>{let u=this.getSelectedLinkNode()??this.getCachedLinkNode();if(u){r(u,d,a,l),this.lastSelectedLinkNodeKey=u.getKey(),c=true;return}let m=$getSelection();if(!$isRangeSelection(m)){c=false;return}e.dispatchCommand(TOGGLE_LINK_COMMAND,{url:d,rel:typeof a>"u"?null:a.trim()||null,target:typeof l>"u"?null:l.trim()||null}),c=true;}),c},removeLink:()=>{let s=false;e.update(()=>{let a=this.getSelectedLinkNode()??this.getCachedLinkNode();if(a){let l=a.getChildren();for(let d of l)a.insertBefore(d);a.remove(),this.lastSelectedLinkNodeKey=null,s=true;return}e.dispatchCommand(TOGGLE_LINK_COMMAND,null);}),s||(this.lastSelectedLinkNodeKey=null);},getCurrentLink:()=>new Promise(s=>{e.getEditorState().read(()=>{let a=this.getSelectedLinkNode()??this.getCachedLinkNode();if(!a){s(null);return}s(this.serializeLinkNode(a));});}),getLinkByKey:s=>new Promise(a=>{e.getEditorState().read(()=>{let l=this.getLinkNodeByKey(s);if(!l){a(null);return}a(this.serializeLinkNode(l));});}),updateLinkByKey:(s,a,l,d)=>{let c=n(a);if(!o(c))return false;let u=false;return e.update(()=>{let m=this.getLinkNodeByKey(s);if(!m){u=false;return}r(m,c,l,d),this.lastSelectedLinkNodeKey=m.getKey(),u=true;}),u},removeLinkByKey:s=>{let a=false;return e.update(()=>{let l=this.getLinkNodeByKey(s);if(!l){a=false;return}this.removeLinkNode(l),this.lastSelectedLinkNodeKey=null,a=true;}),a}}}serializeLinkNode(e){return {url:e.getURL(),rel:e.getRel(),target:e.getTarget()}}removeLinkNode(e){let n=e.getChildren();for(let o of n)e.insertBefore(o);e.remove();}getLinkNodeByKey(e){let n=e.trim();if(!n)return null;let o=$getNodeByKey(n);return $isLinkNode(o)?o:null}getSelectedLinkNode(){let e=$getSelection();if(!e||!$isRangeSelection(e))return null;let n=e.anchor.getNode(),o=e.focus.getNode(),r=e.getNodes(),s=[n,o,...r];for(let a of s){if($isLinkNode(a))return a;let l=a.getParent();if(l&&$isLinkNode(l))return l}return null}getCachedLinkNode(){if(!this.lastSelectedLinkNodeKey)return null;let e=$getNodeByKey(this.lastSelectedLinkNodeKey);return $isLinkNode(e)?e:(this.lastSelectedLinkNodeKey=null,null)}getStateQueries(e){return {isLink:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(o&&$isRangeSelection(o)){let s=o.getNodes()[0];if(s){let a=s.getParent();n($isLinkNode(a)||$isLinkNode(s));}else n(false);}else n(false);});}),isTextSelected:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();o&&$isRangeSelection(o)?n(!o.isCollapsed()):n(false);});})}}},Kc=new cn;var Gc={dependencies:[HorizontalRuleNode],export:i=>$isHorizontalRuleNode(i)?"---":null,regExp:/^(?:---|___)\s*$/,replace:(i,t,e,n)=>{let o=$createHorizontalRuleNode();i.replace(o),n||td(o);},type:"element"},Zc=[Gc],ed=/^(?:---|___)$/;function td(i){let t=i.getNextSibling();if(t&&$isParagraphNode(t)){t.selectStart();return}let e=$createParagraphNode();i.insertAfter(e),e.selectStart();}var dn=class extends k{constructor(){super("horizontalRule",["toolbar"]);}register(t){let e=registerMarkdownShortcuts(t,Zc),n=t.registerCommand(KEY_ENTER_COMMAND,o=>{if(o?.shiftKey)return false;let r=false;return t.update(()=>{let s=$getSelection();if(!s||!$isRangeSelection(s)||!s.isCollapsed())return;let a=s.anchor.getNode();if(!$isTextNode(a))return;let l=a.getParent();if(!l||!$isParagraphNode(l))return;let d=l.getParent();if(!$isRootOrShadowRoot(d))return;let c=a.getTextContent().trim();if(!ed.test(c))return;r=true;let u=$createHorizontalRuleNode();l.replace(u),u.selectNext();}),r},COMMAND_PRIORITY_LOW);return ()=>{e(),n();}}getNodes(){return [HorizontalRuleNode]}getPlugins(){return [jsx(HorizontalRulePlugin,{},"horizontal-rule")]}getCommands(t){return {insertHorizontalRule:()=>{t.dispatchCommand(INSERT_HORIZONTAL_RULE_COMMAND,void 0);}}}getStateQueries(t){return {isHorizontalRuleSelected:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(n&&$isRangeSelection(n)){let r=n.getNodes().some(s=>$isHorizontalRuleNode(s));e(r);}else e(false);});})}}},nd=new dn;var pi=[{value:"default",label:"Default",fontFamily:"inherit"},{value:"sans",label:"Sans",fontFamily:"Arial, Helvetica, sans-serif"},{value:"serif",label:"Serif",fontFamily:"Georgia, 'Times New Roman', serif"},{value:"mono",label:"Mono",fontFamily:"'Courier New', Courier, monospace"}],id={value:"default",label:"Default",fontFamily:"inherit"};function fi(i){return i.trim().toLowerCase()}function sd(i){return /^[a-z0-9][a-z0-9-]*$/i.test(i)}function ad(i){let t=new Set,e=[];for(let o of i){let r=o.value.trim(),s=o.label.trim(),a=o.fontFamily.trim();if(!r||!s||!a||!sd(r))continue;let l=fi(r);t.has(l)||(t.add(l),e.push({value:r,label:s,fontFamily:a,cssImportUrl:o.cssImportUrl?.trim()||void 0}));}return e.length===0?pi:e.some(o=>fi(o.value)==="default")?e:[id,...e]}var un=class extends k{constructor(){super("fontFamily",["toolbar"]);C(this,"loadedFontUrls",new Set);this.config={options:pi,cssLoadStrategy:"none",showInToolbar:true,category:["toolbar"]};}register(){if(this.config.cssLoadStrategy==="preload-all")for(let e of this.config.options)this.ensureFontCssLoaded(e);return ()=>{}}configure(e){let n={...e};return e.options&&(n.options=ad(e.options)),super.configure(n)}getCommands(e){return {setFontFamily:n=>{let o=this.findOption(n);o&&(this.ensureFontCssLoaded(o),this.applyFontFamily(e,o.fontFamily));},clearFontFamily:()=>{this.applyFontFamily(e,"");},getCurrentFontFamily:()=>Promise.resolve(this.getCurrentFontFamilyValue(e)),getFontFamilyOptions:()=>this.config.options}}getStateQueries(e){return {hasCustomFontFamily:()=>Promise.resolve(this.hasCustomFontFamily(e))}}applyFontFamily(e,n){e.update(()=>{let o=$getSelection();$isRangeSelection(o)&&$patchStyleText(o,{"font-family":n});});}hasCustomFontFamily(e){let n=false;return e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let r=$getSelectionStyleValueForProperty(o,"font-family","");n=this.normalizeFontValue(r).length>0;}),n}getCurrentFontFamilyValue(e){let n=null;return e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let r=$getSelectionStyleValueForProperty(o,"font-family","");if(!r){n="default";return}let s=this.normalizeFontValue(r);n=this.config.options.find(l=>this.normalizeFontValue(l.value)===s?true:this.normalizeFontValue(l.fontFamily)===s)?.value??null;}),n}findOption(e){let n=this.normalizeFontValue(e);return this.config.options.find(o=>this.normalizeFontValue(o.value)===n)}normalizeFontValue(e){return e?(e.split(",")[0]??"").replace(/['"]/g,"").trim().toLowerCase():""}ensureFontCssLoaded(e){if(this.config.cssLoadStrategy==="none"||!e.cssImportUrl||typeof document>"u")return;let n=e.cssImportUrl,o=encodeURIComponent(n);if(this.loadedFontUrls.has(n))return;if(document.querySelector(`link[data-luthor-font-url="${o}"]`)){this.loadedFontUrls.add(n);return}let s=document.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-luthor-font-url",o),document.head.appendChild(s),this.loadedFontUrls.add(n);}},ld=new un;var yi=[{value:"default",label:"Default",fontSize:"inherit"},{value:"12",label:"12px",fontSize:"12px"},{value:"14",label:"14px",fontSize:"14px"},{value:"16",label:"16px",fontSize:"16px"},{value:"18",label:"18px",fontSize:"18px"},{value:"20",label:"20px",fontSize:"20px"},{value:"24",label:"24px",fontSize:"24px"},{value:"32",label:"32px",fontSize:"32px"}],dd={value:"default",label:"Default",fontSize:"inherit"};function bi(i){return i.trim().toLowerCase()}function ud(i){return /^[a-z0-9][a-z0-9-]*$/i.test(i)}function md(i){let t=new Set,e=[];for(let o of i){let r=String(o.value).trim(),s=String(o.label).trim(),a=String(o.fontSize).trim();if(!r||!s||!a||!ud(r))continue;let l=bi(r);t.has(l)||(t.add(l),e.push({value:r,label:s,fontSize:a}));}return e.length===0?yi:e.some(o=>bi(o.value)==="default")?e:[dd,...e]}var mn=class extends k{constructor(){super("fontSize",["toolbar"]),this.config={options:yi,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}configure(t){let e={...t};return t.options&&(e.options=md(t.options)),super.configure(e)}getCommands(t){return {setFontSize:e=>{let n=this.findOption(e);n&&this.applyFontSize(t,n.fontSize);},clearFontSize:()=>{this.applyFontSize(t,"");},getCurrentFontSize:()=>Promise.resolve(this.getCurrentFontSizeValue(t)),getFontSizeOptions:()=>this.config.options}}getStateQueries(t){return {hasCustomFontSize:()=>Promise.resolve(this.hasCustomFontSize(t))}}applyFontSize(t,e){t.update(()=>{let n=$getSelection();$isRangeSelection(n)&&$patchStyleText(n,{"font-size":e});});}hasCustomFontSize(t){let e=false;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"font-size",""),r=this.normalizeValue(o);e=r.length>0&&r!=="inherit";}),e}getCurrentFontSizeValue(t){let e=null;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"font-size",""),r=this.normalizeValue(o);if(!r||r==="inherit"){e="default";return}e=this.config.options.find(a=>this.normalizeValue(a.value)===r?true:this.normalizeValue(a.fontSize)===r)?.value??null;}),e}findOption(t){let e=this.normalizeValue(t);return this.config.options.find(n=>this.normalizeValue(n.value)===e)}normalizeValue(t){return t.trim().toLowerCase().replace(/\s+/g,"")}},gd=new mn;var xi=[{value:"default",label:"Default",lineHeight:"normal"},{value:"1",label:"1.0",lineHeight:"1"},{value:"1.15",label:"1.15",lineHeight:"1.15"},{value:"1.5",label:"1.5",lineHeight:"1.5"},{value:"1.75",label:"1.75",lineHeight:"1.75"},{value:"2",label:"2.0",lineHeight:"2"}],Po={value:"default",label:"Default",lineHeight:"1.5"},hd=1;function ko(i){return i.trim().toLowerCase()}function bd(i){return ko(i)==="default"?true:fn(i)!==null}function fn(i){let t=i.trim();if(!/^\d*\.?\d+$/.test(t))return null;let e=Number(t);return !Number.isFinite(e)||e<hd?null:e.toString()}function yd(i,t){let e=new Set,n=[];for(let r of i){let s=r.value.trim(),a=r.label.trim(),l=ko(s);if(!s||!a||!bd(s)||e.has(l))continue;if(l==="default"){e.add(l),n.push({value:s,label:a,lineHeight:t});continue}let d=fn(String(r.lineHeight));d&&(e.add(l),n.push({value:s,label:a,lineHeight:d}));}return n.length===0?xi:n.some(r=>ko(r.value)==="default")?n:[{...Po,lineHeight:t},...n]}function Ed(i){return fn(i)??Po.lineHeight}var gn=class extends k{constructor(){super("lineHeight",["toolbar"]),this.config={options:xi,defaultLineHeight:Po.lineHeight,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}configure(t){let e={...t},n=Ed(String(t.defaultLineHeight??this.config.defaultLineHeight));return e.defaultLineHeight=n,t.options&&(e.options=yd(t.options,n)),super.configure(e)}getCommands(t){return {setLineHeight:e=>{let n=this.findOption(e);n&&this.applyLineHeight(t,n.lineHeight);},clearLineHeight:()=>{this.applyLineHeight(t,"");},getCurrentLineHeight:()=>Promise.resolve(this.getCurrentLineHeightValue(t)),getLineHeightOptions:()=>this.config.options}}getStateQueries(t){return {hasCustomLineHeight:()=>Promise.resolve(this.hasCustomLineHeight(t))}}applyLineHeight(t,e){t.update(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=this.getSelectedTopLevelBlocks(n);for(let r of o){let s=this.withStyleProperty(r.getStyle(),"line-height",e);r.setStyle(s);for(let a of r.getAllTextNodes())$isTextNode(a)&&a.setStyle(this.withStyleProperty(a.getStyle(),"line-height",e));}});}getSelectedTopLevelBlocks(t){let e=new Map;for(let n of t.getNodes()){let o=n.getTopLevelElement();!o||!$isElementNode(o)||o.getType()!=="root"&&e.set(o.getKey(),o);}return [...e.values()]}withStyleProperty(t,e,n){let o=new RegExp(`^${e}\\s*:`,"i"),r=t.split(";").map(a=>a.trim()).filter(a=>a.length>0).filter(a=>!o.test(a)),s=n.trim();return s.length>0&&r.push(`${e}: ${s}`),r.join("; ")}hasCustomLineHeight(t){let e=false;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=this.getSelectedBlocksLineHeight(n);if(o==="mixed"){e=true;return}let r=o??$getSelectionStyleValueForProperty(n,"line-height",""),s=this.normalizeValue(r);e=s.length>0&&s!=="normal";}),e}getCurrentLineHeightValue(t){let e=null;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=this.getSelectedBlocksLineHeight(n);if(o==="mixed"){e=null;return}let r=o??$getSelectionStyleValueForProperty(n,"line-height",""),s=this.normalizeValue(r);if(!s||s==="normal"){e="default";return}if(s===this.normalizeValue(this.config.defaultLineHeight)){e="default";return}e=this.config.options.find(l=>this.normalizeValue(l.value)===s?true:this.normalizeValue(l.lineHeight)===s)?.value??null;}),e}getSelectedBlocksLineHeight(t){let e=this.getSelectedTopLevelBlocks(t);if(e.length===0)return null;let n=null,o="";for(let r of e){let s=this.readStyleProperty(r.getStyle(),"line-height"),a=this.normalizeValue(s);if(n===null){n=a,o=s;continue}if(n!==a)return "mixed"}return o}findOption(t){let e=this.normalizeValue(t);return this.config.options.find(n=>this.normalizeValue(n.value)===e)}normalizeValue(t){let e=t.trim().toLowerCase().replace(/\s+/g,"");return fn(e)??e}readStyleProperty(t,e){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return t.match(new RegExp(`(?:^|;)\\s*${n}\\s*:\\s*([^;]+)`,"i"))?.[1]?.trim()??""}},xd=new gn;var Sd=[{value:"default",label:"Default",color:"inherit"},{value:"black",label:"Black",color:"#111827"},{value:"slate",label:"Slate",color:"#334155"},{value:"red",label:"Red",color:"#dc2626"},{value:"orange",label:"Orange",color:"#ea580c"},{value:"green",label:"Green",color:"#16a34a"},{value:"blue",label:"Blue",color:"#2563eb"},{value:"purple",label:"Purple",color:"#7c3aed"}],pn=class extends k{constructor(){super("textColor",["toolbar"]),this.config={options:Sd,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}getCommands(t){return {setTextColor:e=>{let n=this.findOption(e);if(n){this.applyColor(t,n.color);return}this.isValidCssColor(e)&&this.applyColor(t,e);},clearTextColor:()=>{this.applyColor(t,"");},getCurrentTextColor:()=>Promise.resolve(this.getCurrentTextColorValue(t)),getTextColorOptions:()=>this.config.options}}getStateQueries(t){return {hasCustomTextColor:()=>Promise.resolve(this.hasCustomTextColor(t))}}applyColor(t,e){t.update(()=>{let n=$getSelection();$isRangeSelection(n)&&$patchStyleText(n,{color:e});});}hasCustomTextColor(t){let e=false;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"color","");e=this.normalizeValue(o).length>0;}),e}getCurrentTextColorValue(t){let e=null;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"color","");if(!o){e="default";return}let r=this.normalizeValue(o);e=this.config.options.find(a=>this.normalizeValue(a.value)===r?true:this.normalizeValue(a.color)===r)?.value??o;}),e}findOption(t){let e=this.normalizeValue(t);return this.config.options.find(n=>this.normalizeValue(n.value)===e)}normalizeValue(t){return t.trim().toLowerCase().replace(/\s+/g,"")}isValidCssColor(t){let e=t.trim();return e?typeof CSS<"u"&&typeof CSS.supports=="function"?CSS.supports("color",e):/^#([\da-f]{3}|[\da-f]{6})$/i.test(e):false}},Nd=new pn;var Td=[{value:"default",label:"Default",backgroundColor:"transparent"},{value:"yellow",label:"Yellow",backgroundColor:"#fef08a"},{value:"green",label:"Green",backgroundColor:"#bbf7d0"},{value:"blue",label:"Blue",backgroundColor:"#bfdbfe"},{value:"pink",label:"Pink",backgroundColor:"#fbcfe8"},{value:"orange",label:"Orange",backgroundColor:"#fed7aa"},{value:"purple",label:"Purple",backgroundColor:"#ddd6fe"}],hn=class extends k{constructor(){super("textHighlight",["toolbar"]),this.config={options:Td,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}getCommands(t){return {setTextHighlight:e=>{let n=this.findOption(e);if(n){this.applyHighlight(t,n.backgroundColor);return}this.isValidCssColor(e)&&this.applyHighlight(t,e);},clearTextHighlight:()=>{this.applyHighlight(t,"");},getCurrentTextHighlight:()=>Promise.resolve(this.getCurrentTextHighlightValue(t)),getTextHighlightOptions:()=>this.config.options}}getStateQueries(t){return {hasTextHighlight:()=>Promise.resolve(this.hasTextHighlight(t))}}applyHighlight(t,e){t.update(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=this.normalizeValue(e).length>0;$patchStyleText(n,{"background-color":e,"padding-left":o?"0.1em":"","padding-right":o?"0.1em":"","box-decoration-break":o?"clone":"","-webkit-box-decoration-break":o?"clone":""});});}hasTextHighlight(t){let e=false;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"background-color",""),r=this.normalizeValue(o);e=r.length>0&&r!=="transparent";}),e}getCurrentTextHighlightValue(t){let e=null;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"background-color",""),r=this.normalizeValue(o);if(!r||r==="transparent"){e="default";return}e=this.config.options.find(a=>this.normalizeValue(a.value)===r?true:this.normalizeValue(a.backgroundColor)===r)?.value??o;}),e}findOption(t){let e=this.normalizeValue(t);return this.config.options.find(n=>this.normalizeValue(n.value)===e)}normalizeValue(t){return t.trim().toLowerCase().replace(/\s+/g,"")}isValidCssColor(t){let e=t.trim();return e?typeof CSS<"u"&&typeof CSS.supports=="function"?CSS.supports("color",e):/^#([\da-f]{3}|[\da-f]{6})$/i.test(e):false}},Ld=new hn;var bn=class extends ie{constructor(){super("subscript");}},wd=new bn;var yn=class extends ie{constructor(){super("superscript");}},Rd=new yn;function En(i,t,e){return i<t?t:i>e?e:i}function Id({items:i,position:t,onClose:e,className:n,style:o,itemClassName:r,itemStyle:s,disabledItemClassName:a,disabledItemStyle:l}){return jsx("div",{className:n,style:{position:"fixed",left:t.x,top:t.y,zIndex:"var(--luthor-z-menu, 460)",...o},onClick:d=>d.stopPropagation(),children:i.map((d,c)=>d.separator?jsx("div",{className:"h-px bg-border my-1"},c):jsxs("div",{className:d.disabled?a:r,style:d.disabled?l:s,onClick:()=>{!d.disabled&&d.action&&(d.action(),e());},children:[d.icon&&jsx(d.icon,{className:"mr-2 h-4 w-4"}),d.label]},c))})}var xn=class{constructor(t,e={}){C(this,"providers",new Map);C(this,"currentMenu",null);C(this,"listeners",new Set);C(this,"editor");C(this,"config");this.editor=t,this.config=e;}registerProvider(t){this.providers.set(t.id,t);}unregisterProvider(t){this.providers.delete(t);}handleContextMenu(t){let e=t.target;this.editor.getEditorState().read(()=>{let n=$getSelection(),o=Array.from(this.providers.values()).sort((r,s)=>(s.priority||0)-(r.priority||0));for(let r of o){let s={editor:this.editor,target:e,selection:n,event:t};if(r.canHandle(s)){this.config.preventDefault!==false&&t.preventDefault();let a=r.getItems(s);if(a.length>0){let l=e.getBoundingClientRect();this.showMenu({items:a,position:{x:t.clientX,y:t.clientY},renderer:r.renderer||this.config.defaultRenderer,anchor:{element:e,offsetX:t.clientX-l.left,offsetY:t.clientY-l.top}});return}}}});}showMenu(t){this.currentMenu=this.resolveAnchoredMenuConfig(t),this.notifyListeners();}hideMenu(){this.currentMenu=null,this.notifyListeners();}repositionMenuFromAnchor(){if(!this.currentMenu?.anchor)return;if(!this.currentMenu.anchor.element.isConnected){this.hideMenu();return}let t=this.resolveAnchoredMenuConfig(this.currentMenu);(!this.currentMenu||t.position.x!==this.currentMenu.position.x||t.position.y!==this.currentMenu.position.y)&&(this.currentMenu=t,this.notifyListeners());}getCurrentMenu(){return this.currentMenu}getPortalContainer(){let t=this.editor.getRootElement();return t?t.closest(".luthor-editor-wrapper")??null:null}subscribe(t){return this.listeners.add(t),t(this.currentMenu),()=>{this.listeners.delete(t);}}notifyListeners(){this.listeners.forEach(t=>t(this.currentMenu));}resolveAnchoredMenuConfig(t){if(!t.anchor)return t;let{element:e,offsetX:n,offsetY:o}=t.anchor,r=e.getBoundingClientRect();return {...t,position:{x:r.left+n,y:r.top+o}}}};function _d({extension:i}){let{config:t}=Ie(),[e,n]=useState(null),o=t?.theme?.contextMenu||{},r=i.config,s={container:r?.theme?.container||o.container||"luthor-context-menu",item:r?.theme?.item||o.item||"luthor-context-menu-item",itemDisabled:r?.theme?.itemDisabled||o.itemDisabled||"luthor-context-menu-item-disabled"},a={container:{...r?.styles?.container,...o.styles?.container},item:{...r?.styles?.item,...o.styles?.item},itemDisabled:{...r?.styles?.itemDisabled,...o.styles?.itemDisabled}};if(useEffect(()=>i.subscribe(n),[i]),!e)return null;let l=e.renderer||i.config.defaultRenderer,d=i.manager?.getPortalContainer()??null,c=220,u=Math.min(420,18+e.items.length*34),m=8,g=(()=>{if(!d){let y=typeof window>"u"?0:window.innerWidth,E=typeof window>"u"?0:window.innerHeight,N=Math.max(m,y-c-m),v=Math.max(m,E-u-m);return {x:En(e.position.x,m,N),y:En(e.position.y,m,v)}}let T=d.getBoundingClientRect(),w=e.position.x-T.left,p=e.position.y-T.top,b=Math.max(m,T.width-c-m),f=Math.max(m,T.height-u-m);return {x:En(w,m,b),y:En(p,m,f)}})(),h=d?{position:"absolute",...a.container}:a.container;return createPortal(jsx(l,{items:e.items,position:g,onClose:()=>i.manager?.hideMenu(),className:s.container,style:h,itemClassName:s.item,itemStyle:a.item,disabledItemClassName:s.itemDisabled,disabledItemStyle:a.itemDisabled}),d??document.body)}var Cn=class extends k{constructor(e={}){super("contextMenu",["toolbar"]);C(this,"manager",null);C(this,"pendingListeners",new Set);this.config={defaultRenderer:Id,position:"before",initPriority:100,...e};}configure(e){return this.config={...this.config,...e},this.manager&&Object.assign(this.manager,{config:this.config}),this}register(e){this.manager=new xn(e,this.config),this.pendingListeners.forEach(l=>{this.manager?.subscribe(l);}),this.pendingListeners.clear();let n=l=>{this.manager?.handleContextMenu(l);},o=l=>{l.target.closest(".luthor-context-menu")||this.manager?.hideMenu();},r=l=>{l.key==="Escape"&&this.manager?.hideMenu();},s=()=>{this.manager?.repositionMenuFromAnchor();},a=e.getRootElement();return a?(a.addEventListener("contextmenu",n),document.addEventListener("mousedown",o),document.addEventListener("keydown",r),window.addEventListener("scroll",s,true),window.addEventListener("resize",s),()=>{a.removeEventListener("contextmenu",n),document.removeEventListener("mousedown",o),document.removeEventListener("keydown",r),window.removeEventListener("scroll",s,true),window.removeEventListener("resize",s),this.manager=null;}):()=>{this.manager=null;}}getCommands(e){return {registerProvider:n=>{this.manager||(this.manager=new xn(e,this.config)),this.manager.registerProvider(n);},unregisterProvider:n=>{this.manager?.unregisterProvider(n);},showContextMenu:n=>{this.manager?.showMenu(n);},hideContextMenu:()=>{this.manager?.hideMenu();}}}getStateQueries(e){return {isContextMenuOpen:()=>Promise.resolve(this.manager?.getCurrentMenu()!==null)}}getPlugins(){return [jsx(_d,{extension:this},"context-menu")]}subscribe(e){return this.manager?this.manager.subscribe(e):(this.pendingListeners.add(e),()=>{this.pendingListeners.delete(e);})}},Ao=new Cn;function Wd(i,t,e){return i<t?t:i>e?e:i}function Tn(){let i=$getSelection();if($isTableSelection(i)){let t=i.getNodes().find(e=>$isTableCellNode(e));if($isTableCellNode(t))return t}if($isRangeSelection(i)){let t=i.anchor.getNode(),e=$findCellNode(t);if($isTableCellNode(e))return e}return null}function qd({headersEnabled:i,setHeadersEnabled:t,actions:e}){return jsxs(Fragment,{children:[jsx("button",{type:"button",className:"luthor-table-bubble-button",title:"Insert row above","aria-label":"Insert row above",onClick:e.insertRowAbove,children:"Row \u2191"}),jsx("button",{type:"button",className:"luthor-table-bubble-button",title:"Insert row below","aria-label":"Insert row below",onClick:e.insertRowBelow,children:"Row \u2193"}),jsx("button",{type:"button",className:"luthor-table-bubble-button",title:"Insert column left","aria-label":"Insert column left",onClick:e.insertColumnLeft,children:"Col \u2190"}),jsx("button",{type:"button",className:"luthor-table-bubble-button",title:"Insert column right","aria-label":"Insert column right",onClick:e.insertColumnRight,children:"Col \u2192"}),jsx("button",{type:"button",className:"luthor-table-bubble-button",title:"Delete selected column","aria-label":"Delete selected column",onClick:e.deleteSelectedColumn,children:"Del Col"}),jsx("button",{type:"button",className:"luthor-table-bubble-button",title:"Delete selected row","aria-label":"Delete selected row",onClick:e.deleteSelectedRow,children:"Del Row"}),jsxs("label",{className:"luthor-table-bubble-checkbox",title:"Use first row as table headers",children:[jsx("input",{type:"checkbox",title:"Use first row as table headers","aria-label":"Use first row as table headers",checked:i,onChange:n=>t(n.target.checked)}),"Headers"]}),jsx("button",{type:"button",className:"luthor-table-bubble-button luthor-table-bubble-button-danger",title:"Delete table","aria-label":"Delete table",onClick:e.deleteTable,children:"Delete Table"})]})}function Jd({extension:i}){let{editor:t}=Ie(),[e,n]=useState(()=>t?.isEditable()??true),[o,r]=useState(null),[s,a]=useState(false),[l,d]=useState(false),[c,u]=useState(null),m=useRef(null),g=useRef(null),h=b=>{!t||!t.isEditable()||t.update(()=>{let f=Tn();f&&(f.selectStart(),b(f));});},T=b=>{h(f=>{$getTableNodeFromLexicalNodeOrThrow(f).getChildren().filter(N=>$isTableRowNode(N)).forEach((N,v)=>{N.getChildren().filter(L=>$isTableCellNode(L)).forEach(L=>{let O=b&&v===0?TableCellHeaderStates.ROW:TableCellHeaderStates.NO_STATUS;L.setHeaderStyles(O,TableCellHeaderStates.ROW);});});});};if(useEffect(()=>{if(t)return t.registerEditableListener(b=>{n(b),b||(a(false),u(null));})},[t]),useEffect(()=>{if(!t)return;let b=t.getRootElement(),f=b?.closest(".luthor-editor-wrapper")||b?.parentElement||null;r(f);let y=()=>{t.getEditorState().read(()=>{if(!t.isEditable()){a(false),u(null);return}let v=$getSelection();if($isRangeSelection(v)&&!v.isCollapsed()){a(false),u(null);return}let x=Tn();if(!x){a(false),u(null);return}let O=t.getElementByKey(x.getKey())?.closest("table");if(!O||!f){a(false),u(null);return}let U=$getTableNodeFromLexicalNodeOrThrow(x).getChildren().filter(ge=>$isTableRowNode(ge))[0]?.getChildren().filter(ge=>$isTableCellNode(ge))||[],G=U.length>0&&U.every(ge=>ge.hasHeaderState(TableCellHeaderStates.ROW));d(G);let B=f.getBoundingClientRect(),$=O.getBoundingClientRect(),Y=m.current?.getBoundingClientRect(),I=Y?.width??520,K=Y?.height??44,X=I/2,se=12,j=$.left-B.left+$.width/2,te=se+X,Oe=Math.max(te,B.width-se-X),Ce=Wd(j,te,Oe),He=$.top-B.top>=K+se;u({x:Ce,y:He?$.top-B.top-12:$.bottom-B.top+12,placeAbove:He}),a(true);});};y();let E=t.registerUpdateListener(()=>{y();}),N=()=>{g.current===null&&(g.current=window.requestAnimationFrame(()=>{g.current=null,y();}));};return window.addEventListener("scroll",N,true),window.addEventListener("resize",N),()=>{E(),window.removeEventListener("scroll",N,true),window.removeEventListener("resize",N),g.current!==null&&(cancelAnimationFrame(g.current),g.current=null);}},[t]),!e||!o||!s||!c||typeof document>"u")return null;let w={insertRowAbove:()=>h(()=>$insertTableRowAtSelection(false)),insertRowBelow:()=>h(()=>$insertTableRowAtSelection(true)),insertColumnLeft:()=>h(()=>$insertTableColumnAtSelection(false)),insertColumnRight:()=>h(()=>$insertTableColumnAtSelection(true)),deleteSelectedColumn:()=>h(()=>$deleteTableColumnAtSelection()),deleteSelectedRow:()=>h(()=>$deleteTableRowAtSelection()),deleteTable:()=>h(b=>{$getTableNodeFromLexicalNodeOrThrow(b).remove();})},p=i.config.tableBubbleRenderer?i.config.tableBubbleRenderer({headersEnabled:l,setHeadersEnabled:b=>{d(b),T(b);},actions:w}):jsx(qd,{headersEnabled:l,setHeadersEnabled:b=>{d(b),T(b);},actions:w});return createPortal(jsx("div",{ref:m,className:"luthor-table-bubble-menu",style:{position:"absolute",left:c.x,top:c.y,transform:c.placeAbove?"translate(-50%, -100%)":"translate(-50%, 0)",zIndex:"var(--luthor-z-menu, 460)"},onMouseDown:b=>b.preventDefault(),children:p}),o)}var Ln=class extends k{constructor(e){super("table",["toolbar"]);C(this,"defaultContextMenuItems",e=>[{label:"Insert Row Above",action:()=>e.insertRowAbove()},{label:"Insert Row Below",action:()=>e.insertRowBelow()},{label:"Insert Column Left",action:()=>e.insertColumnLeft()},{label:"Insert Column Right",action:()=>e.insertColumnRight()},{separator:true,label:"",action:()=>{}},{label:"Toggle Row Header",action:()=>e.toggleRowHeader()},{label:"Toggle Column Header",action:()=>e.toggleColumnHeader()},{label:"Merge Cells",action:()=>e.mergeSelectedCells()},{label:"Split Cell",action:()=>e.unmergeSelectedCell()},{separator:true,label:"",action:()=>{}},{label:"Delete Row",action:()=>e.deleteRow()},{label:"Delete Column",action:()=>e.deleteColumn()},{label:"Delete Table",action:()=>e.deleteTable()}]);this.config={rows:3,columns:3,includeHeaders:false,enableContextMenu:true,contextMenuItems:this.defaultContextMenuItems,...e};}getContextMenuItems(e){return typeof this.config.contextMenuItems=="function"?this.config.contextMenuItems(e):Array.isArray(this.config.contextMenuItems)?this.config.contextMenuItems:this.defaultContextMenuItems(e)}configure(e){return this.config={...this.config,...e},e.contextMenuItems&&(this.config.contextMenuItems=e.contextMenuItems),this}register(e){let n;if(this.config.enableContextMenu){let o=this.config.contextMenuExtension||Ao;if(o){let r={id:"table",priority:10,canHandle:({editor:a,target:l,selection:d})=>{if(!a.isEditable())return false;let c=l.closest("td, th, [data-lexical-table-cell]");return c?$isTableSelection(d)?true:c.tagName==="TD"||c.tagName==="TH":false},getItems:({editor:a})=>{let l=this.getCommands(a);return this.getContextMenuItems(l)},renderer:this.config.contextMenuRenderer||o.config?.defaultRenderer};o.getCommands(e).registerProvider(r),n=()=>{let a=o.getCommands(e);a&&a.unregisterProvider("table");};}}return ()=>{n?.();}}getNodes(){return [TableNode,TableRowNode,TableCellNode]}getCommands(e){return {insertTable:n=>{let{rows:o=3,columns:r=3,includeHeaders:s=false}=n;e.update(()=>{let a=$getSelection();if($isRangeSelection(a)){let l=$createTableNodeWithDimensions(o,r,s);a.insertNodes([l]);}});},insertRowAbove:()=>{e.update(()=>{$insertTableRowAtSelection(false);});},insertRowBelow:()=>{e.update(()=>{$insertTableRowAtSelection(true);});},insertColumnLeft:()=>{e.update(()=>{$insertTableColumnAtSelection(false);});},insertColumnRight:()=>{e.update(()=>{$insertTableColumnAtSelection(true);});},toggleRowHeader:()=>{e.update(()=>{let n=Tn();if(!n)return;let o=$getTableNodeFromLexicalNodeOrThrow(n),r=$getTableRowIndexFromTableCellNode(n),s=o.getChildren()[r];if(!$isTableRowNode(s))return;let a=s.getChildren().filter(c=>$isTableCellNode(c)),d=!a.every(c=>c.hasHeaderState(TableCellHeaderStates.ROW))?TableCellHeaderStates.ROW:TableCellHeaderStates.NO_STATUS;a.forEach(c=>{c.setHeaderStyles(d,TableCellHeaderStates.ROW);});});},toggleColumnHeader:()=>{e.update(()=>{let n=Tn();if(!n)return;let o=$getTableNodeFromLexicalNodeOrThrow(n),r=$getTableColumnIndexFromTableCellNode(n),a=o.getChildren().filter(c=>$isTableRowNode(c)).map(c=>c.getChildren()[r]).filter(c=>$isTableCellNode(c)),d=!a.every(c=>c.hasHeaderState(TableCellHeaderStates.COLUMN))?TableCellHeaderStates.COLUMN:TableCellHeaderStates.NO_STATUS;a.forEach(c=>{c.setHeaderStyles(d,TableCellHeaderStates.COLUMN);});});},mergeSelectedCells:()=>{e.update(()=>{let n=$getSelection();if(!$isTableSelection(n))return;let o=n.getNodes().filter(r=>$isTableCellNode(r));o.length<2||$mergeCells(o);});},unmergeSelectedCell:()=>{e.update(()=>{$unmergeCell();});},deleteRow:()=>{e.update(()=>{$deleteTableRowAtSelection();});},deleteColumn:()=>{e.update(()=>{$deleteTableColumnAtSelection();});},deleteTable:()=>{e.update(()=>{let n=$getSelection();$isTableSelection(n)&&n.getNodes().forEach(o=>{$isTableNode(o)&&o.remove();});});},showTableContextMenu:n=>{}}}getStateQueries(e){return {isTableSelected:async()=>e.getEditorState().read(()=>{let n=$getSelection();return $isTableSelection(n)}),isInTableCell:async()=>e.getEditorState().read(()=>{let n=$getSelection();if(!n||typeof n!="object"||!("anchor"in n)||!("focus"in n))return false;try{let o=n.anchor.getNode(),r=n.focus.getNode();return $isTableCellNode(o)||$isTableCellNode(r)}catch{return false}})}}getPlugins(){return [jsx(TablePlugin,{},"table-plugin"),jsx(Jd,{extension:this},"table-quick-actions-plugin")]}},Xd=new Ln;var Ii=9,dt={"decimal-alpha-roman":["decimal","lower-alpha","lower-roman"],"decimal-hierarchical":["decimal"],"upper-roman-upper-alpha":["upper-roman","upper-alpha","decimal","lower-alpha","decimal","lower-alpha","lower-roman","lower-alpha","lower-roman"],"upper-alpha-lower-alpha":["upper-alpha","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman"],"decimal-leading-zero-alpha":["decimal-leading-zero","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman"]},$t={"disc-circle-square":["disc","circle","square"],"arrow-diamond-disc":['"\u25B8"','"\u25C6"',"disc"],"square-square-square":["square","square","square"],"arrow-circle-square":['"\u25B8"',"circle","square"]},ut="decimal-alpha-roman",_i="disc-circle-square",_n="--luthor-checklist-variant",_e="--luthor-unordered-pattern",ji="--luthor-unordered-pattern-token",Be="--luthor-unordered-marker-kind",xe="--luthor-ordered-marker-content",Ai={"disc-arrow-square":"arrow-circle-square","square-circle-disc":"disc-circle-square","arrow-diamond-square":"arrow-diamond-disc","star-circle-square":"disc-circle-square"};function Ki(i){let t=new Map;for(let e of i.split(";")){let n=e.trim();if(!n)continue;let o=n.indexOf(":");if(o<=0)continue;let r=n.slice(0,o).trim(),s=n.slice(o+1).trim();r&&t.set(r,s);}return t}function ru(i){return Array.from(i.entries()).map(([t,e])=>`${t}: ${e}`).join("; ")}function oe(i,t){let e=i.getStyle(),n=Ki(e),o=false;for(let[r,s]of Object.entries(t)){let a=n.get(r);if(s===null||s===""){n.delete(r)&&(o=true);continue}a!==s&&(n.set(r,s),o=true);}o&&i.setStyle(ru(n));}function me(i,t){return Ki(i.getStyle()).get(t)??null}function gt(i,t){let e=[...i];for(let n=0;n<e.length;n+=1){let o=e[n],r=t(o);if(r==="stop")break;r!=="skip-children"&&typeof o?.getChildren=="function"&&e.push(...o.getChildren());}}function An(i){let t=i;for(;t;){if($isListNode(t))return t;t=t.getParent();}return null}function iu(i){let t=i;for(;t;){if($isListItemNode(t))return t;t=t.getParent();}return null}function jt(i){let t=i;for(;;){let e=t.getParent();if(!$isListItemNode(e))return t;let n=e.getParent();if(!$isListNode(n))return t;t=n;}}function Pn(i,t){let e=$getListDepth(i),n=$getListDepth(t);return e-n}function Mn(i,t){let e=t%i.length;return i[e]??i[0]??"disc"}function Di(i,t){let e=i,n="";for(;e>0;){let o=(e-1)%26;n=String.fromCharCode((t?65:97)+o)+n,e=Math.floor((e-1)/26);}return n||(t?"A":"a")}function Hi(i,t){let e=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],n=Math.max(1,Math.floor(i)),o="";for(let[r,s]of e)for(;n>=r;)o+=s,n-=r;return t?o:o.toLowerCase()}function Fi(i,t,e,n){let o=e==="paren"?")":".";return `"${n?n.join("."):i==="decimal-leading-zero"?t<10?`0${t}`:`${t}`:i==="lower-alpha"?Di(t,false):i==="upper-alpha"?Di(t,true):i==="lower-roman"?Hi(t,false):i==="upper-roman"?Hi(t,true):`${t}`}${o}"`}function su(i,t){let e=0;for(let n of i.getChildren())if($isListItemNode(n)&&(zt(n)&&(e+=1),n.getKey()===t.getKey()))return Math.max(1,e);return Math.max(1,e)}function Bi(i,t){let e=[],n=i;for(;n.getKey()!==t.getKey();){let o=n.getParent();if(!$isListItemNode(o))break;let r=o.getParent();if(!$isListNode(r))break;e.push(su(r,o)),n=r;}return e.reverse()}function Hn(i){return i&&Object.hasOwn($t,i)?i:i&&Object.hasOwn(Ai,i)?Ai[i]??_i:_i}function au(i){return i.startsWith('"')&&i.endsWith('"')}function Uo(i){if(au(i)){let t=i.toLowerCase(),e=t.slice(1,-1);return t.includes("\\25c6")||e==="\u25C6"?"diamond":(t.includes("\\25b8")||t.includes("\\27a4")||e==="\u25B8"||e==="\u27A4","arrow")}switch(i){case "disc":return "disc";case "circle":return "circle";case "square":return "square";default:return "disc"}}function lu(i){let t=i.trim();if(!t)return null;let e=t.match(/^(\d+)([.)])$/);if(e){let r=e[1]??"",s=e[2]??".";return {pattern:r.length>1&&r.startsWith("0")?"decimal-leading-zero-alpha":"decimal-alpha-roman",suffix:s===")"?"paren":"dot"}}let n=t.match(/^([IVXLCDMivxlcdm]+)([.)])$/);if(n)return {pattern:"upper-roman-upper-alpha",suffix:(n[2]??".")===")"?"paren":"dot"};let o=t.match(/^([A-Z]+)([.)])$/);return o?{pattern:"upper-alpha-lower-alpha",suffix:(o[2]??".")===")"?"paren":"dot"}:null}function mt(i){let t=new Map,e=i.getNodes();for(let n of e){let o=An(n);if(!o)continue;let r=jt(o);t.set(r.getKey(),r);}if(t.size===0){let n=An(i.anchor.getNode());if(n){let o=jt(n);t.set(o.getKey(),o);}}return [...t.values()]}function On(i,t){let e=Math.max(0,t-1),n=i.anchor.getNode(),o=iu(n);if(o){let s=o.getIndent();if(typeof s=="number")return s>=e}let r=An(n);return r?$getListDepth(r)-1>=e:false}function Yo(i){let t=[];return gt(i.getChildren(),e=>{if($isListNode(e))return "skip-children";$isTextNode(e)&&t.push(e);}),t}function Je(i){let t=[];return gt(i.getChildren(),e=>{if($isListNode(e))return t.push(e),"skip-children"}),t}function zt(i){let t=false,e=false;return gt(i.getChildren(),n=>{if($isListNode(n))return e=true,"skip-children";if($isTextNode(n)&&n.getTextContent().trim().length>0)return t=true,"stop"}),t?true:!e}function zo(i,t){gt(i.getChildren(),e=>{if($isListNode(e))return "skip-children";typeof e.getStyle=="function"&&typeof e.setStyle=="function"&&oe(e,{[ji]:t});});}function cu(i){let t=null;return gt(i.getChildren(),e=>{if($isListNode(e))return "skip-children";if(typeof e.getStyle=="function"){let n=me(e,ji);if(n)return t=Hn(n),"stop"}}),t}function du(i){let t=[i];for(;t.length>0;){let e=t.pop();if(e.getListType()==="check")for(let n of e.getChildren()){if(!$isListItemNode(n))continue;let o=Yo(n);for(let r of o)if(me(r,_n)==="plain")return "plain";t.push(...Je(n));}}return null}function uu(i){let t=[i];for(;t.length>0;){let e=t.pop();if(e.getListType()==="bullet")for(let n of e.getChildren()){if(!$isListItemNode(n))continue;let o=me(n,_e),r=Hn(o);if(o&&Object.hasOwn($t,r))return r;let s=cu(n);if(s)return s;t.push(...Je(n));}}return null}function $o(i){let t=uu(i);if(t)return t;let e=me(i,_e);return Hn(e)}function jo(i){return me(i,_n)==="plain"?"plain":du(i)??"strikethrough"}function In(i){let t=i.anchor.getNode(),e=null,n=null;for(;t;){if(!n&&$isListItemNode(t)&&(n=t),$isListNode(t)){e=t;break}t=t.getParent();}let o=e?jt(e):null;return {listNode:e,listItemNode:n,topListNode:o}}function Qo(i){let t=i.target;if(!(t instanceof HTMLElement))return null;let e=t.closest("li");if(!(e instanceof HTMLLIElement))return null;let n=e.firstElementChild;if(n instanceof HTMLElement&&(n.tagName==="UL"||n.tagName==="OL"))return null;let o=e.parentElement;if(!o||o.__lexicalListType!=="check")return null;let r=e.getBoundingClientRect(),s=i.clientX,a=window.getComputedStyle?window.getComputedStyle(e,"::before"):{width:"0px"},l=Number.parseFloat(a.width);if(!Number.isFinite(l)||l<=0)return null;let c=("pointerType"in i?i.pointerType:"")==="touch"?32:0;return (e.dir==="rtl"?s<r.right+c&&s>r.right-l-c:s>r.left-c&&s<r.left+l+c)?e:null}var Dn=class extends k{constructor(t={}){super("list",["toolbar"]),this.config=t;}getMaxListDepth(){let t=this.config.maxDepth;if(!Number.isFinite(t))return Ii;let e=Math.floor(t);return e>=1?e:Ii}register(t){let e=t.registerNodeTransform(ListNode,d=>{this.syncListNodeStyles(d);}),n=t.registerNodeTransform(ListItemNode,d=>{let c=d.getParent();$isListNode(c)&&this.syncListNodeStyles(c);}),o=t.registerCommand(KEY_SPACE_COMMAND,d=>{let c=false;return t.update(()=>{c=this.handleOrderedListShortcut(t);}),c&&d.preventDefault(),c},COMMAND_PRIORITY_EDITOR),r=t.registerCommand(INDENT_CONTENT_COMMAND,()=>{let d=$getSelection();return !$isRangeSelection(d)||!In(d).listNode?false:On(d,this.getMaxListDepth())},COMMAND_PRIORITY_EDITOR),s=d=>{t.isEditable()||Qo(d)&&(d.preventDefault(),d.stopPropagation());},a=d=>{if(t.isEditable())return;let c=Qo(d);c&&(d.preventDefault(),d.stopPropagation(),t.update(()=>{let u=$getNearestNodeFromDOMNode(c);if(!$isListItemNode(u))return;let m=u.getParent();!$isListNode(m)||m.getListType()!=="check"||u.toggleChecked();}));},l=t.registerRootListener((d,c)=>{c&&(c.removeEventListener("pointerdown",s),c.removeEventListener("click",a)),d&&(d.addEventListener("pointerdown",s),d.addEventListener("click",a));});return ()=>{e(),n(),o(),r(),l();}}getNodes(){return [ListNode,ListItemNode]}getPlugins(){return [jsx(ListPlugin,{hasStrictIndent:true},"list-plugin"),jsx(CheckListPlugin,{},"check-list-plugin")]}getCommands(t){return {toggleUnorderedList:()=>{t.update(()=>{let e=$getSelection();if(!$isRangeSelection(e))return;let n=In(e);if(n.topListNode){if(n.topListNode.getListType()==="bullet"){n.listItemNode&&n.listItemNode.getIndent()>0?t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode);return}this.convertTopListType(n.topListNode,"bullet");return}t.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0);});},toggleOrderedList:()=>{t.update(()=>{let e=$getSelection();if(!$isRangeSelection(e))return;let n=In(e);if(n.topListNode){if(n.topListNode.getListType()==="number"){n.listItemNode&&n.listItemNode.getIndent()>0?t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode);return}this.convertTopListType(n.topListNode,"number");return}t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);});},toggleCheckList:()=>{t.update(()=>{let e=$getSelection();if(!$isRangeSelection(e))return;let n=In(e);if(n.topListNode){if(n.topListNode.getListType()==="check"){n.listItemNode&&n.listItemNode.getIndent()>0?t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode);return}this.convertTopListType(n.topListNode,"check");return}t.dispatchCommand(INSERT_CHECK_LIST_COMMAND,void 0);});},indentList:()=>{t.update(()=>{let e=$getSelection();$isRangeSelection(e)&&(On(e,this.getMaxListDepth())||t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0));});},outdentList:()=>{t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0);},insertNestedUnorderedList:()=>{t.update(()=>{let e=$getSelection();!$isRangeSelection(e)||On(e,this.getMaxListDepth())||(t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),t.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0));});},insertNestedOrderedList:()=>{t.update(()=>{let e=$getSelection();!$isRangeSelection(e)||On(e,this.getMaxListDepth())||(t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0));});},setOrderedListPattern:e=>{t.update(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);let o=$getSelection();if(!$isRangeSelection(o))return;let r=mt(o);for(let s of r)this.applyOrderedPattern(s,e);});},setOrderedListSuffix:e=>{t.update(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=mt(n);for(let r of o)r.getListType()==="number"&&this.applyOrderedSuffix(r,e);});},setUnorderedListPattern:e=>{t.update(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;t.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0);let o=$getSelection();if(!$isRangeSelection(o))return;let r=mt(o);for(let s of r)this.applyUnorderedPattern(s,e);});},setCheckListVariant:e=>{let n=false;t.update(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let r=mt(o);if(r.length===0){n=true;return}for(let s of r)s.getListType()!=="check"&&this.convertTopListType(s,"check"),this.applyCheckListVariant(s,e);}),n&&(t.dispatchCommand(INSERT_CHECK_LIST_COMMAND,void 0),t.update(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let r=mt(o);for(let s of r)s.getListType()!=="check"&&this.convertTopListType(s,"check"),this.applyCheckListVariant(s,e);}));},rehydrateListStyles:()=>{t.update(()=>{let e=$getRoot(),n=new Map;gt(e.getChildren(),o=>{if($isListNode(o)){let r=jt(o);n.set(r.getKey(),r);}});for(let o of n.values()){if(o.getListType()==="number"){let r=me(o,"--luthor-ordered-pattern")??ut,s=Object.hasOwn(dt,r)?r:ut,a=me(o,"--luthor-ordered-suffix")==="paren"?"paren":"dot";this.applyOrderedPattern(o,s),this.applyOrderedSuffix(o,a);continue}if(o.getListType()==="bullet"){let r=$o(o);this.applyUnorderedPattern(o,r);continue}if(o.getListType()==="check"){let r=jo(o);this.applyCheckListVariant(o,r);}}});}}}applyOrderedPattern(t,e){if(t.getListType()!=="number")return;let n=dt[e],o=me(t,"--luthor-ordered-suffix")??"dot";oe(t,{"--luthor-ordered-pattern":e,"--luthor-ordered-suffix":o});let r=[t];for(;r.length>0;){let s=r.pop();if(s.getListType()!=="number")continue;let a=Pn(s,t),l=Mn(n,a),d=e==="decimal-hierarchical";oe(s,{"--luthor-ordered-pattern":e,"--luthor-ordered-suffix":o,"list-style-type":"none",[xe]:null});let c=d?Bi(s,t):null,u=0;for(let m of s.getChildren()){if(!$isListItemNode(m))continue;let g=zt(m);g&&(u+=1);let h=Fi(l,Math.max(1,u),o==="paren"?"paren":"dot",d?[...c??[],Math.max(1,u)]:null);oe(m,{[xe]:g?h:null}),r.push(...Je(m));}}}applyOrderedSuffix(t,e){let n=[t];for(;n.length>0;){let s=n.pop();if(s.getListType()==="number"){oe(s,{"--luthor-ordered-suffix":e});for(let a of s.getChildren())$isListItemNode(a)&&n.push(...Je(a));}}let o=me(t,"--luthor-ordered-pattern")??ut,r=Object.hasOwn(dt,o)?o:ut;this.applyOrderedPattern(t,r);}applyUnorderedPattern(t,e){if(t.getListType()!=="bullet")return;let n=$t[e];oe(t,{[_e]:e});let o=[t];for(;o.length>0;){let r=o.pop();if(r.getListType()!=="bullet")continue;let s=Pn(r,t),a=Mn(n,s),l=Uo(a);oe(r,{[_e]:e,"list-style-type":"none","--luthor-unordered-marker-content":null,[Be]:null,[xe]:null});for(let d of r.getChildren())$isListItemNode(d)&&(oe(d,{[_e]:e,"--luthor-unordered-marker-content":null,[Be]:zt(d)?l:null,[xe]:null}),zo(d,e),o.push(...Je(d)));}}applyCheckListVariant(t,e){if(t.getListType()!=="check")return;let n=[t];for(;n.length>0;){let o=n.pop();if(o.getListType()==="check"){oe(o,{"--luthor-checklist-variant":e,"--luthor-unordered-marker-content":null,[Be]:null,[xe]:null,"--luthor-unordered-pattern":null,"--luthor-ordered-pattern":null,"--luthor-ordered-suffix":null,"list-style-type":null});for(let r of o.getChildren()){if(!$isListItemNode(r))continue;oe(r,{"--luthor-checklist-variant":e,[_e]:null,"--luthor-unordered-marker-content":null,[Be]:null,[xe]:null}),zo(r,null);let s=Yo(r);for(let a of s)oe(a,{[_n]:e==="plain"?"plain":null});n.push(...Je(r));}}}}syncListNodeStyles(t){let e=jt(t);if(e.getListType()==="number"){let n=me(e,"--luthor-ordered-pattern")??ut;if(!Object.hasOwn(dt,n))return;let o=dt[n],r=Pn(t,e),s=Mn(o,r),a=n==="decimal-hierarchical",l=me(e,"--luthor-ordered-suffix")??"dot";oe(t,{"--luthor-ordered-pattern":n,"--luthor-ordered-suffix":l,"list-style-type":"none",[xe]:null});let d=a?Bi(t,e):null,c=0;for(let u of t.getChildren()){if(!$isListItemNode(u))continue;let m=zt(u);m&&(c+=1);let g=Fi(s,Math.max(1,c),l==="paren"?"paren":"dot",a?[...d??[],Math.max(1,c)]:null);oe(u,{[xe]:m?g:null});}return}if(e.getListType()==="bullet"){let n=$o(e),o=$t[n],r=Pn(t,e),s=Mn(o,r),a=Uo(s);oe(t,{[_e]:n,"list-style-type":"none","--luthor-unordered-marker-content":null,[Be]:null,[xe]:null});for(let l of t.getChildren())$isListItemNode(l)&&(oe(l,{[_e]:n,"--luthor-unordered-marker-content":null,[Be]:zt(l)?a:null,[xe]:null}),zo(l,n));return}if(e.getListType()==="check"){let n=jo(e);oe(t,{"--luthor-checklist-variant":n,"--luthor-unordered-marker-content":null,[Be]:null,[xe]:null,"--luthor-unordered-pattern":null,"--luthor-ordered-pattern":null,"--luthor-ordered-suffix":null,"list-style-type":null});for(let o of t.getChildren()){if(!$isListItemNode(o))continue;oe(o,{"--luthor-checklist-variant":n,[_e]:null,"--luthor-unordered-marker-content":null,[Be]:null,[xe]:null});let r=Yo(o);for(let s of r)oe(s,{[_n]:n==="plain"?"plain":null});}}}convertTopListType(t,e){let n=[t];for(;n.length>0;){let r=n.pop();r.setListType(e);for(let s of r.getChildren())$isListItemNode(s)&&n.push(...Je(s));}if(e==="number"){let r=me(t,"--luthor-ordered-pattern"),s=r&&Object.hasOwn(dt,r)?r:ut,a=me(t,"--luthor-ordered-suffix")==="paren"?"paren":"dot";this.applyOrderedPattern(t,s),this.applyOrderedSuffix(t,a);return}if(e==="bullet"){let r=$o(t);this.applyUnorderedPattern(t,r);return}let o=jo(t);this.applyCheckListVariant(t,o);}handleOrderedListShortcut(t){let e=$getSelection();if(!$isRangeSelection(e)||!e.isCollapsed())return false;let n=e.anchor.getNode();if(An(n))return false;let o=n;for(;o&&!$isParagraphNode(o);)o=o.getParent();if(!$isParagraphNode(o))return false;let r=o,s=lu(r.getTextContent());if(!s)return false;r.clear(),t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);let a=$getSelection();if(!$isRangeSelection(a))return true;let l=mt(a);for(let d of l)d.getListType()==="number"&&(this.applyOrderedPattern(d,s.pattern),this.applyOrderedSuffix(d,s.suffix));return true}getStateQueries(t){return {unorderedList:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n)){e(false);return}let o=n.anchor.getNode();for(;o;){if($isListNode(o)){e(o.getListType()==="bullet");return}o=o.getParent();}e(false);});}),orderedList:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n)){e(false);return}let o=n.anchor.getNode();for(;o;){if($isListNode(o)){e(o.getListType()==="number");return}o=o.getParent();}e(false);});}),checkList:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n)){e(false);return}let o=n.anchor.getNode();for(;o;){if($isListNode(o)){e(o.getListType()==="check");return}o=o.getParent();}e(false);});})}}},mu=new Dn;var fu="plain";function Kt(){return fu}function Ui(){return PrismTokenizer}async function Yi(i){return i?.provider?i.provider:i?.loadProvider?i.loadProvider():null}async function Qi(i){return i?i.tokenizer?i.tokenizer:i.getTokenizer?i.getTokenizer():null:null}var $n=class $n extends k{constructor(){super("code",["toolbar"]);C(this,"codeHighlightProviderPromise",null);this.config={syntaxHighlighting:"auto"};}register(e){let n=()=>{},o=false,r=a=>{n(),n=registerCodeHighlighting(e,a);};this.config.syntaxHighlighting!=="disabled"&&(r(this.config.tokenizer??Ui()),this.resolveConfiguredTokenizer().then(a=>{o||!a||r(a);}));let s=e.registerCommand(KEY_TAB_COMMAND,a=>{let l=false;return e.update(()=>{let d=$getSelection();if(!$isRangeSelection(d))return;let c=d.anchor.getNode();this.getBlockNode(c)&&(l=true,!this.hasReachedCodeTabLimit(d)&&d.insertText(" "));}),l?(a?.preventDefault(),true):false},COMMAND_PRIORITY_LOW);return ()=>{o=true,n(),s();}}getNodes(){return [CodeNode,CodeHighlightNode]}getCommands(e){return {toggleCodeBlock:()=>this.toggleCodeBlock(e)}}toggleCodeBlock(e){e.update(()=>{let n=$getSelection();if($isRangeSelection(n)){if(this.getCurrentFormatSync()==="code"){$setBlocksType(n,()=>$createParagraphNode());return}$setBlocksType(n,()=>{let r=$createCodeNode();return r.setTheme?.(Kt()),r});}});}async resolveConfiguredTokenizer(){if(this.config.tokenizer)return this.config.tokenizer;let e=await this.loadCodeHighlightProvider();return Qi(e)}async loadCodeHighlightProvider(){return this.config.provider?this.config.provider:this.codeHighlightProviderPromise?this.codeHighlightProviderPromise:(this.codeHighlightProviderPromise=Yi(this.config),this.codeHighlightProviderPromise)}getStateQueries(e){return {isInCodeBlock:()=>Promise.resolve(this.isFormat("code",e))}}isFormat(e,n){let o=true;return n.getEditorState().read(()=>{let r=$getSelection();if(!$isRangeSelection(r)){o=false;return}let s=r.getNodes();for(let a of s){let l=this.getBlockNode(a);if(!l){o=false;break}if(this.getNodeFormat(l)!==e){o=false;break}}}),o}getBlockNode(e){let n=e;for(;n;){if($isCodeNode(n))return n;n=n.getParent();}return null}getNodeFormat(e){return $isCodeNode(e)?"code":null}getCurrentFormatSync(){let e=$getSelection();if(!$isRangeSelection(e))return null;let n=e.anchor.getNode(),o=this.getBlockNode(n);return o?this.getNodeFormat(o):null}hasReachedCodeTabLimit(e){let n=e.anchor,o=n.getNode();if(typeof o.getTextContent!="function")return false;let r=o.getTextContent(),s=typeof n.offset=="number"?n.offset:r.length,a=Math.max(0,Math.min(r.length,s)),l=r.lastIndexOf(`
6
- `,a-1)+1;return (r.slice(l,a).match(/^\t*/)?.[0].length??0)>=$n.MAX_CODE_TAB_DEPTH}};C($n,"MAX_CODE_TAB_DEPTH",8);var zn=$n,Su=new zn;var Ou='<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M9 9a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-8a2 2 0 0 1-2-2V9Zm2 0h8v10h-8V9Zm-6 8a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v1h-2V5H5v10h1v2H5Z"/></svg>',Iu='<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M20.3 5.7a1 1 0 0 1 0 1.4l-9.2 9.2a1 1 0 0 1-1.4 0L3.7 10.3a1 1 0 1 1 1.4-1.4l5.3 5.3 8.5-8.5a1 1 0 0 1 1.4 0Z"/></svg>',_u=["plaintext","typescript","javascript","markdown","html","css","python","sql","java","c","cpp","rust","powershell","xml"],Kn=class extends k{constructor(){super("codeIntelligence");C(this,"languageOptions",[]);this.config={isCopyAllowed:true};}register(e){this.languageOptions=this.getLanguageOptions();let n=registerMarkdownShortcuts(e,TRANSFORMERS),o=e.registerUpdateListener(({dirtyElements:r,dirtyLeaves:s})=>{(r.size>0||s.size>0)&&this.ensureCodeBlockThemes(e);});return queueMicrotask(()=>{this.ensureCodeBlockThemes(e);}),()=>{n(),o(),this.languageOptions=[];}}getPlugins(){return [createElement(Du,{key:"code-intelligence-controls",extension:this})]}getCommands(e){return {setCodeLanguage:n=>{let o=ft(n),r=this.getThemeForLanguage(o);e.update(()=>{this.getSelectionCodeNodes().forEach(s=>{s.setLanguage(o??null),s.setTheme(r);});});},autoDetectCodeLanguage:async()=>null,getCurrentCodeLanguage:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=this.getSelectionCodeNodes();n(o[0]?.getLanguage()??null);});}),getCodeLanguageOptions:()=>this.getLanguageOptions(),copySelectedCodeBlock:async()=>{if(!this.isCopyAllowed())return false;let n=await this.getPrimaryCodeBlockText(e);return !n||!n.text.trim()?false:Zi(n.text)}}}isCopyAllowed(){return this.config.isCopyAllowed!==false}getLanguageOptionsSnapshot(){return this.languageOptions.length?[...this.languageOptions]:this.getLanguageOptions()}getCodeBlocksSnapshot(e){return e.getEditorState().read(()=>$nodesOfType(CodeNode).map(n=>{let o=ft(n.getLanguage());return {key:n.getKey(),language:o??"plaintext",text:n.getTextContent()}}))}setCodeBlockLanguage(e,n,o){e.isEditable()&&e.update(()=>{let r=$getNodeByKey(n);if(!r||!$isCodeNode(r))return;let s=ft(o);r.setLanguage(s??null),r.setTheme(this.getThemeForLanguage(s));});}getCodeBlockText(e,n){return e.getEditorState().read(()=>{let o=$getNodeByKey(n);return !o||!$isCodeNode(o)?"":o.getTextContent()})}getThemeForLanguage(e){let n=ft(e);return !n||n==="plain"?Kt():"hljs"}ensureCodeBlockThemes(e){let n=e.getEditorState().read(()=>$nodesOfType(CodeNode).map(o=>{let r=o.getTheme?.()??"",s=this.getThemeForLanguage(o.getLanguage());return {key:o.getKey(),nextTheme:s??Kt(),currentTheme:r}}).filter(o=>o.currentTheme!==o.nextTheme));n.length!==0&&e.update(()=>{n.forEach(o=>{let r=$getNodeByKey(o.key);!r||!$isCodeNode(r)||r.setTheme(o.nextTheme);});});}getSelectionCodeNodes(){let e=$getSelection();if(!$isRangeSelection(e))return [];let n=e.getNodes(),o=new Map;return n.forEach(r=>{let s=this.getNearestCodeNode(r);s&&o.set(s.getKey(),s);}),Array.from(o.values())}getNearestCodeNode(e){let n=e;for(;n;){if($isCodeNode(n))return n;n=n.getParent();}return null}getLanguageOptions(){let e=_u.map(r=>ft(r)).filter(r=>!!r),n=zu(this.config.languageOptions);if(!n)return Jo(e);let o=$u(n.values);return n.mode==="replace"?Jo(o):Jo([...e,...o])}async getPrimaryCodeBlockText(e){return new Promise(n=>{e.getEditorState().read(()=>{let r=this.getSelectionCodeNodes()[0];if(!r){n(null);return}let s=r.getTextContent().trim();if(!s){n(null);return}n({key:r.getKey(),text:s});});})}},Au=34;function Du({extension:i}){let[t]=useLexicalComposerContext(),[e,n]=useState(()=>t.isEditable()),[o,r]=useState([]),[s,a]=useState({}),l=useRef(null),d=useRef(new Map),c=useMemo(()=>i.getLanguageOptionsSnapshot(),[i]),u=useCallback(()=>{let y=Gi(t);if(!y)return [];let E=y.getBoundingClientRect(),N=i.getCodeBlocksSnapshot(t),v=[];return N.forEach(x=>{let L=t.getElementByKey(x.key);if(!L||!L.isConnected)return;L.classList.add("luthor-code-block--interactive");let O=L.getBoundingClientRect(),A=Math.max(120,Math.round(O.width)),V=Math.max(0,Math.round(O.top-E.top-Au)),U=Math.max(0,Math.round(O.left-E.left));v.push({key:x.key,language:x.language,top:V,left:U,width:A});}),v},[t,i]),m=useCallback(()=>{let y=u();r(E=>Hu(E,y)?E:y);},[u]),g=useCallback(()=>{l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null,m();}));},[m]),h=useCallback(y=>{let E=d.current.get(y);E&&(clearTimeout(E),d.current.delete(y));},[]),T=useCallback((y,E)=>{h(y),a(v=>({...v,[y]:E}));let N=setTimeout(()=>{a(v=>{if(!(y in v))return v;let x={...v};return delete x[y],x}),d.current.delete(y);},1200);d.current.set(y,N);},[h]),w=useCallback((y,E)=>{e&&(i.setCodeBlockLanguage(t,y,E),g());},[t,i,e,g]),p=i.isCopyAllowed(),b=useCallback(async y=>{if(!p)return;let E=i.getCodeBlockText(t,y);if(!E.trim())return;if(await Zi(E)){T(y,"copied");return}T(y,"error");},[p,t,i,T]);if(useEffect(()=>t.registerEditableListener(n),[t]),useEffect(()=>{g();let y=0,E=null,N=()=>{g(),y+=1,!(y>=20)&&(E=requestAnimationFrame(N));};E=requestAnimationFrame(N);let v=t.registerUpdateListener(()=>{g();}),x=()=>{g();},L=d.current;return window.addEventListener("scroll",x,true),window.addEventListener("resize",x,{passive:true}),()=>{v(),window.removeEventListener("scroll",x,true),window.removeEventListener("resize",x),E!==null&&cancelAnimationFrame(E),l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),L.forEach(O=>clearTimeout(O)),L.clear();}},[t,g]),useEffect(()=>{let y=new Set(o.map(E=>E.key));a(E=>{let N=false,v={};return Object.entries(E).forEach(([x,L])=>{if(y.has(x)){v[x]=L;return}N=true,h(x);}),N?v:E});},[h,o]),typeof document>"u"||o.length===0)return null;let f=Gi(t);return f?createPortal(createElement("div",{className:"luthor-codeblock-controls-layer","aria-hidden":false},o.map(y=>{let E=s[y.key],N=["luthor-codeblock-copy",E==="copied"?"is-copied":"",E==="error"?"is-copy-error":""].filter(Boolean).join(" "),v=E==="copied"?"Copied":E==="error"?"Copy failed":"Copy to clipboard";return createElement("div",{key:y.key,className:"luthor-codeblock-controls","data-code-node-key":y.key,style:{position:"absolute",top:`${y.top}px`,left:`${y.left}px`,width:`${y.width}px`}},createElement("span",{className:"luthor-codeblock-controls-left"},createElement("select",{className:"luthor-codeblock-language",value:y.language,"aria-label":"Code language",disabled:!e,"aria-disabled":!e,onChange:x=>{let L=x.target;w(y.key,L.value);}},c.map(x=>createElement("option",{key:x,value:x},x)))),createElement("span",{className:"luthor-codeblock-controls-right"},p?createElement("button",{className:N,type:"button","aria-label":"Copy code",title:v,"data-tooltip":v,onMouseDown:x=>{x.preventDefault();},onClick:()=>{b(y.key);},dangerouslySetInnerHTML:{__html:E==="copied"?Iu:Ou}}):null))})),f):null}function Hu(i,t){if(i.length!==t.length)return false;for(let e=0;e<i.length;e+=1){let n=i[e],o=t[e];if(!n||!o||n.key!==o.key||n.language!==o.language||n.top!==o.top||n.left!==o.left||n.width!==o.width)return false}return true}async function Zi(i){if(typeof navigator<"u"&&navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(i),!0}catch{}if(typeof document>"u")return false;let t=document.createElement("textarea");t.value=i,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.opacity="0",t.style.pointerEvents="none",t.style.top="0",t.style.left="0",document.body.appendChild(t),t.select(),t.setSelectionRange(0,t.value.length);try{return document.execCommand("copy")}catch{return false}finally{t.remove();}}function Gi(i){let t=i.getRootElement();if(!t)return null;let e=t.closest(".luthor-richtext-container");if(e)return e;let n=t.closest(".luthor-editor-container");return n||t.parentElement}function ft(i){if(!i)return null;let t=i.trim().toLowerCase();if(!t||t==="auto")return null;let e=normalizeCodeLang(t);return !e||e==="auto"||!Fu(e)?null:e}function Fu(i){let t=i.trim().toLowerCase();if(!t)return false;let e=getCodeLanguageOptions().map(([r])=>normalizeCodeLang(r.trim().toLowerCase())).filter(Boolean),n=getCodeLanguages().map(r=>normalizeCodeLang(r.trim().toLowerCase())).filter(Boolean);return new Set([...e,...n]).has(t)}var Bu=new Kn;function zu(i){if(!i)return null;if(Array.isArray(i))return {mode:"append",values:i};let t=i;return {mode:t.mode??"append",values:Array.isArray(t.values)?t.values:[]}}function $u(i){let t=[],e=new Set;for(let n of i){let o=n.trim();if(!o)continue;let r=ft(o);if(!r)throw new Error(`[CodeIntelligenceExtension] Invalid language option "${n}". Use a supported language ID or alias (excluding "auto").`);if(e.has(r))throw new Error(`[CodeIntelligenceExtension] Duplicate language option "${n}". It resolves to "${r}", which is already configured.`);e.add(r),t.push(r);}return t}function Jo(i){return Array.from(new Set(i)).sort((t,e)=>t.localeCompare(e))}var Un=class extends ie{constructor(){super("code");}register(t){let e=super.register(t),n=t.getRootElement();if(!n)return e;let o=a=>{if(a.nodeType===Node.TEXT_NODE)return a;for(let l=0;l<a.childNodes.length;l+=1){let d=a.childNodes[l];if(!d)continue;let c=o(d);if(c)return c}return null},r=a=>{if(a.nodeType===Node.TEXT_NODE)return a;for(let l=a.childNodes.length-1;l>=0;l-=1){let d=a.childNodes[l];if(!d)continue;let c=r(d);if(c)return c}return null},s=a=>{if(a.button!==0)return;let l=window.getSelection();if(l&&l.rangeCount>0&&!l.getRangeAt(0).collapsed)return;let d=a.target;if(!(d instanceof Node))return;let c=d instanceof HTMLElement?d:d.parentElement;if(!c)return;let u=c.closest(".luthor-text-code, code");if(u instanceof HTMLElement||(u=document.elementFromPoint(a.clientX+4,a.clientY)?.closest(".luthor-text-code, code")??null),!(u instanceof HTMLElement)||!n.contains(u))return;let m=u.getBoundingClientRect(),g=Math.max(4,Math.min(8,m.width/2)),h=null,T=0;a.clientX<=m.left+g?(h=o(u),T=0):a.clientX>=m.right-g&&(h=r(u),T=h?.data.length??0),h&&(a.preventDefault(),t.focus(()=>{let w=window.getSelection();if(!w)return;let p=document.createRange();p.setStart(h,T),p.collapse(true),w.removeAllRanges(),w.addRange(p);}));};return n.addEventListener("click",s,true),()=>{n.removeEventListener("click",s,true),e();}}},ju=new Un;var Qn=class extends k{constructor(){super("blockFormat",["toolbar"]);}register(t){let e=t.registerCommand(INSERT_PARAGRAPH_COMMAND,()=>{let o=$getSelection();if($isRangeSelection(o)){let r=o.anchor.getNode(),s=this.getBlockNode(r);if(s&&($isHeadingNode(s)||$isQuoteNode(s)))return false}return false},COMMAND_PRIORITY_NORMAL),n=t.registerCommand(KEY_ENTER_COMMAND,o=>{let r=false;return t.update(()=>{let s=$getSelection();if(!$isRangeSelection(s))return;let a=s.anchor.getNode(),l=this.getBlockNode(a);l&&$isHeadingNode(l)&&!o?.shiftKey&&(this.toggleBlockFormat(t,"p"),r=true);}),r&&o?.preventDefault(),r},COMMAND_PRIORITY_EDITOR);return ()=>{e(),n();}}getNodes(){return [ParagraphNode,HeadingNode,QuoteNode]}getCommands(t){return {toggleBlockFormat:e=>this.toggleBlockFormat(t,e),toggleParagraph:()=>this.toggleBlockFormat(t,"p"),toggleHeading:e=>this.toggleBlockFormat(t,e),toggleQuote:()=>this.toggleBlockFormat(t,"quote"),setTextAlignment:e=>this.setTextAlignment(t,e),getCurrentBlockType:()=>this.getCurrentFormat(t)||"p"}}setTextAlignment(t,e){t.dispatchCommand(FORMAT_ELEMENT_COMMAND,e);}toggleBlockFormat(t,e){t.update(()=>{let n=$getSelection();if($isRangeSelection(n)){if(this.getCurrentFormatSync()===e){$setBlocksType(n,()=>$createParagraphNode());return}$setBlocksType(n,()=>e==="p"?$createParagraphNode():e==="quote"?$createQuoteNode():$createHeadingNode(e));}});}getStateQueries(t){return {isParagraph:()=>Promise.resolve(this.isFormat("p",t)),isH1:()=>Promise.resolve(this.isFormat("h1",t)),isH2:()=>Promise.resolve(this.isFormat("h2",t)),isH3:()=>Promise.resolve(this.isFormat("h3",t)),isH4:()=>Promise.resolve(this.isFormat("h4",t)),isH5:()=>Promise.resolve(this.isFormat("h5",t)),isH6:()=>Promise.resolve(this.isFormat("h6",t)),isQuote:()=>Promise.resolve(this.isFormat("quote",t)),isTextAlignedLeft:()=>Promise.resolve(this.isAlignment("left",t)),isTextAlignedCenter:()=>Promise.resolve(this.isAlignment("center",t)),isTextAlignedRight:()=>Promise.resolve(this.isAlignment("right",t)),isTextAlignedJustify:()=>Promise.resolve(this.isAlignment("justify",t))}}isAlignment(t,e){let n=true;return e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o)){n=false;return}let r=o.getNodes();for(let s of r){let a=this.getBlockNode(s);if(!a){n=false;break}if(this.normalizeAlignment(a.getFormatType())!==t){n=false;break}}}),n}normalizeAlignment(t){return t==="center"||t==="right"||t==="justify"?t:"left"}getBlockNode(t){let e=t;for(;e;){if($isParagraphNode(e)||$isHeadingNode(e)||$isQuoteNode(e))return e;e=e.getParent();}return null}isFormat(t,e){let n=true;return e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o)){n=false;return}let r=o.getNodes();for(let s of r){let a=this.getBlockNode(s);if(!a){n=false;break}if(this.getNodeFormat(a)!==t){n=false;break}}}),n}getNodeFormat(t){return $isParagraphNode(t)?"p":$isHeadingNode(t)?t.getTag():$isQuoteNode(t)?"quote":null}getCurrentFormat(t){let e=null;return t.getEditorState().read(()=>{let n=$getSelection();if($isRangeSelection(n)){let o=n.anchor.getNode(),r=this.getBlockNode(o);r&&(e=this.getNodeFormat(r));}}),e}getCurrentFormatSync(){let t=$getSelection();if(!$isRangeSelection(t))return null;let e=t.anchor.getNode(),n=this.getBlockNode(e);return n?this.getNodeFormat(n):null}},Zu=new Qn;var Vn=class extends k{constructor(){super("history",["toolbar"]);C(this,"canUndoState",false);C(this,"canRedoState",false);}register(e){let n=e.registerCommand(CAN_UNDO_COMMAND,r=>(this.canUndoState=r,false),COMMAND_PRIORITY_LOW),o=e.registerCommand(CAN_REDO_COMMAND,r=>(this.canRedoState=r,false),COMMAND_PRIORITY_LOW);return ()=>{n(),o();}}getPlugins(){return [jsx(HistoryPlugin,{},"history-plugin")]}getCommands(e){return {undo:()=>{e.focus(),e.dispatchCommand(UNDO_COMMAND,void 0);},redo:()=>{e.focus(),e.dispatchCommand(REDO_COMMAND,void 0);},clearHistory:()=>e.dispatchCommand(CLEAR_HISTORY_COMMAND,void 0)}}getStateQueries(e){return {canUndo:async()=>this.canUndoState,canRedo:async()=>this.canRedoState}}},sm=new Vn;var Xn=class extends k{constructor(e){super("draggableBlock",["floating"]);C(this,"isDraggingState",false);C(this,"stateChangeCallbacks",new Set);this.config={showInToolbar:false,position:"after",showMoveButtons:true,showUpButton:true,showDownButton:true,showAddButton:true,buttonStackPosition:"left",enableTextSelectionDrag:true,offsetLeft:-40,offsetRight:10,...e};}register(e){return ()=>{}}getPlugins(){return [jsx(um,{config:this.config,extension:this},"draggable-block")]}getCommands(e){return {moveBlock:(n,o,r)=>{e.isEditable()&&e.update(()=>{let s=$getNodeByKey(n),a=$getNodeByKey(o);s&&a&&(s.remove(),r?a.insertAfter(s):a.insertBefore(s));});},moveCurrentBlockUp:()=>{e.isEditable()&&e.update(()=>{let n=$getSelection();if($isRangeSelection(n)){let o=n.anchor.getNode(),r=$isElementNode(o)?o:o.getParent();if(r&&$isElementNode(r)){let s=r.getPreviousSibling();s&&(r.remove(),s.insertBefore(r));}}});},moveCurrentBlockDown:()=>{e.isEditable()&&e.update(()=>{let n=$getSelection();if($isRangeSelection(n)){let o=n.anchor.getNode(),r=$isElementNode(o)?o:o.getParent();if(r&&$isElementNode(r)){let s=r.getNextSibling();s&&(r.remove(),s.insertAfter(r));}}});}}}getStateQueries(e){return {isDragging:async()=>this.isDraggingState}}setIsDragging(e){this.isDraggingState!==e&&(this.isDraggingState=e,this.stateChangeCallbacks.forEach(n=>n()));}onStateChange(e){return this.stateChangeCallbacks.add(e),()=>this.stateChangeCallbacks.delete(e)}},dm=new Xn;function um({config:i,extension:t}){let[e]=useLexicalComposerContext(),{config:n,extensions:o}=Ie(),s=o.find(S=>S.name==="draggableBlock")?.config,a=useMemo(()=>n?.theme?.draggable||{},[n?.theme?.draggable]),[l,d]=useState(null),[c,u]=useState(false),[m,g]=useState(()=>e.isEditable()),[h,T]=useState(null),[w,p]=useState(false),b=useRef(null),f=useRef(null),y=useRef(null),E=useRef(null),N=useRef(null),v=useRef(null),x=useRef(null),L=useRef(null),[O,A]=useState(null);useEffect(()=>{t.setIsDragging(c);},[c,t]);let V=typeof document<"u"&&typeof window<"u",U=e.getRootElement(),G=V?U?.closest?.(".luthor-editor")||U?.parentElement||document.body:null,B=s?.anchorElem||i.anchorElem||G,$=useMemo(()=>({handle:{cursor:"grab",userSelect:"none"},handleActive:{cursor:"grabbing"},blockDragging:{opacity:.5},dropIndicator:{backgroundColor:"var(--luthor-accent, #3b82f6)",borderRadius:"2px"},addButton:{cursor:"pointer"},buttonStack:{}}),[]),Y=useMemo(()=>({handle:{...$.handle,...a.styles?.handle,...s?.styles?.handle},handleActive:{...$.handleActive,...a.styles?.handleActive,...s?.styles?.handleActive},blockDragging:{...$.blockDragging,...a.styles?.blockDragging,...s?.styles?.blockDragging},dropIndicator:{...$.dropIndicator,...a.styles?.dropIndicator,...s?.styles?.dropIndicator},addButton:{...$.addButton,...a.styles?.addButton,...s?.styles?.addButton},buttonStack:{...$.buttonStack,...a.styles?.buttonStack,...s?.styles?.buttonStack}}),[$,s?.styles,a.styles]),I=useMemo(()=>({handle:s?.theme?.handle||a.handle||"luthor-draggable-handle",handleActive:s?.theme?.handleActive||a.handleActive||"luthor-draggable-handle-active",blockDragging:s?.theme?.blockDragging||a.blockDragging||"luthor-draggable-block-dragging",dropIndicator:s?.theme?.dropIndicator||a.dropIndicator||"luthor-draggable-drop-indicator",addButton:s?.theme?.addButton||a.addButton||"luthor-draggable-add-button",buttonStack:s?.theme?.buttonStack||a.buttonStack||"luthor-draggable-button-stack"}),[s?.theme,a]),K=useCallback(S=>{if(!S||!I.blockDragging)return;(I.blockDragging.includes(" ")?I.blockDragging.split(" ").filter(Boolean):[I.blockDragging]).forEach(M=>S.classList.remove(M)),S.style.opacity="";},[I]),X=useCallback(S=>{if(!S||!I.blockDragging)return;(I.blockDragging.includes(" ")?I.blockDragging.split(" ").filter(Boolean):[I.blockDragging]).forEach(M=>S.classList.add(M)),Object.assign(S.style,Y.blockDragging);},[I,Y.blockDragging]);useEffect(()=>e.registerEditableListener(S=>{g(S),!S&&(u(false),T(null),d(null),p(false),b.current&&K(b.current),b.current=null,f.current=null);}),[e,K]);let se=useCallback(()=>{let S=e.getRootElement();if(S)try{S.focus({preventScroll:!0});}catch{S.focus();}},[e]),j=useCallback(()=>{b.current&&K(b.current),u(false),T(null),se(),setTimeout(()=>{b.current=null,f.current=null;},100);},[K,se]);useEffect(()=>()=>{b.current&&K(b.current),E.current&&clearTimeout(E.current),N.current!==null&&window.cancelAnimationFrame(N.current),x.current!==null&&window.cancelAnimationFrame(x.current);},[K]),useEffect(()=>{y.current=l;},[l]);let te=useCallback(S=>{v.current=S,N.current===null&&(N.current=window.requestAnimationFrame(()=>{N.current=null;let P=v.current;d(M=>M===P?M:P);}));},[]),Oe=useCallback(S=>{L.current=S,x.current===null&&(x.current=window.requestAnimationFrame(()=>{x.current=null;let P=L.current;P!=null&&A(M=>M!=null&&Math.abs(M-P)<.5?M:P);}));},[]),Ce=useCallback(S=>{let P=null;e.update(()=>{let M=$createParagraphNode(),D=$getNearestNodeFromDOMNode(S);if(D)try{D.getTopLevelElementOrThrow().insertAfter(M);}catch{$getRoot().append(M);}else $getRoot().append(M);M.selectStart(),P=M.getKey();}),P&&setTimeout(()=>{let M=e.getElementByKey(P);if(M&&M instanceof HTMLElement&&typeof M.getBoundingClientRect=="function"){te(M);let D=M.getBoundingClientRect();Oe(D.top+window.scrollY+D.height/2);}},0),se();},[e,se,te,Oe]);useEffect(()=>{if(l||b.current)p(true);else {let S=setTimeout(()=>p(false),300);return ()=>clearTimeout(S)}},[l]),useEffect(()=>{let S=M=>{if(!m){te(null);return}if(c)return;let D=e.getRootElement();if(!D)return;let _=M.target;Oe(M.clientY+window.scrollY);let R=_&&_.closest&&(_.closest(".drag-handle-area")||_.closest('[draggable="true"]')||_.closest(".luthor-drag-button")||_.closest(".luthor-draggable-button-stack")),re=window.getSelection(),W=re&&re.rangeCount>0&&!re.isCollapsed,F=null,H=_;for(;H&&H!==D&&H!==document.body;){if(H.parentElement===D){F=H;break}H=H.parentElement;}E.current&&(clearTimeout(E.current),E.current=null),(F||R)&&!W&&!c?F&&te(F):E.current=setTimeout(()=>{te(null),E.current=null;},500);},P=()=>{c||(E.current&&(clearTimeout(E.current),E.current=null),E.current=setTimeout(()=>{te(null),E.current=null;},300));};return document.addEventListener("mousemove",S),document.addEventListener("mouseleave",P),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseleave",P),E.current&&(clearTimeout(E.current),E.current=null),N.current!==null&&(window.cancelAnimationFrame(N.current),N.current=null),x.current!==null&&(window.cancelAnimationFrame(x.current),x.current=null);}},[e,c,m,te,Oe]);let De=useCallback((S,P)=>{if(!e.isEditable()){S.preventDefault();return}S.stopPropagation(),u(true),T(null),b.current=P,X(P);let M=e.read(()=>{let _=$getNearestNodeFromDOMNode(P);return _?_.getKey():null});M&&(f.current=M,S.dataTransfer?.setData("application/x-lexical-drag",JSON.stringify({key:M}))),S.dataTransfer.effectAllowed="move";let D=P.cloneNode(true);D.style.opacity="0.6",D.style.position="absolute",D.style.top="-9999px",D.style.left="-9999px",document.body.appendChild(D),S.dataTransfer.setDragImage(D,0,0),setTimeout(()=>document.body.removeChild(D),0);},[e,X]),He=useCallback((S,P)=>{if(!e.isEditable())return;S.preventDefault(),u(true),b.current=P,X(P);let M=e.read(()=>{let D=$getNearestNodeFromDOMNode(P);return D?D.getKey():null});M&&(f.current=M);},[e,X]),ge=useCallback(S=>{if(!e.isEditable()||!c||!b.current)return;S.preventDefault();let P=S.touches[0];if(!P)return;let M=e.getRootElement();if(!M)return;let D=null,_=document.elementFromPoint(P.clientX,P.clientY);if(_){let R=_;for(;R&&R!==M;){if(R.parentElement===M){D=R;break}R=R.parentElement;}}if(D&&D!==b.current){let R=D.getBoundingClientRect(),re=P.clientY<R.top+R.height/2;T({top:re?R.top+window.scrollY:R.bottom+window.scrollY,left:R.left+window.scrollX,width:R.width});}else T(null);},[e,c]),Se=useCallback(S=>{if(!e.isEditable()){j();return}if(!c||!f.current)return;S.preventDefault();let P=S.changedTouches[0];if(!P)return;let M=e.getRootElement();if(!M)return;let D=null,_=document.elementFromPoint(P.clientX,P.clientY);if(_){let R=_;for(;R&&R!==M;){if(R.parentElement===M){D=R;break}R=R.parentElement;}}D&&D!==b.current&&(e.update(()=>{let R=$getNodeByKey(f.current),re=$getNearestNodeFromDOMNode(D);if(R&&re){let W=D.getBoundingClientRect(),F=P.clientY>=W.top+W.height/2;R.remove(),F?re.insertAfter(R):re.insertBefore(R);}}),setTimeout(()=>{if(f.current)try{let R=e.getElementByKey(f.current);R&&R instanceof HTMLElement&&typeof R.getBoundingClientRect=="function"&&d(R);}catch(R){console.warn("Error finding moved element:",R);}},50)),j();},[e,c,j]);useEffect(()=>{let S=e.getRootElement();if(!S)return;let P=_=>{if(!e.isEditable()){_.preventDefault();return}let R=_.target;if(R.nodeType!==Node.ELEMENT_NODE&&(R=R.parentNode),!R||!(R instanceof HTMLElement)){_.preventDefault();return}if(R.closest('[draggable="true"]'))return;let W=window.getSelection();if(!W||W.isCollapsed||!(s?.enableTextSelectionDrag??i.enableTextSelectionDrag)){_.preventDefault();return}let F=W.anchorNode;F?.nodeType===Node.TEXT_NODE&&(F=F.parentNode);let H=null;for(;F&&F!==S;){if(F.parentNode===S){H=F;break}F=F.parentNode;}if(!H){_.preventDefault();return}W.collapse(W.anchorNode,W.anchorOffset);let ne=e.read(()=>$getNearestNodeFromDOMNode(H)?.getKey()??null);if(!ne){_.preventDefault();return}_.dataTransfer.clearData(),_.dataTransfer.setData("application/x-lexical-drag",JSON.stringify({key:ne})),_.dataTransfer.effectAllowed="move";let q=H.cloneNode(true);q.style.opacity="0.6",q.style.position="absolute",q.style.top="-9999px",q.style.left="-9999px",document.body.appendChild(q),_.dataTransfer.setDragImage(q,0,0),setTimeout(()=>document.body.removeChild(q),0),u(true),T(null),b.current=H,X(H),f.current=ne;},M=_=>{if(!e.isEditable())return;let R=_.target;if(R.nodeType!==Node.ELEMENT_NODE&&(R=R.parentNode),!R||!(R instanceof HTMLElement))return;let re=R;_.preventDefault(),_.dataTransfer.dropEffect="move";let W=null,F=re;for(;F&&F!==S;){if(F.parentElement===S){W=F;break}F=F.parentElement;}if(W&&W!==b.current){let H=W.getBoundingClientRect(),ne=_.clientY<H.top+H.height/2;T({top:ne?H.top+window.scrollY:H.bottom+window.scrollY,left:H.left+window.scrollX,width:H.width});}else T(null);},D=_=>{if(!e.isEditable())return;let R=_.target;if(R.nodeType!==Node.ELEMENT_NODE&&(R=R.parentNode),!R||!(R instanceof HTMLElement))return;let re=R;_.preventDefault(),T(null);let W=_.dataTransfer?.getData("application/x-lexical-drag");if(!W){j();return}let{key:F}=JSON.parse(W);if(!F){j();return}let H=null,ne=re;for(;ne&&ne!==S;){if(ne.parentElement===S){H=ne;break}ne=ne.parentElement;}H&&H!==b.current&&(e.update(()=>{let q=$getNodeByKey(F),Re=$getNearestNodeFromDOMNode(H);if(q&&Re){let nt=H.getBoundingClientRect(),qt=_.clientY>=nt.top+nt.height/2;q.remove(),qt?Re.insertAfter(q):Re.insertBefore(q);}}),setTimeout(()=>{if(f.current)try{let q=e.getElementByKey(f.current);q&&q instanceof HTMLElement&&typeof q.getBoundingClientRect=="function"&&d(q);}catch(q){console.warn("Error finding moved element:",q);}se();},50)),j();};return S.addEventListener("dragstart",P),S.addEventListener("dragover",M),S.addEventListener("drop",D),S.addEventListener("dragend",j),()=>{S.removeEventListener("dragstart",P),S.removeEventListener("dragover",M),S.removeEventListener("drop",D),S.removeEventListener("dragend",j);}},[e,j,X,se,s?.enableTextSelectionDrag,i.enableTextSelectionDrag]),useEffect(()=>{if(!c)return;let S=()=>{j();},P=D=>{D.key==="Escape"&&j();},M=()=>{document.hidden&&j();};return window.addEventListener("dragend",S),window.addEventListener("drop",S),window.addEventListener("blur",S),document.addEventListener("keydown",P),document.addEventListener("visibilitychange",M),()=>{window.removeEventListener("dragend",S),window.removeEventListener("drop",S),window.removeEventListener("blur",S),document.removeEventListener("keydown",P),document.removeEventListener("visibilitychange",M);}},[c,j]),useEffect(()=>{let S=e.getRootElement();if(!S)return;let P=null,M=0,D=0,_=W=>{if(!e.isEditable()||W.touches.length!==1||!(s?.enableTextSelectionDrag??i.enableTextSelectionDrag))return;let F=W.touches[0];if(!F)return;let H=W.target;if(H.nodeType!==Node.ELEMENT_NODE&&(H=H.parentNode),!H||!(H instanceof HTMLElement))return;let ne=H;ne.closest('[draggable="true"]')||(M=F.clientX,D=F.clientY,P=setTimeout(()=>{P=null;let q=null,Re=ne;for(;Re&&Re!==S;){if(Re.parentElement===S){q=Re;break}Re=Re.parentElement;}if(!q)return;let nt=window.getSelection();nt&&!nt.isCollapsed&&nt.collapseToStart(),u(true),b.current=q,X(q);let qt=e.read(()=>$getNearestNodeFromDOMNode(q)?.getKey()??null);qt&&(f.current=qt);},500));},R=W=>{if(P&&W.touches.length===1){let F=W.touches[0];if(!F)return;let H=F.clientX-M,ne=F.clientY-D;Math.sqrt(H*H+ne*ne)>10&&(clearTimeout(P),P=null);}},re=()=>{P&&(clearTimeout(P),P=null);};return S.addEventListener("touchstart",_,{passive:false}),S.addEventListener("touchmove",R,{passive:false}),S.addEventListener("touchend",re,{passive:false}),document.addEventListener("touchmove",ge,{passive:false}),document.addEventListener("touchend",Se,{passive:false}),()=>{S.removeEventListener("touchstart",_),S.removeEventListener("touchmove",R),S.removeEventListener("touchend",re),document.removeEventListener("touchmove",ge),document.removeEventListener("touchend",Se);}},[e,X,j,c,ge,Se,s?.enableTextSelectionDrag,i.enableTextSelectionDrag]);let we=l||b.current;if(!m||!V||!B||!we||typeof we.getBoundingClientRect!="function")return null;let fe=we.getBoundingClientRect();if(!fe.width||!fe.height)return null;let tt=U?.closest?.(".luthor-editor")||null,ao=tt||U;if(!ao)return null;let Ps=ao.getBoundingClientRect(),Ms=window.getComputedStyle(ao),Os=Number.parseFloat(Ms.getPropertyValue("--luthor-drag-gutter-width"))||40,ar=m&&(s?.showAddButton??i.showAddButton)!==false,Is=ar?52:24,_s=Ps.left+window.scrollX+Math.max(0,(Os-Is)/2),As=(s?.buttonStackPosition||i.buttonStackPosition)==="right"?fe.right+window.scrollX+(s?.offsetRight||i.offsetRight||10):tt?_s:fe.left+window.scrollX+(s?.offsetLeft||i.offsetLeft||-40),Wt=24,lr=Wt/2,lo=fe.top+window.scrollY,cr=fe.bottom+window.scrollY,Ds=lo+fe.height/2,Hs=O??Ds,Fs=lo+Wt/2,Bs=cr-Wt/2,zs=Math.min(Bs,Math.max(Fs,Hs)),dr=lo,$s=Math.max(dr,cr-(lr+Wt/2)),js=Math.min($s,Math.max(dr,zs-lr)),ur=B.getBoundingClientRect(),mr=B===document.body?0:ur.left+window.scrollX,gr=B===document.body?0:ur.top+window.scrollY,Ks=As-mr,Us=js-gr;return jsxs(Fragment,{children:[createPortal(jsx("div",{className:`luthor-draggable-button-stack ${I.buttonStack} ${w?"":"fade-out"}`,style:{position:"absolute",left:0,top:0,transform:`translate3d(${Ks}px, ${Us}px, 0)`,zIndex:40,display:"flex",flexDirection:"row",gap:"6px",alignItems:"center",pointerEvents:"auto",willChange:"transform, opacity",backfaceVisibility:"hidden",perspective:"1000px",transition:"transform 140ms cubic-bezier(0.2, 0, 0, 1), opacity 140ms ease",...Y.buttonStack},children:jsxs("div",{style:{display:"flex",flexDirection:"row",alignItems:"center",gap:"4px"},children:[ar&&jsx("button",{type:"button","aria-label":"Add block",title:"Add",className:`luthor-drag-button ${I.addButton}`,onMouseDown:S=>{S.preventDefault(),S.stopPropagation();},onClick:S=>{S.preventDefault(),S.stopPropagation(),!(!we||c)&&Ce(we);},style:Y.addButton,children:"+"}),s?.handleRenderer||i.handleRenderer?(s?.handleRenderer||i.handleRenderer)({rect:fe,isDragging:c,onDragStart:S=>De(S,we),className:`luthor-drag-button ${I.handle} ${c?I.handleActive:""}`.trim()}):jsx("div",{className:`luthor-drag-button ${I.handle} ${c?I.handleActive:""}`.trim(),draggable:true,onDragStart:S=>De(S,we),onDragEnd:j,onTouchStart:S=>He(S,we),style:c?Y.handleActive:Y.handle,children:"\u22EE\u22EE"})]})}),B),h&&(s?.dropIndicatorRenderer||i.dropIndicatorRenderer?createPortal((s?.dropIndicatorRenderer||i.dropIndicatorRenderer)({...h,className:I.dropIndicator}),B):createPortal(jsx("div",{className:I.dropIndicator,style:{position:"absolute",top:h.top-4-gr,left:h.left-mr,width:h.width,height:"8px",pointerEvents:"none",zIndex:9997,...Y.dropIndicator}}),B))]})}function ds(i){let t=renderToStaticMarkup(i),e=document.createElement("div");e.innerHTML=t;let n=e.firstElementChild;return e.remove(),n}function Sm(i){let t=i.isContainer??false,e=createCommand("insert-custom-node");function n({node:l,payload:d,nodeKey:c,children:u}){let[m]=useLexicalComposerContext(),[g,h]=useState(false);useEffect(()=>m.registerUpdateListener(({editorState:w})=>{w.read(()=>{let p=$getSelection();h($isNodeSelection(p)&&p.getNodes().some(b=>b.__key===c));});}),[m,c]);let T=w=>{m.update(()=>{let p=l.getWritable();p.__payload={...p.__payload,...w};});};return i.render?i.render({node:l,payload:d,children:u,nodeKey:c,isSelected:g,updatePayload:T}):null}class o extends ElementNode{constructor(c={},u,m){super(m);C(this,"__payload");C(this,"__nodeType");this.__payload=c,this.__nodeType=u;}static getType(){return i.nodeType}static clone(c){return new o(c.__payload,c.__nodeType,c.__key)}isSelectable(){return true}canBeEmpty(){return false}canInsertTextBefore(){return false}canInsertTextAfter(){return false}static importJSON(c){let{payload:u}=c;return new o(u,c.type)}static importDOM(){return i.importDOM?i.importDOM():{}}static exportDOM(c,{node:u}){if(i.exportDOM){let g=document.createElement("div");return i.exportDOM(c,{element:g,node:u})}let m=document.createElement("div");return m.setAttribute("data-custom-node-type",i.nodeType),{element:m}}exportJSON(){return {type:this.__nodeType,version:1,payload:this.__payload,children:this.getChildren().map(c=>c.exportJSON()),direction:null,format:"",indent:0}}createDOM(c){if(i.createDOM){let m=i.createDOM(c,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m.setAttribute("data-lexical-key",this.getKey()),m}if(i.jsx){let m=i.jsx({node:this,payload:this.__payload,nodeKey:this.getKey(),isSelected:false,updatePayload:h=>{this.setPayload(h);}}),g=ds(m);return g.setAttribute("data-custom-node-type",this.__nodeType),g.setAttribute("data-lexical-key",this.getKey()),g}let u=document.createElement("div");return u.setAttribute("data-custom-node-type",this.__nodeType),u.setAttribute("data-lexical-key",this.getKey()),u.style.border="2px solid #ccc",u.style.borderRadius="8px",u.style.padding="16px",u.style.margin="8px 0",u.style.position="relative",u}updateDOM(c,u,m){return i.updateDOM?i.updateDOM(c,u,m):false}getPayload(){return this.__payload}setPayload(c){let u=this.getWritable();u.__payload={...this.__payload,...c};}}class r extends DecoratorNode{constructor(c={},u,m){super(m);C(this,"__payload");C(this,"__nodeType");this.__payload=c,this.__nodeType=u;}static getType(){return i.nodeType}static clone(c){return new r(c.__payload,c.__nodeType,c.__key)}isSelectable(){return true}static importJSON(c){let{payload:u}=c;return new r(u,c.type)}static importDOM(){return i.importDOM?i.importDOM():{}}static exportDOM(c,{node:u}){if(i.exportDOM){let g=document.createElement("span");return i.exportDOM(c,{element:g,node:u})}let m=document.createElement("span");return m.setAttribute("data-custom-node-type",i.nodeType),{element:m}}exportJSON(){return {type:this.__nodeType,version:1,payload:this.__payload}}createDOM(c){let u=document.createElement("span");if(u.setAttribute("data-custom-node-type",this.__nodeType),i.createDOM){let m=i.createDOM(c,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m}return u}updateDOM(c,u,m){return i.updateDOM?i.updateDOM(c,u,m):false}getPayload(){return this.__payload}setPayload(c){let u=this.getWritable();u.__payload={...this.__payload,...c};}decorate(){return jsx(n,{node:this,payload:this.__payload,nodeKey:this.__key})}}function s(l=i.defaultPayload||{}){if(t){let d=new o(l,i.nodeType);if(i.initialChildren)i.initialChildren().forEach(u=>{if(u.type==="paragraph"){let m=$createParagraphNode();u.children&&u.children.forEach(g=>{g.type==="text"&&m.append($createTextNode(g.text||""));}),d.append(m);}});else {let c=$createParagraphNode();c.append($createTextNode("")),d.append(c);}return d}else return new r(l,i.nodeType)}class a extends k{constructor(){super(i.nodeType,["toolbar"]);}register(d){let c=d.registerCommand(e,m=>(d.update(()=>{let g=s(m),h=$getSelection();$isRangeSelection(h)?h.insertNodes([g]):$getRoot().append($createParagraphNode().append(g));}),true),COMMAND_PRIORITY_EDITOR),u=d.registerUpdateListener(({editorState:m})=>{t&&m.read(()=>{let g=$getSelection(),h=$isNodeSelection(g)?g.getNodes():[];d.getEditorState().read(()=>{let T=$getRoot(),w=p=>{if(p.getType()===i.nodeType){let b=h.some(y=>y.__key===p.__key),f=document.querySelector(`[data-lexical-key="${p.__key}"]`);f&&(f.setAttribute("data-selected",b.toString()),f.style.borderColor=b?"#007ACC":"#ccc",f.style.backgroundColor=b?"#f0f8ff":"transparent");}"getChildren"in p&&p.getChildren().forEach(w);};w(T);});});});return ()=>{c(),u();}}getNodes(){return t?[o]:[r]}getCommands(d){return {...{insertCustomNode:u=>d.dispatchCommand(e,u)},...i.commands?i.commands(d):{}}}getStateQueries(d){return {...{isCustomNodeActive:()=>new Promise(u=>{d.getEditorState().read(()=>{let m=$getSelection();u(!!m&&$isNodeSelection(m)&&m.getNodes().some(g=>g.getType()===i.nodeType));});})},...i.stateQueries?i.stateQueries(d):{}}}}return {extension:new a,$createCustomNode:s,jsxToDOM:ds}}function us(i,t,e){return e<=t?t:Math.min(e,Math.max(t,i))}function Lm(i,t,e,n){let o=i.getBoundingClientRect(),r=t.getBoundingClientRect(),s=us(e,o.left+1,o.right-1),a=us(n,r.top+1,r.bottom-1);return {x:s,y:a}}function wm(i,t){let e=document,n=window.getSelection();if(!n)return;let o=e.caretPositionFromPoint?.(i,t);if(o){let s=document.createRange();s.setStart(o.offsetNode,o.offset),s.collapse(true),n.removeAllRanges(),n.addRange(s);return}let r=e.caretRangeFromPoint?.(i,t);r&&(r.collapse(true),n.removeAllRanges(),n.addRange(r));}function ms(i,t,e){let r=Array.from(i.children).filter(l=>l instanceof HTMLElement).reduce((l,d)=>{let c=d.getBoundingClientRect(),u=c.top+c.height/2;if(!l)return d;let m=l.getBoundingClientRect(),g=m.top+m.height/2;return Math.abs(u-e)<Math.abs(g-e)?d:l},null)??i.firstElementChild??i,{x:s,y:a}=Lm(i,r,t,e);i.focus(),wm(s,a);}function Rm(i){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(()=>i());return}globalThis.setTimeout(i,0);}function gs(i){return !!i.closest(["button","a","input","textarea","select","[role='button']","[role='checkbox']","iframe","video","audio","embed","object",".luthor-list-item-unchecked",".luthor-list-item-checked","[data-lexical-iframe-embed]","[data-lexical-youtube-embed]","[data-iframe-embed]","[data-youtube-video]",".luthor-media-embed-shell"].join(", "))}var fs=i=>{let{contentEditable:t,placeholder:e,className:n,nonEditableVisualMode:o=false,onEditIntent:r,classNames:s,styles:a,errorBoundary:l}=i,d=Yt.useContext(bt),c=d?.lexical??null,[u,m]=Yt.useState(!o),g=Yt.useRef(null),h=d?.config,T=typeof h?.placeholder=="string"?h.placeholder:void 0,w=h?.classNames,p=h?.styles,b=e??T??"Start writing...",f=s?.placeholder||w?.placeholder||je.richText?.placeholder||"luthor-placeholder",y={position:"absolute",pointerEvents:"none",zIndex:1,...p?.placeholder,...a?.placeholder};return Yt.useEffect(()=>{m(!o);},[o]),Yt.useEffect(()=>{c?.setEditable(u);},[u,c]),jsx("div",{className:s?.container||w?.container||n||je.container||"luthor-editor-container",onMouseDown:E=>{if(E.button!==0)return;let N=E.target;if(!N||gs(N))return;let v=E.currentTarget,x=E.clientX,L=E.clientY;if(o&&!u){if(r){g.current={clientX:x,clientY:L};return}let A=v.querySelector("[contenteditable]");if(!A)return;E.preventDefault(),c?.setEditable(true),m(true),Rm(()=>{let V=v.querySelector("[contenteditable='true']")??A;ms(V,x,L);});return}let O=v.querySelector("[contenteditable='true']");!O||O.contains(N)||(E.preventDefault(),ms(O,x,L));},onMouseUp:E=>{if(E.button!==0||!r||!o||u){g.current=null;return}let N=E.target;if(!N||gs(N)){g.current=null;return}let v=g.current;if(g.current=null,!v)return;let x=Math.abs(E.clientX-v.clientX),L=Math.abs(E.clientY-v.clientY);if(x>4||L>4)return;let O=window.getSelection();O&&!O.isCollapsed||r({clientX:E.clientX,clientY:E.clientY});},style:{position:"relative",cursor:o?"default":"text",...p?.container,...a?.container},children:jsx(RichTextPlugin,{contentEditable:t||jsx("div",{style:{display:"block"},children:jsx(ContentEditable,{className:s?.contentEditable||w?.contentEditable||je.richText?.contentEditable||"luthor-content-editable",style:{...o?{cursor:"default",caretColor:"transparent",userSelect:"text",WebkitUserSelect:"text"}:{},...p?.contentEditable,...a?.contentEditable}})}),placeholder:typeof b=="string"?jsx("div",{className:f,style:y,children:b}):b||jsx("div",{className:f,style:y,children:"Start writing..."}),ErrorBoundary:l||Mm})})},nr=class extends k{constructor(t={}){super("richText",["floating"]),this.config={showInToolbar:false,position:"after",...t};}register(t){return ()=>{}}getPlugins(){return [jsx(fs,{...this.config},"rich-text")]}},km=new nr,Pm=i=>jsx(fs,{...i}),Mm=({children:i,onError:t})=>{try{return jsx(Fragment,{children:i})}catch(e){return console.error("RichTextPlugin Error:",e),t(e),jsxs("div",{className:"editor-error-boundary",children:[jsx("h3",{children:"Editor Error"}),jsx("p",{children:"Something went wrong with the editor. Please refresh the page."})]})}};var Cs=8,$m=9,Zn=class extends k{constructor(t={}){super("tabIndent",["toolbar"]),this.config=t;}register(t){let e=t.registerCommand(KEY_TAB_COMMAND,n=>{let o=$getSelection();if(!$isRangeSelection(o))return false;let r=o.anchor.getNode();if(this.isInCodeBlock(r))return false;n.preventDefault();let s=this.resolveTabContext(r);return s==="paragraph"?(n.shiftKey||t.update(()=>{let a=$getSelection();if($isRangeSelection(a)){if(this.hasReachedTextTabLimit(a))return;a.insertText(" ");}}),true):s==="list"?n.shiftKey?(t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0),true):(this.isListAtMaxDepth(r)||t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),true):s==="heading"?n.shiftKey?(t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0),true):(this.isBlockAtMaxIndent(r)||t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),true):true},COMMAND_PRIORITY_LOW);return ()=>{e();}}isInCodeBlock(t){let e=t;for(;e;){if($isCodeNode(e))return true;e=e.getParent();}return false}isListAtMaxDepth(t){let e=this.config.maxListDepth,n=Number.isFinite(e)?Math.max(1,Math.floor(e)):$m,o=Math.max(0,n-1),r=this.findNearestListItemNode(t);if(r&&typeof r.getIndent=="function"){let a=r.getIndent();if(typeof a=="number")return a>=o}let s=this.findNearestListNode(t);return s?$getListDepth(s)-1>=o:false}isBlockAtMaxIndent(t){let e=t;for(;e;){if($isRootOrShadowRoot(e))return false;if(typeof e.getIndent=="function"){let n=e.getIndent();if(typeof n=="number")return n>=Cs}e=e.getParent();}return false}resolveTabContext(t){let e=t;for(;e;){if($isListNode(e))return "list";if($isHeadingNode(e))return "heading";if($isParagraphNode(e))return "paragraph";if($isRootOrShadowRoot(e))break;e=e.getParent();}return "other"}findNearestListNode(t){let e=t;for(;e;){if($isListNode(e))return e;e=e.getParent();}return null}findNearestListItemNode(t){let e=t;for(;e;){if($isListItemNode(e))return e;e=e.getParent();}return null}hasReachedTextTabLimit(t){let e=t.anchor,n=e.getNode();if(typeof n.getTextContent!="function")return false;let o=n.getTextContent(),r=typeof e.offset=="number"?e.offset:o.length,s=Math.max(0,Math.min(o.length,r)),a=o.lastIndexOf(`
7
- `,s-1)+1;return (o.slice(a,s).match(/^\t*/)?.[0].length??0)>=Cs}},jm=new Zn;var Ts=[{emoji:"\u{1F600}",label:"Grinning Face",shortcodes:["grinning"],keywords:["happy","smile"]},{emoji:"\u{1F604}",label:"Smile",shortcodes:["smile"],keywords:["happy","joy"]},{emoji:"\u{1F60A}",label:"Blush",shortcodes:["blush"],keywords:["warm","happy"]},{emoji:"\u{1F609}",label:"Wink",shortcodes:["wink"],keywords:["playful"]},{emoji:"\u{1F60D}",label:"Heart Eyes",shortcodes:["heart_eyes"],keywords:["love"]},{emoji:"\u{1F618}",label:"Kiss",shortcodes:["kiss"],keywords:["love"]},{emoji:"\u{1F914}",label:"Thinking",shortcodes:["thinking"],keywords:["hmm"]},{emoji:"\u{1F60E}",label:"Cool",shortcodes:["sunglasses"],keywords:["cool"]},{emoji:"\u{1F62D}",label:"Loudly Crying",shortcodes:["sob"],keywords:["cry","sad"]},{emoji:"\u{1F622}",label:"Crying",shortcodes:["cry"],keywords:["sad"]},{emoji:"\u{1F621}",label:"Pouting",shortcodes:["rage"],keywords:["angry"]},{emoji:"\u{1F62E}",label:"Open Mouth",shortcodes:["open_mouth"],keywords:["surprised"]},{emoji:"\u{1F44D}",label:"Thumbs Up",shortcodes:["thumbsup","+1"],keywords:["approve"]},{emoji:"\u{1F44E}",label:"Thumbs Down",shortcodes:["thumbsdown","-1"],keywords:["disapprove"]},{emoji:"\u{1F44F}",label:"Clap",shortcodes:["clap"],keywords:["applause"]},{emoji:"\u{1F64F}",label:"Folded Hands",shortcodes:["pray"],keywords:["thanks"]},{emoji:"\u{1F525}",label:"Fire",shortcodes:["fire"],keywords:["lit","hot"]},{emoji:"\u2728",label:"Sparkles",shortcodes:["sparkles"],keywords:["shine"]},{emoji:"\u{1F389}",label:"Party Popper",shortcodes:["tada"],keywords:["celebrate"]},{emoji:"\u2764\uFE0F",label:"Red Heart",shortcodes:["heart"],keywords:["love"]},{emoji:"\u{1F4AF}",label:"Hundred",shortcodes:["100"],keywords:["perfect"]},{emoji:"\u2705",label:"Check Mark",shortcodes:["white_check_mark"],keywords:["done"]},{emoji:"\u{1F680}",label:"Rocket",shortcodes:["rocket"],keywords:["launch"]},{emoji:"\u{1F91D}",label:"Handshake",shortcodes:["handshake"],keywords:["agreement"]},{emoji:"\u{1F3AF}",label:"Target",shortcodes:["dart"],keywords:["goal"]},{emoji:"\u{1F4A1}",label:"Light Bulb",shortcodes:["bulb"],keywords:["idea"]},{emoji:"\u{1F9E0}",label:"Brain",shortcodes:["brain"],keywords:["think"]},{emoji:"\u{1F6E0}\uFE0F",label:"Hammer and Wrench",shortcodes:["tools"],keywords:["build"]},{emoji:"\u{1F4CC}",label:"Pushpin",shortcodes:["pushpin"],keywords:["pin"]},{emoji:"\u{1F4CE}",label:"Paperclip",shortcodes:["paperclip"],keywords:["attach"]},{emoji:"\u{1F4C5}",label:"Calendar",shortcodes:["calendar"],keywords:["date"]},{emoji:"\u{1F4DD}",label:"Memo",shortcodes:["memo"],keywords:["note"]},{emoji:"\u{1F4AC}",label:"Speech Balloon",shortcodes:["speech_balloon"],keywords:["comment"]},{emoji:"\u{1F4F7}",label:"Camera",shortcodes:["camera"],keywords:["photo"]},{emoji:"\u{1F3AC}",label:"Clapper Board",shortcodes:["clapper"],keywords:["video","gif"]}],Ns=Ts,to={":)":"\u{1F60A}",":(":"\u{1F641}",":D":"\u{1F604}",";)":"\u{1F609}",":P":"\u{1F61B}",":p":"\u{1F61B}",":O":"\u{1F62E}",":o":"\u{1F62E}",":|":"\u{1F610}",":/":"\u{1F615}",":'(":"\u{1F622}","<3":"\u2764\uFE0F"};function Qm(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vt(i){return i.trim().toLowerCase().replace(/^:+|:+$/g,"")}function vs(i){return i.toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}function ir(i){let t=i.map(o=>({...o,shortcodes:[...o.shortcodes],keywords:o.keywords?[...o.keywords]:void 0})),e=new Map,n=t.map(o=>{let r=(o.shortcodes||[]).map(a=>Vt(a)).filter(Boolean);for(let a of r)e.has(a)||e.set(a,o);let s=vs([o.label,...r,...o.keywords||[]].join(" "));return {item:o,searchable:s}});return {getAll:()=>[...t],resolveShortcode:o=>e.get(Vt(o))??null,search:(o,r)=>{let s=Math.max(0,r?.limit??t.length);if(s===0)return [];let a=vs(o);return a?n.filter(l=>l.searchable.includes(a)).slice(0,s).map(l=>l.item):t.slice(0,s)}}}function Ls(i){return Array.isArray(i)?i.map(t=>typeof t=="string"?t.trim():"").filter(t=>t.length>0):[]}function Vm(i){let t=Ls(i.shortcodes);return t.length>0?t.map(e=>Vt(e)):typeof i.shortcodes=="string"?i.shortcodes.split(/[,\s]+/).map(e=>Vt(e)).filter(Boolean):[]}function rr(i){if(!i||typeof i!="object")return null;let t=i;if(!t.emojis||typeof t.emojis!="object")return null;let e=[];for(let[n,o]of Object.entries(t.emojis)){if(!o||typeof o!="object")continue;let r=o,s=typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():n,l=(Array.isArray(r.skins)?r.skins:[])[0],d=typeof l?.native=="string"?l.native:"";if(!d)continue;let c=Array.from(new Set([Vt(n),...Vm(r)].filter(Boolean)));c.length!==0&&e.push({emoji:d,label:s,shortcodes:c,keywords:Ls(r.keywords)});}return e.length===0?null:ir(e)}async function Wm(i){return new Function("name","return import(name);")(i)}var no=class extends k{constructor(e={}){super("emoji",["toolbar"]);C(this,"listeners",[]);C(this,"isOpen",false);C(this,"query","");C(this,"position",null);C(this,"suggestions",[]);C(this,"activeMatch",null);C(this,"viewportRafId",null);C(this,"applyingAutoReplace",false);C(this,"catalogAdapter",ir(Ns));C(this,"hasExplicitCatalogConfig",false);C(this,"hasExplicitAdapterConfig",false);C(this,"externalCatalogDetectionStarted",false);this.hasExplicitCatalogConfig=Object.prototype.hasOwnProperty.call(e,"catalog"),this.hasExplicitAdapterConfig=Object.prototype.hasOwnProperty.call(e,"catalogAdapter"),this.config={trigger:":",maxSuggestions:8,maxQueryLength:32,autoReplaceSymbols:true,symbolReplacements:to,autoDetectExternalCatalog:true,offset:{x:0,y:8},...e},this.catalogAdapter=this.resolveCatalogAdapter(this.config);}configure(e){return this.config={...this.config,...e,symbolReplacements:{...this.config.symbolReplacements||to,...e.symbolReplacements||{}}},Object.prototype.hasOwnProperty.call(e,"catalog")&&(this.hasExplicitCatalogConfig=true),Object.prototype.hasOwnProperty.call(e,"catalogAdapter")&&(this.hasExplicitAdapterConfig=true),this.catalogAdapter=this.resolveCatalogAdapter(this.config),this.isOpen&&(this.suggestions=this.getSuggestions(this.query),this.isOpen=this.suggestions.length>0,this.notifyListeners()),this}register(e){this.tryEnableExternalCatalog();let n=e.registerUpdateListener(()=>{this.updateFromSelection(e);}),o=e.registerCommand(PASTE_COMMAND,l=>{if(!this.config.autoReplaceSymbols)return false;let d=l.clipboardData;if(!d)return false;let c=d.getData("text/plain"),u=d.getData("text/html");if(!c||u)return false;let m=this.replaceSymbolsInText(c);return m===c?false:(l.preventDefault(),e.update(()=>{let g=$getSelection();$isRangeSelection(g)&&g.insertText(m);}),true)},COMMAND_PRIORITY_EDITOR),r=l=>{this.isOpen&&l.key==="Escape"&&(l.preventDefault(),this.closeEmojiSuggestions());},s=l=>{l.target?.closest(".luthor-emoji-menu")||this.isOpen&&this.closeEmojiSuggestions();},a=()=>{!this.isOpen||!this.activeMatch||this.viewportRafId===null&&(this.viewportRafId=window.requestAnimationFrame(()=>{this.viewportRafId=null;let l=this.getCaretPosition();if(!l){this.closeEmojiSuggestions();return}this.position=l,this.notifyListeners();}));};return document.addEventListener("keydown",r),document.addEventListener("pointerdown",s),window.addEventListener("scroll",a,true),window.addEventListener("resize",a),()=>{n(),o(),document.removeEventListener("keydown",r),document.removeEventListener("pointerdown",s),window.removeEventListener("scroll",a,true),window.removeEventListener("resize",a),this.viewportRafId!==null&&(cancelAnimationFrame(this.viewportRafId),this.viewportRafId=null),this.activeMatch=null,this.isOpen=false,this.query="",this.position=null,this.suggestions=[],this.notifyListeners();}}getCommands(e){return {insertEmoji:n=>{e.update(()=>{let o=$getSelection();$isRangeSelection(o)&&o.insertText(n);});},executeEmojiSuggestion:n=>this.executeEmojiSuggestion(e,n),closeEmojiSuggestions:()=>this.closeEmojiSuggestions(),getEmojiSuggestions:(n="")=>this.getSuggestions(n),getEmojiCatalog:()=>this.getCatalog(),resolveEmojiShortcode:n=>this.resolveShortcode(n),setEmojiCatalog:n=>{this.hasExplicitCatalogConfig=true,this.hasExplicitAdapterConfig=false,this.config={...this.config,catalog:[...n],catalogAdapter:void 0},this.catalogAdapter=this.resolveCatalogAdapter(this.config),this.isOpen&&(this.suggestions=this.getSuggestions(this.query),this.isOpen=this.suggestions.length>0,this.notifyListeners());},setEmojiCatalogAdapter:n=>{this.hasExplicitAdapterConfig=true,this.config={...this.config,catalogAdapter:n},this.catalogAdapter=this.resolveCatalogAdapter(this.config),this.isOpen&&(this.suggestions=this.getSuggestions(this.query),this.isOpen=this.suggestions.length>0,this.notifyListeners());},getEmojiCatalogAdapter:()=>this.catalogAdapter}}getStateQueries(e){return {isEmojiSuggestionOpen:()=>Promise.resolve(this.isOpen)}}subscribe(e){return this.listeners.push(e),e(this.getState()),()=>{this.listeners=this.listeners.filter(n=>n!==e);}}getCatalog(){return this.catalogAdapter.getAll()}getSuggestions(e){let n=this.config.maxSuggestions??8;return this.catalogAdapter.search(e,{limit:n})}resolveShortcode(e){return this.catalogAdapter.resolveShortcode(e)}resolveCatalogAdapter(e){return e.catalogAdapter?e.catalogAdapter:ir(e.catalog||Ns)}async tryEnableExternalCatalog(){if(this.externalCatalogDetectionStarted||(this.externalCatalogDetectionStarted=true,!this.config.autoDetectExternalCatalog)||this.hasExplicitCatalogConfig||this.hasExplicitAdapterConfig)return;let e=globalThis.__EMOJI_MART_DATA__||globalThis.EmojiMart?.data,n=rr(e);if(n){this.catalogAdapter=n,this.refreshSuggestionsIfOpen();return}try{let r=await Wm("@emoji-mart/data"),s=rr(r.default)||rr(r.data);s&&(this.catalogAdapter=s,this.refreshSuggestionsIfOpen());}catch{}}refreshSuggestionsIfOpen(){this.isOpen&&(this.suggestions=this.getSuggestions(this.query),this.isOpen=this.suggestions.length>0,this.notifyListeners());}updateFromSelection(e){let n=null;if(e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o)||!o.isCollapsed()){this.closeIfNeeded();return}if(this.isSelectionInsideCodeBlock(o)){this.closeIfNeeded();return}let r=o.anchor.getNode();if(!$isTextNode(r)){this.closeIfNeeded();return}let s=o.anchor.offset,a=r.getTextContent(),l=a.slice(0,s);if(this.config.autoReplaceSymbols&&!this.applyingAutoReplace){let w=this.detectSymbolReplacement(a,l,s);w&&(n={nodeKey:r.getKey(),startOffset:w.startOffset,endOffset:w.endOffset,emoji:w.emoji});}let d=this.config.trigger||":",c=l.lastIndexOf(d);if(c<0){this.closeIfNeeded();return}let u=l.slice(0,c);if(!(u.length===0||/\s/.test(u[u.length-1]||""))){this.closeIfNeeded();return}let g=l.slice(c+d.length);if(/\s/.test(g)||g.length>(this.config.maxQueryLength??32)){this.closeIfNeeded();return}let h=this.getSuggestions(g),T=this.getCaretPosition();this.query=g,this.position=T,this.suggestions=h,this.isOpen=h.length>0,this.activeMatch={nodeKey:r.getKey(),startOffset:c,endOffset:s},this.notifyListeners();}),n!==null){let o=n;this.applyingAutoReplace=true,e.update(()=>{let r=$getNodeByKey(o.nodeKey);if(!$isTextNode(r))return;let s=Math.max(0,o.endOffset-o.startOffset);r.spliceText(o.startOffset,s,o.emoji,true);let a=o.startOffset+o.emoji.length;r.select(a,a);}),this.applyingAutoReplace=false;}}isSelectionInsideCodeBlock(e){if(!$isRangeSelection(e))return false;let n=e.anchor.getNode();for(;n;){if($isCodeNode(n))return true;n=n.getParent();}return false}detectSymbolReplacement(e,n,o){let r=Object.entries(this.config.symbolReplacements||to).sort((s,a)=>a[0].length-s[0].length);for(let[s,a]of r){if(!n.endsWith(s))continue;let l=o-s.length,d=l>0&&e[l-1]||"",c=o<e.length&&e[o]||"",u=l===0||/\s|[([{>"'`]/.test(d),m=o===e.length||/\s|[.,!?;:)\]}"'`]/.test(c);if(u&&m)return {startOffset:l,endOffset:o,emoji:a}}return null}replaceSymbolsInText(e){let n=Object.entries(this.config.symbolReplacements||to),o=e;for(let[r,s]of n){let a=Qm(r),l=new RegExp(`(^|\\s)${a}(?=$|\\s|[.,!?;:])`,"g");o=o.replace(l,`$1${s}`);}return o}executeEmojiSuggestion(e,n){if(!n)return false;if(this.activeMatch){let o=this.activeMatch;return e.update(()=>{let r=$getNodeByKey(o.nodeKey);if(!$isTextNode(r))return;let s=Math.max(0,o.endOffset-o.startOffset);r.spliceText(o.startOffset,s,n,true);let a=o.startOffset+n.length;r.select(a,a);}),this.closeEmojiSuggestions(),true}return e.update(()=>{let o=$getSelection();$isRangeSelection(o)&&o.insertText(n);}),this.closeEmojiSuggestions(),true}closeEmojiSuggestions(){this.isOpen=false,this.query="",this.position=null,this.suggestions=[],this.activeMatch=null,this.notifyListeners();}closeIfNeeded(){!this.isOpen&&!this.activeMatch||this.closeEmojiSuggestions();}getCaretPosition(){if(typeof window>"u")return null;let e=window.getSelection();if(!e||e.rangeCount===0)return null;let n=e.getRangeAt(0).cloneRange();n.collapse(true);let o=n.getBoundingClientRect(),s=n.getClientRects()[0]||o;return {x:s.left+(this.config.offset?.x??0),y:s.bottom+(this.config.offset?.y??8)}}getState(){return {isOpen:this.isOpen,query:this.query,position:this.position,suggestions:this.suggestions}}notifyListeners(){let e=this.getState();this.listeners.forEach(n=>n(e));}},qm=new no;var oo=class extends k{constructor(){super("floatingToolbar",["floating"]);C(this,"isVisible",false);C(this,"selectionRect",null);this.config={render:()=>null,debounceMs:100,offset:{x:0,y:8},positionStrategy:"below",theme:{container:"luthor-floating-toolbar",button:"luthor-floating-toolbar-button",buttonActive:"luthor-floating-toolbar-button-active"}};}register(e){return ()=>{}}getPlugins(){return [jsx(og,{extension:this,config:this.config},"floating-toolbar")]}getCommands(e){return {}}getStateQueries(e){return {isFloatingVisible:async()=>this.isVisible}}updateContext(e,n){this.config&&(this.config.commands=e,this.config.activeStates=n);}getSelectionRect(){return this.selectionRect}getIsVisible(){return this.isVisible}setVisible(e){this.isVisible=e;}setSelectionRect(e){this.selectionRect=e;}},ng=new oo;function og({extension:i,config:t}){let[e]=useLexicalComposerContext(),{config:n}=Ie(),[o,r]=useState(false),[s,a]=useState(null),[l,d]=useState(null),c=useRef(null),u=f=>(f.querySelector('[data-luthor-selection-anchor="true"]')??f).getBoundingClientRect(),m=(f,y)=>{let E;return (...N)=>{clearTimeout(E),E=setTimeout(()=>f(()=>N),y);}},g=useCallback((f,y)=>{if(typeof window>"u"||y===document.body)return f;let E=window.pageXOffset||document.documentElement.scrollLeft||0,N=window.pageYOffset||document.documentElement.scrollTop||0,v=y.getBoundingClientRect(),x=v.left+E,L=v.top+N,O=t.toolbarDimensions?.width||300,A=t.toolbarDimensions?.height||40,V=f.x-x,U=f.y-L,G=Math.max(10,Math.min(V,Math.max(10,v.width-O-10))),B=Math.max(10,Math.min(U,Math.max(10,v.height-A-10)));return {...f,x:G,y:B,top:f.top-L,left:f.left-x,bottom:f.bottom-L,right:f.right-x,positionFromRight:false}},[t.toolbarDimensions?.height,t.toolbarDimensions?.width]),h=useCallback(f=>{let y=t.offset||{y:8},E=t.positionStrategy||"below",N=window.pageXOffset||document.documentElement.scrollLeft||0,v=window.pageYOffset||document.documentElement.scrollTop||0,x=window.innerWidth,L=window.innerHeight,O=f.bottom+v+y.y;E==="above"?O=f.top+v-y.y:E==="auto"&&(O=L-f.bottom>60?f.bottom+v+y.y:f.top+v-y.y);let A=t.getActiveStates?.(),V=!!A?.isIframeEmbedSelected||!!A?.isYouTubeEmbedSelected,U=t.toolbarDimensions?.width||(V?132:300),G=t.toolbarDimensions?.height||40,B=10,$=f.left+f.width/2,Y=$+N,I,K,X=$-B,se=x-$-B,j=U/2,te=$-j,Oe=$+j,Ce=te<B,De=Oe>x-B;return !Ce&&!De?(I=Y-j,K=false):Ce||X<j?(I=N+B,K=false):De||se<j?(I=N+x-U-B,K=true):(I=Y-j,K=false),O-G<v?O=f.bottom+v+y.y:O+G>v+L&&(O=f.top+v-y.y-G),{x:I,y:O,width:f.width,height:f.height,top:f.top+v,left:f.left+N,bottom:f.bottom+v,right:f.right+N,positionFromRight:K}},[t]);useEffect(()=>{i.setVisible(o);},[o,i]),useEffect(()=>{let f=()=>{e.getEditorState().read(()=>{let x=$getSelection(),L=null,O=null;if($isRangeSelection(x)&&!x.isCollapsed()){let A=window.getSelection();A&&A.rangeCount>0&&(L=A.getRangeAt(0).getBoundingClientRect(),O=x);}else if($isNodeSelection(x)){let A=x.getNodes();if(A.length>0){let V=A[0];if(V){let U=V.getKey(),G=e.getElementByKey(U);G&&(L=u(G));}}}if(L&&L.width>0&&L.height>0){let A=h(L);a(A),d(O),r(true),i.setSelectionRect(A);}else a(null),d(null),r(false),i.setSelectionRect(null);});},y=m(f,t.debounceMs||100),E=e.registerUpdateListener(()=>{y();}),N=()=>{y();},v=()=>{c.current===null&&(c.current=window.requestAnimationFrame(()=>{c.current=null,f();}));};return document.addEventListener("selectionchange",N),window.addEventListener("scroll",v,true),window.addEventListener("resize",v),()=>{E(),document.removeEventListener("selectionchange",N),window.removeEventListener("scroll",v,true),window.removeEventListener("resize",v),c.current!==null&&(cancelAnimationFrame(c.current),c.current=null);}},[e,t.debounceMs,h,i]);let T=()=>{r(false),a(null),d(null);};if(!t.render)return console.warn("FloatingToolbarExtension: No render function provided in config."),null;if(typeof document>"u")return null;let w=e.getRootElement()?.closest(".luthor-editor-wrapper"),p=t.anchorElem||w||document.body,b=s&&p?g(s,p):s;return createPortal(t.render({isVisible:o,selectionRect:b,selection:l,editor:e,commands:t.getCommands?.()||{},activeStates:t.getActiveStates?.()||{},hide:T,theme:n?.theme?.floatingToolbar||t.theme||{}}),p)}var ro=class extends k{constructor(){super("commandPalette",["toolbar"]);C(this,"isOpen",false);C(this,"commands",new Map);C(this,"listeners",[]);}register(e){let n=o=>{(o.metaKey||o.ctrlKey)&&o.shiftKey&&o.key==="P"&&(o.preventDefault(),this.toggleCommandPalette()),o.key==="Escape"&&this.isOpen&&this.hideCommandPalette();};return document.addEventListener("keydown",n),this.registerTableCommands(e),()=>{document.removeEventListener("keydown",n);}}getCommands(e){return {showCommandPalette:()=>this.showCommandPalette(),hideCommandPalette:()=>this.hideCommandPalette(),registerCommand:n=>this.registerCommand(n),unregisterCommand:n=>this.unregisterCommand(n)}}getStateQueries(e){return {isCommandPaletteOpen:()=>Promise.resolve(this.isOpen)}}showCommandPalette(){this.isOpen=true,this.notifyListeners();}hideCommandPalette(){this.isOpen=false,this.notifyListeners();}toggleCommandPalette(){this.isOpen=!this.isOpen,this.notifyListeners();}registerCommand(e){this.commands.set(e.id,e),this.notifyListeners();}unregisterCommand(e){this.commands.delete(e),this.notifyListeners();}registerTableCommands(e){[{id:"table.insertRowAbove",label:"Insert Row Above",category:"Table",action:()=>{console.log("Insert row above");},keywords:["table","row","insert","above"]},{id:"table.insertRowBelow",label:"Insert Row Below",category:"Table",action:()=>{console.log("Insert row below");},keywords:["table","row","insert","below"]},{id:"table.insertColumnLeft",label:"Insert Column Left",category:"Table",action:()=>{console.log("Insert column left");},keywords:["table","column","insert","left"]},{id:"table.insertColumnRight",label:"Insert Column Right",category:"Table",action:()=>{console.log("Insert column right");},keywords:["table","column","insert","right"]},{id:"table.deleteRow",label:"Delete Row",category:"Table",action:()=>{console.log("Delete row");},keywords:["table","row","delete","remove"]},{id:"table.deleteColumn",label:"Delete Column",category:"Table",action:()=>{console.log("Delete column");},keywords:["table","column","delete","remove"]}].forEach(o=>this.registerCommand(o));}notifyListeners(){let e=Array.from(this.commands.values());this.listeners.forEach(n=>n(this.isOpen,e));}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(n=>n!==e);}}getAllCommands(){return Array.from(this.commands.values())}},ig=new ro;var cg=new Set(["paragraph","heading"]),io=class extends k{constructor(e={}){super("slashCommand",["toolbar"]);C(this,"commands",new Map);C(this,"listeners",[]);C(this,"isOpen",false);C(this,"query","");C(this,"position",null);C(this,"activeMatch",null);C(this,"viewportRafId",null);this.config={trigger:"/",offset:{x:0,y:8},...e},this.setSlashCommands(this.config.items??[]);}register(e){let n=e.registerUpdateListener(()=>{this.updateMatchFromSelection(e);}),o=a=>{this.isOpen&&a.key==="Escape"&&(a.preventDefault(),this.closeSlashMenu());};document.addEventListener("keydown",o);let r=a=>{a.target?.closest(".luthor-slash-menu")||this.isOpen&&this.closeSlashMenu();},s=()=>{!this.isOpen||!this.activeMatch||this.viewportRafId===null&&(this.viewportRafId=window.requestAnimationFrame(()=>{this.viewportRafId=null;let a=this.getCaretPosition();if(!a){this.closeSlashMenu();return}this.position=a,this.notifyListeners();}));};return document.addEventListener("pointerdown",r),window.addEventListener("scroll",s,true),window.addEventListener("resize",s),()=>{n(),document.removeEventListener("keydown",o),document.removeEventListener("pointerdown",r),window.removeEventListener("scroll",s,true),window.removeEventListener("resize",s),this.viewportRafId!==null&&(cancelAnimationFrame(this.viewportRafId),this.viewportRafId=null),this.activeMatch=null,this.isOpen=false,this.query="",this.position=null,this.notifyListeners();}}getCommands(e){return {registerSlashCommand:n=>this.registerSlashCommand(n),unregisterSlashCommand:n=>this.unregisterSlashCommand(n),setSlashCommands:n=>this.setSlashCommands(n),closeSlashMenu:()=>this.closeSlashMenu(),executeSlashCommand:n=>this.executeSlashCommand(e,n)}}getStateQueries(e){return {isSlashMenuOpen:()=>Promise.resolve(this.isOpen)}}subscribe(e){return this.listeners.push(e),e(this.getState()),()=>{this.listeners=this.listeners.filter(n=>n!==e);}}getAllCommands(){return Array.from(this.commands.values())}registerSlashCommand(e){this.commands.set(e.id,e),this.notifyListeners();}unregisterSlashCommand(e){this.commands.delete(e),this.notifyListeners();}setSlashCommands(e){let n=new Map;for(let o of e)!o?.id||n.has(o.id)||n.set(o.id,o);this.commands=n,this.notifyListeners();}closeSlashMenu(){this.isOpen=false,this.query="",this.position=null,this.activeMatch=null,this.notifyListeners();}executeSlashCommand(e,n){let o=this.commands.get(n);if(!o)return false;if(this.activeMatch){let r=this.activeMatch;e.update(()=>{let s=$getNodeByKey(r.nodeKey);if(!$isTextNode(s))return;let a=Math.max(0,Math.min(r.endOffset,s.getTextContentSize()));s.select(a,a);let l=Math.max(0,r.endOffset-r.startOffset);l>0&&s.spliceText(r.startOffset,l,"",true);});}return this.closeSlashMenu(),o.action(),true}updateMatchFromSelection(e){e.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n)||!n.isCollapsed()){this.closeIfNeeded();return}let o=n.anchor.getNode();if(!$isTextNode(o)){this.closeIfNeeded();return}let r=ug(o);if(!cg.has(r)){this.closeIfNeeded();return}let s=n.anchor.offset,l=o.getTextContent().slice(0,s),d=this.config.trigger||"/",c=l.lastIndexOf(d);if(c<0){this.closeIfNeeded();return}let u=l.slice(0,c);if(!mg(u)){this.closeIfNeeded();return}let m=l.slice(c+d.length);if(/\s/.test(m)){this.closeIfNeeded();return}let g=this.getCaretPosition();this.isOpen=true,this.query=m,this.position=g,this.activeMatch={nodeKey:o.getKey(),startOffset:c,endOffset:s,query:m},this.notifyListeners();});}closeIfNeeded(){!this.isOpen&&!this.activeMatch||this.closeSlashMenu();}getCaretPosition(){if(typeof window>"u")return null;let e=window.getSelection();if(!e||e.rangeCount===0)return null;let n=e.getRangeAt(0).cloneRange();n.collapse(true);let o=n.getBoundingClientRect(),s=n.getClientRects()[0]||o,a=this.config.offset?.x??0,l=this.config.offset?.y??8;return {x:s.left+a,y:s.bottom+l}}getState(){return {isOpen:this.isOpen,query:this.query,position:this.position,commands:this.getAllCommands()}}notifyListeners(){let e=this.getState();this.listeners.forEach(n=>n(e));}},dg=new io;function ug(i){try{return i.getTopLevelElementOrThrow?.()?.getType?.()??""}catch{return ""}}function mg(i){return i.trim().length===0}var so=class extends k{constructor(){super("enterKeyBehavior",["floating"]),this.config={...this.config||{},showInToolbar:false,initPriority:100};}register(t){let e,n=r=>{if(r.key!=="Enter")return;let s=false;t.update(()=>{let a=$getSelection();if(!$isRangeSelection(a))return;let l=a.anchor.getNode();if(r.shiftKey){let T=$findCellNode(l);if($isTableCellNode(T)){let b=$getTableNodeFromLexicalNodeOrThrow(T),f=$createParagraphNode();b.insertAfter(f),f.selectStart(),s=true;return}let w=this.findQuoteNode(l);if(w){let b=$createParagraphNode();w.insertAfter(b),b.selectStart(),s=true;return}let p=this.findCodeNode(l);if(p){let b=$createParagraphNode();p.insertAfter(b),b.selectStart(),s=true;return}return}let d=this.findQuoteNode(l);if(!d||!a.isCollapsed())return;let c=this.findDirectQuoteChild(l,d)||d.getLastChild();if(!c){let T=$createParagraphNode();d.append(T),T.selectStart(),s=true;return}let u=this.isEmptyQuoteLine(c),m=c.getPreviousSibling(),g=this.isEmptyQuoteLine(m);if(u&&g){let T=c,w=m;T.remove(),w?.remove();let p=$createParagraphNode();d.insertAfter(p),p.selectStart(),s=true;return}let h=$createParagraphNode();c.insertAfter(h),h.selectStart(),s=true;}),s&&(r.preventDefault(),r.stopPropagation());},o=t.registerRootListener((r,s)=>{e?.(),e=void 0,s&&s.removeEventListener("keydown",n,true),r&&(r.addEventListener("keydown",n,true),e=()=>{r.removeEventListener("keydown",n,true);});});return ()=>{e?.(),o();}}getCommands(t){return {insertHardBreak:()=>{t.focus(),t.dispatchCommand(INSERT_LINE_BREAK_COMMAND,false);}}}findQuoteNode(t){let e=t;for(;e;){if($isQuoteNode(e))return e;e=e.getParent();}return null}findCodeNode(t){let e=t;for(;e;){if($isCodeNode(e))return e;e=e.getParent();}return null}findDirectQuoteChild(t,e){let n=t;for(;n&&n.getParent&&n.getParent()!==e;)n=n.getParent();return n?.getParent&&n.getParent()===e?n:null}isEmptyQuoteLine(t){return t?t.getTextContent().trim()==="":false}},Cg=new so;export{k as BaseExtension,sa as BaseProvider,Qn as BlockFormatExtension,rn as BoldExtension,zn as CodeExtension,Un as CodeFormatExtension,Kn as CodeIntelligenceExtension,ro as CommandPaletteExtension,Cn as ContextMenuExtension,Xn as DraggableBlockExtension,no as EmojiExtension,so as EnterKeyBehaviorExtension,la as ExtensionCategory,oo as FloatingToolbarExtension,un as FontFamilyExtension,mn as FontSizeExtension,Vn as HistoryExtension,dn as HorizontalRuleExtension,en as IframeEmbedExtension,Gt as ImageExtension,sn as ItalicExtension,Ts as LIGHTWEIGHT_EMOJI_CATALOG,fr as LUTHOR_EDITOR_THEME_TOKENS,gn as LineHeightExtension,cn as LinkExtension,Dn as ListExtension,Pm as RichText,io as SlashCommandExtension,ln as StrikethroughExtension,bn as SubscriptExtension,yn as SuperscriptExtension,Zn as TabIndentExtension,Ln as TableExtension,pn as TextColorExtension,ie as TextFormatExtension,hn as TextHighlightExtension,an as UnderlineExtension,nn as YouTubeEmbedExtension,It as appendMetadataEnvelopes,Zu as blockFormatExtension,Pc as boldExtension,ua as clearLexicalSelection,Su as codeExtension,ju as codeFormatExtension,Bu as codeIntelligenceExtension,ig as commandPaletteExtension,Ao as contextMenuExtension,Sm as createCustomNodeExtension,br as createEditorSystem,Ws as createEditorThemeStyleVars,ca as createExtension,je as defaultLuthorTheme,dm as draggableBlockExtension,qm as emojiExtension,Cg as enterKeyBehaviorExtension,_t as extractMetadataEnvelopes,ng as floatingToolbarExtension,ld as fontFamilyExtension,gd as fontSizeExtension,sm as historyExtension,nd as horizontalRuleExtension,Rc as htmlToJSON,Ba as iframeEmbedExtension,La as imageExtension,Js as isLuthorTheme,Mc as italicExtension,kc as jsonToHTML,Jl as jsonToMarkdown,xd as lineHeightExtension,Kc as linkExtension,mu as listExtension,ql as markdownToJSON,qs as mergeThemes,Ot as prepareDocumentForBridge,At as rehydrateDocumentFromEnvelopes,ma as resolveLinkNodeKeyFromAnchor,km as richTextExtension,dg as slashCommandExtension,_c as strikethroughExtension,wd as subscriptExtension,Rd as superscriptExtension,jm as tabIndentExtension,Xd as tableExtension,Nd as textColorExtension,Ld as textHighlightExtension,Ic as underlineExtension,Ie as useBaseEditor,Ja as youTubeEmbedExtension};
4
+ `}${n}`:n}function Dt(i){let t=[],e=[],n=new RegExp(Za.source,"g");for(let o of i.matchAll(n)){if(Number.parseInt(o[1]??"",10)!==1){e.push(`Ignoring metadata envelope version v${o[1]??"unknown"}.`);continue}try{let s=JSON.parse(o[2]??"");if(!ke(s)){e.push("Ignoring metadata envelope with non-object payload.");continue}let a=typeof s.type=="string"?s.type:"",l=typeof s.id=="string"?s.id:"",c=typeof s.fallback=="string"?s.fallback:"",d=s.strategy==="merge"||s.strategy==="replace"?s.strategy:void 0,m=(Array.isArray(s.path)?s.path:[]).filter(p=>Number.isInteger(p)&&p>=0).map(p=>Number(p)),g=ke(s.node)?s.node:null;if(!l||!a||!g){e.push("Ignoring metadata envelope with missing required fields.");continue}t.push({id:l,type:a,path:m,node:g,fallback:c,strategy:d});}catch{e.push("Ignoring malformed metadata envelope payload.");}}return {content:i.replace(n,"").trimEnd(),envelopes:t,warnings:e}}function Ht(i,t){if(t.length===0)return i;let e=lt(i.root);for(let n of t){if(n.strategy==="merge"){sl(e,n.path,n.node);continue}if(rl(e,n.path,n.node))continue;Array.isArray(e.children)||(e.children=[]),e.children.push(lt(n.node));}return {...i,root:e}}function al(i){return Object.keys(i).length>0}function an(i,t){let e=Yr(i),n=Array.isArray(e.root.children)?e.root.children:[],o=[],r=(s,a)=>{for(let[l,c]of s.entries()){if(!ke(c))continue;let d=[...a,l],u=typeof c.type=="string"?c.type:"";if(!u||!t.supportedNodeTypes.has(u))continue;let m=t.extractPatch({mode:t.mode,type:u,path:d,node:c});m&&al(m)&&o.push({id:Kr(u,d,o.length+1),type:u,path:d,node:m,fallback:"",strategy:"merge"}),Array.isArray(c.children)&&r(c.children,d);}};return r(n,[]),o}var Dl={dependencies:[HorizontalRuleNode],export:i=>$isHorizontalRuleNode(i)?"---":null,regExp:/^(?:---|___)\s*$/,replace:(i,t,e)=>{i.replace($createHorizontalRuleNode());},type:"element"},Hl={format:["underline"],tag:"++",type:"text-format"};function Zr(i){return i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ei(i){return i.replace(/\\(["\\])/g,"$1")}function ti(i){try{let t=JSON.parse(i);if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}catch{return null}return null}var Fl={dependencies:[G],export:i=>{if(!(i instanceof G))return null;let t=i.getPayload(),e=t.caption??"",n=e?` "${Zr(e)}"`:"";return `[iframe](${t.src}${n})`},regExp:/^\[iframe\]\(([^)\s]+)(?:\s+"((?:[^"\\]|\\.)*)")?\)\s*(?:<!--\s*luthor:iframe\s+({[\s\S]*?})\s*-->)?\s*$/,replace:(i,t,e)=>{let[,n,o,r]=e;if(!n)return;let s=typeof o=="string"?ei(o):"",a=640,l=360,c="center",d;if(typeof r=="string"&&r.length>0){let u=ti(r);if(u){let m=Number(u.width);Number.isFinite(m)&&(a=m);let g=Number(u.height);Number.isFinite(g)&&(l=g),(u.alignment==="left"||u.alignment==="center"||u.alignment==="right")&&(c=u.alignment),typeof u.title=="string"&&(d=u.title);}}i.replace(new G({src:n,width:a,height:l,alignment:c,title:d,caption:s}));},type:"element"},Bl={dependencies:[V],export:i=>{if(!(i instanceof V))return null;let t=i.getPayload(),e=t.caption??"",n=e?` "${Zr(e)}"`:"";return `[youtube](${t.src}${n})`},regExp:/^\[youtube\]\(([^)\s]+)(?:\s+"((?:[^"\\]|\\.)*)")?\)\s*(?:<!--\s*luthor:youtube\s+({[\s\S]*?})\s*-->)?\s*$/,replace:(i,t,e)=>{let[,n,o,r]=e;if(!n)return;let s=typeof o=="string"?ei(o):"",a=640,l=360,c="center",d=0;if(typeof r=="string"&&r.length>0){let u=ti(r);if(u){let m=Number(u.width);Number.isFinite(m)&&(a=m);let g=Number(u.height);Number.isFinite(g)&&(l=g),(u.alignment==="left"||u.alignment==="center"||u.alignment==="right")&&(c=u.alignment);let p=Number(u.start);Number.isFinite(p)&&(d=p);}}i.replace(new V({src:n,width:a,height:l,alignment:c,caption:s,start:d}));},type:"element"},zl={dependencies:[TableNode,TableRowNode,TableCellNode],export:i=>{if(!$isTableNode(i))return null;let t=i.getChildren();if(t.length===0)return null;let e=[];if(t.forEach(r=>{if(!$isTableRowNode(r))return;let s=[];r.getChildren().forEach(a=>{$isTableCellNode(a)&&s.push(a.getTextContent().trim());}),s.length>0&&e.push(s);}),e.length===0||!e[0])return null;let n=[];n.push(`| ${e[0].join(" | ")} |`);let o=e[0].length||1;n.push(`| ${Array(o).fill("---").join(" | ")} |`);for(let r=1;r<e.length;r+=1){let a=[...e[r]??[]];for(;a.length<o;)a.push("");n.push(`| ${a.join(" | ")} |`);}return n.join(`
5
+ `)},regExpStart:/^\|.*\|$/,regExpEnd:{optional:true,regExp:/^$/},replace:(i,t,e,n,o,r)=>{let s=e[0];if(!s)return;let l=[s,...o??[]].filter(g=>typeof g=="string").filter(g=>{let p=g.trim();return p.length>0&&p.includes("|")&&p.split("|").length>1});if(l.length<2)return;let c=[];if(l.forEach(g=>{let p=g.split("|").slice(1,-1).map(T=>T.trim());p.length>0&&c.push(p);}),c.length===0||!c[0])return;let d=c.filter(g=>!g.every(p=>/^:?-+:?$/.test(p)));if(d.length===0)return;let u=$createTableNodeWithDimensions(d.length,Math.max(...d.map(g=>g.length)),false),m=u.getChildren();d.forEach((g,p)=>{let T=m[p];if(!$isTableRowNode(T))return;let w=T.getChildren();g.forEach((b,h)=>{let N=w[h];if(!$isTableCellNode(N))return;N.clear();let f=$createParagraphNode();b&&f.append($createTextNode(b)),N.append(f);});}),i.append(u);},type:"multiline-element"},ni=[...TRANSFORMERS,Hl,Dl,zl,_r,Fl,Bl],oi=new Set(["root","paragraph","text","linebreak","tab","heading","quote","list","listitem","link","autolink","code","code-highlight","horizontalrule","image","iframe-embed","youtube-embed","table","tablerow","tablecell"]),$l=IS_BOLD|IS_ITALIC|IS_STRIKETHROUGH|IS_CODE|IS_HIGHLIGHT|IS_UNDERLINE,jl={root:new Set(["type","version","children"]),paragraph:new Set(["type","version","children"]),text:new Set(["type","version","text","format"]),linebreak:new Set(["type","version"]),tab:new Set(["type","version"]),heading:new Set(["type","version","tag","children"]),quote:new Set(["type","version","children"]),list:new Set(["type","version","listType","start","children"]),listitem:new Set(["type","version","value","checked","children"]),link:new Set(["type","version","url","title","children"]),autolink:new Set(["type","version","url","title","children"]),code:new Set(["type","version","language","children"]),"code-highlight":new Set(["type","version","text","highlightType"]),horizontalrule:new Set(["type","version"]),image:new Set(["type","version","src","alt","caption","alignment"]),"iframe-embed":new Set(["type","version","src","caption"]),"youtube-embed":new Set(["type","version","src","caption"]),table:new Set(["type","version","children"]),tablerow:new Set(["type","version","children"]),tablecell:new Set(["type","version","children"])};function Kl(i){return i===void 0?i:JSON.parse(JSON.stringify(i))}function Ul(i){return Object.keys(i).length>0}function Yl(i,t){switch(i){case "textFormat":return t===0;case "textStyle":return t==="";case "format":return t===""||t===0;case "indent":return t===0;case "direction":return t===null;case "detail":return t===0;case "mode":return t==="normal";case "style":return t===""||t===null;case "headerState":return t===0;case "colSpan":case "rowSpan":return t===1;case "width":case "height":return t==null;case "backgroundColor":return t===null||t==="";case "verticalAlign":return t==null||t==="";case "rowStriping":return t===false;case "frozenColumnCount":case "frozenRowCount":return t===0;case "colWidths":return Array.isArray(t)&&t.length===0;case "uploading":return t===false||t===void 0;case "title":return t===""||t===null||t===void 0;default:return false}}function Ql(i,t,e){if(Yl(t,e))return true;if(i==="iframe-embed"){if(t==="width")return e===640;if(t==="height")return e===360;if(t==="alignment")return e==="center"}if(i==="youtube-embed"){if(t==="width")return e===640;if(t==="height")return e===360;if(t==="alignment")return e==="center";if(t==="start")return e===0}return false}function Vl(i,t){let e=jl[t];if(!e)return null;let n={};for(let[o,r]of Object.entries(i))if(!(o==="children"||o==="type")){if(t==="text"&&o==="format"&&typeof r=="number"){let s=r&~$l;s!==0&&(n.__luthorTextFormatExtra=s);continue}e.has(o)||r!==void 0&&(Ql(t,o,r)||(n[o]=Kl(r)));}return Ul(n)?n:null}function Wl(i){return an(i,{mode:"markdown",supportedNodeTypes:oi,extractPatch:({node:t,type:e})=>Vl(t,e)})}function ri(){return createEditor({namespace:"luthor-markdown-converter",onError:i=>{throw i},nodes:[ParagraphNode,TextNode,LineBreakNode,TabNode,HeadingNode,QuoteNode,ListNode,ListItemNode,LinkNode,AutoLinkNode,CodeNode,CodeHighlightNode,HorizontalRuleNode,U,G,V,TableNode,TableRowNode,TableCellNode]})}function ql(i,t){let e=typeof t=="string"?t:JSON.stringify(t??{});return i.parseEditorState(e)}function Jl(i){let{content:t,envelopes:e,warnings:n}=Dt(i);for(let s of n)console.warn(`[luthor-headless] ${s}`);let o=ri();o.update(()=>{$convertFromMarkdownString(t,ni);},{discrete:true});let r=o.getEditorState().toJSON();return Ht(r,e)}function Xl(i){let t=_t(i,{mode:"markdown",supportedNodeTypes:oi}),e=Wl(i),n=ri(),o=ql(n,t.document);n.setEditorState(o,{tag:"history-merge"});let r=o.read(()=>$convertToMarkdownString(ni));return At(r,[...t.envelopes,...e])}var ai=new Set(["root","paragraph","text","linebreak","tab","heading","quote","list","listitem","link","autolink","code","code-highlight","horizontalrule","image","iframe-embed","youtube-embed","table","tablerow","tablecell"]),yc={root:new Set(["type","version","format","indent","direction","children"]),paragraph:new Set(["type","version","format","indent","direction","children"]),text:new Set(["type","version","text","detail","format","mode","style"]),linebreak:new Set(["type","version"]),tab:new Set(["type","version"]),heading:new Set(["type","version","tag","format","indent","direction","children"]),quote:new Set(["type","version","format","indent","direction","children"]),list:new Set(["type","version","listType","start","tag","format","indent","direction","style","children"]),listitem:new Set(["type","version","value","checked","format","indent","direction","style","children"]),link:new Set(["type","version","url","target","rel","title","children"]),autolink:new Set(["type","version","url","target","rel","title","isUnlinked","children"]),code:new Set(["type","version","language","format","indent","direction","children"]),"code-highlight":new Set(["type","version","text","highlightType"]),horizontalrule:new Set(["type","version"]),image:new Set(["type","version","src","alt","caption","alignment","className","style","width","height"]),"iframe-embed":new Set(["type","version","src","width","height","alignment","title","caption"]),"youtube-embed":new Set(["type","version","src","width","height","alignment","caption","start"]),table:new Set(["type","version","format","indent","direction","children","rowStriping","frozenColumnCount","frozenRowCount","colWidths","style"]),tablerow:new Set(["type","version","height","children"]),tablecell:new Set(["type","version","headerState","colSpan","rowSpan","width","backgroundColor","verticalAlign","children"])};function Ec(i){return i===void 0?i:JSON.parse(JSON.stringify(i))}function xc(i){return Object.keys(i).length>0}function Cc(i,t){switch(i){case "textFormat":return t===0;case "textStyle":return t==="";case "format":return t===""||t===0;case "indent":return t===0;case "direction":return t===null;case "detail":return t===0;case "mode":return t==="normal";case "style":return t===""||t===null;case "uploading":return t===false||t===void 0;default:return false}}function Sc(i,t){let e=yc[t];if(!e)return null;let n={};for(let[o,r]of Object.entries(i))o==="children"||o==="type"||e.has(o)||r!==void 0&&(Cc(o,r)||(n[o]=Ec(r)));return xc(n)?n:null}function Nc(i){return an(i,{mode:"html",supportedNodeTypes:ai,extractPatch:({node:t,type:e})=>Sc(t,e)})}var vc=new Set(["pre","script","style","textarea"]);function li(){return createEditor({namespace:"luthor-html-converter",onError:i=>{throw i},nodes:[ParagraphNode,TextNode,LineBreakNode,TabNode,HeadingNode,QuoteNode,ListNode,ListItemNode,LinkNode,AutoLinkNode,CodeNode,CodeHighlightNode,HorizontalRuleNode,U,G,V,TableNode,TableRowNode,TableCellNode]})}function Tc(i,t){let e=typeof t=="string"?t:JSON.stringify(t??{});return i.parseEditorState(e)}function ci(){if(typeof document>"u"||typeof window>"u"||typeof DOMParser>"u")throw new Error("HTML conversion requires browser DOM APIs (document/window/DOMParser).")}function ii(i){if(!i)return false;let t=i.getAttribute("style");return t?/\bwhite-space\s*:\s*(pre|pre-wrap|pre-line)\b/i.test(t):false}function Lc(i){let t=i.parentElement;for(;t;){if(vc.has(t.tagName.toLowerCase()))return true;t=t.parentElement;}return false}function si(i,t){let e=t==="previous"?i.previousSibling:i.nextSibling;for(;e;){if(e.nodeType!==Node.TEXT_NODE||(e.textContent??"").trim().length>0)return e;e=t==="previous"?e.previousSibling:e.nextSibling;}return null}function wc(i,t){if(!i||!t||/\s$/.test(i)||/^\s/.test(t))return false;let e=i.at(-1)??"",n=t[0]??"";return !(!e||!n||/^[,.;:!?)]$/.test(n)||/^[([{"']$/.test(e))}function Rc(i){let t=Array.from(i.querySelectorAll("[style]"));for(let r of t){if(!ii(r)||r.childNodes.length!==1||r.firstChild?.nodeType!==Node.TEXT_NODE)continue;let s=r.firstChild;/[\r\n]/.test(s.data)&&(s.data=s.data.replace(/^\s*\r?\n\s*/,"").replace(/\r?\n\s*$/,""));}let e=i.createTreeWalker(i.body,NodeFilter.SHOW_TEXT),n=[],o=e.nextNode();for(;o;){let r=o,s=r.data,a=r.parentElement;if(!/^[\s\r\n\t]+$/.test(s)||!/[\r\n]/.test(s)||Lc(r)||ii(a)){o=e.nextNode();continue}let l=si(r,"previous"),c=si(r,"next"),d=l?.textContent??"",u=c?.textContent??"";wc(d,u)?n.push({node:r,replacement:" "}):n.push({node:r,replacement:null}),o=e.nextNode();}for(let r of n)if(r.node.parentNode){if(r.replacement===null){r.node.parentNode.removeChild(r.node);continue}r.node.data=r.replacement;}}function kc(i){ci();let{content:t,envelopes:e,warnings:n}=Dt(i);for(let s of n)console.warn(`[luthor-headless] ${s}`);let o=li();o.update(()=>{let s=new DOMParser().parseFromString(t,"text/html");Rc(s);let a=$generateNodesFromDOM(o,s),l=$getRoot();l.clear(),l.append(...a);},{discrete:true});let r=o.getEditorState().toJSON();return Ht(r,e)}function Mc(i){ci();let t=_t(i,{mode:"html",supportedNodeTypes:ai}),e=Nc(i),n=li(),o=Tc(n,t.document);n.setEditorState(o,{tag:"history-merge"});let r=o.read(()=>$generateHtmlFromNodes(n,null));return At(r,[...t.envelopes,...e])}var ln=class extends ie{constructor(){super("bold");}},Pc=new ln;var cn=class extends ie{constructor(){super("italic");}},Oc=new cn;var Ic={format:["underline"],tag:"++",type:"text-format"},dn=class extends ie{constructor(){super("underline");}getMarkdownTransformers(){return [Ic]}},_c=new dn;var un=class extends ie{constructor(){super("strikethrough");}},Ac=new un;var mn=class extends k{constructor(){super("link",["toolbar"]);x(this,"lastSelectedLinkNodeKey",null);this.config={autoLinkText:false,clickableLinks:true,openLinksInNewTab:true,linkSelectedTextOnPaste:true,validateUrl:e=>{try{return new URL(e),!0}catch{return false}}};}register(e){let n=e.registerCommand(PASTE_COMMAND,r=>{let s=r.clipboardData;if(!s)return false;let a=s.getData("text/plain");return a&&this.config.validateUrl(a)&&this.config.autoLinkUrls?(r.preventDefault(),e.update(()=>{let l=$getSelection();if($isRangeSelection(l))if(l.isCollapsed()){let c=$createLinkNode(a);c.append($createTextNode(a)),l.insertNodes([c]);}else if(this.config.linkSelectedTextOnPaste)e.dispatchCommand(TOGGLE_LINK_COMMAND,a);else {l.insertText(a);let c=$getSelection();c&&$isRangeSelection(c)&&c.getNodes()[0]&&e.dispatchCommand(TOGGLE_LINK_COMMAND,a);}}),true):false},3),o=e.registerUpdateListener(({editorState:r})=>{r.read(()=>{let s=this.getSelectedLinkNode();if(s){this.lastSelectedLinkNodeKey=s.getKey();return}if(this.lastSelectedLinkNodeKey){let a=$getNodeByKey(this.lastSelectedLinkNodeKey);$isLinkNode(a)||(this.lastSelectedLinkNodeKey=null);}});});return ()=>{n(),o();}}getNodes(){let e=[LinkNode];return this.config.autoLinkText&&e.push(AutoLinkNode),e}getPlugins(){let e=[];if(e.push(jsx(LinkPlugin,{validateUrl:this.config.validateUrl},"link-plugin")),this.config.clickableLinks!==false&&e.push(jsx(ClickableLinkPlugin,{newTab:this.config.openLinksInNewTab!==false},"clickable-link")),this.config.autoLinkText){let n=o=>{let s=/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_.+~#?&//=]*)/g.exec(o);return s&&this.config.validateUrl(s[0])?{text:s[0],url:s[0],index:s.index,length:s[0].length}:null};e.push(jsx(AutoLinkPlugin,{matchers:[n]},"auto-link"));}return e}getCommands(e){let n=s=>s.trim(),o=s=>s.length>0&&!!this.config.validateUrl?.(s),r=(s,a,l,c)=>{s.setURL(a),typeof l<"u"&&s.setRel(l.trim()||null),typeof c<"u"&&s.setTarget(c.trim()||null);};return {insertLink:(s,a)=>{if(s){let l=n(s);if(!o(l))return;a&&e.update(()=>{let c=$getSelection();c&&c.insertText(a);}),e.dispatchCommand(TOGGLE_LINK_COMMAND,l);}else {let l=prompt("Enter URL:");if(l){let c=n(l);if(!o(c))return;e.dispatchCommand(TOGGLE_LINK_COMMAND,c);}}},updateLink:(s,a,l)=>{let c=n(s);if(!o(c))return false;let d=false;return e.update(()=>{let u=this.getSelectedLinkNode()??this.getCachedLinkNode();if(u){r(u,c,a,l),this.lastSelectedLinkNodeKey=u.getKey(),d=true;return}let m=$getSelection();if(!$isRangeSelection(m)){d=false;return}e.dispatchCommand(TOGGLE_LINK_COMMAND,{url:c,rel:typeof a>"u"?null:a.trim()||null,target:typeof l>"u"?null:l.trim()||null}),d=true;}),d},removeLink:()=>{let s=false;e.update(()=>{let a=this.getSelectedLinkNode()??this.getCachedLinkNode();if(a){let l=a.getChildren();for(let c of l)a.insertBefore(c);a.remove(),this.lastSelectedLinkNodeKey=null,s=true;return}e.dispatchCommand(TOGGLE_LINK_COMMAND,null);}),s||(this.lastSelectedLinkNodeKey=null);},getCurrentLink:()=>new Promise(s=>{e.getEditorState().read(()=>{let a=this.getSelectedLinkNode()??this.getCachedLinkNode();if(!a){s(null);return}s(this.serializeLinkNode(a));});}),getLinkByKey:s=>new Promise(a=>{e.getEditorState().read(()=>{let l=this.getLinkNodeByKey(s);if(!l){a(null);return}a(this.serializeLinkNode(l));});}),updateLinkByKey:(s,a,l,c)=>{let d=n(a);if(!o(d))return false;let u=false;return e.update(()=>{let m=this.getLinkNodeByKey(s);if(!m){u=false;return}r(m,d,l,c),this.lastSelectedLinkNodeKey=m.getKey(),u=true;}),u},removeLinkByKey:s=>{let a=false;return e.update(()=>{let l=this.getLinkNodeByKey(s);if(!l){a=false;return}this.removeLinkNode(l),this.lastSelectedLinkNodeKey=null,a=true;}),a}}}serializeLinkNode(e){return {url:e.getURL(),rel:e.getRel(),target:e.getTarget()}}removeLinkNode(e){let n=e.getChildren();for(let o of n)e.insertBefore(o);e.remove();}getLinkNodeByKey(e){let n=e.trim();if(!n)return null;let o=$getNodeByKey(n);return $isLinkNode(o)?o:null}getSelectedLinkNode(){let e=$getSelection();if(!e||!$isRangeSelection(e))return null;let n=e.anchor.getNode(),o=e.focus.getNode(),r=e.getNodes(),s=[n,o,...r];for(let a of s){if($isLinkNode(a))return a;let l=a.getParent();if(l&&$isLinkNode(l))return l}return null}getCachedLinkNode(){if(!this.lastSelectedLinkNodeKey)return null;let e=$getNodeByKey(this.lastSelectedLinkNodeKey);return $isLinkNode(e)?e:(this.lastSelectedLinkNodeKey=null,null)}getStateQueries(e){return {isLink:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(o&&$isRangeSelection(o)){let s=o.getNodes()[0];if(s){let a=s.getParent();n($isLinkNode(a)||$isLinkNode(s));}else n(false);}else n(false);});}),isTextSelected:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();o&&$isRangeSelection(o)?n(!o.isCollapsed()):n(false);});})}}},Uc=new mn;var Zc={dependencies:[HorizontalRuleNode],export:i=>$isHorizontalRuleNode(i)?"---":null,regExp:/^(?:---|___)\s*$/,replace:(i,t,e,n)=>{let o=$createHorizontalRuleNode();i.replace(o),n||nd(o);},type:"element"},ed=[Zc],td=/^(?:---|___)$/;function nd(i){let t=i.getNextSibling();if(t&&$isParagraphNode(t)){t.selectStart();return}let e=$createParagraphNode();i.insertAfter(e),e.selectStart();}var gn=class extends k{constructor(){super("horizontalRule",["toolbar"]);}register(t){let e=registerMarkdownShortcuts(t,ed),n=t.registerCommand(KEY_ENTER_COMMAND,o=>{if(o?.shiftKey)return false;let r=false;return t.update(()=>{let s=$getSelection();if(!s||!$isRangeSelection(s)||!s.isCollapsed())return;let a=s.anchor.getNode();if(!$isTextNode(a))return;let l=a.getParent();if(!l||!$isParagraphNode(l))return;let c=l.getParent();if(!$isRootOrShadowRoot(c))return;let d=a.getTextContent().trim();if(!td.test(d))return;r=true;let u=$createHorizontalRuleNode();l.replace(u),u.selectNext();}),r},COMMAND_PRIORITY_LOW);return ()=>{e(),n();}}getNodes(){return [HorizontalRuleNode]}getPlugins(){return [jsx(HorizontalRulePlugin,{},"horizontal-rule")]}getCommands(t){return {insertHorizontalRule:()=>{t.dispatchCommand(INSERT_HORIZONTAL_RULE_COMMAND,void 0);}}}getStateQueries(t){return {isHorizontalRuleSelected:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(n&&$isRangeSelection(n)){let r=n.getNodes().some(s=>$isHorizontalRuleNode(s));e(r);}else e(false);});})}}},od=new gn;var yi=[{value:"default",label:"Default",fontFamily:"inherit"},{value:"sans",label:"Sans",fontFamily:"Arial, Helvetica, sans-serif"},{value:"serif",label:"Serif",fontFamily:"Georgia, 'Times New Roman', serif"},{value:"mono",label:"Mono",fontFamily:"'Courier New', Courier, monospace"}],sd={value:"default",label:"Default",fontFamily:"inherit"};function bi(i){return i.trim().toLowerCase()}function ad(i){return /^[a-z0-9][a-z0-9-]*$/i.test(i)}function ld(i){let t=new Set,e=[];for(let o of i){let r=o.value.trim(),s=o.label.trim(),a=o.fontFamily.trim();if(!r||!s||!a||!ad(r))continue;let l=bi(r);t.has(l)||(t.add(l),e.push({value:r,label:s,fontFamily:a,cssImportUrl:o.cssImportUrl?.trim()||void 0}));}return e.length===0?yi:e.some(o=>bi(o.value)==="default")?e:[sd,...e]}var fn=class extends k{constructor(){super("fontFamily",["toolbar"]);x(this,"loadedFontUrls",new Set);this.config={options:yi,cssLoadStrategy:"none",showInToolbar:true,category:["toolbar"]};}register(){if(this.config.cssLoadStrategy==="preload-all")for(let e of this.config.options)this.ensureFontCssLoaded(e);return ()=>{}}configure(e){let n={...e};return e.options&&(n.options=ld(e.options)),super.configure(n)}getCommands(e){return {setFontFamily:n=>{let o=this.findOption(n);o&&(this.ensureFontCssLoaded(o),this.applyFontFamily(e,o.fontFamily));},clearFontFamily:()=>{this.applyFontFamily(e,"");},getCurrentFontFamily:()=>Promise.resolve(this.getCurrentFontFamilyValue(e)),getFontFamilyOptions:()=>this.config.options}}getStateQueries(e){return {hasCustomFontFamily:()=>Promise.resolve(this.hasCustomFontFamily(e))}}applyFontFamily(e,n){e.update(()=>{let o=$getSelection();$isRangeSelection(o)&&$patchStyleText(o,{"font-family":n});});}hasCustomFontFamily(e){let n=false;return e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let r=$getSelectionStyleValueForProperty(o,"font-family","");n=this.normalizeFontValue(r).length>0;}),n}getCurrentFontFamilyValue(e){let n=null;return e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let r=$getSelectionStyleValueForProperty(o,"font-family","");if(!r){n="default";return}let s=this.normalizeFontValue(r);n=this.config.options.find(l=>this.normalizeFontValue(l.value)===s?true:this.normalizeFontValue(l.fontFamily)===s)?.value??null;}),n}findOption(e){let n=this.normalizeFontValue(e);return this.config.options.find(o=>this.normalizeFontValue(o.value)===n)}normalizeFontValue(e){return e?(e.split(",")[0]??"").replace(/['"]/g,"").trim().toLowerCase():""}ensureFontCssLoaded(e){if(this.config.cssLoadStrategy==="none"||!e.cssImportUrl||typeof document>"u")return;let n=e.cssImportUrl,o=encodeURIComponent(n);if(this.loadedFontUrls.has(n))return;if(document.querySelector(`link[data-luthor-font-url="${o}"]`)){this.loadedFontUrls.add(n);return}let s=document.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-luthor-font-url",o),document.head.appendChild(s),this.loadedFontUrls.add(n);}},cd=new fn;var Ci=[{value:"default",label:"Default",fontSize:"inherit"},{value:"12",label:"12px",fontSize:"12px"},{value:"14",label:"14px",fontSize:"14px"},{value:"16",label:"16px",fontSize:"16px"},{value:"18",label:"18px",fontSize:"18px"},{value:"20",label:"20px",fontSize:"20px"},{value:"24",label:"24px",fontSize:"24px"},{value:"32",label:"32px",fontSize:"32px"}],ud={value:"default",label:"Default",fontSize:"inherit"};function xi(i){return i.trim().toLowerCase()}function md(i){return /^[a-z0-9][a-z0-9-]*$/i.test(i)}function gd(i){let t=new Set,e=[];for(let o of i){let r=String(o.value).trim(),s=String(o.label).trim(),a=String(o.fontSize).trim();if(!r||!s||!a||!md(r))continue;let l=xi(r);t.has(l)||(t.add(l),e.push({value:r,label:s,fontSize:a}));}return e.length===0?Ci:e.some(o=>xi(o.value)==="default")?e:[ud,...e]}var pn=class extends k{constructor(){super("fontSize",["toolbar"]),this.config={options:Ci,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}configure(t){let e={...t};return t.options&&(e.options=gd(t.options)),super.configure(e)}getCommands(t){return {setFontSize:e=>{let n=this.findOption(e);n&&this.applyFontSize(t,n.fontSize);},clearFontSize:()=>{this.applyFontSize(t,"");},getCurrentFontSize:()=>Promise.resolve(this.getCurrentFontSizeValue(t)),getFontSizeOptions:()=>this.config.options}}getStateQueries(t){return {hasCustomFontSize:()=>Promise.resolve(this.hasCustomFontSize(t))}}applyFontSize(t,e){t.update(()=>{let n=$getSelection();$isRangeSelection(n)&&$patchStyleText(n,{"font-size":e});});}hasCustomFontSize(t){let e=false;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"font-size",""),r=this.normalizeValue(o);e=r.length>0&&r!=="inherit";}),e}getCurrentFontSizeValue(t){let e=null;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"font-size",""),r=this.normalizeValue(o);if(!r||r==="inherit"){e="default";return}e=this.config.options.find(a=>this.normalizeValue(a.value)===r?true:this.normalizeValue(a.fontSize)===r)?.value??null;}),e}findOption(t){let e=this.normalizeValue(t);return this.config.options.find(n=>this.normalizeValue(n.value)===e)}normalizeValue(t){return t.trim().toLowerCase().replace(/\s+/g,"")}},fd=new pn;var Ni=[{value:"default",label:"Default",lineHeight:"normal"},{value:"1",label:"1.0",lineHeight:"1"},{value:"1.15",label:"1.15",lineHeight:"1.15"},{value:"1.5",label:"1.5",lineHeight:"1.5"},{value:"1.75",label:"1.75",lineHeight:"1.75"},{value:"2",label:"2.0",lineHeight:"2"}],_o={value:"default",label:"Default",lineHeight:"1.5"},bd=1;function Io(i){return i.trim().toLowerCase()}function yd(i){return Io(i)==="default"?true:bn(i)!==null}function bn(i){let t=i.trim();if(!/^\d*\.?\d+$/.test(t))return null;let e=Number(t);return !Number.isFinite(e)||e<bd?null:e.toString()}function Ed(i,t){let e=new Set,n=[];for(let r of i){let s=r.value.trim(),a=r.label.trim(),l=Io(s);if(!s||!a||!yd(s)||e.has(l))continue;if(l==="default"){e.add(l),n.push({value:s,label:a,lineHeight:t});continue}let c=bn(String(r.lineHeight));c&&(e.add(l),n.push({value:s,label:a,lineHeight:c}));}return n.length===0?Ni:n.some(r=>Io(r.value)==="default")?n:[{..._o,lineHeight:t},...n]}function xd(i){return bn(i)??_o.lineHeight}var hn=class extends k{constructor(){super("lineHeight",["toolbar"]),this.config={options:Ni,defaultLineHeight:_o.lineHeight,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}configure(t){let e={...t},n=xd(String(t.defaultLineHeight??this.config.defaultLineHeight));return e.defaultLineHeight=n,t.options&&(e.options=Ed(t.options,n)),super.configure(e)}getCommands(t){return {setLineHeight:e=>{let n=this.findOption(e);n&&this.applyLineHeight(t,n.lineHeight);},clearLineHeight:()=>{this.applyLineHeight(t,"");},getCurrentLineHeight:()=>Promise.resolve(this.getCurrentLineHeightValue(t)),getLineHeightOptions:()=>this.config.options}}getStateQueries(t){return {hasCustomLineHeight:()=>Promise.resolve(this.hasCustomLineHeight(t))}}applyLineHeight(t,e){t.update(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=this.getSelectedTopLevelBlocks(n);for(let r of o){let s=this.withStyleProperty(r.getStyle(),"line-height",e);r.setStyle(s);for(let a of r.getAllTextNodes())$isTextNode(a)&&a.setStyle(this.withStyleProperty(a.getStyle(),"line-height",e));}});}getSelectedTopLevelBlocks(t){let e=new Map;for(let n of t.getNodes()){let o=n.getTopLevelElement();!o||!$isElementNode(o)||o.getType()!=="root"&&e.set(o.getKey(),o);}return [...e.values()]}withStyleProperty(t,e,n){let o=new RegExp(`^${e}\\s*:`,"i"),r=t.split(";").map(a=>a.trim()).filter(a=>a.length>0).filter(a=>!o.test(a)),s=n.trim();return s.length>0&&r.push(`${e}: ${s}`),r.join("; ")}hasCustomLineHeight(t){let e=false;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=this.getSelectedBlocksLineHeight(n);if(o==="mixed"){e=true;return}let r=o??$getSelectionStyleValueForProperty(n,"line-height",""),s=this.normalizeValue(r);e=s.length>0&&s!=="normal";}),e}getCurrentLineHeightValue(t){let e=null;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=this.getSelectedBlocksLineHeight(n);if(o==="mixed"){e=null;return}let r=o??$getSelectionStyleValueForProperty(n,"line-height",""),s=this.normalizeValue(r);if(!s||s==="normal"){e="default";return}if(s===this.normalizeValue(this.config.defaultLineHeight)){e="default";return}e=this.config.options.find(l=>this.normalizeValue(l.value)===s?true:this.normalizeValue(l.lineHeight)===s)?.value??null;}),e}getSelectedBlocksLineHeight(t){let e=this.getSelectedTopLevelBlocks(t);if(e.length===0)return null;let n=null,o="";for(let r of e){let s=this.readStyleProperty(r.getStyle(),"line-height"),a=this.normalizeValue(s);if(n===null){n=a,o=s;continue}if(n!==a)return "mixed"}return o}findOption(t){let e=this.normalizeValue(t);return this.config.options.find(n=>this.normalizeValue(n.value)===e)}normalizeValue(t){let e=t.trim().toLowerCase().replace(/\s+/g,"");return bn(e)??e}readStyleProperty(t,e){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return t.match(new RegExp(`(?:^|;)\\s*${n}\\s*:\\s*([^;]+)`,"i"))?.[1]?.trim()??""}},Cd=new hn;var Nd=[{value:"default",label:"Default",color:"inherit"},{value:"black",label:"Black",color:"#111827"},{value:"slate",label:"Slate",color:"#334155"},{value:"red",label:"Red",color:"#dc2626"},{value:"orange",label:"Orange",color:"#ea580c"},{value:"green",label:"Green",color:"#16a34a"},{value:"blue",label:"Blue",color:"#2563eb"},{value:"purple",label:"Purple",color:"#7c3aed"}],yn=class extends k{constructor(){super("textColor",["toolbar"]),this.config={options:Nd,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}getCommands(t){return {setTextColor:e=>{let n=this.findOption(e);if(n){this.applyColor(t,n.color);return}this.isValidCssColor(e)&&this.applyColor(t,e);},clearTextColor:()=>{this.applyColor(t,"");},getCurrentTextColor:()=>Promise.resolve(this.getCurrentTextColorValue(t)),getTextColorOptions:()=>this.config.options}}getStateQueries(t){return {hasCustomTextColor:()=>Promise.resolve(this.hasCustomTextColor(t))}}applyColor(t,e){t.update(()=>{let n=$getSelection();$isRangeSelection(n)&&$patchStyleText(n,{color:e});});}hasCustomTextColor(t){let e=false;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"color","");e=this.normalizeValue(o).length>0;}),e}getCurrentTextColorValue(t){let e=null;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"color","");if(!o){e="default";return}let r=this.normalizeValue(o);e=this.config.options.find(a=>this.normalizeValue(a.value)===r?true:this.normalizeValue(a.color)===r)?.value??o;}),e}findOption(t){let e=this.normalizeValue(t);return this.config.options.find(n=>this.normalizeValue(n.value)===e)}normalizeValue(t){return t.trim().toLowerCase().replace(/\s+/g,"")}isValidCssColor(t){let e=t.trim();return e?typeof CSS<"u"&&typeof CSS.supports=="function"?CSS.supports("color",e):/^#([\da-f]{3}|[\da-f]{6})$/i.test(e):false}},vd=new yn;var Ld=[{value:"default",label:"Default",backgroundColor:"transparent"},{value:"yellow",label:"Yellow",backgroundColor:"#fef08a"},{value:"green",label:"Green",backgroundColor:"#bbf7d0"},{value:"blue",label:"Blue",backgroundColor:"#bfdbfe"},{value:"pink",label:"Pink",backgroundColor:"#fbcfe8"},{value:"orange",label:"Orange",backgroundColor:"#fed7aa"},{value:"purple",label:"Purple",backgroundColor:"#ddd6fe"}],En=class extends k{constructor(){super("textHighlight",["toolbar"]),this.config={options:Ld,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}getCommands(t){return {setTextHighlight:e=>{let n=this.findOption(e);if(n){this.applyHighlight(t,n.backgroundColor);return}this.isValidCssColor(e)&&this.applyHighlight(t,e);},clearTextHighlight:()=>{this.applyHighlight(t,"");},getCurrentTextHighlight:()=>Promise.resolve(this.getCurrentTextHighlightValue(t)),getTextHighlightOptions:()=>this.config.options}}getStateQueries(t){return {hasTextHighlight:()=>Promise.resolve(this.hasTextHighlight(t))}}applyHighlight(t,e){t.update(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=this.normalizeValue(e).length>0;$patchStyleText(n,{"background-color":e,"padding-left":o?"0.1em":"","padding-right":o?"0.1em":"","box-decoration-break":o?"clone":"","-webkit-box-decoration-break":o?"clone":""});});}hasTextHighlight(t){let e=false;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"background-color",""),r=this.normalizeValue(o);e=r.length>0&&r!=="transparent";}),e}getCurrentTextHighlightValue(t){let e=null;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"background-color",""),r=this.normalizeValue(o);if(!r||r==="transparent"){e="default";return}e=this.config.options.find(a=>this.normalizeValue(a.value)===r?true:this.normalizeValue(a.backgroundColor)===r)?.value??o;}),e}findOption(t){let e=this.normalizeValue(t);return this.config.options.find(n=>this.normalizeValue(n.value)===e)}normalizeValue(t){return t.trim().toLowerCase().replace(/\s+/g,"")}isValidCssColor(t){let e=t.trim();return e?typeof CSS<"u"&&typeof CSS.supports=="function"?CSS.supports("color",e):/^#([\da-f]{3}|[\da-f]{6})$/i.test(e):false}},wd=new En;var xn=class extends ie{constructor(){super("subscript");}},Rd=new xn;var Cn=class extends ie{constructor(){super("superscript");}},kd=new Cn;function Sn(i,t,e){return i<t?t:i>e?e:i}function _d({items:i,position:t,onClose:e,className:n,style:o,itemClassName:r,itemStyle:s,disabledItemClassName:a,disabledItemStyle:l}){return jsx("div",{className:n,style:{position:"fixed",left:t.x,top:t.y,zIndex:"var(--luthor-z-menu, 460)",...o},onClick:c=>c.stopPropagation(),children:i.map((c,d)=>c.separator?jsx("div",{className:"h-px bg-border my-1"},d):jsxs("div",{className:c.disabled?a:r,style:c.disabled?l:s,onClick:()=>{!c.disabled&&c.action&&(c.action(),e());},children:[c.icon&&jsx(c.icon,{className:"mr-2 h-4 w-4"}),c.label]},d))})}var Nn=class{constructor(t,e={}){x(this,"providers",new Map);x(this,"currentMenu",null);x(this,"listeners",new Set);x(this,"editor");x(this,"config");this.editor=t,this.config=e;}registerProvider(t){this.providers.set(t.id,t);}unregisterProvider(t){this.providers.delete(t);}handleContextMenu(t){let e=t.target;this.editor.getEditorState().read(()=>{let n=$getSelection(),o=Array.from(this.providers.values()).sort((r,s)=>(s.priority||0)-(r.priority||0));for(let r of o){let s={editor:this.editor,target:e,selection:n,event:t};if(r.canHandle(s)){this.config.preventDefault!==false&&t.preventDefault();let a=r.getItems(s);if(a.length>0){let l=e.getBoundingClientRect();this.showMenu({items:a,position:{x:t.clientX,y:t.clientY},renderer:r.renderer||this.config.defaultRenderer,anchor:{element:e,offsetX:t.clientX-l.left,offsetY:t.clientY-l.top}});return}}}});}showMenu(t){this.currentMenu=this.resolveAnchoredMenuConfig(t),this.notifyListeners();}hideMenu(){this.currentMenu=null,this.notifyListeners();}repositionMenuFromAnchor(){if(!this.currentMenu?.anchor)return;if(!this.currentMenu.anchor.element.isConnected){this.hideMenu();return}let t=this.resolveAnchoredMenuConfig(this.currentMenu);(!this.currentMenu||t.position.x!==this.currentMenu.position.x||t.position.y!==this.currentMenu.position.y)&&(this.currentMenu=t,this.notifyListeners());}getCurrentMenu(){return this.currentMenu}getPortalContainer(){let t=this.editor.getRootElement();return t?t.closest(".luthor-editor-wrapper")??null:null}subscribe(t){return this.listeners.add(t),t(this.currentMenu),()=>{this.listeners.delete(t);}}notifyListeners(){this.listeners.forEach(t=>t(this.currentMenu));}resolveAnchoredMenuConfig(t){if(!t.anchor)return t;let{element:e,offsetX:n,offsetY:o}=t.anchor,r=e.getBoundingClientRect();return {...t,position:{x:r.left+n,y:r.top+o}}}};function Ad({extension:i}){let{config:t}=Ae(),[e,n]=useState(null),o=t?.theme?.contextMenu||{},r=i.config,s={container:r?.theme?.container||o.container||"luthor-context-menu",item:r?.theme?.item||o.item||"luthor-context-menu-item",itemDisabled:r?.theme?.itemDisabled||o.itemDisabled||"luthor-context-menu-item-disabled"},a={container:{...r?.styles?.container,...o.styles?.container},item:{...r?.styles?.item,...o.styles?.item},itemDisabled:{...r?.styles?.itemDisabled,...o.styles?.itemDisabled}};if(useEffect(()=>i.subscribe(n),[i]),!e)return null;let l=e.renderer||i.config.defaultRenderer,c=i.manager?.getPortalContainer()??null,d=220,u=Math.min(420,18+e.items.length*34),m=8,g=(()=>{if(!c){let y=typeof window>"u"?0:window.innerWidth,S=typeof window>"u"?0:window.innerHeight;return {width:y,height:S}}let f=c.getBoundingClientRect();return {width:f.width,height:f.height}})(),p=Math.max(0,g.width-m*2),T=Math.max(0,g.height-m*2),w=Math.min(d,p||d),b=Math.min(u,T||u),h=(()=>{if(!c){let A=Math.max(m,g.width-w-m),F=Math.max(m,g.height-b-m);return {x:Sn(e.position.x,m,A),y:Sn(e.position.y,m,F)}}let f=c.getBoundingClientRect(),y=e.position.x-f.left+c.scrollLeft,S=e.position.y-f.top+c.scrollTop,L=c.scrollLeft+m,E=c.scrollTop+m,v=Math.max(L,c.scrollLeft+f.width-w-m),M=Math.max(E,c.scrollTop+f.height-b-m);return {x:Sn(y,L,v),y:Sn(S,E,M)}})(),N=c?{position:"absolute",...a.container,maxWidth:p>0?p:void 0,maxHeight:T>0?T:void 0,overflowY:"auto",overscrollBehavior:"contain"}:{...a.container,maxWidth:p>0?p:void 0,maxHeight:T>0?T:void 0,overflowY:"auto",overscrollBehavior:"contain"};return createPortal(jsx(l,{items:e.items,position:h,onClose:()=>i.manager?.hideMenu(),className:s.container,style:N,itemClassName:s.item,itemStyle:a.item,disabledItemClassName:s.itemDisabled,disabledItemStyle:a.itemDisabled}),c??document.body)}var vn=class extends k{constructor(e={}){super("contextMenu",["toolbar"]);x(this,"manager",null);x(this,"pendingListeners",new Set);this.config={defaultRenderer:_d,position:"before",initPriority:100,...e};}configure(e){return this.config={...this.config,...e},this.manager&&Object.assign(this.manager,{config:this.config}),this}register(e){this.manager=new Nn(e,this.config),this.pendingListeners.forEach(l=>{this.manager?.subscribe(l);}),this.pendingListeners.clear();let n=l=>{this.manager?.handleContextMenu(l);},o=l=>{l.target.closest(".luthor-context-menu")||this.manager?.hideMenu();},r=l=>{l.key==="Escape"&&this.manager?.hideMenu();},s=()=>{this.manager?.repositionMenuFromAnchor();},a=e.getRootElement();return a?(a.addEventListener("contextmenu",n),document.addEventListener("mousedown",o),document.addEventListener("keydown",r),window.addEventListener("scroll",s,true),window.addEventListener("resize",s),()=>{a.removeEventListener("contextmenu",n),document.removeEventListener("mousedown",o),document.removeEventListener("keydown",r),window.removeEventListener("scroll",s,true),window.removeEventListener("resize",s),this.manager=null;}):()=>{this.manager=null;}}getCommands(e){return {registerProvider:n=>{this.manager||(this.manager=new Nn(e,this.config)),this.manager.registerProvider(n);},unregisterProvider:n=>{this.manager?.unregisterProvider(n);},showContextMenu:n=>{this.manager?.showMenu(n);},hideContextMenu:()=>{this.manager?.hideMenu();}}}getStateQueries(e){return {isContextMenuOpen:()=>Promise.resolve(this.manager?.getCurrentMenu()!==null)}}getPlugins(){return [jsx(Ad,{extension:this},"context-menu")]}subscribe(e){return this.manager?this.manager.subscribe(e):(this.pendingListeners.add(e),()=>{this.pendingListeners.delete(e);})}},Bo=new vn;function Ri(i,t,e){return i<t?t:i>e?e:i}function Rn(){let i=$getSelection();if($isTableSelection(i)){let t=i.getNodes().find(e=>$isTableCellNode(e));if($isTableCellNode(t))return t}if($isRangeSelection(i)){let t=i.anchor.getNode(),e=$findCellNode(t);if($isTableCellNode(e))return e}return null}function qd({headersEnabled:i,setHeadersEnabled:t,actions:e}){return jsxs(Fragment,{children:[jsx("button",{type:"button",className:"luthor-table-bubble-button",title:"Insert row above","aria-label":"Insert row above",onClick:e.insertRowAbove,children:"Row \u2191"}),jsx("button",{type:"button",className:"luthor-table-bubble-button",title:"Insert row below","aria-label":"Insert row below",onClick:e.insertRowBelow,children:"Row \u2193"}),jsx("button",{type:"button",className:"luthor-table-bubble-button",title:"Insert column left","aria-label":"Insert column left",onClick:e.insertColumnLeft,children:"Col \u2190"}),jsx("button",{type:"button",className:"luthor-table-bubble-button",title:"Insert column right","aria-label":"Insert column right",onClick:e.insertColumnRight,children:"Col \u2192"}),jsx("button",{type:"button",className:"luthor-table-bubble-button",title:"Delete selected column","aria-label":"Delete selected column",onClick:e.deleteSelectedColumn,children:"Del Col"}),jsx("button",{type:"button",className:"luthor-table-bubble-button",title:"Delete selected row","aria-label":"Delete selected row",onClick:e.deleteSelectedRow,children:"Del Row"}),jsxs("label",{className:"luthor-table-bubble-checkbox",title:"Use first row as table headers",children:[jsx("input",{type:"checkbox",title:"Use first row as table headers","aria-label":"Use first row as table headers",checked:i,onChange:n=>t(n.target.checked)}),"Headers"]}),jsx("button",{type:"button",className:"luthor-table-bubble-button luthor-table-bubble-button-danger",title:"Delete table","aria-label":"Delete table",onClick:e.deleteTable,children:"Delete Table"})]})}function Jd({extension:i}){let{editor:t}=Ae(),[e,n]=useState(()=>t?.isEditable()??true),[o,r]=useState(null),[s,a]=useState(false),[l,c]=useState(false),[d,u]=useState(null),m=useRef(null),g=useRef(null),p=h=>{!t||!t.isEditable()||t.update(()=>{let N=Rn();N&&(N.selectStart(),h(N));});},T=h=>{p(N=>{$getTableNodeFromLexicalNodeOrThrow(N).getChildren().filter(S=>$isTableRowNode(S)).forEach((S,L)=>{S.getChildren().filter(v=>$isTableCellNode(v)).forEach(v=>{let M=h&&L===0?TableCellHeaderStates.ROW:TableCellHeaderStates.NO_STATUS;v.setHeaderStyles(M,TableCellHeaderStates.ROW);});});});};if(useEffect(()=>{if(t)return t.registerEditableListener(h=>{n(h),h||(a(false),u(null));})},[t]),useEffect(()=>{if(!t)return;let h=t.getRootElement(),N=h?.closest(".luthor-editor-wrapper")||h?.parentElement||null;r(N);let f=()=>{t.getEditorState().read(()=>{if(!t.isEditable()){a(false),u(null);return}let L=$getSelection();if($isRangeSelection(L)&&!L.isCollapsed()){a(false),u(null);return}let E=Rn();if(!E){a(false),u(null);return}let M=t.getElementByKey(E.getKey())?.closest("table");if(!M||!N){a(false),u(null);return}let Q=$getTableNodeFromLexicalNodeOrThrow(E).getChildren().filter(Fe=>$isTableRowNode(Fe))[0]?.getChildren().filter(Fe=>$isTableCellNode(Fe))||[],te=Q.length>0&&Q.every(Fe=>Fe.hasHeaderState(TableCellHeaderStates.ROW));c(te);let B=N.getBoundingClientRect(),z=M.getBoundingClientRect(),K=m.current?.getBoundingClientRect(),I=K?.width??520,j=K?.height??44,Y=12,le=Math.max(0,B.width-Y*2),X=Math.min(I,le||I)/2,Pe=z.left-B.left+z.width/2,Se=Y+X,Oe=Math.max(Se,B.width-Y-X),Ie=Ri(Pe,Se,Oe),_e=z.top-B.top,me=B.bottom-z.bottom,pe=_e>=j+Y,ue=me>=j+Y,yt=pe||!ue?z.top-B.top-12-j:z.bottom-B.top+12,Jt=Y,uo=Math.max(Jt,B.height-j-Y),mo=Ri(yt,Jt,uo);u({x:Ie,y:mo,maxWidth:le}),a(true);});};f();let y=t.registerUpdateListener(()=>{f();}),S=()=>{g.current===null&&(g.current=window.requestAnimationFrame(()=>{g.current=null,f();}));};return window.addEventListener("scroll",S,true),window.addEventListener("resize",S),()=>{y(),window.removeEventListener("scroll",S,true),window.removeEventListener("resize",S),g.current!==null&&(cancelAnimationFrame(g.current),g.current=null);}},[t]),!e||!o||!s||!d||typeof document>"u")return null;let w={insertRowAbove:()=>p(()=>$insertTableRowAtSelection(false)),insertRowBelow:()=>p(()=>$insertTableRowAtSelection(true)),insertColumnLeft:()=>p(()=>$insertTableColumnAtSelection(false)),insertColumnRight:()=>p(()=>$insertTableColumnAtSelection(true)),deleteSelectedColumn:()=>p(()=>$deleteTableColumnAtSelection()),deleteSelectedRow:()=>p(()=>$deleteTableRowAtSelection()),deleteTable:()=>p(h=>{$getTableNodeFromLexicalNodeOrThrow(h).remove();})},b=i.config.tableBubbleRenderer?i.config.tableBubbleRenderer({headersEnabled:l,setHeadersEnabled:h=>{c(h),T(h);},actions:w}):jsx(qd,{headersEnabled:l,setHeadersEnabled:h=>{c(h),T(h);},actions:w});return createPortal(jsx("div",{ref:m,className:"luthor-table-bubble-menu",style:{position:"absolute",left:d.x,top:d.y,transform:"translateX(-50%)",maxWidth:d.maxWidth>0?d.maxWidth:void 0,overflowX:"auto",zIndex:"var(--luthor-z-menu, 460)"},onMouseDown:h=>h.preventDefault(),children:b}),o)}var kn=class extends k{constructor(e){super("table",["toolbar"]);x(this,"defaultContextMenuItems",e=>[{label:"Insert Row Above",action:()=>e.insertRowAbove()},{label:"Insert Row Below",action:()=>e.insertRowBelow()},{label:"Insert Column Left",action:()=>e.insertColumnLeft()},{label:"Insert Column Right",action:()=>e.insertColumnRight()},{separator:true,label:"",action:()=>{}},{label:"Toggle Row Header",action:()=>e.toggleRowHeader()},{label:"Toggle Column Header",action:()=>e.toggleColumnHeader()},{label:"Merge Cells",action:()=>e.mergeSelectedCells()},{label:"Split Cell",action:()=>e.unmergeSelectedCell()},{separator:true,label:"",action:()=>{}},{label:"Delete Row",action:()=>e.deleteRow()},{label:"Delete Column",action:()=>e.deleteColumn()},{label:"Delete Table",action:()=>e.deleteTable()}]);this.config={rows:3,columns:3,includeHeaders:false,enableContextMenu:true,contextMenuItems:this.defaultContextMenuItems,...e};}getContextMenuItems(e){return typeof this.config.contextMenuItems=="function"?this.config.contextMenuItems(e):Array.isArray(this.config.contextMenuItems)?this.config.contextMenuItems:this.defaultContextMenuItems(e)}configure(e){return this.config={...this.config,...e},e.contextMenuItems&&(this.config.contextMenuItems=e.contextMenuItems),this}register(e){let n;if(this.config.enableContextMenu){let o=this.config.contextMenuExtension||Bo;if(o){let r={id:"table",priority:10,canHandle:({editor:a,target:l,selection:c})=>{if(!a.isEditable())return false;let d=l.closest("td, th, [data-lexical-table-cell]");return d?$isTableSelection(c)?true:d.tagName==="TD"||d.tagName==="TH":false},getItems:({editor:a})=>{let l=this.getCommands(a);return this.getContextMenuItems(l)},renderer:this.config.contextMenuRenderer||o.config?.defaultRenderer};o.getCommands(e).registerProvider(r),n=()=>{let a=o.getCommands(e);a&&a.unregisterProvider("table");};}}return ()=>{n?.();}}getNodes(){return [TableNode,TableRowNode,TableCellNode]}getCommands(e){return {insertTable:n=>{let{rows:o=3,columns:r=3,includeHeaders:s=false}=n;e.update(()=>{let a=$getSelection();if($isRangeSelection(a)){let l=$createTableNodeWithDimensions(o,r,s);a.insertNodes([l]);}});},insertRowAbove:()=>{e.update(()=>{$insertTableRowAtSelection(false);});},insertRowBelow:()=>{e.update(()=>{$insertTableRowAtSelection(true);});},insertColumnLeft:()=>{e.update(()=>{$insertTableColumnAtSelection(false);});},insertColumnRight:()=>{e.update(()=>{$insertTableColumnAtSelection(true);});},toggleRowHeader:()=>{e.update(()=>{let n=Rn();if(!n)return;let o=$getTableNodeFromLexicalNodeOrThrow(n),r=$getTableRowIndexFromTableCellNode(n),s=o.getChildren()[r];if(!$isTableRowNode(s))return;let a=s.getChildren().filter(d=>$isTableCellNode(d)),c=!a.every(d=>d.hasHeaderState(TableCellHeaderStates.ROW))?TableCellHeaderStates.ROW:TableCellHeaderStates.NO_STATUS;a.forEach(d=>{d.setHeaderStyles(c,TableCellHeaderStates.ROW);});});},toggleColumnHeader:()=>{e.update(()=>{let n=Rn();if(!n)return;let o=$getTableNodeFromLexicalNodeOrThrow(n),r=$getTableColumnIndexFromTableCellNode(n),a=o.getChildren().filter(d=>$isTableRowNode(d)).map(d=>d.getChildren()[r]).filter(d=>$isTableCellNode(d)),c=!a.every(d=>d.hasHeaderState(TableCellHeaderStates.COLUMN))?TableCellHeaderStates.COLUMN:TableCellHeaderStates.NO_STATUS;a.forEach(d=>{d.setHeaderStyles(c,TableCellHeaderStates.COLUMN);});});},mergeSelectedCells:()=>{e.update(()=>{let n=$getSelection();if(!$isTableSelection(n))return;let o=n.getNodes().filter(r=>$isTableCellNode(r));o.length<2||$mergeCells(o);});},unmergeSelectedCell:()=>{e.update(()=>{$unmergeCell();});},deleteRow:()=>{e.update(()=>{$deleteTableRowAtSelection();});},deleteColumn:()=>{e.update(()=>{$deleteTableColumnAtSelection();});},deleteTable:()=>{e.update(()=>{let n=$getSelection();$isTableSelection(n)&&n.getNodes().forEach(o=>{$isTableNode(o)&&o.remove();});});},showTableContextMenu:n=>{}}}getStateQueries(e){return {isTableSelected:async()=>e.getEditorState().read(()=>{let n=$getSelection();return $isTableSelection(n)}),isInTableCell:async()=>e.getEditorState().read(()=>{let n=$getSelection();if(!n||typeof n!="object"||!("anchor"in n)||!("focus"in n))return false;try{let o=n.anchor.getNode(),r=n.focus.getNode();return $isTableCellNode(o)||$isTableCellNode(r)}catch{return false}})}}getPlugins(){return [jsx(TablePlugin,{},"table-plugin"),jsx(Jd,{extension:this},"table-quick-actions-plugin")]}},Xd=new kn;var Hi=9,ut={"decimal-alpha-roman":["decimal","lower-alpha","lower-roman"],"decimal-hierarchical":["decimal"],"upper-roman-upper-alpha":["upper-roman","upper-alpha","decimal","lower-alpha","decimal","lower-alpha","lower-roman","lower-alpha","lower-roman"],"upper-alpha-lower-alpha":["upper-alpha","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman"],"decimal-leading-zero-alpha":["decimal-leading-zero","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman"]},Kt={"disc-circle-square":["disc","circle","square"],"arrow-diamond-disc":['"\u25B8"','"\u25C6"',"disc"],"square-square-square":["square","square","square"],"arrow-circle-square":['"\u25B8"',"circle","square"]},mt="decimal-alpha-roman",Fi="disc-circle-square",Hn="--luthor-checklist-variant",De="--luthor-unordered-pattern",Qi="--luthor-unordered-pattern-token",ze="--luthor-unordered-marker-kind",Ce="--luthor-ordered-marker-content",Bi={"disc-arrow-square":"arrow-circle-square","square-circle-disc":"disc-circle-square","arrow-diamond-square":"arrow-diamond-disc","star-circle-square":"disc-circle-square"};function Vi(i){let t=new Map;for(let e of i.split(";")){let n=e.trim();if(!n)continue;let o=n.indexOf(":");if(o<=0)continue;let r=n.slice(0,o).trim(),s=n.slice(o+1).trim();r&&t.set(r,s);}return t}function ru(i){return Array.from(i.entries()).map(([t,e])=>`${t}: ${e}`).join("; ")}function oe(i,t){let e=i.getStyle(),n=Vi(e),o=false;for(let[r,s]of Object.entries(t)){let a=n.get(r);if(s===null||s===""){n.delete(r)&&(o=true);continue}a!==s&&(n.set(r,s),o=true);}o&&i.setStyle(ru(n));}function fe(i,t){return Vi(i.getStyle()).get(t)??null}function ft(i,t){let e=[...i];for(let n=0;n<e.length;n+=1){let o=e[n],r=t(o);if(r==="stop")break;r!=="skip-children"&&typeof o?.getChildren=="function"&&e.push(...o.getChildren());}}function Fn(i){let t=i;for(;t;){if($isListNode(t))return t;t=t.getParent();}return null}function iu(i){let t=i;for(;t;){if($isListItemNode(t))return t;t=t.getParent();}return null}function Ut(i){let t=i;for(;;){let e=t.getParent();if(!$isListItemNode(e))return t;let n=e.getParent();if(!$isListNode(n))return t;t=n;}}function In(i,t){let e=$getListDepth(i),n=$getListDepth(t);return e-n}function _n(i,t){let e=t%i.length;return i[e]??i[0]??"disc"}function zi(i,t){let e=i,n="";for(;e>0;){let o=(e-1)%26;n=String.fromCharCode((t?65:97)+o)+n,e=Math.floor((e-1)/26);}return n||(t?"A":"a")}function $i(i,t){let e=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],n=Math.max(1,Math.floor(i)),o="";for(let[r,s]of e)for(;n>=r;)o+=s,n-=r;return t?o:o.toLowerCase()}function ji(i,t,e,n){let o=e==="paren"?")":".";return `"${n?n.join("."):i==="decimal-leading-zero"?t<10?`0${t}`:`${t}`:i==="lower-alpha"?zi(t,false):i==="upper-alpha"?zi(t,true):i==="lower-roman"?$i(t,false):i==="upper-roman"?$i(t,true):`${t}`}${o}"`}function su(i,t){let e=0;for(let n of i.getChildren())if($isListItemNode(n)&&(jt(n)&&(e+=1),n.getKey()===t.getKey()))return Math.max(1,e);return Math.max(1,e)}function Ki(i,t){let e=[],n=i;for(;n.getKey()!==t.getKey();){let o=n.getParent();if(!$isListItemNode(o))break;let r=o.getParent();if(!$isListNode(r))break;e.push(su(r,o)),n=r;}return e.reverse()}function zn(i){return i&&Object.hasOwn(Kt,i)?i:i&&Object.hasOwn(Bi,i)?Bi[i]??Fi:Fi}function au(i){return i.startsWith('"')&&i.endsWith('"')}function Wo(i){if(au(i)){let t=i.toLowerCase(),e=t.slice(1,-1);return t.includes("\\25c6")||e==="\u25C6"?"diamond":(t.includes("\\25b8")||t.includes("\\27a4")||e==="\u25B8"||e==="\u27A4","arrow")}switch(i){case "disc":return "disc";case "circle":return "circle";case "square":return "square";default:return "disc"}}function lu(i){let t=i.trim();if(!t)return null;let e=t.match(/^(\d+)([.)])$/);if(e){let r=e[1]??"",s=e[2]??".";return {pattern:r.length>1&&r.startsWith("0")?"decimal-leading-zero-alpha":"decimal-alpha-roman",suffix:s===")"?"paren":"dot"}}let n=t.match(/^([IVXLCDMivxlcdm]+)([.)])$/);if(n)return {pattern:"upper-roman-upper-alpha",suffix:(n[2]??".")===")"?"paren":"dot"};let o=t.match(/^([A-Z]+)([.)])$/);return o?{pattern:"upper-alpha-lower-alpha",suffix:(o[2]??".")===")"?"paren":"dot"}:null}function gt(i){let t=new Map,e=i.getNodes();for(let n of e){let o=Fn(n);if(!o)continue;let r=Ut(o);t.set(r.getKey(),r);}if(t.size===0){let n=Fn(i.anchor.getNode());if(n){let o=Ut(n);t.set(o.getKey(),o);}}return [...t.values()]}function An(i,t){let e=Math.max(0,t-1),n=i.anchor.getNode(),o=iu(n);if(o){let s=o.getIndent();if(typeof s=="number")return s>=e}let r=Fn(n);return r?$getListDepth(r)-1>=e:false}function qo(i){let t=[];return ft(i.getChildren(),e=>{if($isListNode(e))return "skip-children";$isTextNode(e)&&t.push(e);}),t}function Ge(i){let t=[];return ft(i.getChildren(),e=>{if($isListNode(e))return t.push(e),"skip-children"}),t}function jt(i){let t=false,e=false;return ft(i.getChildren(),n=>{if($isListNode(n))return e=true,"skip-children";if($isTextNode(n)&&n.getTextContent().trim().length>0)return t=true,"stop"}),t?true:!e}function Uo(i,t){ft(i.getChildren(),e=>{if($isListNode(e))return "skip-children";typeof e.getStyle=="function"&&typeof e.setStyle=="function"&&oe(e,{[Qi]:t});});}function cu(i){let t=null;return ft(i.getChildren(),e=>{if($isListNode(e))return "skip-children";if(typeof e.getStyle=="function"){let n=fe(e,Qi);if(n)return t=zn(n),"stop"}}),t}function du(i){let t=[i];for(;t.length>0;){let e=t.pop();if(e.getListType()==="check")for(let n of e.getChildren()){if(!$isListItemNode(n))continue;let o=qo(n);for(let r of o)if(fe(r,Hn)==="plain")return "plain";t.push(...Ge(n));}}return null}function uu(i){let t=[i];for(;t.length>0;){let e=t.pop();if(e.getListType()==="bullet")for(let n of e.getChildren()){if(!$isListItemNode(n))continue;let o=fe(n,De),r=zn(o);if(o&&Object.hasOwn(Kt,r))return r;let s=cu(n);if(s)return s;t.push(...Ge(n));}}return null}function Yo(i){let t=uu(i);if(t)return t;let e=fe(i,De);return zn(e)}function Qo(i){return fe(i,Hn)==="plain"?"plain":du(i)??"strikethrough"}function Dn(i){let t=i.anchor.getNode(),e=null,n=null;for(;t;){if(!n&&$isListItemNode(t)&&(n=t),$isListNode(t)){e=t;break}t=t.getParent();}let o=e?Ut(e):null;return {listNode:e,listItemNode:n,topListNode:o}}function Jo(i){let t=i.target;if(!(t instanceof HTMLElement))return null;let e=t.closest("li");if(!(e instanceof HTMLLIElement))return null;let n=e.firstElementChild;if(n instanceof HTMLElement&&(n.tagName==="UL"||n.tagName==="OL"))return null;let o=e.parentElement;if(!o||o.__lexicalListType!=="check")return null;let r=e.getBoundingClientRect(),s=i.clientX,a=window.getComputedStyle?window.getComputedStyle(e,"::before"):{width:"0px"},l=Number.parseFloat(a.width);if(!Number.isFinite(l)||l<=0)return null;let d=("pointerType"in i?i.pointerType:"")==="touch"?32:0;return (e.dir==="rtl"?s<r.right+d&&s>r.right-l-d:s>r.left-d&&s<r.left+l+d)?e:null}var Bn=class extends k{constructor(t={}){super("list",["toolbar"]),this.config=t;}getMaxListDepth(){let t=this.config.maxDepth;if(!Number.isFinite(t))return Hi;let e=Math.floor(t);return e>=1?e:Hi}register(t){let e=t.registerNodeTransform(ListNode,c=>{this.syncListNodeStyles(c);}),n=t.registerNodeTransform(ListItemNode,c=>{let d=c.getParent();$isListNode(d)&&this.syncListNodeStyles(d);}),o=t.registerCommand(KEY_SPACE_COMMAND,c=>{let d=false;return t.update(()=>{d=this.handleOrderedListShortcut(t);}),d&&c.preventDefault(),d},COMMAND_PRIORITY_EDITOR),r=t.registerCommand(INDENT_CONTENT_COMMAND,()=>{let c=$getSelection();return !$isRangeSelection(c)||!Dn(c).listNode?false:An(c,this.getMaxListDepth())},COMMAND_PRIORITY_EDITOR),s=c=>{t.isEditable()||Jo(c)&&(c.preventDefault(),c.stopPropagation());},a=c=>{if(t.isEditable())return;let d=Jo(c);d&&(c.preventDefault(),c.stopPropagation(),t.update(()=>{let u=$getNearestNodeFromDOMNode(d);if(!$isListItemNode(u))return;let m=u.getParent();!$isListNode(m)||m.getListType()!=="check"||u.toggleChecked();}));},l=t.registerRootListener((c,d)=>{d&&(d.removeEventListener("pointerdown",s),d.removeEventListener("click",a)),c&&(c.addEventListener("pointerdown",s),c.addEventListener("click",a));});return ()=>{e(),n(),o(),r(),l();}}getNodes(){return [ListNode,ListItemNode]}getPlugins(){return [jsx(ListPlugin,{hasStrictIndent:true},"list-plugin"),jsx(CheckListPlugin,{},"check-list-plugin")]}getCommands(t){return {toggleUnorderedList:()=>{t.update(()=>{let e=$getSelection();if(!$isRangeSelection(e))return;let n=Dn(e);if(n.topListNode){if(n.topListNode.getListType()==="bullet"){n.listItemNode&&n.listItemNode.getIndent()>0?t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode);return}this.convertTopListType(n.topListNode,"bullet");return}t.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0);});},toggleOrderedList:()=>{t.update(()=>{let e=$getSelection();if(!$isRangeSelection(e))return;let n=Dn(e);if(n.topListNode){if(n.topListNode.getListType()==="number"){n.listItemNode&&n.listItemNode.getIndent()>0?t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode);return}this.convertTopListType(n.topListNode,"number");return}t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);});},toggleCheckList:()=>{t.update(()=>{let e=$getSelection();if(!$isRangeSelection(e))return;let n=Dn(e);if(n.topListNode){if(n.topListNode.getListType()==="check"){n.listItemNode&&n.listItemNode.getIndent()>0?t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode);return}this.convertTopListType(n.topListNode,"check");return}t.dispatchCommand(INSERT_CHECK_LIST_COMMAND,void 0);});},indentList:()=>{t.update(()=>{let e=$getSelection();$isRangeSelection(e)&&(An(e,this.getMaxListDepth())||t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0));});},outdentList:()=>{t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0);},insertNestedUnorderedList:()=>{t.update(()=>{let e=$getSelection();!$isRangeSelection(e)||An(e,this.getMaxListDepth())||(t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),t.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0));});},insertNestedOrderedList:()=>{t.update(()=>{let e=$getSelection();!$isRangeSelection(e)||An(e,this.getMaxListDepth())||(t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0));});},setOrderedListPattern:e=>{t.update(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);let o=$getSelection();if(!$isRangeSelection(o))return;let r=gt(o);for(let s of r)this.applyOrderedPattern(s,e);});},setOrderedListSuffix:e=>{t.update(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=gt(n);for(let r of o)r.getListType()==="number"&&this.applyOrderedSuffix(r,e);});},setUnorderedListPattern:e=>{t.update(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;t.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0);let o=$getSelection();if(!$isRangeSelection(o))return;let r=gt(o);for(let s of r)this.applyUnorderedPattern(s,e);});},setCheckListVariant:e=>{let n=false;t.update(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let r=gt(o);if(r.length===0){n=true;return}for(let s of r)s.getListType()!=="check"&&this.convertTopListType(s,"check"),this.applyCheckListVariant(s,e);}),n&&(t.dispatchCommand(INSERT_CHECK_LIST_COMMAND,void 0),t.update(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let r=gt(o);for(let s of r)s.getListType()!=="check"&&this.convertTopListType(s,"check"),this.applyCheckListVariant(s,e);}));},rehydrateListStyles:()=>{t.update(()=>{let e=$getRoot(),n=new Map;ft(e.getChildren(),o=>{if($isListNode(o)){let r=Ut(o);n.set(r.getKey(),r);}});for(let o of n.values()){if(o.getListType()==="number"){let r=fe(o,"--luthor-ordered-pattern")??mt,s=Object.hasOwn(ut,r)?r:mt,a=fe(o,"--luthor-ordered-suffix")==="paren"?"paren":"dot";this.applyOrderedPattern(o,s),this.applyOrderedSuffix(o,a);continue}if(o.getListType()==="bullet"){let r=Yo(o);this.applyUnorderedPattern(o,r);continue}if(o.getListType()==="check"){let r=Qo(o);this.applyCheckListVariant(o,r);}}});}}}applyOrderedPattern(t,e){if(t.getListType()!=="number")return;let n=ut[e],o=fe(t,"--luthor-ordered-suffix")??"dot";oe(t,{"--luthor-ordered-pattern":e,"--luthor-ordered-suffix":o});let r=[t];for(;r.length>0;){let s=r.pop();if(s.getListType()!=="number")continue;let a=In(s,t),l=_n(n,a),c=e==="decimal-hierarchical";oe(s,{"--luthor-ordered-pattern":e,"--luthor-ordered-suffix":o,"list-style-type":"none",[Ce]:null});let d=c?Ki(s,t):null,u=0;for(let m of s.getChildren()){if(!$isListItemNode(m))continue;let g=jt(m);g&&(u+=1);let p=ji(l,Math.max(1,u),o==="paren"?"paren":"dot",c?[...d??[],Math.max(1,u)]:null);oe(m,{[Ce]:g?p:null}),r.push(...Ge(m));}}}applyOrderedSuffix(t,e){let n=[t];for(;n.length>0;){let s=n.pop();if(s.getListType()==="number"){oe(s,{"--luthor-ordered-suffix":e});for(let a of s.getChildren())$isListItemNode(a)&&n.push(...Ge(a));}}let o=fe(t,"--luthor-ordered-pattern")??mt,r=Object.hasOwn(ut,o)?o:mt;this.applyOrderedPattern(t,r);}applyUnorderedPattern(t,e){if(t.getListType()!=="bullet")return;let n=Kt[e];oe(t,{[De]:e});let o=[t];for(;o.length>0;){let r=o.pop();if(r.getListType()!=="bullet")continue;let s=In(r,t),a=_n(n,s),l=Wo(a);oe(r,{[De]:e,"list-style-type":"none","--luthor-unordered-marker-content":null,[ze]:null,[Ce]:null});for(let c of r.getChildren())$isListItemNode(c)&&(oe(c,{[De]:e,"--luthor-unordered-marker-content":null,[ze]:jt(c)?l:null,[Ce]:null}),Uo(c,e),o.push(...Ge(c)));}}applyCheckListVariant(t,e){if(t.getListType()!=="check")return;let n=[t];for(;n.length>0;){let o=n.pop();if(o.getListType()==="check"){oe(o,{"--luthor-checklist-variant":e,"--luthor-unordered-marker-content":null,[ze]:null,[Ce]:null,"--luthor-unordered-pattern":null,"--luthor-ordered-pattern":null,"--luthor-ordered-suffix":null,"list-style-type":null});for(let r of o.getChildren()){if(!$isListItemNode(r))continue;oe(r,{"--luthor-checklist-variant":e,[De]:null,"--luthor-unordered-marker-content":null,[ze]:null,[Ce]:null}),Uo(r,null);let s=qo(r);for(let a of s)oe(a,{[Hn]:e==="plain"?"plain":null});n.push(...Ge(r));}}}}syncListNodeStyles(t){let e=Ut(t);if(e.getListType()==="number"){let n=fe(e,"--luthor-ordered-pattern")??mt;if(!Object.hasOwn(ut,n))return;let o=ut[n],r=In(t,e),s=_n(o,r),a=n==="decimal-hierarchical",l=fe(e,"--luthor-ordered-suffix")??"dot";oe(t,{"--luthor-ordered-pattern":n,"--luthor-ordered-suffix":l,"list-style-type":"none",[Ce]:null});let c=a?Ki(t,e):null,d=0;for(let u of t.getChildren()){if(!$isListItemNode(u))continue;let m=jt(u);m&&(d+=1);let g=ji(s,Math.max(1,d),l==="paren"?"paren":"dot",a?[...c??[],Math.max(1,d)]:null);oe(u,{[Ce]:m?g:null});}return}if(e.getListType()==="bullet"){let n=Yo(e),o=Kt[n],r=In(t,e),s=_n(o,r),a=Wo(s);oe(t,{[De]:n,"list-style-type":"none","--luthor-unordered-marker-content":null,[ze]:null,[Ce]:null});for(let l of t.getChildren())$isListItemNode(l)&&(oe(l,{[De]:n,"--luthor-unordered-marker-content":null,[ze]:jt(l)?a:null,[Ce]:null}),Uo(l,n));return}if(e.getListType()==="check"){let n=Qo(e);oe(t,{"--luthor-checklist-variant":n,"--luthor-unordered-marker-content":null,[ze]:null,[Ce]:null,"--luthor-unordered-pattern":null,"--luthor-ordered-pattern":null,"--luthor-ordered-suffix":null,"list-style-type":null});for(let o of t.getChildren()){if(!$isListItemNode(o))continue;oe(o,{"--luthor-checklist-variant":n,[De]:null,"--luthor-unordered-marker-content":null,[ze]:null,[Ce]:null});let r=qo(o);for(let s of r)oe(s,{[Hn]:n==="plain"?"plain":null});}}}convertTopListType(t,e){let n=[t];for(;n.length>0;){let r=n.pop();r.setListType(e);for(let s of r.getChildren())$isListItemNode(s)&&n.push(...Ge(s));}if(e==="number"){let r=fe(t,"--luthor-ordered-pattern"),s=r&&Object.hasOwn(ut,r)?r:mt,a=fe(t,"--luthor-ordered-suffix")==="paren"?"paren":"dot";this.applyOrderedPattern(t,s),this.applyOrderedSuffix(t,a);return}if(e==="bullet"){let r=Yo(t);this.applyUnorderedPattern(t,r);return}let o=Qo(t);this.applyCheckListVariant(t,o);}handleOrderedListShortcut(t){let e=$getSelection();if(!$isRangeSelection(e)||!e.isCollapsed())return false;let n=e.anchor.getNode();if(Fn(n))return false;let o=n;for(;o&&!$isParagraphNode(o);)o=o.getParent();if(!$isParagraphNode(o))return false;let r=o,s=lu(r.getTextContent());if(!s)return false;r.clear(),t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);let a=$getSelection();if(!$isRangeSelection(a))return true;let l=gt(a);for(let c of l)c.getListType()==="number"&&(this.applyOrderedPattern(c,s.pattern),this.applyOrderedSuffix(c,s.suffix));return true}getStateQueries(t){return {unorderedList:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n)){e(false);return}let o=n.anchor.getNode();for(;o;){if($isListNode(o)){e(o.getListType()==="bullet");return}o=o.getParent();}e(false);});}),orderedList:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n)){e(false);return}let o=n.anchor.getNode();for(;o;){if($isListNode(o)){e(o.getListType()==="number");return}o=o.getParent();}e(false);});}),checkList:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n)){e(false);return}let o=n.anchor.getNode();for(;o;){if($isListNode(o)){e(o.getListType()==="check");return}o=o.getParent();}e(false);});})}}},mu=new Bn;var fu="plain";function Yt(){return fu}function Wi(){return PrismTokenizer}async function qi(i){return i?.provider?i.provider:i?.loadProvider?i.loadProvider():null}async function Ji(i){return i?i.tokenizer?i.tokenizer:i.getTokenizer?i.getTokenizer():null:null}var Un=class Un extends k{constructor(){super("code",["toolbar"]);x(this,"codeHighlightProviderPromise",null);this.config={syntaxHighlighting:"auto"};}register(e){let n=()=>{},o=false,r=a=>{n(),n=registerCodeHighlighting(e,a);};this.config.syntaxHighlighting!=="disabled"&&(r(this.config.tokenizer??Wi()),this.resolveConfiguredTokenizer().then(a=>{o||!a||r(a);}));let s=e.registerCommand(KEY_TAB_COMMAND,a=>{let l=false;return e.update(()=>{let c=$getSelection();if(!$isRangeSelection(c))return;let d=c.anchor.getNode();this.getBlockNode(d)&&(l=true,!this.hasReachedCodeTabLimit(c)&&c.insertText(" "));}),l?(a?.preventDefault(),true):false},COMMAND_PRIORITY_LOW);return ()=>{o=true,n(),s();}}getNodes(){return [CodeNode,CodeHighlightNode]}getCommands(e){return {toggleCodeBlock:()=>this.toggleCodeBlock(e)}}toggleCodeBlock(e){e.update(()=>{let n=$getSelection();if($isRangeSelection(n)){if(this.getCurrentFormatSync()==="code"){$setBlocksType(n,()=>$createParagraphNode());return}$setBlocksType(n,()=>{let r=$createCodeNode();return r.setTheme?.(Yt()),r});}});}async resolveConfiguredTokenizer(){if(this.config.tokenizer)return this.config.tokenizer;let e=await this.loadCodeHighlightProvider();return Ji(e)}async loadCodeHighlightProvider(){return this.config.provider?this.config.provider:this.codeHighlightProviderPromise?this.codeHighlightProviderPromise:(this.codeHighlightProviderPromise=qi(this.config),this.codeHighlightProviderPromise)}getStateQueries(e){return {isInCodeBlock:()=>Promise.resolve(this.isFormat("code",e))}}isFormat(e,n){let o=true;return n.getEditorState().read(()=>{let r=$getSelection();if(!$isRangeSelection(r)){o=false;return}let s=r.getNodes();for(let a of s){let l=this.getBlockNode(a);if(!l){o=false;break}if(this.getNodeFormat(l)!==e){o=false;break}}}),o}getBlockNode(e){let n=e;for(;n;){if($isCodeNode(n))return n;n=n.getParent();}return null}getNodeFormat(e){return $isCodeNode(e)?"code":null}getCurrentFormatSync(){let e=$getSelection();if(!$isRangeSelection(e))return null;let n=e.anchor.getNode(),o=this.getBlockNode(n);return o?this.getNodeFormat(o):null}hasReachedCodeTabLimit(e){let n=e.anchor,o=n.getNode();if(typeof o.getTextContent!="function")return false;let r=o.getTextContent(),s=typeof n.offset=="number"?n.offset:r.length,a=Math.max(0,Math.min(r.length,s)),l=r.lastIndexOf(`
6
+ `,a-1)+1;return (r.slice(l,a).match(/^\t*/)?.[0].length??0)>=Un.MAX_CODE_TAB_DEPTH}};x(Un,"MAX_CODE_TAB_DEPTH",8);var Kn=Un,Su=new Kn;var Ou='<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M9 9a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-8a2 2 0 0 1-2-2V9Zm2 0h8v10h-8V9Zm-6 8a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v1h-2V5H5v10h1v2H5Z"/></svg>',Iu='<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M20.3 5.7a1 1 0 0 1 0 1.4l-9.2 9.2a1 1 0 0 1-1.4 0L3.7 10.3a1 1 0 1 1 1.4-1.4l5.3 5.3 8.5-8.5a1 1 0 0 1 1.4 0Z"/></svg>',_u=["plaintext","typescript","javascript","markdown","html","css","python","sql","java","c","cpp","rust","powershell","xml"],Qn=class extends k{constructor(){super("codeIntelligence");x(this,"languageOptions",[]);this.config={isCopyAllowed:true};}register(e){this.languageOptions=this.getLanguageOptions();let n=registerMarkdownShortcuts(e,TRANSFORMERS),o=e.registerUpdateListener(({dirtyElements:r,dirtyLeaves:s})=>{(r.size>0||s.size>0)&&this.ensureCodeBlockThemes(e);});return queueMicrotask(()=>{this.ensureCodeBlockThemes(e);}),()=>{n(),o(),this.languageOptions=[];}}getPlugins(){return [createElement(Du,{key:"code-intelligence-controls",extension:this})]}getCommands(e){return {setCodeLanguage:n=>{let o=pt(n),r=this.getThemeForLanguage(o);e.update(()=>{this.getSelectionCodeNodes().forEach(s=>{s.setLanguage(o??null),s.setTheme(r);});});},autoDetectCodeLanguage:async()=>null,getCurrentCodeLanguage:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=this.getSelectionCodeNodes();n(o[0]?.getLanguage()??null);});}),getCodeLanguageOptions:()=>this.getLanguageOptions(),copySelectedCodeBlock:async()=>{if(!this.isCopyAllowed())return false;let n=await this.getPrimaryCodeBlockText(e);return !n||!n.text.trim()?false:os(n.text)}}}isCopyAllowed(){return this.config.isCopyAllowed!==false}getLanguageOptionsSnapshot(){return this.languageOptions.length?[...this.languageOptions]:this.getLanguageOptions()}getCodeBlocksSnapshot(e){return e.getEditorState().read(()=>$nodesOfType(CodeNode).map(n=>{let o=pt(n.getLanguage());return {key:n.getKey(),language:o??"plaintext",text:n.getTextContent()}}))}setCodeBlockLanguage(e,n,o){e.isEditable()&&e.update(()=>{let r=$getNodeByKey(n);if(!r||!$isCodeNode(r))return;let s=pt(o);r.setLanguage(s??null),r.setTheme(this.getThemeForLanguage(s));});}getCodeBlockText(e,n){return e.getEditorState().read(()=>{let o=$getNodeByKey(n);return !o||!$isCodeNode(o)?"":o.getTextContent()})}getThemeForLanguage(e){let n=pt(e);return !n||n==="plain"?Yt():"hljs"}ensureCodeBlockThemes(e){let n=e.getEditorState().read(()=>$nodesOfType(CodeNode).map(o=>{let r=o.getTheme?.()??"",s=this.getThemeForLanguage(o.getLanguage());return {key:o.getKey(),nextTheme:s??Yt(),currentTheme:r}}).filter(o=>o.currentTheme!==o.nextTheme));n.length!==0&&e.update(()=>{n.forEach(o=>{let r=$getNodeByKey(o.key);!r||!$isCodeNode(r)||r.setTheme(o.nextTheme);});});}getSelectionCodeNodes(){let e=$getSelection();if(!$isRangeSelection(e))return [];let n=e.getNodes(),o=new Map;return n.forEach(r=>{let s=this.getNearestCodeNode(r);s&&o.set(s.getKey(),s);}),Array.from(o.values())}getNearestCodeNode(e){let n=e;for(;n;){if($isCodeNode(n))return n;n=n.getParent();}return null}getLanguageOptions(){let e=_u.map(r=>pt(r)).filter(r=>!!r),n=zu(this.config.languageOptions);if(!n)return er(e);let o=$u(n.values);return n.mode==="replace"?er(o):er([...e,...o])}async getPrimaryCodeBlockText(e){return new Promise(n=>{e.getEditorState().read(()=>{let r=this.getSelectionCodeNodes()[0];if(!r){n(null);return}let s=r.getTextContent().trim();if(!s){n(null);return}n({key:r.getKey(),text:s});});})}},Au=34;function Du({extension:i}){let[t]=useLexicalComposerContext(),[e,n]=useState(()=>t.isEditable()),[o,r]=useState([]),[s,a]=useState({}),l=useRef(null),c=useRef(new Map),d=useMemo(()=>i.getLanguageOptionsSnapshot(),[i]),u=useCallback(()=>{let f=ns(t);if(!f)return [];let y=f.getBoundingClientRect(),S=i.getCodeBlocksSnapshot(t),L=[];return S.forEach(E=>{let v=t.getElementByKey(E.key);if(!v||!v.isConnected)return;v.classList.add("luthor-code-block--interactive");let M=v.getBoundingClientRect(),A=Math.max(120,Math.round(M.width)),F=Math.max(0,Math.round(M.top-y.top-Au)),Q=Math.max(0,Math.round(M.left-y.left));L.push({key:E.key,language:E.language,top:F,left:Q,width:A});}),L},[t,i]),m=useCallback(()=>{let f=u();r(y=>Hu(y,f)?y:f);},[u]),g=useCallback(()=>{l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null,m();}));},[m]),p=useCallback(f=>{let y=c.current.get(f);y&&(clearTimeout(y),c.current.delete(f));},[]),T=useCallback((f,y)=>{p(f),a(L=>({...L,[f]:y}));let S=setTimeout(()=>{a(L=>{if(!(f in L))return L;let E={...L};return delete E[f],E}),c.current.delete(f);},1200);c.current.set(f,S);},[p]),w=useCallback((f,y)=>{e&&(i.setCodeBlockLanguage(t,f,y),g());},[t,i,e,g]),b=i.isCopyAllowed(),h=useCallback(async f=>{if(!b)return;let y=i.getCodeBlockText(t,f);if(!y.trim())return;if(await os(y)){T(f,"copied");return}T(f,"error");},[b,t,i,T]);if(useEffect(()=>t.registerEditableListener(n),[t]),useEffect(()=>{g();let f=0,y=null,S=()=>{g(),f+=1,!(f>=20)&&(y=requestAnimationFrame(S));};y=requestAnimationFrame(S);let L=t.registerUpdateListener(()=>{g();}),E=()=>{g();},v=c.current;return window.addEventListener("scroll",E,true),window.addEventListener("resize",E,{passive:true}),()=>{L(),window.removeEventListener("scroll",E,true),window.removeEventListener("resize",E),y!==null&&cancelAnimationFrame(y),l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),v.forEach(M=>clearTimeout(M)),v.clear();}},[t,g]),useEffect(()=>{let f=new Set(o.map(y=>y.key));a(y=>{let S=false,L={};return Object.entries(y).forEach(([E,v])=>{if(f.has(E)){L[E]=v;return}S=true,p(E);}),S?L:y});},[p,o]),typeof document>"u"||o.length===0)return null;let N=ns(t);return N?createPortal(createElement("div",{className:"luthor-codeblock-controls-layer","aria-hidden":false},o.map(f=>{let y=s[f.key],S=["luthor-codeblock-copy",y==="copied"?"is-copied":"",y==="error"?"is-copy-error":""].filter(Boolean).join(" "),L=y==="copied"?"Copied":y==="error"?"Copy failed":"Copy to clipboard";return createElement("div",{key:f.key,className:"luthor-codeblock-controls","data-code-node-key":f.key,style:{position:"absolute",top:`${f.top}px`,left:`${f.left}px`,width:`${f.width}px`}},createElement("span",{className:"luthor-codeblock-controls-left"},createElement("select",{className:"luthor-codeblock-language",value:f.language,"aria-label":"Code language",disabled:!e,"aria-disabled":!e,onChange:E=>{let v=E.target;w(f.key,v.value);}},d.map(E=>createElement("option",{key:E,value:E},E)))),createElement("span",{className:"luthor-codeblock-controls-right"},b?createElement("button",{className:S,type:"button","aria-label":"Copy code",title:L,"data-tooltip":L,onMouseDown:E=>{E.preventDefault();},onClick:()=>{h(f.key);},dangerouslySetInnerHTML:{__html:y==="copied"?Iu:Ou}}):null))})),N):null}function Hu(i,t){if(i.length!==t.length)return false;for(let e=0;e<i.length;e+=1){let n=i[e],o=t[e];if(!n||!o||n.key!==o.key||n.language!==o.language||n.top!==o.top||n.left!==o.left||n.width!==o.width)return false}return true}async function os(i){if(typeof navigator<"u"&&navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(i),!0}catch{}if(typeof document>"u")return false;let t=document.createElement("textarea");t.value=i,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.opacity="0",t.style.pointerEvents="none",t.style.top="0",t.style.left="0",document.body.appendChild(t),t.select(),t.setSelectionRange(0,t.value.length);try{return document.execCommand("copy")}catch{return false}finally{t.remove();}}function ns(i){let t=i.getRootElement();if(!t)return null;let e=t.closest(".luthor-richtext-container");if(e)return e;let n=t.closest(".luthor-editor-container");return n||t.parentElement}function pt(i){if(!i)return null;let t=i.trim().toLowerCase();if(!t||t==="auto")return null;let e=normalizeCodeLang(t);return !e||e==="auto"||!Fu(e)?null:e}function Fu(i){let t=i.trim().toLowerCase();if(!t)return false;let e=getCodeLanguageOptions().map(([r])=>normalizeCodeLang(r.trim().toLowerCase())).filter(Boolean),n=getCodeLanguages().map(r=>normalizeCodeLang(r.trim().toLowerCase())).filter(Boolean);return new Set([...e,...n]).has(t)}var Bu=new Qn;function zu(i){if(!i)return null;if(Array.isArray(i))return {mode:"append",values:i};let t=i;return {mode:t.mode??"append",values:Array.isArray(t.values)?t.values:[]}}function $u(i){let t=[],e=new Set;for(let n of i){let o=n.trim();if(!o)continue;let r=pt(o);if(!r)throw new Error(`[CodeIntelligenceExtension] Invalid language option "${n}". Use a supported language ID or alias (excluding "auto").`);if(e.has(r))throw new Error(`[CodeIntelligenceExtension] Duplicate language option "${n}". It resolves to "${r}", which is already configured.`);e.add(r),t.push(r);}return t}function er(i){return Array.from(new Set(i)).sort((t,e)=>t.localeCompare(e))}var Vn=class extends ie{constructor(){super("code");}register(t){let e=super.register(t),n=t.getRootElement();if(!n)return e;let o=a=>{if(a.nodeType===Node.TEXT_NODE)return a;for(let l=0;l<a.childNodes.length;l+=1){let c=a.childNodes[l];if(!c)continue;let d=o(c);if(d)return d}return null},r=a=>{if(a.nodeType===Node.TEXT_NODE)return a;for(let l=a.childNodes.length-1;l>=0;l-=1){let c=a.childNodes[l];if(!c)continue;let d=r(c);if(d)return d}return null},s=a=>{if(a.button!==0)return;let l=window.getSelection();if(l&&l.rangeCount>0&&!l.getRangeAt(0).collapsed)return;let c=a.target;if(!(c instanceof Node))return;let d=c instanceof HTMLElement?c:c.parentElement;if(!d)return;let u=d.closest(".luthor-text-code, code");if(u instanceof HTMLElement||(u=document.elementFromPoint(a.clientX+4,a.clientY)?.closest(".luthor-text-code, code")??null),!(u instanceof HTMLElement)||!n.contains(u))return;let m=u.getBoundingClientRect(),g=Math.max(4,Math.min(8,m.width/2)),p=null,T=0;a.clientX<=m.left+g?(p=o(u),T=0):a.clientX>=m.right-g&&(p=r(u),T=p?.data.length??0),p&&(a.preventDefault(),t.focus(()=>{let w=window.getSelection();if(!w)return;let b=document.createRange();b.setStart(p,T),b.collapse(true),w.removeAllRanges(),w.addRange(b);}));};return n.addEventListener("click",s,true),()=>{n.removeEventListener("click",s,true),e();}}},ju=new Vn;var qn=class extends k{constructor(){super("blockFormat",["toolbar"]);}register(t){let e=t.registerCommand(INSERT_PARAGRAPH_COMMAND,()=>{let o=$getSelection();if($isRangeSelection(o)){let r=o.anchor.getNode(),s=this.getBlockNode(r);if(s&&($isHeadingNode(s)||$isQuoteNode(s)))return false}return false},COMMAND_PRIORITY_NORMAL),n=t.registerCommand(KEY_ENTER_COMMAND,o=>{let r=false;return t.update(()=>{let s=$getSelection();if(!$isRangeSelection(s))return;let a=s.anchor.getNode(),l=this.getBlockNode(a);l&&$isHeadingNode(l)&&!o?.shiftKey&&(this.toggleBlockFormat(t,"p"),r=true);}),r&&o?.preventDefault(),r},COMMAND_PRIORITY_EDITOR);return ()=>{e(),n();}}getNodes(){return [ParagraphNode,HeadingNode,QuoteNode]}getCommands(t){return {toggleBlockFormat:e=>this.toggleBlockFormat(t,e),toggleParagraph:()=>this.toggleBlockFormat(t,"p"),toggleHeading:e=>this.toggleBlockFormat(t,e),toggleQuote:()=>this.toggleBlockFormat(t,"quote"),setTextAlignment:e=>this.setTextAlignment(t,e),getCurrentBlockType:()=>this.getCurrentFormat(t)||"p"}}setTextAlignment(t,e){t.dispatchCommand(FORMAT_ELEMENT_COMMAND,e);}toggleBlockFormat(t,e){t.update(()=>{let n=$getSelection();if($isRangeSelection(n)){if(this.getCurrentFormatSync()===e){$setBlocksType(n,()=>$createParagraphNode());return}$setBlocksType(n,()=>e==="p"?$createParagraphNode():e==="quote"?$createQuoteNode():$createHeadingNode(e));}});}getStateQueries(t){return {isParagraph:()=>Promise.resolve(this.isFormat("p",t)),isH1:()=>Promise.resolve(this.isFormat("h1",t)),isH2:()=>Promise.resolve(this.isFormat("h2",t)),isH3:()=>Promise.resolve(this.isFormat("h3",t)),isH4:()=>Promise.resolve(this.isFormat("h4",t)),isH5:()=>Promise.resolve(this.isFormat("h5",t)),isH6:()=>Promise.resolve(this.isFormat("h6",t)),isQuote:()=>Promise.resolve(this.isFormat("quote",t)),isTextAlignedLeft:()=>Promise.resolve(this.isAlignment("left",t)),isTextAlignedCenter:()=>Promise.resolve(this.isAlignment("center",t)),isTextAlignedRight:()=>Promise.resolve(this.isAlignment("right",t)),isTextAlignedJustify:()=>Promise.resolve(this.isAlignment("justify",t))}}isAlignment(t,e){let n=true;return e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o)){n=false;return}let r=o.getNodes();for(let s of r){let a=this.getBlockNode(s);if(!a){n=false;break}if(this.normalizeAlignment(a.getFormatType())!==t){n=false;break}}}),n}normalizeAlignment(t){return t==="center"||t==="right"||t==="justify"?t:"left"}getBlockNode(t){let e=t;for(;e;){if($isParagraphNode(e)||$isHeadingNode(e)||$isQuoteNode(e))return e;e=e.getParent();}return null}isFormat(t,e){let n=true;return e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o)){n=false;return}let r=o.getNodes();for(let s of r){let a=this.getBlockNode(s);if(!a){n=false;break}if(this.getNodeFormat(a)!==t){n=false;break}}}),n}getNodeFormat(t){return $isParagraphNode(t)?"p":$isHeadingNode(t)?t.getTag():$isQuoteNode(t)?"quote":null}getCurrentFormat(t){let e=null;return t.getEditorState().read(()=>{let n=$getSelection();if($isRangeSelection(n)){let o=n.anchor.getNode(),r=this.getBlockNode(o);r&&(e=this.getNodeFormat(r));}}),e}getCurrentFormatSync(){let t=$getSelection();if(!$isRangeSelection(t))return null;let e=t.anchor.getNode(),n=this.getBlockNode(e);return n?this.getNodeFormat(n):null}},Zu=new qn;var Jn=class extends k{constructor(){super("history",["toolbar"]);x(this,"canUndoState",false);x(this,"canRedoState",false);}register(e){let n=e.registerCommand(CAN_UNDO_COMMAND,r=>(this.canUndoState=r,false),COMMAND_PRIORITY_LOW),o=e.registerCommand(CAN_REDO_COMMAND,r=>(this.canRedoState=r,false),COMMAND_PRIORITY_LOW);return ()=>{n(),o();}}getPlugins(){return [jsx(HistoryPlugin,{},"history-plugin")]}getCommands(e){return {undo:()=>{e.focus(),e.dispatchCommand(UNDO_COMMAND,void 0);},redo:()=>{e.focus(),e.dispatchCommand(REDO_COMMAND,void 0);},clearHistory:()=>e.dispatchCommand(CLEAR_HISTORY_COMMAND,void 0)}}getStateQueries(e){return {canUndo:async()=>this.canUndoState,canRedo:async()=>this.canRedoState}}},sm=new Jn;var eo=class extends k{constructor(e){super("draggableBlock",["floating"]);x(this,"isDraggingState",false);x(this,"stateChangeCallbacks",new Set);this.config={showInToolbar:false,position:"after",showMoveButtons:true,showUpButton:true,showDownButton:true,showAddButton:true,buttonStackPosition:"left",enableTextSelectionDrag:true,offsetLeft:-40,offsetRight:10,...e};}register(e){return ()=>{}}getPlugins(){return [jsx(um,{config:this.config,extension:this},"draggable-block")]}getCommands(e){return {moveBlock:(n,o,r)=>{e.isEditable()&&e.update(()=>{let s=$getNodeByKey(n),a=$getNodeByKey(o);s&&a&&(s.remove(),r?a.insertAfter(s):a.insertBefore(s));});},moveCurrentBlockUp:()=>{e.isEditable()&&e.update(()=>{let n=$getSelection();if($isRangeSelection(n)){let o=n.anchor.getNode(),r=$isElementNode(o)?o:o.getParent();if(r&&$isElementNode(r)){let s=r.getPreviousSibling();s&&(r.remove(),s.insertBefore(r));}}});},moveCurrentBlockDown:()=>{e.isEditable()&&e.update(()=>{let n=$getSelection();if($isRangeSelection(n)){let o=n.anchor.getNode(),r=$isElementNode(o)?o:o.getParent();if(r&&$isElementNode(r)){let s=r.getNextSibling();s&&(r.remove(),s.insertAfter(r));}}});}}}getStateQueries(e){return {isDragging:async()=>this.isDraggingState}}setIsDragging(e){this.isDraggingState!==e&&(this.isDraggingState=e,this.stateChangeCallbacks.forEach(n=>n()));}onStateChange(e){return this.stateChangeCallbacks.add(e),()=>this.stateChangeCallbacks.delete(e)}},dm=new eo;function um({config:i,extension:t}){let[e]=useLexicalComposerContext(),{config:n,extensions:o}=Ae(),s=o.find(C=>C.name==="draggableBlock")?.config,a=useMemo(()=>n?.theme?.draggable||{},[n?.theme?.draggable]),[l,c]=useState(null),[d,u]=useState(false),[m,g]=useState(()=>e.isEditable()),[p,T]=useState(null),[w,b]=useState(false),h=useRef(null),N=useRef(null),f=useRef(null),y=useRef(null),S=useRef(null),L=useRef(null),E=useRef(null),v=useRef(null),[M,A]=useState(null);useEffect(()=>{t.setIsDragging(d);},[d,t]);let F=typeof document<"u"&&typeof window<"u",Q=e.getRootElement(),te=F?Q?.closest?.(".luthor-editor")||Q?.parentElement||document.body:null,B=s?.anchorElem||i.anchorElem||te,z=useMemo(()=>({handle:{cursor:"grab",userSelect:"none"},handleActive:{cursor:"grabbing"},blockDragging:{opacity:.5},dropIndicator:{backgroundColor:"var(--luthor-accent, #3b82f6)",borderRadius:"2px"},addButton:{cursor:"pointer"},buttonStack:{}}),[]),K=useMemo(()=>({handle:{...z.handle,...a.styles?.handle,...s?.styles?.handle},handleActive:{...z.handleActive,...a.styles?.handleActive,...s?.styles?.handleActive},blockDragging:{...z.blockDragging,...a.styles?.blockDragging,...s?.styles?.blockDragging},dropIndicator:{...z.dropIndicator,...a.styles?.dropIndicator,...s?.styles?.dropIndicator},addButton:{...z.addButton,...a.styles?.addButton,...s?.styles?.addButton},buttonStack:{...z.buttonStack,...a.styles?.buttonStack,...s?.styles?.buttonStack}}),[z,s?.styles,a.styles]),I=useMemo(()=>({handle:s?.theme?.handle||a.handle||"luthor-draggable-handle",handleActive:s?.theme?.handleActive||a.handleActive||"luthor-draggable-handle-active",blockDragging:s?.theme?.blockDragging||a.blockDragging||"luthor-draggable-block-dragging",dropIndicator:s?.theme?.dropIndicator||a.dropIndicator||"luthor-draggable-drop-indicator",addButton:s?.theme?.addButton||a.addButton||"luthor-draggable-add-button",buttonStack:s?.theme?.buttonStack||a.buttonStack||"luthor-draggable-button-stack"}),[s?.theme,a]),j=useCallback(C=>{if(!C||!I.blockDragging)return;(I.blockDragging.includes(" ")?I.blockDragging.split(" ").filter(Boolean):[I.blockDragging]).forEach(O=>C.classList.remove(O)),C.style.opacity="";},[I]),Y=useCallback(C=>{if(!C||!I.blockDragging)return;(I.blockDragging.includes(" ")?I.blockDragging.split(" ").filter(Boolean):[I.blockDragging]).forEach(O=>C.classList.add(O)),Object.assign(C.style,K.blockDragging);},[I,K.blockDragging]);useEffect(()=>e.registerEditableListener(C=>{g(C),!C&&(u(false),T(null),c(null),b(false),h.current&&j(h.current),h.current=null,N.current=null);}),[e,j]);let le=useCallback(()=>{let C=e.getRootElement();if(C)try{C.focus({preventScroll:!0});}catch{C.focus();}},[e]),J=useCallback(()=>{h.current&&j(h.current),u(false),T(null),le(),setTimeout(()=>{h.current=null,N.current=null;},100);},[j,le]);useEffect(()=>()=>{h.current&&j(h.current),y.current&&clearTimeout(y.current),S.current!==null&&window.cancelAnimationFrame(S.current),E.current!==null&&window.cancelAnimationFrame(E.current);},[j]),useEffect(()=>{f.current=l;},[l]);let X=useCallback(C=>{L.current=C,S.current===null&&(S.current=window.requestAnimationFrame(()=>{S.current=null;let P=L.current;c(O=>O===P?O:P);}));},[]),Pe=useCallback(C=>{v.current=C,E.current===null&&(E.current=window.requestAnimationFrame(()=>{E.current=null;let P=v.current;P!=null&&A(O=>O!=null&&Math.abs(O-P)<.5?O:P);}));},[]),Se=useCallback(C=>{let P=null;e.update(()=>{let O=$createParagraphNode(),D=$getNearestNodeFromDOMNode(C);if(D)try{D.getTopLevelElementOrThrow().insertAfter(O);}catch{$getRoot().append(O);}else $getRoot().append(O);O.selectStart(),P=O.getKey();}),P&&setTimeout(()=>{let O=e.getElementByKey(P);if(O&&O instanceof HTMLElement&&typeof O.getBoundingClientRect=="function"){X(O);let D=O.getBoundingClientRect();Pe(D.top+window.scrollY+D.height/2);}},0),le();},[e,le,X,Pe]);useEffect(()=>{if(l||h.current)b(true);else {let C=setTimeout(()=>b(false),300);return ()=>clearTimeout(C)}},[l]),useEffect(()=>{let C=O=>{if(!m){X(null);return}if(d)return;let D=e.getRootElement();if(!D)return;let _=O.target;Pe(O.clientY+window.scrollY);let R=_&&_.closest&&(_.closest(".drag-handle-area")||_.closest('[draggable="true"]')||_.closest(".luthor-drag-button")||_.closest(".luthor-draggable-button-stack")),re=window.getSelection(),W=re&&re.rangeCount>0&&!re.isCollapsed,$=null,H=_;for(;H&&H!==D&&H!==document.body;){if(H.parentElement===D){$=H;break}H=H.parentElement;}y.current&&(clearTimeout(y.current),y.current=null),($||R)&&!W&&!d?$&&X($):y.current=setTimeout(()=>{X(null),y.current=null;},500);},P=()=>{d||(y.current&&(clearTimeout(y.current),y.current=null),y.current=setTimeout(()=>{X(null),y.current=null;},300));};return document.addEventListener("mousemove",C),document.addEventListener("mouseleave",P),()=>{document.removeEventListener("mousemove",C),document.removeEventListener("mouseleave",P),y.current&&(clearTimeout(y.current),y.current=null),S.current!==null&&(window.cancelAnimationFrame(S.current),S.current=null),E.current!==null&&(window.cancelAnimationFrame(E.current),E.current=null);}},[e,d,m,X,Pe]);let Oe=useCallback((C,P)=>{if(!e.isEditable()){C.preventDefault();return}C.stopPropagation(),u(true),T(null),h.current=P,Y(P);let O=e.read(()=>{let _=$getNearestNodeFromDOMNode(P);return _?_.getKey():null});O&&(N.current=O,C.dataTransfer?.setData("application/x-lexical-drag",JSON.stringify({key:O}))),C.dataTransfer.effectAllowed="move";let D=P.cloneNode(true);D.style.opacity="0.6",D.style.position="absolute",D.style.top="-9999px",D.style.left="-9999px",document.body.appendChild(D),C.dataTransfer.setDragImage(D,0,0),setTimeout(()=>document.body.removeChild(D),0);},[e,Y]),Ie=useCallback((C,P)=>{if(!e.isEditable())return;C.preventDefault(),u(true),h.current=P,Y(P);let O=e.read(()=>{let D=$getNearestNodeFromDOMNode(P);return D?D.getKey():null});O&&(N.current=O);},[e,Y]),_e=useCallback(C=>{if(!e.isEditable()||!d||!h.current)return;C.preventDefault();let P=C.touches[0];if(!P)return;let O=e.getRootElement();if(!O)return;let D=null,_=document.elementFromPoint(P.clientX,P.clientY);if(_){let R=_;for(;R&&R!==O;){if(R.parentElement===O){D=R;break}R=R.parentElement;}}if(D&&D!==h.current){let R=D.getBoundingClientRect(),re=P.clientY<R.top+R.height/2;T({top:re?R.top+window.scrollY:R.bottom+window.scrollY,left:R.left+window.scrollX,width:R.width});}else T(null);},[e,d]),me=useCallback(C=>{if(!e.isEditable()){J();return}if(!d||!N.current)return;C.preventDefault();let P=C.changedTouches[0];if(!P)return;let O=e.getRootElement();if(!O)return;let D=null,_=document.elementFromPoint(P.clientX,P.clientY);if(_){let R=_;for(;R&&R!==O;){if(R.parentElement===O){D=R;break}R=R.parentElement;}}D&&D!==h.current&&(e.update(()=>{let R=$getNodeByKey(N.current),re=$getNearestNodeFromDOMNode(D);if(R&&re){let W=D.getBoundingClientRect(),$=P.clientY>=W.top+W.height/2;R.remove(),$?re.insertAfter(R):re.insertBefore(R);}}),setTimeout(()=>{if(N.current)try{let R=e.getElementByKey(N.current);R&&R instanceof HTMLElement&&typeof R.getBoundingClientRect=="function"&&c(R);}catch(R){console.warn("Error finding moved element:",R);}},50)),J();},[e,d,J]);useEffect(()=>{let C=e.getRootElement();if(!C)return;let P=_=>{if(!e.isEditable()){_.preventDefault();return}let R=_.target;if(R.nodeType!==Node.ELEMENT_NODE&&(R=R.parentNode),!R||!(R instanceof HTMLElement)){_.preventDefault();return}if(R.closest('[draggable="true"]'))return;let W=window.getSelection();if(!W||W.isCollapsed||!(s?.enableTextSelectionDrag??i.enableTextSelectionDrag)){_.preventDefault();return}let $=W.anchorNode;$?.nodeType===Node.TEXT_NODE&&($=$.parentNode);let H=null;for(;$&&$!==C;){if($.parentNode===C){H=$;break}$=$.parentNode;}if(!H){_.preventDefault();return}W.collapse(W.anchorNode,W.anchorOffset);let ne=e.read(()=>$getNearestNodeFromDOMNode(H)?.getKey()??null);if(!ne){_.preventDefault();return}_.dataTransfer.clearData(),_.dataTransfer.setData("application/x-lexical-drag",JSON.stringify({key:ne})),_.dataTransfer.effectAllowed="move";let q=H.cloneNode(true);q.style.opacity="0.6",q.style.position="absolute",q.style.top="-9999px",q.style.left="-9999px",document.body.appendChild(q),_.dataTransfer.setDragImage(q,0,0),setTimeout(()=>document.body.removeChild(q),0),u(true),T(null),h.current=H,Y(H),N.current=ne;},O=_=>{if(!e.isEditable())return;let R=_.target;if(R.nodeType!==Node.ELEMENT_NODE&&(R=R.parentNode),!R||!(R instanceof HTMLElement))return;let re=R;_.preventDefault(),_.dataTransfer.dropEffect="move";let W=null,$=re;for(;$&&$!==C;){if($.parentElement===C){W=$;break}$=$.parentElement;}if(W&&W!==h.current){let H=W.getBoundingClientRect(),ne=_.clientY<H.top+H.height/2;T({top:ne?H.top+window.scrollY:H.bottom+window.scrollY,left:H.left+window.scrollX,width:H.width});}else T(null);},D=_=>{if(!e.isEditable())return;let R=_.target;if(R.nodeType!==Node.ELEMENT_NODE&&(R=R.parentNode),!R||!(R instanceof HTMLElement))return;let re=R;_.preventDefault(),T(null);let W=_.dataTransfer?.getData("application/x-lexical-drag");if(!W){J();return}let{key:$}=JSON.parse(W);if(!$){J();return}let H=null,ne=re;for(;ne&&ne!==C;){if(ne.parentElement===C){H=ne;break}ne=ne.parentElement;}H&&H!==h.current&&(e.update(()=>{let q=$getNodeByKey($),we=$getNearestNodeFromDOMNode(H);if(q&&we){let ot=H.getBoundingClientRect(),Gt=_.clientY>=ot.top+ot.height/2;q.remove(),Gt?we.insertAfter(q):we.insertBefore(q);}}),setTimeout(()=>{if(N.current)try{let q=e.getElementByKey(N.current);q&&q instanceof HTMLElement&&typeof q.getBoundingClientRect=="function"&&c(q);}catch(q){console.warn("Error finding moved element:",q);}le();},50)),J();};return C.addEventListener("dragstart",P),C.addEventListener("dragover",O),C.addEventListener("drop",D),C.addEventListener("dragend",J),()=>{C.removeEventListener("dragstart",P),C.removeEventListener("dragover",O),C.removeEventListener("drop",D),C.removeEventListener("dragend",J);}},[e,J,Y,le,s?.enableTextSelectionDrag,i.enableTextSelectionDrag]),useEffect(()=>{if(!d)return;let C=()=>{J();},P=D=>{D.key==="Escape"&&J();},O=()=>{document.hidden&&J();};return window.addEventListener("dragend",C),window.addEventListener("drop",C),window.addEventListener("blur",C),document.addEventListener("keydown",P),document.addEventListener("visibilitychange",O),()=>{window.removeEventListener("dragend",C),window.removeEventListener("drop",C),window.removeEventListener("blur",C),document.removeEventListener("keydown",P),document.removeEventListener("visibilitychange",O);}},[d,J]),useEffect(()=>{let C=e.getRootElement();if(!C)return;let P=null,O=0,D=0,_=W=>{if(!e.isEditable()||W.touches.length!==1||!(s?.enableTextSelectionDrag??i.enableTextSelectionDrag))return;let $=W.touches[0];if(!$)return;let H=W.target;if(H.nodeType!==Node.ELEMENT_NODE&&(H=H.parentNode),!H||!(H instanceof HTMLElement))return;let ne=H;ne.closest('[draggable="true"]')||(O=$.clientX,D=$.clientY,P=setTimeout(()=>{P=null;let q=null,we=ne;for(;we&&we!==C;){if(we.parentElement===C){q=we;break}we=we.parentElement;}if(!q)return;let ot=window.getSelection();ot&&!ot.isCollapsed&&ot.collapseToStart(),u(true),h.current=q,Y(q);let Gt=e.read(()=>$getNearestNodeFromDOMNode(q)?.getKey()??null);Gt&&(N.current=Gt);},500));},R=W=>{if(P&&W.touches.length===1){let $=W.touches[0];if(!$)return;let H=$.clientX-O,ne=$.clientY-D;Math.sqrt(H*H+ne*ne)>10&&(clearTimeout(P),P=null);}},re=()=>{P&&(clearTimeout(P),P=null);};return C.addEventListener("touchstart",_,{passive:false}),C.addEventListener("touchmove",R,{passive:false}),C.addEventListener("touchend",re,{passive:false}),document.addEventListener("touchmove",_e,{passive:false}),document.addEventListener("touchend",me,{passive:false}),()=>{C.removeEventListener("touchstart",_),C.removeEventListener("touchmove",R),C.removeEventListener("touchend",re),document.removeEventListener("touchmove",_e),document.removeEventListener("touchend",me);}},[e,Y,J,d,_e,me,s?.enableTextSelectionDrag,i.enableTextSelectionDrag]);let pe=l||h.current;if(!m||!F||!B||!pe||typeof pe.getBoundingClientRect!="function")return null;let ue=pe.getBoundingClientRect();if(!ue.width||!ue.height)return null;let Ke=Q?.closest?.(".luthor-editor")||null,yt=Ke||Q;if(!yt)return null;let Jt=yt.getBoundingClientRect(),uo=window.getComputedStyle(yt),mo=Number.parseFloat(uo.getPropertyValue("--luthor-drag-gutter-width"))||40,Fe=m&&(s?.showAddButton??i.showAddButton)!==false,_s=Fe?52:24,As=Jt.left+window.scrollX+Math.max(0,(mo-_s)/2),Ds=(s?.buttonStackPosition||i.buttonStackPosition)==="right"?ue.right+window.scrollX+(s?.offsetRight||i.offsetRight||10):Ke?As:ue.left+window.scrollX+(s?.offsetLeft||i.offsetLeft||-40),Xt=24,ur=Xt/2,go=ue.top+window.scrollY,mr=ue.bottom+window.scrollY,Hs=go+ue.height/2,Fs=M??Hs,Bs=go+Xt/2,zs=mr-Xt/2,$s=Math.min(zs,Math.max(Bs,Fs)),gr=go,js=Math.max(gr,mr-(ur+Xt/2)),Ks=Math.min(js,Math.max(gr,$s-ur)),fr=B.getBoundingClientRect(),pr=B===document.body?0:fr.left+window.scrollX,hr=B===document.body?0:fr.top+window.scrollY,Us=Ds-pr,Ys=Ks-hr;return jsxs(Fragment,{children:[createPortal(jsx("div",{className:`luthor-draggable-button-stack ${I.buttonStack} ${w?"":"fade-out"}`,style:{position:"absolute",left:0,top:0,transform:`translate3d(${Us}px, ${Ys}px, 0)`,zIndex:40,display:"flex",flexDirection:"row",gap:"6px",alignItems:"center",pointerEvents:"auto",willChange:"transform, opacity",backfaceVisibility:"hidden",perspective:"1000px",transition:"transform 140ms cubic-bezier(0.2, 0, 0, 1), opacity 140ms ease",...K.buttonStack},children:jsxs("div",{style:{display:"flex",flexDirection:"row",alignItems:"center",gap:"4px"},children:[Fe&&jsx("button",{type:"button","aria-label":"Add block",title:"Add",className:`luthor-drag-button ${I.addButton}`,onMouseDown:C=>{C.preventDefault(),C.stopPropagation();},onClick:C=>{C.preventDefault(),C.stopPropagation(),!(!pe||d)&&Se(pe);},style:K.addButton,children:"+"}),s?.handleRenderer||i.handleRenderer?(s?.handleRenderer||i.handleRenderer)({rect:ue,isDragging:d,onDragStart:C=>Oe(C,pe),className:`luthor-drag-button ${I.handle} ${d?I.handleActive:""}`.trim()}):jsx("div",{className:`luthor-drag-button ${I.handle} ${d?I.handleActive:""}`.trim(),draggable:true,onDragStart:C=>Oe(C,pe),onDragEnd:J,onTouchStart:C=>Ie(C,pe),style:d?K.handleActive:K.handle,children:"\u22EE\u22EE"})]})}),B),p&&(s?.dropIndicatorRenderer||i.dropIndicatorRenderer?createPortal((s?.dropIndicatorRenderer||i.dropIndicatorRenderer)({...p,className:I.dropIndicator}),B):createPortal(jsx("div",{className:I.dropIndicator,style:{position:"absolute",top:p.top-4-hr,left:p.left-pr,width:p.width,height:"8px",pointerEvents:"none",zIndex:9997,...K.dropIndicator}}),B))]})}function fs(i){let t=renderToStaticMarkup(i),e=document.createElement("div");e.innerHTML=t;let n=e.firstElementChild;return e.remove(),n}function Sm(i){let t=i.isContainer??false,e=createCommand("insert-custom-node");function n({node:l,payload:c,nodeKey:d,children:u}){let[m]=useLexicalComposerContext(),[g,p]=useState(false);useEffect(()=>m.registerUpdateListener(({editorState:w})=>{w.read(()=>{let b=$getSelection();p($isNodeSelection(b)&&b.getNodes().some(h=>h.__key===d));});}),[m,d]);let T=w=>{m.update(()=>{let b=l.getWritable();b.__payload={...b.__payload,...w};});};return i.render?i.render({node:l,payload:c,children:u,nodeKey:d,isSelected:g,updatePayload:T}):null}class o extends ElementNode{constructor(d={},u,m){super(m);x(this,"__payload");x(this,"__nodeType");this.__payload=d,this.__nodeType=u;}static getType(){return i.nodeType}static clone(d){return new o(d.__payload,d.__nodeType,d.__key)}isSelectable(){return true}canBeEmpty(){return false}canInsertTextBefore(){return false}canInsertTextAfter(){return false}static importJSON(d){let{payload:u}=d;return new o(u,d.type)}static importDOM(){return i.importDOM?i.importDOM():{}}static exportDOM(d,{node:u}){if(i.exportDOM){let g=document.createElement("div");return i.exportDOM(d,{element:g,node:u})}let m=document.createElement("div");return m.setAttribute("data-custom-node-type",i.nodeType),{element:m}}exportJSON(){return {type:this.__nodeType,version:1,payload:this.__payload,children:this.getChildren().map(d=>d.exportJSON()),direction:null,format:"",indent:0}}createDOM(d){if(i.createDOM){let m=i.createDOM(d,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m.setAttribute("data-lexical-key",this.getKey()),m}if(i.jsx){let m=i.jsx({node:this,payload:this.__payload,nodeKey:this.getKey(),isSelected:false,updatePayload:p=>{this.setPayload(p);}}),g=fs(m);return g.setAttribute("data-custom-node-type",this.__nodeType),g.setAttribute("data-lexical-key",this.getKey()),g}let u=document.createElement("div");return u.setAttribute("data-custom-node-type",this.__nodeType),u.setAttribute("data-lexical-key",this.getKey()),u.style.border="2px solid #ccc",u.style.borderRadius="8px",u.style.padding="16px",u.style.margin="8px 0",u.style.position="relative",u}updateDOM(d,u,m){return i.updateDOM?i.updateDOM(d,u,m):false}getPayload(){return this.__payload}setPayload(d){let u=this.getWritable();u.__payload={...this.__payload,...d};}}class r extends DecoratorNode{constructor(d={},u,m){super(m);x(this,"__payload");x(this,"__nodeType");this.__payload=d,this.__nodeType=u;}static getType(){return i.nodeType}static clone(d){return new r(d.__payload,d.__nodeType,d.__key)}isSelectable(){return true}static importJSON(d){let{payload:u}=d;return new r(u,d.type)}static importDOM(){return i.importDOM?i.importDOM():{}}static exportDOM(d,{node:u}){if(i.exportDOM){let g=document.createElement("span");return i.exportDOM(d,{element:g,node:u})}let m=document.createElement("span");return m.setAttribute("data-custom-node-type",i.nodeType),{element:m}}exportJSON(){return {type:this.__nodeType,version:1,payload:this.__payload}}createDOM(d){let u=document.createElement("span");if(u.setAttribute("data-custom-node-type",this.__nodeType),i.createDOM){let m=i.createDOM(d,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m}return u}updateDOM(d,u,m){return i.updateDOM?i.updateDOM(d,u,m):false}getPayload(){return this.__payload}setPayload(d){let u=this.getWritable();u.__payload={...this.__payload,...d};}decorate(){return jsx(n,{node:this,payload:this.__payload,nodeKey:this.__key})}}function s(l=i.defaultPayload||{}){if(t){let c=new o(l,i.nodeType);if(i.initialChildren)i.initialChildren().forEach(u=>{if(u.type==="paragraph"){let m=$createParagraphNode();u.children&&u.children.forEach(g=>{g.type==="text"&&m.append($createTextNode(g.text||""));}),c.append(m);}});else {let d=$createParagraphNode();d.append($createTextNode("")),c.append(d);}return c}else return new r(l,i.nodeType)}class a extends k{constructor(){super(i.nodeType,["toolbar"]);}register(c){let d=c.registerCommand(e,m=>(c.update(()=>{let g=s(m),p=$getSelection();$isRangeSelection(p)?p.insertNodes([g]):$getRoot().append($createParagraphNode().append(g));}),true),COMMAND_PRIORITY_EDITOR),u=c.registerUpdateListener(({editorState:m})=>{t&&m.read(()=>{let g=$getSelection(),p=$isNodeSelection(g)?g.getNodes():[];c.getEditorState().read(()=>{let T=$getRoot(),w=b=>{if(b.getType()===i.nodeType){let h=p.some(f=>f.__key===b.__key),N=document.querySelector(`[data-lexical-key="${b.__key}"]`);N&&(N.setAttribute("data-selected",h.toString()),N.style.borderColor=h?"#007ACC":"#ccc",N.style.backgroundColor=h?"#f0f8ff":"transparent");}"getChildren"in b&&b.getChildren().forEach(w);};w(T);});});});return ()=>{d(),u();}}getNodes(){return t?[o]:[r]}getCommands(c){return {...{insertCustomNode:u=>c.dispatchCommand(e,u)},...i.commands?i.commands(c):{}}}getStateQueries(c){return {...{isCustomNodeActive:()=>new Promise(u=>{c.getEditorState().read(()=>{let m=$getSelection();u(!!m&&$isNodeSelection(m)&&m.getNodes().some(g=>g.getType()===i.nodeType));});})},...i.stateQueries?i.stateQueries(c):{}}}}return {extension:new a,$createCustomNode:s,jsxToDOM:fs}}function ps(i,t,e){return e<=t?t:Math.min(e,Math.max(t,i))}function Lm(i,t,e,n){let o=i.getBoundingClientRect(),r=t.getBoundingClientRect(),s=ps(e,o.left+1,o.right-1),a=ps(n,r.top+1,r.bottom-1);return {x:s,y:a}}function wm(i,t){let e=document,n=window.getSelection();if(!n)return;let o=e.caretPositionFromPoint?.(i,t);if(o){let s=document.createRange();s.setStart(o.offsetNode,o.offset),s.collapse(true),n.removeAllRanges(),n.addRange(s);return}let r=e.caretRangeFromPoint?.(i,t);r&&(r.collapse(true),n.removeAllRanges(),n.addRange(r));}function hs(i,t,e){let r=Array.from(i.children).filter(l=>l instanceof HTMLElement).reduce((l,c)=>{let d=c.getBoundingClientRect(),u=d.top+d.height/2;if(!l)return c;let m=l.getBoundingClientRect(),g=m.top+m.height/2;return Math.abs(u-e)<Math.abs(g-e)?c:l},null)??i.firstElementChild??i,{x:s,y:a}=Lm(i,r,t,e);i.focus(),wm(s,a);}function Rm(i){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(()=>i());return}globalThis.setTimeout(i,0);}function bs(i){return !!i.closest(["button","a","input","textarea","select","[role='button']","[role='checkbox']","iframe","video","audio","embed","object",".luthor-list-item-unchecked",".luthor-list-item-checked","[data-lexical-iframe-embed]","[data-lexical-youtube-embed]","[data-iframe-embed]","[data-youtube-video]",".luthor-media-embed-shell"].join(", "))}var ys=i=>{let{contentEditable:t,placeholder:e,className:n,nonEditableVisualMode:o=false,onEditIntent:r,classNames:s,styles:a,errorBoundary:l}=i,c=Vt.useContext(Et),d=c?.lexical??null,[u,m]=Vt.useState(!o),g=Vt.useRef(null),p=c?.config,T=typeof p?.placeholder=="string"?p.placeholder:void 0,w=p?.classNames,b=p?.styles,h=e??T??"Start writing...",N=s?.placeholder||w?.placeholder||Ue.richText?.placeholder||"luthor-placeholder",f={position:"absolute",pointerEvents:"none",zIndex:1,...b?.placeholder,...a?.placeholder};return Vt.useEffect(()=>{m(!o);},[o]),Vt.useEffect(()=>{d?.setEditable(u);},[u,d]),jsx("div",{className:s?.container||w?.container||n||Ue.container||"luthor-editor-container",onMouseDown:y=>{if(y.button!==0)return;let S=y.target;if(!S||bs(S))return;let L=y.currentTarget,E=y.clientX,v=y.clientY;if(o&&!u){if(r){g.current={clientX:E,clientY:v};return}let A=L.querySelector("[contenteditable]");if(!A)return;y.preventDefault(),d?.setEditable(true),m(true),Rm(()=>{let F=L.querySelector("[contenteditable='true']")??A;hs(F,E,v);});return}let M=L.querySelector("[contenteditable='true']");!M||M.contains(S)||(y.preventDefault(),hs(M,E,v));},onMouseUp:y=>{if(y.button!==0||!r||!o||u){g.current=null;return}let S=y.target;if(!S||bs(S)){g.current=null;return}let L=g.current;if(g.current=null,!L)return;let E=Math.abs(y.clientX-L.clientX),v=Math.abs(y.clientY-L.clientY);if(E>4||v>4)return;let M=window.getSelection();M&&!M.isCollapsed||r({clientX:y.clientX,clientY:y.clientY});},style:{position:"relative",cursor:o?"default":"text",...b?.container,...a?.container},children:jsx(RichTextPlugin,{contentEditable:t||jsx("div",{style:{display:"block"},children:jsx(ContentEditable,{className:s?.contentEditable||w?.contentEditable||Ue.richText?.contentEditable||"luthor-content-editable",style:{...o?{cursor:"default",caretColor:"transparent",userSelect:"text",WebkitUserSelect:"text"}:{},...b?.contentEditable,...a?.contentEditable}})}),placeholder:typeof h=="string"?jsx("div",{className:N,style:f,children:h}):h||jsx("div",{className:N,style:f,children:"Start writing..."}),ErrorBoundary:l||Pm})})},sr=class extends k{constructor(t={}){super("richText",["floating"]),this.config={showInToolbar:false,position:"after",...t};}register(t){return ()=>{}}getPlugins(){return [jsx(ys,{...this.config},"rich-text")]}},km=new sr,Mm=i=>jsx(ys,{...i}),Pm=({children:i,onError:t})=>{try{return jsx(Fragment,{children:i})}catch(e){return console.error("RichTextPlugin Error:",e),t(e),jsxs("div",{className:"editor-error-boundary",children:[jsx("h3",{children:"Editor Error"}),jsx("p",{children:"Something went wrong with the editor. Please refresh the page."})]})}};var Ts=8,$m=9,no=class extends k{constructor(t={}){super("tabIndent",["toolbar"]),this.config=t;}register(t){let e=t.registerCommand(KEY_TAB_COMMAND,n=>{let o=$getSelection();if(!$isRangeSelection(o))return false;let r=o.anchor.getNode();if(this.isInCodeBlock(r))return false;n.preventDefault();let s=this.resolveTabContext(r);return s==="paragraph"?(n.shiftKey||t.update(()=>{let a=$getSelection();if($isRangeSelection(a)){if(this.hasReachedTextTabLimit(a))return;a.insertText(" ");}}),true):s==="list"?n.shiftKey?(t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0),true):(this.isListAtMaxDepth(r)||t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),true):s==="heading"?n.shiftKey?(t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0),true):(this.isBlockAtMaxIndent(r)||t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),true):true},COMMAND_PRIORITY_LOW);return ()=>{e();}}isInCodeBlock(t){let e=t;for(;e;){if($isCodeNode(e))return true;e=e.getParent();}return false}isListAtMaxDepth(t){let e=this.config.maxListDepth,n=Number.isFinite(e)?Math.max(1,Math.floor(e)):$m,o=Math.max(0,n-1),r=this.findNearestListItemNode(t);if(r&&typeof r.getIndent=="function"){let a=r.getIndent();if(typeof a=="number")return a>=o}let s=this.findNearestListNode(t);return s?$getListDepth(s)-1>=o:false}isBlockAtMaxIndent(t){let e=t;for(;e;){if($isRootOrShadowRoot(e))return false;if(typeof e.getIndent=="function"){let n=e.getIndent();if(typeof n=="number")return n>=Ts}e=e.getParent();}return false}resolveTabContext(t){let e=t;for(;e;){if($isListNode(e))return "list";if($isHeadingNode(e))return "heading";if($isParagraphNode(e))return "paragraph";if($isRootOrShadowRoot(e))break;e=e.getParent();}return "other"}findNearestListNode(t){let e=t;for(;e;){if($isListNode(e))return e;e=e.getParent();}return null}findNearestListItemNode(t){let e=t;for(;e;){if($isListItemNode(e))return e;e=e.getParent();}return null}hasReachedTextTabLimit(t){let e=t.anchor,n=e.getNode();if(typeof n.getTextContent!="function")return false;let o=n.getTextContent(),r=typeof e.offset=="number"?e.offset:o.length,s=Math.max(0,Math.min(o.length,r)),a=o.lastIndexOf(`
7
+ `,s-1)+1;return (o.slice(a,s).match(/^\t*/)?.[0].length??0)>=Ts}},jm=new no;var ks=[{emoji:"\u{1F600}",label:"Grinning Face",shortcodes:["grinning"],keywords:["happy","smile"]},{emoji:"\u{1F604}",label:"Smile",shortcodes:["smile"],keywords:["happy","joy"]},{emoji:"\u{1F60A}",label:"Blush",shortcodes:["blush"],keywords:["warm","happy"]},{emoji:"\u{1F609}",label:"Wink",shortcodes:["wink"],keywords:["playful"]},{emoji:"\u{1F60D}",label:"Heart Eyes",shortcodes:["heart_eyes"],keywords:["love"]},{emoji:"\u{1F618}",label:"Kiss",shortcodes:["kiss"],keywords:["love"]},{emoji:"\u{1F914}",label:"Thinking",shortcodes:["thinking"],keywords:["hmm"]},{emoji:"\u{1F60E}",label:"Cool",shortcodes:["sunglasses"],keywords:["cool"]},{emoji:"\u{1F62D}",label:"Loudly Crying",shortcodes:["sob"],keywords:["cry","sad"]},{emoji:"\u{1F622}",label:"Crying",shortcodes:["cry"],keywords:["sad"]},{emoji:"\u{1F621}",label:"Pouting",shortcodes:["rage"],keywords:["angry"]},{emoji:"\u{1F62E}",label:"Open Mouth",shortcodes:["open_mouth"],keywords:["surprised"]},{emoji:"\u{1F44D}",label:"Thumbs Up",shortcodes:["thumbsup","+1"],keywords:["approve"]},{emoji:"\u{1F44E}",label:"Thumbs Down",shortcodes:["thumbsdown","-1"],keywords:["disapprove"]},{emoji:"\u{1F44F}",label:"Clap",shortcodes:["clap"],keywords:["applause"]},{emoji:"\u{1F64F}",label:"Folded Hands",shortcodes:["pray"],keywords:["thanks"]},{emoji:"\u{1F525}",label:"Fire",shortcodes:["fire"],keywords:["lit","hot"]},{emoji:"\u2728",label:"Sparkles",shortcodes:["sparkles"],keywords:["shine"]},{emoji:"\u{1F389}",label:"Party Popper",shortcodes:["tada"],keywords:["celebrate"]},{emoji:"\u2764\uFE0F",label:"Red Heart",shortcodes:["heart"],keywords:["love"]},{emoji:"\u{1F4AF}",label:"Hundred",shortcodes:["100"],keywords:["perfect"]},{emoji:"\u2705",label:"Check Mark",shortcodes:["white_check_mark"],keywords:["done"]},{emoji:"\u{1F680}",label:"Rocket",shortcodes:["rocket"],keywords:["launch"]},{emoji:"\u{1F91D}",label:"Handshake",shortcodes:["handshake"],keywords:["agreement"]},{emoji:"\u{1F3AF}",label:"Target",shortcodes:["dart"],keywords:["goal"]},{emoji:"\u{1F4A1}",label:"Light Bulb",shortcodes:["bulb"],keywords:["idea"]},{emoji:"\u{1F9E0}",label:"Brain",shortcodes:["brain"],keywords:["think"]},{emoji:"\u{1F6E0}\uFE0F",label:"Hammer and Wrench",shortcodes:["tools"],keywords:["build"]},{emoji:"\u{1F4CC}",label:"Pushpin",shortcodes:["pushpin"],keywords:["pin"]},{emoji:"\u{1F4CE}",label:"Paperclip",shortcodes:["paperclip"],keywords:["attach"]},{emoji:"\u{1F4C5}",label:"Calendar",shortcodes:["calendar"],keywords:["date"]},{emoji:"\u{1F4DD}",label:"Memo",shortcodes:["memo"],keywords:["note"]},{emoji:"\u{1F4AC}",label:"Speech Balloon",shortcodes:["speech_balloon"],keywords:["comment"]},{emoji:"\u{1F4F7}",label:"Camera",shortcodes:["camera"],keywords:["photo"]},{emoji:"\u{1F3AC}",label:"Clapper Board",shortcodes:["clapper"],keywords:["video","gif"]}],ws=ks,ro={":)":"\u{1F60A}",":(":"\u{1F641}",":D":"\u{1F604}",";)":"\u{1F609}",":P":"\u{1F61B}",":p":"\u{1F61B}",":O":"\u{1F62E}",":o":"\u{1F62E}",":|":"\u{1F610}",":/":"\u{1F615}",":'(":"\u{1F622}","<3":"\u2764\uFE0F"};function Qm(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qt(i){return i.trim().toLowerCase().replace(/^:+|:+$/g,"")}function Rs(i){return i.toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}function cr(i){let t=i.map(o=>({...o,shortcodes:[...o.shortcodes],keywords:o.keywords?[...o.keywords]:void 0})),e=new Map,n=t.map(o=>{let r=(o.shortcodes||[]).map(a=>qt(a)).filter(Boolean);for(let a of r)e.has(a)||e.set(a,o);let s=Rs([o.label,...r,...o.keywords||[]].join(" "));return {item:o,searchable:s}});return {getAll:()=>[...t],resolveShortcode:o=>e.get(qt(o))??null,search:(o,r)=>{let s=Math.max(0,r?.limit??t.length);if(s===0)return [];let a=Rs(o);return a?n.filter(l=>l.searchable.includes(a)).slice(0,s).map(l=>l.item):t.slice(0,s)}}}function Ms(i){return Array.isArray(i)?i.map(t=>typeof t=="string"?t.trim():"").filter(t=>t.length>0):[]}function Vm(i){let t=Ms(i.shortcodes);return t.length>0?t.map(e=>qt(e)):typeof i.shortcodes=="string"?i.shortcodes.split(/[,\s]+/).map(e=>qt(e)).filter(Boolean):[]}function lr(i){if(!i||typeof i!="object")return null;let t=i;if(!t.emojis||typeof t.emojis!="object")return null;let e=[];for(let[n,o]of Object.entries(t.emojis)){if(!o||typeof o!="object")continue;let r=o,s=typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():n,l=(Array.isArray(r.skins)?r.skins:[])[0],c=typeof l?.native=="string"?l.native:"";if(!c)continue;let d=Array.from(new Set([qt(n),...Vm(r)].filter(Boolean)));d.length!==0&&e.push({emoji:c,label:s,shortcodes:d,keywords:Ms(r.keywords)});}return e.length===0?null:cr(e)}async function Wm(i){return new Function("name","return import(name);")(i)}var io=class extends k{constructor(e={}){super("emoji",["toolbar"]);x(this,"listeners",[]);x(this,"isOpen",false);x(this,"query","");x(this,"position",null);x(this,"suggestions",[]);x(this,"activeMatch",null);x(this,"viewportRafId",null);x(this,"applyingAutoReplace",false);x(this,"catalogAdapter",cr(ws));x(this,"hasExplicitCatalogConfig",false);x(this,"hasExplicitAdapterConfig",false);x(this,"externalCatalogDetectionStarted",false);this.hasExplicitCatalogConfig=Object.prototype.hasOwnProperty.call(e,"catalog"),this.hasExplicitAdapterConfig=Object.prototype.hasOwnProperty.call(e,"catalogAdapter"),this.config={trigger:":",maxSuggestions:8,maxQueryLength:32,autoReplaceSymbols:true,symbolReplacements:ro,autoDetectExternalCatalog:true,offset:{x:0,y:8},...e},this.catalogAdapter=this.resolveCatalogAdapter(this.config);}configure(e){return this.config={...this.config,...e,symbolReplacements:{...this.config.symbolReplacements||ro,...e.symbolReplacements||{}}},Object.prototype.hasOwnProperty.call(e,"catalog")&&(this.hasExplicitCatalogConfig=true),Object.prototype.hasOwnProperty.call(e,"catalogAdapter")&&(this.hasExplicitAdapterConfig=true),this.catalogAdapter=this.resolveCatalogAdapter(this.config),this.isOpen&&(this.suggestions=this.getSuggestions(this.query),this.isOpen=this.suggestions.length>0,this.notifyListeners()),this}register(e){this.tryEnableExternalCatalog();let n=e.registerUpdateListener(()=>{this.updateFromSelection(e);}),o=e.registerCommand(PASTE_COMMAND,l=>{if(!this.config.autoReplaceSymbols)return false;let c=l.clipboardData;if(!c)return false;let d=c.getData("text/plain"),u=c.getData("text/html");if(!d||u)return false;let m=this.replaceSymbolsInText(d);return m===d?false:(l.preventDefault(),e.update(()=>{let g=$getSelection();$isRangeSelection(g)&&g.insertText(m);}),true)},COMMAND_PRIORITY_EDITOR),r=l=>{this.isOpen&&l.key==="Escape"&&(l.preventDefault(),this.closeEmojiSuggestions());},s=l=>{l.target?.closest(".luthor-emoji-menu")||this.isOpen&&this.closeEmojiSuggestions();},a=()=>{!this.isOpen||!this.activeMatch||this.viewportRafId===null&&(this.viewportRafId=window.requestAnimationFrame(()=>{this.viewportRafId=null;let l=this.getCaretPosition();if(!l){this.closeEmojiSuggestions();return}this.position=l,this.notifyListeners();}));};return document.addEventListener("keydown",r),document.addEventListener("pointerdown",s),window.addEventListener("scroll",a,true),window.addEventListener("resize",a),()=>{n(),o(),document.removeEventListener("keydown",r),document.removeEventListener("pointerdown",s),window.removeEventListener("scroll",a,true),window.removeEventListener("resize",a),this.viewportRafId!==null&&(cancelAnimationFrame(this.viewportRafId),this.viewportRafId=null),this.activeMatch=null,this.isOpen=false,this.query="",this.position=null,this.suggestions=[],this.notifyListeners();}}getCommands(e){return {insertEmoji:n=>{e.update(()=>{let o=$getSelection();$isRangeSelection(o)&&o.insertText(n);});},executeEmojiSuggestion:n=>this.executeEmojiSuggestion(e,n),closeEmojiSuggestions:()=>this.closeEmojiSuggestions(),getEmojiSuggestions:(n="")=>this.getSuggestions(n),getEmojiCatalog:()=>this.getCatalog(),resolveEmojiShortcode:n=>this.resolveShortcode(n),setEmojiCatalog:n=>{this.hasExplicitCatalogConfig=true,this.hasExplicitAdapterConfig=false,this.config={...this.config,catalog:[...n],catalogAdapter:void 0},this.catalogAdapter=this.resolveCatalogAdapter(this.config),this.isOpen&&(this.suggestions=this.getSuggestions(this.query),this.isOpen=this.suggestions.length>0,this.notifyListeners());},setEmojiCatalogAdapter:n=>{this.hasExplicitAdapterConfig=true,this.config={...this.config,catalogAdapter:n},this.catalogAdapter=this.resolveCatalogAdapter(this.config),this.isOpen&&(this.suggestions=this.getSuggestions(this.query),this.isOpen=this.suggestions.length>0,this.notifyListeners());},getEmojiCatalogAdapter:()=>this.catalogAdapter}}getStateQueries(e){return {isEmojiSuggestionOpen:()=>Promise.resolve(this.isOpen)}}subscribe(e){return this.listeners.push(e),e(this.getState()),()=>{this.listeners=this.listeners.filter(n=>n!==e);}}getCatalog(){return this.catalogAdapter.getAll()}getSuggestions(e){let n=this.config.maxSuggestions??8;return this.catalogAdapter.search(e,{limit:n})}resolveShortcode(e){return this.catalogAdapter.resolveShortcode(e)}resolveCatalogAdapter(e){return e.catalogAdapter?e.catalogAdapter:cr(e.catalog||ws)}async tryEnableExternalCatalog(){if(this.externalCatalogDetectionStarted||(this.externalCatalogDetectionStarted=true,!this.config.autoDetectExternalCatalog)||this.hasExplicitCatalogConfig||this.hasExplicitAdapterConfig)return;let e=globalThis.__EMOJI_MART_DATA__||globalThis.EmojiMart?.data,n=lr(e);if(n){this.catalogAdapter=n,this.refreshSuggestionsIfOpen();return}try{let r=await Wm("@emoji-mart/data"),s=lr(r.default)||lr(r.data);s&&(this.catalogAdapter=s,this.refreshSuggestionsIfOpen());}catch{}}refreshSuggestionsIfOpen(){this.isOpen&&(this.suggestions=this.getSuggestions(this.query),this.isOpen=this.suggestions.length>0,this.notifyListeners());}updateFromSelection(e){let n=null;if(e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o)||!o.isCollapsed()){this.closeIfNeeded();return}if(this.isSelectionInsideCodeBlock(o)){this.closeIfNeeded();return}let r=o.anchor.getNode();if(!$isTextNode(r)){this.closeIfNeeded();return}let s=o.anchor.offset,a=r.getTextContent(),l=a.slice(0,s);if(this.config.autoReplaceSymbols&&!this.applyingAutoReplace){let w=this.detectSymbolReplacement(a,l,s);w&&(n={nodeKey:r.getKey(),startOffset:w.startOffset,endOffset:w.endOffset,emoji:w.emoji});}let c=this.config.trigger||":",d=l.lastIndexOf(c);if(d<0){this.closeIfNeeded();return}let u=l.slice(0,d);if(!(u.length===0||/\s/.test(u[u.length-1]||""))){this.closeIfNeeded();return}let g=l.slice(d+c.length);if(/\s/.test(g)||g.length>(this.config.maxQueryLength??32)){this.closeIfNeeded();return}let p=this.getSuggestions(g),T=this.getCaretPosition();this.query=g,this.position=T,this.suggestions=p,this.isOpen=p.length>0,this.activeMatch={nodeKey:r.getKey(),startOffset:d,endOffset:s},this.notifyListeners();}),n!==null){let o=n;this.applyingAutoReplace=true,e.update(()=>{let r=$getNodeByKey(o.nodeKey);if(!$isTextNode(r))return;let s=Math.max(0,o.endOffset-o.startOffset);r.spliceText(o.startOffset,s,o.emoji,true);let a=o.startOffset+o.emoji.length;r.select(a,a);}),this.applyingAutoReplace=false;}}isSelectionInsideCodeBlock(e){if(!$isRangeSelection(e))return false;let n=e.anchor.getNode();for(;n;){if($isCodeNode(n))return true;n=n.getParent();}return false}detectSymbolReplacement(e,n,o){let r=Object.entries(this.config.symbolReplacements||ro).sort((s,a)=>a[0].length-s[0].length);for(let[s,a]of r){if(!n.endsWith(s))continue;let l=o-s.length,c=l>0&&e[l-1]||"",d=o<e.length&&e[o]||"",u=l===0||/\s|[([{>"'`]/.test(c),m=o===e.length||/\s|[.,!?;:)\]}"'`]/.test(d);if(u&&m)return {startOffset:l,endOffset:o,emoji:a}}return null}replaceSymbolsInText(e){let n=Object.entries(this.config.symbolReplacements||ro),o=e;for(let[r,s]of n){let a=Qm(r),l=new RegExp(`(^|\\s)${a}(?=$|\\s|[.,!?;:])`,"g");o=o.replace(l,`$1${s}`);}return o}executeEmojiSuggestion(e,n){if(!n)return false;if(this.activeMatch){let o=this.activeMatch;return e.update(()=>{let r=$getNodeByKey(o.nodeKey);if(!$isTextNode(r))return;let s=Math.max(0,o.endOffset-o.startOffset);r.spliceText(o.startOffset,s,n,true);let a=o.startOffset+n.length;r.select(a,a);}),this.closeEmojiSuggestions(),true}return e.update(()=>{let o=$getSelection();$isRangeSelection(o)&&o.insertText(n);}),this.closeEmojiSuggestions(),true}closeEmojiSuggestions(){this.isOpen=false,this.query="",this.position=null,this.suggestions=[],this.activeMatch=null,this.notifyListeners();}closeIfNeeded(){!this.isOpen&&!this.activeMatch||this.closeEmojiSuggestions();}getCaretPosition(){if(typeof window>"u")return null;let e=window.getSelection();if(!e||e.rangeCount===0)return null;let n=e.getRangeAt(0).cloneRange();n.collapse(true);let o=n.getBoundingClientRect(),s=n.getClientRects()[0]||o;return {x:s.left+(this.config.offset?.x??0),y:s.bottom+(this.config.offset?.y??8)}}getState(){return {isOpen:this.isOpen,query:this.query,position:this.position,suggestions:this.suggestions}}notifyListeners(){let e=this.getState();this.listeners.forEach(n=>n(e));}},qm=new io;var so=class extends k{constructor(){super("floatingToolbar",["floating"]);x(this,"isVisible",false);x(this,"selectionRect",null);this.config={render:()=>null,debounceMs:100,offset:{x:0,y:8},positionStrategy:"below",theme:{container:"luthor-floating-toolbar",button:"luthor-floating-toolbar-button",buttonActive:"luthor-floating-toolbar-button-active"}};}register(e){return ()=>{}}getPlugins(){return [jsx(og,{extension:this,config:this.config},"floating-toolbar")]}getCommands(e){return {}}getStateQueries(e){return {isFloatingVisible:async()=>this.isVisible}}updateContext(e,n){this.config&&(this.config.commands=e,this.config.activeStates=n);}getSelectionRect(){return this.selectionRect}getIsVisible(){return this.isVisible}setVisible(e){this.isVisible=e;}setSelectionRect(e){this.selectionRect=e;}},ng=new so;function og({extension:i,config:t}){let[n]=useLexicalComposerContext(),{config:o}=Ae(),[r,s]=useState(false),[a,l]=useState(null),[c,d]=useState(null),u=useRef(null),m=f=>(f.querySelector('[data-luthor-selection-anchor="true"]')??f).getBoundingClientRect(),g=(f,y)=>{let S;return (...L)=>{clearTimeout(S),S=setTimeout(()=>f(()=>L),y);}},p=useCallback((f,y)=>{if(typeof window>"u"||y===document.body)return f;let S=window.pageXOffset||document.documentElement.scrollLeft||0,L=window.pageYOffset||document.documentElement.scrollTop||0,E=y.getBoundingClientRect(),v=E.left+S,M=E.top+L,A=t.toolbarDimensions?.width||420,F=t.toolbarDimensions?.height||40,Q=f.x-v,te=f.y-M,B=Math.max(20,Math.min(Q,Math.max(20,E.width-A-20))),z=Math.max(20,Math.min(te,Math.max(20,E.height-F-20)));return {...f,x:B,y:z,top:f.top-M,left:f.left-v,bottom:f.bottom-M,right:f.right-v,positionFromRight:f.positionFromRight}},[t.toolbarDimensions?.height,t.toolbarDimensions?.width,20]),T=useCallback(f=>{let y=t.offset||{y:8},S=t.positionStrategy||"below",L=window.pageXOffset||document.documentElement.scrollLeft||0,E=window.pageYOffset||document.documentElement.scrollTop||0,v=window.innerWidth,M=window.innerHeight,A=f.bottom+E+y.y;S==="above"?A=f.top+E-y.y:S==="auto"&&(A=M-f.bottom>60?f.bottom+E+y.y:f.top+E-y.y);let F=t.getActiveStates?.(),Q=!!F?.isIframeEmbedSelected||!!F?.isYouTubeEmbedSelected,te=t.toolbarDimensions?.width||(Q?132:420),B=t.toolbarDimensions?.height||40,z=20,K=f.left+f.width/2,I=K+L,j,Y,le=K-z,J=v-K-z,X=te/2,Pe=K-X,Se=K+X,Oe=Pe<z,Ie=Se>v-z;return !Oe&&!Ie?(j=I-X,Y=false):Oe||le<X?(j=L+z,Y=false):Ie||J<X?(j=L+v-te-z,Y=true):(j=I-X,Y=false),A-B<E?A=f.bottom+E+y.y:A+B>E+M&&(A=f.top+E-y.y-B),{x:j,y:A,width:f.width,height:f.height,top:f.top+E,left:f.left+L,bottom:f.bottom+E,right:f.right+L,positionFromRight:Y}},[t,20]);useEffect(()=>{i.setVisible(r);},[r,i]),useEffect(()=>{let f=()=>{n.getEditorState().read(()=>{let v=$getSelection(),M=null,A=null;if($isRangeSelection(v)&&!v.isCollapsed()){let F=window.getSelection();F&&F.rangeCount>0&&(M=F.getRangeAt(0).getBoundingClientRect(),A=v);}else if($isNodeSelection(v)){let F=v.getNodes();if(F.length>0){let Q=F[0];if(Q){let te=Q.getKey(),B=n.getElementByKey(te);B&&(M=m(B));}}}if(M&&M.width>0&&M.height>0){let F=T(M);l(F),d(A),s(true),i.setSelectionRect(F);}else l(null),d(null),s(false),i.setSelectionRect(null);});},y=g(f,t.debounceMs||100),S=n.registerUpdateListener(()=>{y();}),L=()=>{y();},E=()=>{u.current===null&&(u.current=window.requestAnimationFrame(()=>{u.current=null,f();}));};return document.addEventListener("selectionchange",L),window.addEventListener("scroll",E,true),window.addEventListener("resize",E),()=>{S(),document.removeEventListener("selectionchange",L),window.removeEventListener("scroll",E,true),window.removeEventListener("resize",E),u.current!==null&&(cancelAnimationFrame(u.current),u.current=null);}},[n,t.debounceMs,T,i]);let w=()=>{s(false),l(null),d(null);};if(!t.render)return console.warn("FloatingToolbarExtension: No render function provided in config."),null;if(typeof document>"u")return null;let b=n.getRootElement()?.closest(".luthor-editor-wrapper"),h=t.anchorElem||b||document.body,N=a&&h?p(a,h):a;return createPortal(t.render({isVisible:r,selectionRect:N,selection:c,editor:n,commands:t.getCommands?.()||{},activeStates:t.getActiveStates?.()||{},hide:w,theme:o?.theme?.floatingToolbar||t.theme||{}}),h)}var ao=class extends k{constructor(){super("commandPalette",["toolbar"]);x(this,"isOpen",false);x(this,"commands",new Map);x(this,"listeners",[]);}register(e){let n=o=>{(o.metaKey||o.ctrlKey)&&o.shiftKey&&o.key==="P"&&(o.preventDefault(),this.toggleCommandPalette()),o.key==="Escape"&&this.isOpen&&this.hideCommandPalette();};return document.addEventListener("keydown",n),this.registerTableCommands(e),()=>{document.removeEventListener("keydown",n);}}getCommands(e){return {showCommandPalette:()=>this.showCommandPalette(),hideCommandPalette:()=>this.hideCommandPalette(),registerCommand:n=>this.registerCommand(n),unregisterCommand:n=>this.unregisterCommand(n)}}getStateQueries(e){return {isCommandPaletteOpen:()=>Promise.resolve(this.isOpen)}}showCommandPalette(){this.isOpen=true,this.notifyListeners();}hideCommandPalette(){this.isOpen=false,this.notifyListeners();}toggleCommandPalette(){this.isOpen=!this.isOpen,this.notifyListeners();}registerCommand(e){this.commands.set(e.id,e),this.notifyListeners();}unregisterCommand(e){this.commands.delete(e),this.notifyListeners();}registerTableCommands(e){[{id:"table.insertRowAbove",label:"Insert Row Above",category:"Table",action:()=>{console.log("Insert row above");},keywords:["table","row","insert","above"]},{id:"table.insertRowBelow",label:"Insert Row Below",category:"Table",action:()=>{console.log("Insert row below");},keywords:["table","row","insert","below"]},{id:"table.insertColumnLeft",label:"Insert Column Left",category:"Table",action:()=>{console.log("Insert column left");},keywords:["table","column","insert","left"]},{id:"table.insertColumnRight",label:"Insert Column Right",category:"Table",action:()=>{console.log("Insert column right");},keywords:["table","column","insert","right"]},{id:"table.deleteRow",label:"Delete Row",category:"Table",action:()=>{console.log("Delete row");},keywords:["table","row","delete","remove"]},{id:"table.deleteColumn",label:"Delete Column",category:"Table",action:()=>{console.log("Delete column");},keywords:["table","column","delete","remove"]}].forEach(o=>this.registerCommand(o));}notifyListeners(){let e=Array.from(this.commands.values());this.listeners.forEach(n=>n(this.isOpen,e));}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(n=>n!==e);}}getAllCommands(){return Array.from(this.commands.values())}},ig=new ao;var cg=new Set(["paragraph","heading"]),lo=class extends k{constructor(e={}){super("slashCommand",["toolbar"]);x(this,"commands",new Map);x(this,"listeners",[]);x(this,"isOpen",false);x(this,"query","");x(this,"position",null);x(this,"activeMatch",null);x(this,"viewportRafId",null);this.config={trigger:"/",offset:{x:0,y:8},...e},this.setSlashCommands(this.config.items??[]);}register(e){let n=e.registerUpdateListener(()=>{this.updateMatchFromSelection(e);}),o=a=>{this.isOpen&&a.key==="Escape"&&(a.preventDefault(),this.closeSlashMenu());};document.addEventListener("keydown",o);let r=a=>{a.target?.closest(".luthor-slash-menu")||this.isOpen&&this.closeSlashMenu();},s=()=>{!this.isOpen||!this.activeMatch||this.viewportRafId===null&&(this.viewportRafId=window.requestAnimationFrame(()=>{this.viewportRafId=null;let a=this.getCaretPosition();if(!a){this.closeSlashMenu();return}this.position=a,this.notifyListeners();}));};return document.addEventListener("pointerdown",r),window.addEventListener("scroll",s,true),window.addEventListener("resize",s),()=>{n(),document.removeEventListener("keydown",o),document.removeEventListener("pointerdown",r),window.removeEventListener("scroll",s,true),window.removeEventListener("resize",s),this.viewportRafId!==null&&(cancelAnimationFrame(this.viewportRafId),this.viewportRafId=null),this.activeMatch=null,this.isOpen=false,this.query="",this.position=null,this.notifyListeners();}}getCommands(e){return {registerSlashCommand:n=>this.registerSlashCommand(n),unregisterSlashCommand:n=>this.unregisterSlashCommand(n),setSlashCommands:n=>this.setSlashCommands(n),closeSlashMenu:()=>this.closeSlashMenu(),executeSlashCommand:n=>this.executeSlashCommand(e,n)}}getStateQueries(e){return {isSlashMenuOpen:()=>Promise.resolve(this.isOpen)}}subscribe(e){return this.listeners.push(e),e(this.getState()),()=>{this.listeners=this.listeners.filter(n=>n!==e);}}getAllCommands(){return Array.from(this.commands.values())}registerSlashCommand(e){this.commands.set(e.id,e),this.notifyListeners();}unregisterSlashCommand(e){this.commands.delete(e),this.notifyListeners();}setSlashCommands(e){let n=new Map;for(let o of e)!o?.id||n.has(o.id)||n.set(o.id,o);this.commands=n,this.notifyListeners();}closeSlashMenu(){this.isOpen=false,this.query="",this.position=null,this.activeMatch=null,this.notifyListeners();}executeSlashCommand(e,n){let o=this.commands.get(n);if(!o)return false;if(this.activeMatch){let r=this.activeMatch;e.update(()=>{let s=$getNodeByKey(r.nodeKey);if(!$isTextNode(s))return;let a=Math.max(0,Math.min(r.endOffset,s.getTextContentSize()));s.select(a,a);let l=Math.max(0,r.endOffset-r.startOffset);l>0&&s.spliceText(r.startOffset,l,"",true);});}return this.closeSlashMenu(),o.action(),true}updateMatchFromSelection(e){e.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n)||!n.isCollapsed()){this.closeIfNeeded();return}let o=n.anchor.getNode();if(!$isTextNode(o)){this.closeIfNeeded();return}let r=ug(o);if(!cg.has(r)){this.closeIfNeeded();return}let s=n.anchor.offset,l=o.getTextContent().slice(0,s),c=this.config.trigger||"/",d=l.lastIndexOf(c);if(d<0){this.closeIfNeeded();return}let u=l.slice(0,d);if(!mg(u)){this.closeIfNeeded();return}let m=l.slice(d+c.length);if(/\s/.test(m)){this.closeIfNeeded();return}let g=this.getCaretPosition();this.isOpen=true,this.query=m,this.position=g,this.activeMatch={nodeKey:o.getKey(),startOffset:d,endOffset:s,query:m},this.notifyListeners();});}closeIfNeeded(){!this.isOpen&&!this.activeMatch||this.closeSlashMenu();}getCaretPosition(){if(typeof window>"u")return null;let e=window.getSelection();if(!e||e.rangeCount===0)return null;let n=e.getRangeAt(0).cloneRange();n.collapse(true);let o=n.getBoundingClientRect(),s=n.getClientRects()[0]||o,a=this.config.offset?.x??0,l=this.config.offset?.y??8;return {x:s.left+a,y:s.bottom+l}}getState(){return {isOpen:this.isOpen,query:this.query,position:this.position,commands:this.getAllCommands()}}notifyListeners(){let e=this.getState();this.listeners.forEach(n=>n(e));}},dg=new lo;function ug(i){try{return i.getTopLevelElementOrThrow?.()?.getType?.()??""}catch{return ""}}function mg(i){return i.trim().length===0}var co=class extends k{constructor(){super("enterKeyBehavior",["floating"]),this.config={...this.config||{},showInToolbar:false,initPriority:100};}register(t){let e,n=r=>{if(r.key!=="Enter")return;let s=false;t.update(()=>{let a=$getSelection();if(!$isRangeSelection(a))return;let l=a.anchor.getNode();if(r.shiftKey){let T=$findCellNode(l);if($isTableCellNode(T)){let h=$getTableNodeFromLexicalNodeOrThrow(T),N=$createParagraphNode();h.insertAfter(N),N.selectStart(),s=true;return}let w=this.findQuoteNode(l);if(w){let h=$createParagraphNode();w.insertAfter(h),h.selectStart(),s=true;return}let b=this.findCodeNode(l);if(b){let h=$createParagraphNode();b.insertAfter(h),h.selectStart(),s=true;return}return}let c=this.findQuoteNode(l);if(!c||!a.isCollapsed())return;let d=this.findDirectQuoteChild(l,c)||c.getLastChild();if(!d){let T=$createParagraphNode();c.append(T),T.selectStart(),s=true;return}let u=this.isEmptyQuoteLine(d),m=d.getPreviousSibling(),g=this.isEmptyQuoteLine(m);if(u&&g){let T=d,w=m;T.remove(),w?.remove();let b=$createParagraphNode();c.insertAfter(b),b.selectStart(),s=true;return}let p=$createParagraphNode();d.insertAfter(p),p.selectStart(),s=true;}),s&&(r.preventDefault(),r.stopPropagation());},o=t.registerRootListener((r,s)=>{e?.(),e=void 0,s&&s.removeEventListener("keydown",n,true),r&&(r.addEventListener("keydown",n,true),e=()=>{r.removeEventListener("keydown",n,true);});});return ()=>{e?.(),o();}}getCommands(t){return {insertHardBreak:()=>{t.focus(),t.dispatchCommand(INSERT_LINE_BREAK_COMMAND,false);}}}findQuoteNode(t){let e=t;for(;e;){if($isQuoteNode(e))return e;e=e.getParent();}return null}findCodeNode(t){let e=t;for(;e;){if($isCodeNode(e))return e;e=e.getParent();}return null}findDirectQuoteChild(t,e){let n=t;for(;n&&n.getParent&&n.getParent()!==e;)n=n.getParent();return n?.getParent&&n.getParent()===e?n:null}isEmptyQuoteLine(t){return t?t.getTextContent().trim()==="":false}},Cg=new co;export{k as BaseExtension,aa as BaseProvider,qn as BlockFormatExtension,ln as BoldExtension,Kn as CodeExtension,Vn as CodeFormatExtension,Qn as CodeIntelligenceExtension,ao as CommandPaletteExtension,vn as ContextMenuExtension,eo as DraggableBlockExtension,io as EmojiExtension,co as EnterKeyBehaviorExtension,ca as ExtensionCategory,so as FloatingToolbarExtension,fn as FontFamilyExtension,pn as FontSizeExtension,Jn as HistoryExtension,gn as HorizontalRuleExtension,on as IframeEmbedExtension,tn as ImageExtension,cn as ItalicExtension,ks as LIGHTWEIGHT_EMOJI_CATALOG,br as LUTHOR_EDITOR_THEME_TOKENS,hn as LineHeightExtension,mn as LinkExtension,Bn as ListExtension,Mm as RichText,lo as SlashCommandExtension,un as StrikethroughExtension,xn as SubscriptExtension,Cn as SuperscriptExtension,no as TabIndentExtension,kn as TableExtension,yn as TextColorExtension,ie as TextFormatExtension,En as TextHighlightExtension,dn as UnderlineExtension,sn as YouTubeEmbedExtension,At as appendMetadataEnvelopes,Zu as blockFormatExtension,Pc as boldExtension,ma as clearLexicalSelection,Su as codeExtension,ju as codeFormatExtension,Bu as codeIntelligenceExtension,ig as commandPaletteExtension,Bo as contextMenuExtension,Sm as createCustomNodeExtension,xr as createEditorSystem,qs as createEditorThemeStyleVars,da as createExtension,Ue as defaultLuthorTheme,dm as draggableBlockExtension,qm as emojiExtension,Cg as enterKeyBehaviorExtension,Dt as extractMetadataEnvelopes,ng as floatingToolbarExtension,cd as fontFamilyExtension,fd as fontSizeExtension,sm as historyExtension,od as horizontalRuleExtension,kc as htmlToJSON,za as iframeEmbedExtension,wa as imageExtension,Xs as isLuthorTheme,Oc as italicExtension,Mc as jsonToHTML,Xl as jsonToMarkdown,Cd as lineHeightExtension,Uc as linkExtension,mu as listExtension,Jl as markdownToJSON,Js as mergeThemes,_t as prepareDocumentForBridge,Ht as rehydrateDocumentFromEnvelopes,ga as resolveLinkNodeKeyFromAnchor,km as richTextExtension,dg as slashCommandExtension,Ac as strikethroughExtension,Rd as subscriptExtension,kd as superscriptExtension,jm as tabIndentExtension,Xd as tableExtension,vd as textColorExtension,wd as textHighlightExtension,_c as underlineExtension,Ae as useBaseEditor,Xa as youTubeEmbedExtension};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lyfie/luthor-headless",
3
- "version": "2.6.3",
3
+ "version": "2.6.4",
4
4
  "description": "Luthor Editor - A headless, extensible rich text editor built on Lexical",
5
5
  "type": "module",
6
6
  "private": false,
@@ -48,8 +48,8 @@
48
48
  "tsup": "^8.0.0",
49
49
  "typescript": "^5.7.3",
50
50
  "vitest": "^3.2.4",
51
- "@repo/typescript-config": "0.0.0",
52
- "@repo/eslint-config": "0.0.0"
51
+ "@repo/eslint-config": "0.0.0",
52
+ "@repo/typescript-config": "0.0.0"
53
53
  },
54
54
  "peerDependencies": {
55
55
  "@lexical/code": ">=0.40.0",