@lyfie/luthor-headless 2.7.1 → 2.7.3
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.
- package/README.md +1 -3
- package/dist/index.d.ts +1 -8
- package/dist/index.js +42 -42
- package/package.json +2 -3
package/dist/index.js
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
import ln,{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,$createTextNode,DecoratorNode,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,IS_BOLD,IS_ITALIC,IS_STRIKETHROUGH,IS_CODE,IS_HIGHLIGHT,IS_UNDERLINE,createEditor,TextNode,LineBreakNode,TabNode,ElementNode}from'lexical';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {$createLinkNode,TOGGLE_LINK_COMMAND,$isLinkNode,LinkNode,AutoLinkNode}from'@lexical/link';import {TRANSFORMERS,CHECK_LIST,registerMarkdownShortcuts,UNORDERED_LIST,$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,getCodeLanguages}from'@lexical/code';import {TableNode,TableRowNode,TableCellNode,$createTableNodeWithDimensions,$isTableRowNode,$isTableCellNode,$isTableNode,$isTableSelection,$deleteTableColumnAtSelection,$deleteTableRowAtSelection,$unmergeCell,$mergeCells,$getTableNodeFromLexicalNodeOrThrow,$getTableColumnIndexFromTableCellNode,TableCellHeaderStates,$getTableRowIndexFromTableCellNode,$insertTableColumnAtSelection,$insertTableRowAtSelection,$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 wl=Object.defineProperty;var kl=(r,t,e)=>t in r?wl(r,t,{enumerable:true,configurable:true,writable:true,value:e}):r[t]=e;var T=(r,t,e)=>kl(r,typeof t!="symbol"?t+"":t,e);var ui=["--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 Rl(r){return typeof r=="string"&&r.trim().length>0}function Ml(r){if(!r)return;let t={};for(let e of ui){let n=r[e];Rl(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 Pl(r,t){return {...r,...t,text:{...r.text,...t.text},list:{...r.list,...t.list,nested:{...r.list?.nested,...t.list?.nested}},heading:{...r.heading,...t.heading},codeHighlight:{...r.codeHighlight,...t.codeHighlight},toolbar:{...r.toolbar,...t.toolbar},draggable:{...r.draggable,...t.draggable,styles:{...r.draggable?.styles,...t.draggable?.styles}},floatingToolbar:{...r.floatingToolbar,...t.floatingToolbar,styles:{...r.floatingToolbar?.styles,...t.floatingToolbar?.styles}},richText:{...r.richText,...t.richText},styles:{toolbar:{...r.styles?.toolbar,...t.styles?.toolbar},draggable:{...r.styles?.draggable,...t.styles?.draggable},floatingToolbar:{...r.styles?.floatingToolbar,...t.styles?.floatingToolbar},...t.styles}}}function Al(r){return r&&typeof r=="object"}function mi(r){let t=r;for(;t;){if(t.getType()==="code")return true;t=t.getParent();}return false}function gi(){let r=$getSelection();if(!$isRangeSelection(r))return false;let t=r.anchor.getNode(),e=r.focus.getNode();return mi(t)||mi(e)}var Lt=createContext(null),jo=class{constructor(){T(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.`));}},jl=new jo;function hi(){function r(){let n=useContext(Lt);if(!n)throw new Error("useEditor must be used within Provider");return n}function t({children:n,config:o={},extensions:i}){let[s]=useLexicalComposerContext(),a=useMemo(()=>({formatText:(h,p)=>{s&&(h==="code"&&s.getEditorState().read(()=>gi())||s.dispatchCommand(FORMAT_TEXT_COMMAND,h));}}),[s]),l=useMemo(()=>{if(!s)return {};let h={};for(let p of i)Object.assign(h,p.getCommands(s));return h},[i,s]),d=useMemo(()=>({...a,...l}),[a,l]),{plugins:c,pluginsBefore:u,pluginsAfter:m}=useMemo(()=>{let h=[],p=[];for(let S of i){let N=S.getPlugins?.()||[];(S.config?.position||"before")==="after"?p.push(...N):h.push(...N);}return {plugins:[...h,...p],pluginsBefore:h,pluginsAfter:p}},[i]);useEffect(()=>{if(!s)return;let p=[...i].sort((S,N)=>{let b=S.config?.initPriority??0;return (N.config?.initPriority??0)-b}).map(S=>S.register(s));return ()=>p.forEach(S=>S&&S())},[s,i]);let f=useMemo(()=>{if(!s)return {};let h={};for(let p of i)p.getStateQueries&&Object.assign(h,p.getStateQueries(s));return h},[i,s]),[g,y]=useState(()=>{let h={};return Object.keys(f).forEach(p=>h[p]=false),h});useEffect(()=>{let h=Object.keys(f);y(p=>{let S={};for(let b of h){let E=p[b];S[b]=E??false;}if(Object.keys(p).length!==h.length)return S;for(let b of h)if(p[b]!==S[b])return S;return p});},[f]),useEffect(()=>{if(!s)return;let h=true,p=0,S=async()=>{let E=++p,x=Object.entries(f).map(async([I,D])=>{try{let Y=await D();return [I,Y]}catch{return [I,false]}}),L=await Promise.all(x);if(!h||E!==p)return;let k=Object.fromEntries(L);y(I=>{let D=I,Y=k,ee=Object.keys(D),B=Object.keys(Y);if(ee.length!==B.length)return k;for(let z of B)if(D[z]!==Y[z])return k;return I});};S();let N=s.registerUpdateListener(()=>{S();}),b=i.map(E=>{let w=E;if(typeof w.onStateChange=="function")return w.onStateChange(()=>{S();})}).filter(E=>typeof E=="function");return ()=>{h=false,N(),b.forEach(E=>E());}},[s,f,i]);let C={editor:s,config:o,extensions:i,commands:d,activeStates:g,stateQueries:f,listeners:{registerUpdate:h=>s?.registerUpdateListener(h)||(()=>{}),registerPaste:h=>s?.registerCommand(PASTE_COMMAND,h,COMMAND_PRIORITY_EDITOR)||(()=>{})},export:{toJSON:()=>s?.getEditorState().toJSON()},import:{fromJSON:h=>{if(s&&(typeof h=="string"||typeof h=="object"&&h!==null)){s.setEditorState(s.parseEditorState(h));let p=d;typeof p.rehydrateListStyles=="function"&&queueMicrotask(()=>{p.rehydrateListStyles?.();});}}},lexical:s,extensionsAPI:jl,plugins:c,hasExtension:h=>i.some(p=>p.name===h)};return jsxs(Lt.Provider,{value:C,children:[u,n,m]})}function e(n){let o=useMemo(()=>n.extensions.flatMap(a=>a.getNodes?.()||[]),[n.extensions]),i=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:i,children:jsx(t,{...n})})}return {Provider:e,useEditor:r}}var Ul=hi(),Kl=Ul.Provider,Oe=()=>{let r=useContext(Lt);if(!r)throw new Error("useBaseEditor must be used within Provider");return r};var Vl=(o=>(o.Toolbar="toolbar",o.Sidebar="sidebar",o.ContextMenu="contextmenu",o.Floating="floating",o))(Vl||{});var M=class{constructor(t,e=["toolbar"]){T(this,"name");T(this,"category",["toolbar"]);T(this,"config",{});T(this,"supportedFormats",[]);T(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 Ql(r){return new class extends M{constructor(){super(r.name,r.category||["toolbar"]);T(this,"_plugins",[]);T(this,"_nodes",[]);T(this,"_initialize");r.config&&(this.config={...this.config,...r.config}),this._initialize=r.initialize,r.supportedFormats&&(this.supportedFormats=r.supportedFormats),r.nodes&&(this._nodes=r.nodes),r.plugins&&(this._plugins=r.plugins);}register(e){let n=this._initialize?.(e);return ()=>{typeof n=="function"&&n();}}getNodes(){return this._nodes}getPlugins(){return this._plugins}getCommands(e){return r.commands?r.commands(e):{}}getStateQueries(e){return r.stateQueries?r.stateQueries(e):{}}}}function ql(r){r.update(()=>{$setSelection(null);});}function Jl(r,t){let e=t.getAttribute("data-lexical-node-key")?.trim();if(e)return e;let n=null;return r.read(()=>{let o=$getNearestNodeFromDOMNode(t);if($isLinkNode(o)){n=o.getKey();return}let i=t.firstChild;if(!i)return;let s=$getNearestNodeFromDOMNode(i);if($isLinkNode(s)){n=s.getKey();return}let a=s?.getParent();a&&$isLinkNode(a)&&(n=a.getKey());}),n}var ae=class extends M{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 Ve=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=e.closest("a[href]"),i=this.resolveAlignment(e,n),s;if(n){let u=n.querySelector("figcaption");u&&(s=u.textContent||void 0);}let a=e.getAttribute("width"),l=e.getAttribute("height"),d=a?Number(a):void 0,c=l?Number(l):void 0;try{return {node:Xe(e.src,e.alt||"",s,o?.getAttribute("href")||void 0,o?.getAttribute("title")||void 0,i,e.className||void 0,this.extractStyleObject(e),Number.isFinite(d)?d: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 i=e.querySelector("figcaption")?.textContent||void 0,s=n.closest("a[href]"),a=this.resolveAlignment(n,e),l=n.getAttribute("width"),d=n.getAttribute("height"),c=l?Number(l):void 0,u=d?Number(d):void 0;try{return {node:Xe(n.src,n.alt||"",i,s?.getAttribute("href")||void 0,s?.getAttribute("title")||void 0,a,n.className||void 0,this.extractStyleObject(n),Number.isFinite(c)?c:void 0,Number.isFinite(u)?u: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,linkHref:t.__linkHref,linkTitle:t.__linkTitle,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,linkHref:i,linkTitle:s,alignment:a,className:l,style:d,width:c,height:u,uploading:m}=t;if(!e||e.length===0)throw new Error("Cannot import ImageNode with empty src");return Xe(e,n,o,i,s,a,l,d?this.recordToStyleObject(d):void 0,c,u,m)}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",t.__linkHref){let o=document.createElement("a");o.href=t.__linkHref,t.__linkTitle&&(o.title=t.__linkTitle),o.target="_blank",o.rel="noopener noreferrer",o.appendChild(n),e.appendChild(o);}else e.appendChild(n);if(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 i of n){if(i.classList.contains("align-left"))return "left";if(i.classList.contains("align-center"))return "center";if(i.classList.contains("align-right"))return "right"}let o=e?.getAttribute("data-align");if(o==="left"||o==="center"||o==="right")return o;for(let i of n){if(i.style.textAlign==="left")return "left";if(i.style.textAlign==="center")return "center";if(i.style.textAlign==="right")return "right";if(i.style.float==="left")return "left";if(i.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:wh,exportDOM:kh,importJSON:Rh,exportJSON:Mh}=Ve;var Ti=createCommand("insert-image"),Ri=cc,Vo=true,Qo=false,Li=50,vi=50,wi=2400,ki=2400;function gn(r,t,e){return Math.min(e,Math.max(t,Math.round(r)))}function lc(r,t,e,n){return r&&n&&t&&!e}function cc({src:r,alt:t,caption:e,linkHref:n,linkTitle:o,alignment:i="none",className:s="",style:a,nodeKey:l,width:d,height:c,resizable:u=true,scaleByRatio:m=false,uploading:f=false}){let[g]=useLexicalComposerContext(),y=useRef(null),C=useRef(null),h=useRef(null),p=useRef(0),S=useRef(0),[N,b]=useState(false),[E,w]=useState(false),[x,L]=useState(()=>g.isEditable()),[k,I]=useState(d||"auto"),[D,Y]=useState(c||"auto");useEffect(()=>()=>{r&&r.startsWith("blob:")&&URL.revokeObjectURL(r);},[r]),useEffect(()=>{I(d||"auto"),Y(c||"auto"),p.current=typeof d=="number"?d:0,S.current=typeof c=="number"?c:0;},[d,c]),useEffect(()=>()=>{h.current!=null&&window.cancelAnimationFrame(h.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>g.registerEditableListener(O=>{L(O);}),[g]),useEffect(()=>{if(l)return g.registerUpdateListener(({editorState:O})=>{O.read(()=>{let J=$getSelection();if($isNodeSelection(J)){let G=J.getNodes();b(G.some(Z=>Z.getKey()===l));}else b(false);});})},[g,l]);let ee=O=>{x&&(O.preventDefault(),O.stopPropagation(),l&&g.update(()=>{let J=$createNodeSelection();J.add(l),$setSelection(J);}));},B=O=>J=>{if(!x||!y.current||!l)return;J.preventDefault(),J.stopPropagation(),w(true),document.body.style.userSelect="none",document.body.style.cursor=O==="width"?"ew-resize":"ns-resize";let G=J.clientX,Z=J.clientY,ge=y.current.clientWidth||(typeof k=="number"?k:100),be=y.current.clientHeight||(typeof D=="number"?D:100),Te=Number.isFinite(ge)&&Number.isFinite(be)&&ge>0&&be>0?ge/be:null;p.current=ge,S.current=be;let je=()=>{h.current=null,C.current&&(C.current.style.width=`${p.current}px`),y.current&&(y.current.style.height=`${S.current}px`);},Ue=re=>{let Tt=!!Te&&(m?!re.shiftKey:re.shiftKey),_e=O==="width"?gn(ge+(re.clientX-G),Li,wi):p.current,Ke=O==="height"?gn(be+(re.clientY-Z),vi,ki):S.current;Tt&&Te&&(O==="width"?Ke=gn(_e/Te,vi,ki):_e=gn(Ke*Te,Li,wi)),p.current=_e,S.current=Ke,h.current==null&&(h.current=window.requestAnimationFrame(je));},fe=()=>{h.current!=null&&(window.cancelAnimationFrame(h.current),h.current=null),w(false),I(p.current),Y(S.current),g.update(()=>{let re=$getNodeByKey(l);re instanceof U&&re.setWidthAndHeight(p.current,S.current);}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",Ue),document.removeEventListener("mouseup",fe);};document.addEventListener("mousemove",Ue),document.addEventListener("mouseup",fe);},z={margin:0,display:"block",position:"relative",...a},W={maxWidth:"100%",display:"block",borderRadius:"4px",width:typeof k=="number"?"100%":"auto",height:typeof D=="number"?`${D}px`:D,margin:0},j={fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"},K=lc(x,N,E,u);return jsxs("figure",{className:`lexical-image align-${i} ${s} ${N?"selected":""} ${E?"resizing":""} ${f?"uploading":""}`,style:z,children:[jsxs("div",{ref:C,className:`luthor-media-embed-shell${N?" is-selected":""}${E?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{position:"relative",display:"inline-block",width:k,maxWidth:"100%",cursor:x?"pointer":"default"},onClick:x?ee:void 0,children:[n?jsx("a",{href:n,title:o,target:"_blank",rel:"noopener noreferrer",onClick:O=>{x&&O.preventDefault();},children:jsx("img",{ref:y,src:r,alt:t,style:W})}):jsx("img",{ref:y,src:r,alt:t,style:W}),u?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:B("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:B("height")})]}):null]}),e&&jsx("figcaption",{style:j,children:e}),jsx("div",{style:{clear:"both",height:0,fontSize:0}})]})}var U=class r extends DecoratorNode{constructor(e="",n="",o,i,s,a="none",l,d,c,u,m,f){super(f);T(this,"__src");T(this,"__alt");T(this,"__caption");T(this,"__linkHref");T(this,"__linkTitle");T(this,"__alignment");T(this,"__className");T(this,"__style");T(this,"__width");T(this,"__height");T(this,"__uploading");this.__src=e&&e.length>0?e:"",this.__alt=n,this.__caption=o,this.__linkHref=i,this.__linkTitle=s,this.__alignment=a,this.__className=l,this.__style=d,this.__width=c,this.__height=u,this.__uploading=m;}static getType(){return "image"}static clone(e){return new r(e.__src,e.__alt,e.__caption,e.__linkHref,e.__linkTitle,e.__alignment,e.__className,e.__style,e.__width,e.__height,e.__uploading,e.__key)}static importDOM(){return Ve.importDOM()}static importJSON(e){return Ve.importJSON(e)}createDOM(e){let n=document.createElement("div"),o=e.theme?.image||"",i=this.__alignment;return n.className=`${o} lexical-image-container align-${i}`.trim(),n.style.display=i==="center"?"block":"inline-block",n.style.float=i==="left"?"left":i==="right"?"right":"none",n.style.margin=i==="center"?"1rem auto":i==="left"?"0 1rem 1rem 0":i==="right"?"0 0 1rem 1rem":"1rem 0",n.style.textAlign=i==="center"?"center":"inherit",n.style.position="relative",n}updateDOM(e,n,o){let i=this.__alignment;if(i!==e.__alignment){let s=o.theme?.image||"";n.className=`${s} lexical-image-container align-${i}`.trim();}return n.style.display=i==="center"?"block":"inline-block",n.style.float=i==="left"?"left":i==="right"?"right":"none",n.style.margin=i==="center"?"1rem auto":i==="left"?"0 1rem 1rem 0":i==="right"?"0 0 1rem 1rem":"1rem 0",n.style.textAlign=i==="center"?"center":"inherit",n.style.position="relative",false}exportDOM(){return Ve.exportDOM(this)}exportJSON(){return Ve.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;}setLink(e,n){let o=this.getWritable();o.__linkHref=e,o.__linkTitle=n;}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(Ri,{src:this.__src,alt:this.__alt,caption:this.__caption,linkHref:this.__linkHref,linkTitle:this.__linkTitle,alignment:this.__alignment,className:this.__className,style:this.__style,nodeKey:this.getKey(),width:this.__width,height:this.__height,resizable:Vo,scaleByRatio:Qo,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 Xe(r,t,e,n,o,i="none",s,a,l,d,c){if(!r||r.length===0)throw new Error("Cannot create ImageNode with empty src");return new U(r,t,e,n,o,i,s,a,l,d,c)}var pn=class extends M{constructor(){super("image",["toolbar"]);T(this,"recentImages",new Set);T(this,"lastSelectedImageNodeKey",null);this.config={...this.config,resizable:true,scaleByRatio:false,pasteListener:{insert:true,replace:true},debug:false,forceUpload:false},Vo=true,Qo=false;}configure(e){e.customRenderer&&(Ri=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,Vo=n.resizable??true,Qo=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 U);c&&(this.lastSelectedImageNodeKey=c.getKey());});}),o=e.registerCommand(Ti,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(f=>{e.update(()=>{let g=$getNodeByKey(u.getKey());g instanceof U&&(g.setSrc(f),g.__uploading=!1);});}).catch(f=>{console.error("Upload failed:",f),e.update(()=>{let g=$getNodeByKey(u.getKey());g instanceof U&&(g.__uploading=!1);});}));let u=Xe(d,l.alt,l.caption,l.linkHref,l.linkTitle,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 f=$createParagraphNode();f.append(u),$getRoot().append(f);}}catch(d){console.error("\u274C Insertion error:",d);}}),true),COMMAND_PRIORITY_EDITOR),i=e.registerCommand(KEY_DELETE_COMMAND,()=>{let l=$getSelection();if($isNodeSelection(l)){let d=l.getNodes();if(d.some(c=>c instanceof U))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 U))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(f=>f.type==="text/html");for(let f of c)if(f.type.startsWith("image/")){if(m)continue;d.preventDefault();let g=f.getAsFile();if(!g)continue;l("\u{1F4CB} Pasting image:",g.name),(this.config.uploadHandler&&this.config.forceUpload?this.config.uploadHandler(g).catch(C=>(console.error("Upload failed:",C),URL.createObjectURL(g))):Promise.resolve(URL.createObjectURL(g))).then(C=>{if(this.recentImages.has(C)){l("\u{1F6AB} Duplicate paste image src detected, skipping:",C);return}this.recentImages.add(C),setTimeout(()=>this.recentImages.delete(C),1e3);let h=false,p;this.config.uploadHandler&&this.config.forceUpload&&g&&(h=true,this.config.uploadHandler(g).then(S=>{e.update(()=>{let N=$getNodeByKey(p.getKey());N instanceof U&&(N.setSrc(S),N.__uploading=false);});}).catch(S=>{console.error("Upload failed:",S),e.update(()=>{let N=$getNodeByKey(p.getKey());N instanceof U&&(N.__uploading=false);});})),e.update(()=>{let S=$getSelection(),N=g.name||"Pasted image";if($isNodeSelection(S)&&this.config.pasteListener?.replace){let E=S.getNodes().find(w=>w instanceof U);if(E){l("\u{1F504} Replacing selected image src"),E.setSrc(C),E.__uploading=h,u=true;return}}this.config.pasteListener?.insert&&(l("\u2795 Inserting new pasted image"),p=Xe(C,N,void 0,void 0,void 0,"none",void 0,void 0,void 0,void 0,h),$isRangeSelection(S)?S.insertNodes([p]):$getRoot().append($createParagraphNode().append(p)),u=true);});});break}return u},COMMAND_PRIORITY_NORMAL);}return ()=>{n(),o(),i(),s(),a();}}getNodes(){return [U]}getCommands(e){return {insertImage:n=>{e.dispatchCommand(Ti,n);},setImageAlignment:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();for(let s of i)s instanceof U&&s.setAlignment(n);}});},setImageCaption:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();for(let s of i)s instanceof U&&s.setCaption(n);return}if(this.lastSelectedImageNodeKey){let i=$getNodeByKey(this.lastSelectedImageNodeKey);i instanceof U?i.setCaption(n):this.lastSelectedImageNodeKey=null;}});},getImageCaption:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes().find(s=>s instanceof U);if(i){n(i.__caption??"");return}}if(this.lastSelectedImageNodeKey){let i=$getNodeByKey(this.lastSelectedImageNodeKey);if(i instanceof U){n(i.__caption??"");return}}n("");});}),setImageClassName:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();for(let s of i)s instanceof U&&s.setClassName(n);}});},setImageStyle:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();for(let s of i)s instanceof U&&s.setStyle(n);}});}}}getStateQueries(e){return {imageSelected:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();n(i.length===1&&i[0]instanceof U);}else n(false);});}),isImageAlignedLeft:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();if(i.length===1&&i[0]instanceof U){n(i[0].__alignment==="left");return}}n(false);});}),isImageAlignedCenter:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();if(i.length===1&&i[0]instanceof U){n(i[0].__alignment==="center");return}}n(false);});}),isImageAlignedRight:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();if(i.length===1&&i[0]instanceof U){n(i[0].__alignment==="right");return}}n(false);});}),isImageAlignedNone:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();if(i.length===1&&i[0]instanceof U){n(i[0].__alignment==="none");return}}n(false);});})}}},dc=new pn;function Yo(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\]/g,"\\]")}function Wo(r){return r.replace(/\\(["\\\]])/g,"$1")}function uc(r){let t=r.trim();if(!t)return null;let e=t.match(/^(<[^>\r\n]+>|[^\s]+)(?:\s+"((?:[^"\\]|\\.)*)")?$/);if(!e||!e[1])return null;let n=e[1].trim(),o=n.startsWith("<")&&n.endsWith(">")?n.slice(1,-1).trim():n;if(!o)return null;let i=typeof e[2]=="string"&&e[2].length>0?Wo(e[2]):void 0;return {href:o,...i?{title:i}:{}}}function mc(r){let t={alignment:"none"},e=r.trim();if(!e)return t;let n=/<!--\s*([a-z-]+)\s*:\s*([\s\S]*?)\s*-->/gi,o=n.exec(e),i=0;for(;o;){if(e.slice(i,o.index).trim().length>0)return null;let l=(o[1]??"").trim().toLowerCase(),d=(o[2]??"").trim();if(l==="align"){let c=d.toLowerCase();(c==="left"||c==="center"||c==="right")&&(t.alignment=c);}if(l==="link"){let c=uc(d);c&&(t.linkHref=c.href,t.linkTitle=c.title);}i=n.lastIndex,o=n.exec(e);}return e.slice(i).trim().length>0?null:t}var Mi={dependencies:[U],export:r=>{if(!gc(r))return null;let t=r,e=t.__src||"",n=t.__alt||"",o=t.__caption||"",i=t.__linkHref?.trim()??"",s=t.__linkTitle?.trim()??"",a=t.__alignment||"none";if(!e)return null;let l=`}"`),l+=")";let d=i?(()=>{let c=s?` "${Yo(s)}"`:"";return `[${l}](${i}${c})`})():l;return a!=="none"&&(d+=` <!-- align:${a} -->`),d},regExp:/^!\[((?:\\.|[^\]])*)\]\(([^)\s]+)(?:\s+"((?:[^"\\]|\\.)*)")?\)(\s*(?:<!--[\s\S]*?-->\s*)*)$/,replace:(r,t,e,n)=>{let[,o,i,s,a]=e;if(!i)return;let l=mc(String(a??""));if(!l)return;let d=Xe(i,typeof o=="string"?Wo(o):"",typeof s=="string"&&s.length>0?Wo(s):void 0,l.linkHref,l.linkTitle,l.alignment,void 0,void 0,void 0,void 0,false);r.replace(d);},type:"element"};function gc(r){return r instanceof U}function qo(r,t,e){return r&&t&&!e}function Jo(r,t,e){return r?t&&!e?"auto":"none":"auto"}function Sc(r){let t=r.trim();return /^https?:\/\//i.test(t)?t:`https://${t}`}function Ai(r){try{let t=new URL(Sc(r.trim()));return t.protocol!=="http:"&&t.protocol!=="https:"||!t.hostname?null:t}catch{return null}}function Pe(r,t,e){return Math.min(e,Math.max(t,Math.round(r)))}function Nc(r){return r==="center"?{margin:"1rem auto",width:"fit-content",maxWidth:"100%"}:r==="left"?{margin:"1rem auto 1rem 0",width:"fit-content",maxWidth:"100%"}:{margin:"1rem 0 1rem auto",width:"fit-content",maxWidth:"100%"}}var At=240,It=140,_t=1600,Ot=1200,X=class r extends DecoratorNode{constructor(e,n){super(n);T(this,"__payload");this.__payload=e;}static getType(){return "iframe-embed"}static clone(e){return new r(e.__payload,e.__key)}static importJSON(e){return new r({src:e.src,width:Pe(e.width,At,_t),height:Pe(e.height,It,Ot),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 i=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 r({src:i,width:Pe(s,At,_t),height:Pe(a,It,Ot),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(Tc,{nodeKey:this.__key,payload:this.__payload})}isInline(){return false}isKeyboardSelectable(){return true}};function Tc({nodeKey:r,payload:t}){let[e]=useLexicalComposerContext(),[n,o]=useState(()=>e.isEditable()),[i,s]=useState(false),[a,l]=useState(false),[d,c]=useState(t.width),[u,m]=useState(t.height),f=useRef(t.width),g=useRef(t.height),y=useRef(null),C=useRef(null),h=useRef(null);useEffect(()=>{c(t.width),m(t.height),f.current=t.width,g.current=t.height;},[t.width,t.height]),useEffect(()=>()=>{h.current!=null&&window.cancelAnimationFrame(h.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 k=L.getNodes().some(I=>I.getKey()===r);s(k);});}),[e,r]);let p=x=>{e.update(()=>{let L=$getNodeByKey(r);L instanceof X&&L.setPayload(x);});},S=x=>{x.preventDefault(),x.stopPropagation(),e.update(()=>{let L=$createNodeSelection();L.add(r),$setSelection(L);});},N=x=>L=>{if(L.preventDefault(),L.stopPropagation(),!y.current)return;let I=L.clientX,D=L.clientY,Y=d,ee=u;document.body.style.userSelect="none",document.body.style.cursor=x==="width"?"ew-resize":"ns-resize",l(true);let B=()=>{h.current=null,y.current&&(y.current.style.width=`${f.current}px`),C.current&&(C.current.style.height=`${g.current}px`);},z=j=>{let K=x==="width"?Pe(Y+(j.clientX-I),At,_t):f.current,O=x==="height"?Pe(ee+(j.clientY-D),It,Ot):g.current;f.current=K,g.current=O,h.current==null&&(h.current=window.requestAnimationFrame(B));},W=()=>{h.current!=null&&(window.cancelAnimationFrame(h.current),h.current=null),l(false),c(f.current),m(g.current),p({width:f.current,height:g.current}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",z),document.removeEventListener("mouseup",W);};document.addEventListener("mousemove",z),document.addEventListener("mouseup",W);},b=useMemo(()=>Nc(t.alignment),[t.alignment]),E=useMemo(()=>({marginTop:"0.5rem",textAlign:"center",color:"#666",fontSize:"0.9em",fontStyle:"italic"}),[]),w=qo(n,i,a);return jsxs("div",{style:b,children:[jsxs("div",{ref:y,className:`luthor-media-embed-shell${i?" is-selected":""}${a?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{width:d,maxWidth:"100%"},onClick:n?S:void 0,children:[jsx("iframe",{ref:C,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:Jo(n,i,a)}}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize iframe width","aria-hidden":!w,tabIndex:w?0:-1,style:{opacity:w?1:0,pointerEvents:w?"auto":"none"},onMouseDown:N("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize iframe height","aria-hidden":!w,tabIndex:w?0:-1,style:{opacity:w?1:0,pointerEvents:w?"auto":"none"},onMouseDown:N("height")})]}),t.caption?jsx("figcaption",{style:E,children:t.caption}):null]})}var bn=class extends M{constructor(t){super("iframeEmbed",["toolbar"]),this.config={defaultWidth:640,defaultHeight:360,defaultAlignment:"center",...t};}register(t){return ()=>{}}getNodes(){return [X]}getPlugins(){return []}getCommands(t){return {insertIframeEmbed:(e,n,o,i)=>{let s=Ai(e);s&&t.update(()=>{let a=new X({src:s.toString(),width:Pe(n??this.config.defaultWidth??640,At,_t),height:Pe(o??this.config.defaultHeight??360,It,Ot),alignment:this.config.defaultAlignment??"center",title:i,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 X&&o.setPayload({alignment:e});});});},resizeIframeEmbed:(e,n)=>{t.update(()=>{let o=$getSelection();$isNodeSelection(o)&&o.getNodes().forEach(i=>{i instanceof X&&i.setPayload({width:Pe(e,At,_t),height:Pe(n,It,Ot)});});});},setIframeEmbedCaption:e=>{t.update(()=>{let n=$getSelection();$isNodeSelection(n)&&n.getNodes().forEach(o=>{o instanceof X&&o.setPayload({caption:e});});});},getIframeEmbedCaption:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isNodeSelection(n)){e("");return}let o=n.getNodes().find(i=>i instanceof X);e(o?.getPayload().caption??"");});}),updateIframeEmbedUrl:e=>{let n=Ai(e);if(!n)return false;let o=false;return t.update(()=>{let i=$getSelection();$isNodeSelection(i)&&i.getNodes().forEach(s=>{s instanceof X&&(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(i=>i instanceof X);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 X));});}),isIframeEmbedAlignedLeft:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=$getSelection();if(!$isNodeSelection(n)){e(false);return}let o=n.getNodes().find(i=>i instanceof X);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(i=>i instanceof X);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(i=>i instanceof X);e(o?.getPayload().alignment==="right");});})}}},Lc=new bn;var ut=240,mt=140,gt=1600,ft=1200;function xe(r,t,e){return Math.min(e,Math.max(t,Math.round(r)))}function Ac(r){return r==="center"?{margin:"1rem auto",width:"fit-content",maxWidth:"100%"}:r==="left"?{margin:"1rem auto 1rem 0",width:"fit-content",maxWidth:"100%"}:{margin:"1rem 0 1rem auto",width:"fit-content",maxWidth:"100%"}}function Ic(r){let t=r.trim();return /^https?:\/\//i.test(t)?t:`https://${t}`}function Go(r){try{return new URL(Ic(r))}catch{return null}}function Hi(r){return /^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/.*)?$/i.test(r)}function ve(r){return typeof r=="string"&&/^[A-Za-z0-9_-]{3,}$/.test(r)}function Fi(r){let t=r.hostname.toLowerCase(),e=r.pathname;if(t==="youtu.be"){let i=e.split("/").filter(Boolean)[0];return ve(i)?{videoId:i}:null}if(e==="/playlist"){let i=r.searchParams.get("list");return ve(i)?{playlistId:i}:null}if(e.startsWith("/shorts/")){let i=e.split("/")[2];return ve(i)?{videoId:i}:null}if(e.startsWith("/embed/")){let i=e.split("/")[2];if(!i)return null;if(i==="videoseries"){let s=r.searchParams.get("list");return ve(s)?{playlistId:s}:null}return ve(i)?{videoId:i}:null}if(e==="/watch"){let i=r.searchParams.get("list"),s=r.searchParams.get("v"),a={};return ve(s)&&(a.videoId=s),ve(i)&&(a.playlistId=i),a.videoId||a.playlistId?a:null}let n=r.searchParams.get("v"),o=r.searchParams.get("list");return ve(n)||ve(o)?{videoId:ve(n)?n:void 0,playlistId:ve(o)?o:void 0}:null}function _c(r,t){if(!Hi(r))return null;let e=Go(r);if(!e)return null;if(e.pathname.includes("/embed/"))return e.toString();let n=Fi(e);if(!n)return null;let o=t.nocookie?"https://www.youtube-nocookie.com/embed/":"https://www.youtube.com/embed/",i="";if(n.playlistId&&!n.videoId?i=`${o}videoseries?list=${encodeURIComponent(n.playlistId)}`:n.videoId&&(i=`${o}${encodeURIComponent(n.videoId)}`),!i)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 i;let a=i.includes("?")?"&":"?";return `${i}${a}${s.join("&")}`}function Oi(r,t){let e=Go(r);if(!e||!Hi(t))return null;let n=Go(t);if(!n)return null;let o=Fi(n);if(!o||!o.videoId&&!o.playlistId)return null;let i=new URLSearchParams(e.search);i.delete("v"),i.delete("list"),i.delete("index"),o.playlistId&&i.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=i.toString(),d.toString()}var V=class r extends DecoratorNode{constructor(e,n){super(n);T(this,"__payload");this.__payload=e;}static getType(){return "youtube-embed"}static clone(e){return new r(e.__payload,e.__key)}static importJSON(e){return new r({src:e.src,width:xe(e.width,ut,gt),height:xe(e.height,mt,ft),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 i=o.querySelector("iframe");if(!i)return {node:null};let s=i.getAttribute("src")??"",a=Number(i.getAttribute("width")??"640"),l=Number(i.getAttribute("height")??"480"),d=o.getAttribute("data-align")??"center",u=o.querySelector("figcaption")?.textContent??o.getAttribute("data-caption")??"",m=Number(i.getAttribute("data-start")??"0");return {node:new r({src:s,width:xe(a,ut,gt),height:xe(l,mt,ft),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 i=o.querySelector("iframe");if(!i)return {node:null};let s=i.getAttribute("src")??"",a=Number(i.getAttribute("width")??"640"),l=Number(i.getAttribute("height")??"480"),d=o.getAttribute("data-align")??"center",u=o.querySelector("figcaption")?.textContent??o.getAttribute("data-caption")??"",m=Number(i.getAttribute("data-start")??"0");return {node:new r({src:s,width:xe(a,ut,gt),height:xe(l,mt,ft),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(Oc,{nodeKey:this.__key,payload:this.__payload})}isInline(){return false}isKeyboardSelectable(){return true}};function Oc({nodeKey:r,payload:t}){let[e]=useLexicalComposerContext(),[n,o]=useState(()=>e.isEditable()),[i,s]=useState(false),[a,l]=useState(false),[d,c]=useState(t.width),[u,m]=useState(t.height),f=useRef(t.width),g=useRef(t.height),y=useRef(null),C=useRef(null),h=useRef(null);useEffect(()=>{c(t.width),m(t.height),f.current=t.width,g.current=t.height;},[t.width,t.height]),useEffect(()=>()=>{h.current!=null&&window.cancelAnimationFrame(h.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 k=L.getNodes().some(I=>I.getKey()===r);s(k);});}),[e,r]);let p=x=>{e.update(()=>{let L=$getNodeByKey(r);L instanceof V&&L.setPayload(x);});},S=x=>{x.preventDefault(),x.stopPropagation(),e.update(()=>{let L=$createNodeSelection();L.add(r),$setSelection(L);});},N=x=>L=>{if(L.preventDefault(),L.stopPropagation(),!y.current)return;let I=L.clientX,D=L.clientY,Y=d,ee=u;document.body.style.userSelect="none",document.body.style.cursor=x==="width"?"ew-resize":"ns-resize",l(true);let B=()=>{h.current=null,y.current&&(y.current.style.width=`${f.current}px`),C.current&&(C.current.style.height=`${g.current}px`);},z=j=>{let K=x==="width"?xe(Y+(j.clientX-I),ut,gt):f.current,O=x==="height"?xe(ee+(j.clientY-D),mt,ft):g.current;f.current=K,g.current=O,h.current==null&&(h.current=window.requestAnimationFrame(B));},W=()=>{h.current!=null&&(window.cancelAnimationFrame(h.current),h.current=null),l(false),c(f.current),m(g.current),p({width:f.current,height:g.current}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",z),document.removeEventListener("mouseup",W);};document.addEventListener("mousemove",z),document.addEventListener("mouseup",W);},b=useMemo(()=>Ac(t.alignment),[t.alignment]),E=qo(n,i,a),w=useMemo(()=>({fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"}),[]);return jsxs("div",{style:b,children:[jsxs("div",{ref:y,className:`luthor-media-embed-shell${i?" is-selected":""}${a?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{width:d,maxWidth:"100%"},onClick:n?S:void 0,children:[jsx("iframe",{ref:C,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:Jo(n,i,a)}}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize YouTube embed width","aria-hidden":!E,tabIndex:E?0:-1,style:{opacity:E?1:0,pointerEvents:E?"auto":"none"},onMouseDown:N("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize YouTube embed height","aria-hidden":!E,tabIndex:E?0:-1,style:{opacity:E?1:0,pointerEvents:E?"auto":"none"},onMouseDown:N("height")})]}),t.caption?jsx("figcaption",{style:w,children:t.caption}):null]})}var En=class extends M{constructor(e){super("youtubeEmbed",["toolbar"]);T(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 i=o.getNodes().find(s=>s instanceof V);i&&(this.lastSelectedYouTubeNodeKey=i.getKey());});})}getNodes(){return [V]}getPlugins(){return []}getCommands(e){return {insertYouTubeEmbed:(n,o,i,s)=>{let a=_c(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:xe(o??this.config.defaultWidth??640,ut,gt),height:xe(i??this.config.defaultHeight??480,mt,ft),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(i=>{i instanceof V&&i.setPayload({alignment:n});});});},resizeYouTubeEmbed:(n,o)=>{e.update(()=>{let i=$getSelection();$isNodeSelection(i)&&i.getNodes().forEach(s=>{s instanceof V&&s.setPayload({width:xe(n,ut,gt),height:xe(o,mt,ft)});});});},setYouTubeEmbedCaption:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){o.getNodes().forEach(i=>{i instanceof V&&i.setPayload({caption:n});});return}if(this.lastSelectedYouTubeNodeKey){let i=$getNodeByKey(this.lastSelectedYouTubeNodeKey);i instanceof V?i.setPayload({caption:n}):this.lastSelectedYouTubeNodeKey=null;}});},getYouTubeEmbedCaption:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes().find(s=>s instanceof V);if(i){n(i.getPayload().caption??"");return}}if(this.lastSelectedYouTubeNodeKey){let i=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(i instanceof V){n(i.getPayload().caption??"");return}}n("");});}),updateYouTubeEmbedUrl:n=>{let o=false;return e.update(()=>{let i=$getSelection();if($isNodeSelection(i)){i.getNodes().forEach(s=>{if(s instanceof V){let a=Oi(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=Oi(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 i=o.getNodes().find(s=>s instanceof V);if(i){n(i.getPayload().src??"");return}}if(this.lastSelectedYouTubeNodeKey){let i=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(i instanceof V){n(i.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(i=>i instanceof V));});}),isYouTubeEmbedAlignedLeft:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){n(false);return}let i=o.getNodes().find(s=>s instanceof V);n(i?.getPayload().alignment==="left");});}),isYouTubeEmbedAlignedCenter:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){n(false);return}let i=o.getNodes().find(s=>s instanceof V);n(i?.getPayload().alignment==="center");});}),isYouTubeEmbedAlignedRight:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){n(false);return}let i=o.getNodes().find(s=>s instanceof V);n(i?.getPayload().alignment==="right");});})}}},Dc=new En;var Hc="luthor:meta";var Fc=/<!--\s*luthor:meta\s+v(\d+)\s+({[\s\S]*?})\s*-->/g;function Ae(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function pt(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function er(r){return {type:"text",version:1,text:r,detail:0,format:0,mode:"normal",style:""}}function Xo(r){return {type:"paragraph",version:1,format:"",indent:0,direction:null,children:[er(r)]}}function Bc(r){return {type:"listitem",version:1,value:1,checked:null,indent:0,direction:null,format:"",children:[er(r)]}}function zc(r,t){return `[Unsupported ${t} preserved in ${r} metadata]`}function Zo(r,t,e){let n=t.length>0?t.join("."):"root";return `${r}:${n}:${e}`}function $c(r,t){return r==="root"||r==="quote"?Xo(t):r==="list"?Bc(t):r==="paragraph"||r==="heading"||r==="listitem"||r==="link"||r==="autolink"||r==="code"||r==="code-highlight"?er(t):Xo(t)}function zi(r,t,e,n,o,i){let s=[];for(let[a,l]of r.entries()){if(!Ae(l))continue;let d=[...e,a],c=typeof l.type=="string"?l.type:"";if(!o.has(c)){let m=zc(n,c||"node"),f={id:Zo(c||"node",d,i.length+1),type:c||"node",path:d,node:pt(l),fallback:m};i.push(f),s.push($c(t,m));continue}let u={...l};Array.isArray(l.children)&&(u.children=zi(l.children,c,d,n,o,i)),s.push(u);}return s}function jc(){return {type:"root",version:1,format:"",indent:0,direction:null,children:[Xo("")]}}function $i(r){let t=typeof r=="string"?JSON.parse(r):r;if(!Ae(t)||!Ae(t.root))return {root:jc()};let e=t.root,n=Array.isArray(e.children)?e.children:[];return {root:{...e,type:"root",children:n}}}function Uc(r,t,e){if(t.length===0)return false;let n=r;for(let i of t.slice(0,-1)){if(!Array.isArray(n.children)||i<0||i>=n.children.length)return false;let s=n.children[i];if(!Ae(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]=pt(e),true):o===n.children.length?(n.children.push(pt(e)),true):false}function Kc(r,t){if(t.length===0)return r;let e=r;for(let n of t){if(!Array.isArray(e.children)||n<0||n>=e.children.length)return null;let o=e.children[n];if(!Ae(o))return null;e=o;}return e}function ji(r,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 i=typeof r.format=="number"?r.format:Number(r.format??0);r.format=Number.isFinite(i)?i|o:o;continue}if(Ae(n)&&Ae(r[e])){ji(r[e],n);continue}r[e]=pt(n);}}function Yc(r,t,e){let n=Kc(r,t);return n?(ji(n,e),true):false}function zt(r,t){let e=$i(r),n=Array.isArray(e.root.children)?e.root.children:[],o=[],i=zi(n,"root",[],t.mode,t.supportedNodeTypes,o);return {document:{root:{...e.root,type:"root",children:i}},envelopes:o}}function $t(r,t){if(t.length===0)return r;let n=t.map(o=>{let i=JSON.stringify(o);return `<!-- ${Hc} v1 ${i} -->`}).join(`
|
|
1
|
+
import sn,{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,$createTextNode,DecoratorNode,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,IS_BOLD,IS_ITALIC,IS_STRIKETHROUGH,IS_CODE,IS_HIGHLIGHT,IS_UNDERLINE,createEditor,TextNode,LineBreakNode,TabNode,ElementNode}from'lexical';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {$createLinkNode,TOGGLE_LINK_COMMAND,$isLinkNode,LinkNode,AutoLinkNode}from'@lexical/link';import {TRANSFORMERS,CHECK_LIST,registerMarkdownShortcuts,UNORDERED_LIST,$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,getCodeLanguages}from'@lexical/code';import {TableNode,TableRowNode,TableCellNode,$createTableNodeWithDimensions,$isTableRowNode,$isTableCellNode,$isTableNode,$isTableSelection,$deleteTableColumnAtSelection,$deleteTableRowAtSelection,$unmergeCell,$mergeCells,$getTableNodeFromLexicalNodeOrThrow,$getTableColumnIndexFromTableCellNode,TableCellHeaderStates,$getTableRowIndexFromTableCellNode,$insertTableColumnAtSelection,$insertTableRowAtSelection,$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 ml=Object.defineProperty;var gl=(r,t,e)=>t in r?ml(r,t,{enumerable:true,configurable:true,writable:true,value:e}):r[t]=e;var N=(r,t,e)=>gl(r,typeof t!="symbol"?t+"":t,e);var Zr=["--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 fl(r){return typeof r=="string"&&r.trim().length>0}function pl(r){if(!r)return;let t={};for(let e of Zr){let n=r[e];fl(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 hl(r,t){return {...r,...t,text:{...r.text,...t.text},list:{...r.list,...t.list,nested:{...r.list?.nested,...t.list?.nested}},heading:{...r.heading,...t.heading},codeHighlight:{...r.codeHighlight,...t.codeHighlight},toolbar:{...r.toolbar,...t.toolbar},draggable:{...r.draggable,...t.draggable,styles:{...r.draggable?.styles,...t.draggable?.styles}},floatingToolbar:{...r.floatingToolbar,...t.floatingToolbar,styles:{...r.floatingToolbar?.styles,...t.floatingToolbar?.styles}},richText:{...r.richText,...t.richText},styles:{toolbar:{...r.styles?.toolbar,...t.styles?.toolbar},draggable:{...r.styles?.draggable,...t.styles?.draggable},floatingToolbar:{...r.styles?.floatingToolbar,...t.styles?.floatingToolbar},...t.styles}}}function bl(r){return r&&typeof r=="object"}function ei(r){let t=r;for(;t;){if(t.getType()==="code")return true;t=t.getParent();}return false}function ti(){let r=$getSelection();if(!$isRangeSelection(r))return false;let t=r.anchor.getNode(),e=r.focus.getNode();return ei(t)||ei(e)}var vt=createContext(null),Oo=class{constructor(){N(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.`));}},wl=new Oo;function ri(){function r(){let n=useContext(vt);if(!n)throw new Error("useEditor must be used within Provider");return n}function t({children:n,config:o={},extensions:i}){let[s]=useLexicalComposerContext(),a=useMemo(()=>({formatText:(b,p)=>{s&&(b==="code"&&s.getEditorState().read(()=>ti())||s.dispatchCommand(FORMAT_TEXT_COMMAND,b));}}),[s]),l=useMemo(()=>{if(!s)return {};let b={};for(let p of i)Object.assign(b,p.getCommands(s));return b},[i,s]),d=useMemo(()=>({...a,...l}),[a,l]),{plugins:c,pluginsBefore:u,pluginsAfter:m}=useMemo(()=>{let b=[],p=[];for(let C of i){let S=C.getPlugins?.()||[];(C.config?.position||"before")==="after"?p.push(...S):b.push(...S);}return {plugins:[...b,...p],pluginsBefore:b,pluginsAfter:p}},[i]);useEffect(()=>{if(!s)return;let p=[...i].sort((C,S)=>{let h=C.config?.initPriority??0;return (S.config?.initPriority??0)-h}).map(C=>C.register(s));return ()=>p.forEach(C=>C&&C())},[s,i]);let f=useMemo(()=>{if(!s)return {};let b={};for(let p of i)p.getStateQueries&&Object.assign(b,p.getStateQueries(s));return b},[i,s]),[g,x]=useState(()=>{let b={};return Object.keys(f).forEach(p=>b[p]=false),b});useEffect(()=>{let b=Object.keys(f);x(p=>{let C={};for(let h of b){let y=p[h];C[h]=y??false;}if(Object.keys(p).length!==b.length)return C;for(let h of b)if(p[h]!==C[h])return C;return p});},[f]),useEffect(()=>{if(!s)return;let b=true,p=0,C=async()=>{let y=++p,E=Object.entries(f).map(async([I,D])=>{try{let Y=await D();return [I,Y]}catch{return [I,false]}}),T=await Promise.all(E);if(!b||y!==p)return;let k=Object.fromEntries(T);x(I=>{let D=I,Y=k,ee=Object.keys(D),B=Object.keys(Y);if(ee.length!==B.length)return k;for(let z of B)if(D[z]!==Y[z])return k;return I});};C();let S=s.registerUpdateListener(()=>{C();}),h=i.map(y=>{let w=y;if(typeof w.onStateChange=="function")return w.onStateChange(()=>{C();})}).filter(y=>typeof y=="function");return ()=>{b=false,S(),h.forEach(y=>y());}},[s,f,i]);let L={editor:s,config:o,extensions:i,commands:d,activeStates:g,stateQueries:f,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 p=d;typeof p.rehydrateListStyles=="function"&&queueMicrotask(()=>{p.rehydrateListStyles?.();});}}},lexical:s,extensionsAPI:wl,plugins:c,hasExtension:b=>i.some(p=>p.name===b)};return jsxs(vt.Provider,{value:L,children:[u,n,m]})}function e(n){let o=useMemo(()=>n.extensions.flatMap(a=>a.getNodes?.()||[]),[n.extensions]),i=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:i,children:jsx(t,{...n})})}return {Provider:e,useEditor:r}}var kl=ri(),Rl=kl.Provider,Oe=()=>{let r=useContext(vt);if(!r)throw new Error("useBaseEditor must be used within Provider");return r};var Pl=(o=>(o.Toolbar="toolbar",o.Sidebar="sidebar",o.ContextMenu="contextmenu",o.Floating="floating",o))(Pl||{});var M=class{constructor(t,e=["toolbar"]){N(this,"name");N(this,"category",["toolbar"]);N(this,"config",{});N(this,"supportedFormats",[]);N(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 Al(r){return new class extends M{constructor(){super(r.name,r.category||["toolbar"]);N(this,"_plugins",[]);N(this,"_nodes",[]);N(this,"_initialize");r.config&&(this.config={...this.config,...r.config}),this._initialize=r.initialize,r.supportedFormats&&(this.supportedFormats=r.supportedFormats),r.nodes&&(this._nodes=r.nodes),r.plugins&&(this._plugins=r.plugins);}register(e){let n=this._initialize?.(e);return ()=>{typeof n=="function"&&n();}}getNodes(){return this._nodes}getPlugins(){return this._plugins}getCommands(e){return r.commands?r.commands(e):{}}getStateQueries(e){return r.stateQueries?r.stateQueries(e):{}}}}function _l(r){r.update(()=>{$setSelection(null);});}function Ol(r,t){let e=t.getAttribute("data-lexical-node-key")?.trim();if(e)return e;let n=null;return r.read(()=>{let o=$getNearestNodeFromDOMNode(t);if($isLinkNode(o)){n=o.getKey();return}let i=t.firstChild;if(!i)return;let s=$getNearestNodeFromDOMNode(i);if($isLinkNode(s)){n=s.getKey();return}let a=s?.getParent();a&&$isLinkNode(a)&&(n=a.getKey());}),n}var ae=class extends M{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 Ye=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=e.closest("a[href]"),i=this.resolveAlignment(e,n),s;if(n){let u=n.querySelector("figcaption");u&&(s=u.textContent||void 0);}let a=e.getAttribute("width"),l=e.getAttribute("height"),d=a?Number(a):void 0,c=l?Number(l):void 0;try{return {node:Xe(e.src,e.alt||"",s,o?.getAttribute("href")||void 0,o?.getAttribute("title")||void 0,i,e.className||void 0,this.extractStyleObject(e),Number.isFinite(d)?d: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 i=e.querySelector("figcaption")?.textContent||void 0,s=n.closest("a[href]"),a=this.resolveAlignment(n,e),l=n.getAttribute("width"),d=n.getAttribute("height"),c=l?Number(l):void 0,u=d?Number(d):void 0;try{return {node:Xe(n.src,n.alt||"",i,s?.getAttribute("href")||void 0,s?.getAttribute("title")||void 0,a,n.className||void 0,this.extractStyleObject(n),Number.isFinite(c)?c:void 0,Number.isFinite(u)?u: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,linkHref:t.__linkHref,linkTitle:t.__linkTitle,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,linkHref:i,linkTitle:s,alignment:a,className:l,style:d,width:c,height:u,uploading:m}=t;if(!e||e.length===0)throw new Error("Cannot import ImageNode with empty src");return Xe(e,n,o,i,s,a,l,d?this.recordToStyleObject(d):void 0,c,u,m)}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",t.__linkHref){let o=document.createElement("a");o.href=t.__linkHref,t.__linkTitle&&(o.title=t.__linkTitle),o.target="_blank",o.rel="noopener noreferrer",o.appendChild(n),e.appendChild(o);}else e.appendChild(n);if(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 i of n){if(i.classList.contains("align-left"))return "left";if(i.classList.contains("align-center"))return "center";if(i.classList.contains("align-right"))return "right"}let o=e?.getAttribute("data-align");if(o==="left"||o==="center"||o==="right")return o;for(let i of n){if(i.style.textAlign==="left")return "left";if(i.style.textAlign==="center")return "center";if(i.style.textAlign==="right")return "right";if(i.style.float==="left")return "left";if(i.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:ah,exportDOM:lh,importJSON:ch,exportJSON:dh}=Ye;var mi=createCommand("insert-image"),bi=Wl,Bo=true,zo=false,gi=50,fi=50,pi=2400,hi=2400;function un(r,t,e){return Math.min(e,Math.max(t,Math.round(r)))}function Ql(r,t,e,n){return r&&n&&t&&!e}function Wl({src:r,alt:t,caption:e,linkHref:n,linkTitle:o,alignment:i="none",className:s="",style:a,nodeKey:l,width:d,height:c,resizable:u=true,scaleByRatio:m=false,uploading:f=false}){let[g]=useLexicalComposerContext(),x=useRef(null),L=useRef(null),b=useRef(null),p=useRef(0),C=useRef(0),[S,h]=useState(false),[y,w]=useState(false),[E,T]=useState(()=>g.isEditable()),[k,I]=useState(d||"auto"),[D,Y]=useState(c||"auto");useEffect(()=>()=>{r&&r.startsWith("blob:")&&URL.revokeObjectURL(r);},[r]),useEffect(()=>{I(d||"auto"),Y(c||"auto"),p.current=typeof d=="number"?d:0,C.current=typeof c=="number"?c:0;},[d,c]),useEffect(()=>()=>{b.current!=null&&window.cancelAnimationFrame(b.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>g.registerEditableListener(O=>{T(O);}),[g]),useEffect(()=>{if(l)return g.registerUpdateListener(({editorState:O})=>{O.read(()=>{let q=$getSelection();if($isNodeSelection(q)){let X=q.getNodes();h(X.some(Z=>Z.getKey()===l));}else h(false);});})},[g,l]);let ee=O=>{E&&(O.preventDefault(),O.stopPropagation(),l&&g.update(()=>{let q=$createNodeSelection();q.add(l),$setSelection(q);}));},B=O=>q=>{if(!E||!x.current||!l)return;q.preventDefault(),q.stopPropagation(),w(true),document.body.style.userSelect="none",document.body.style.cursor=O==="width"?"ew-resize":"ns-resize";let X=q.clientX,Z=q.clientY,ge=x.current.clientWidth||(typeof k=="number"?k:100),be=x.current.clientHeight||(typeof D=="number"?D:100),Te=Number.isFinite(ge)&&Number.isFinite(be)&&ge>0&&be>0?ge/be:null;p.current=ge,C.current=be;let $e=()=>{b.current=null,L.current&&(L.current.style.width=`${p.current}px`),x.current&&(x.current.style.height=`${C.current}px`);},je=re=>{let Tt=!!Te&&(m?!re.shiftKey:re.shiftKey),_e=O==="width"?un(ge+(re.clientX-X),gi,pi):p.current,Ke=O==="height"?un(be+(re.clientY-Z),fi,hi):C.current;Tt&&Te&&(O==="width"?Ke=un(_e/Te,fi,hi):_e=un(Ke*Te,gi,pi)),p.current=_e,C.current=Ke,b.current==null&&(b.current=window.requestAnimationFrame($e));},fe=()=>{b.current!=null&&(window.cancelAnimationFrame(b.current),b.current=null),w(false),I(p.current),Y(C.current),g.update(()=>{let re=$getNodeByKey(l);re instanceof K&&re.setWidthAndHeight(p.current,C.current);}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",je),document.removeEventListener("mouseup",fe);};document.addEventListener("mousemove",je),document.addEventListener("mouseup",fe);},z={margin:0,display:"block",position:"relative",...a},W={maxWidth:"100%",display:"block",borderRadius:"4px",width:typeof k=="number"?"100%":"auto",height:typeof D=="number"?`${D}px`:D,margin:0},j={fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"},U=Ql(E,S,y,u);return jsxs("figure",{className:`lexical-image align-${i} ${s} ${S?"selected":""} ${y?"resizing":""} ${f?"uploading":""}`,style:z,children:[jsxs("div",{ref:L,className:`luthor-media-embed-shell${S?" is-selected":""}${y?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{position:"relative",display:"inline-block",width:k,maxWidth:"100%",cursor:E?"pointer":"default"},onClick:E?ee:void 0,children:[n?jsx("a",{href:n,title:o,target:"_blank",rel:"noopener noreferrer",onClick:O=>{E&&O.preventDefault();},children:jsx("img",{ref:x,src:r,alt:t,style:W})}):jsx("img",{ref:x,src:r,alt:t,style:W}),u?jsxs(Fragment,{children:[jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize image width","aria-hidden":!U,tabIndex:U?0:-1,style:{opacity:U?1:0,pointerEvents:U?"auto":"none"},onMouseDown:B("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize image height","aria-hidden":!U,tabIndex:U?0:-1,style:{opacity:U?1:0,pointerEvents:U?"auto":"none"},onMouseDown:B("height")})]}):null]}),e&&jsx("figcaption",{style:j,children:e}),jsx("div",{style:{clear:"both",height:0,fontSize:0}})]})}var K=class r extends DecoratorNode{constructor(e="",n="",o,i,s,a="none",l,d,c,u,m,f){super(f);N(this,"__src");N(this,"__alt");N(this,"__caption");N(this,"__linkHref");N(this,"__linkTitle");N(this,"__alignment");N(this,"__className");N(this,"__style");N(this,"__width");N(this,"__height");N(this,"__uploading");this.__src=e&&e.length>0?e:"",this.__alt=n,this.__caption=o,this.__linkHref=i,this.__linkTitle=s,this.__alignment=a,this.__className=l,this.__style=d,this.__width=c,this.__height=u,this.__uploading=m;}static getType(){return "image"}static clone(e){return new r(e.__src,e.__alt,e.__caption,e.__linkHref,e.__linkTitle,e.__alignment,e.__className,e.__style,e.__width,e.__height,e.__uploading,e.__key)}static importDOM(){return Ye.importDOM()}static importJSON(e){return Ye.importJSON(e)}createDOM(e){let n=document.createElement("div"),o=e.theme?.image||"",i=this.__alignment;return n.className=`${o} lexical-image-container align-${i}`.trim(),n.style.display=i==="center"?"block":"inline-block",n.style.float=i==="left"?"left":i==="right"?"right":"none",n.style.margin=i==="center"?"1rem auto":i==="left"?"0 1rem 1rem 0":i==="right"?"0 0 1rem 1rem":"1rem 0",n.style.textAlign=i==="center"?"center":"inherit",n.style.position="relative",n}updateDOM(e,n,o){let i=this.__alignment;if(i!==e.__alignment){let s=o.theme?.image||"";n.className=`${s} lexical-image-container align-${i}`.trim();}return n.style.display=i==="center"?"block":"inline-block",n.style.float=i==="left"?"left":i==="right"?"right":"none",n.style.margin=i==="center"?"1rem auto":i==="left"?"0 1rem 1rem 0":i==="right"?"0 0 1rem 1rem":"1rem 0",n.style.textAlign=i==="center"?"center":"inherit",n.style.position="relative",false}exportDOM(){return Ye.exportDOM(this)}exportJSON(){return Ye.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;}setLink(e,n){let o=this.getWritable();o.__linkHref=e,o.__linkTitle=n;}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(bi,{src:this.__src,alt:this.__alt,caption:this.__caption,linkHref:this.__linkHref,linkTitle:this.__linkTitle,alignment:this.__alignment,className:this.__className,style:this.__style,nodeKey:this.getKey(),width:this.__width,height:this.__height,resizable:Bo,scaleByRatio:zo,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 Xe(r,t,e,n,o,i="none",s,a,l,d,c){if(!r||r.length===0)throw new Error("Cannot create ImageNode with empty src");return new K(r,t,e,n,o,i,s,a,l,d,c)}var gn=class extends M{constructor(){super("image",["toolbar"]);N(this,"recentImages",new Set);N(this,"lastSelectedImageNodeKey",null);this.config={...this.config,resizable:true,scaleByRatio:false,pasteListener:{insert:true,replace:true},debug:false,forceUpload:false},Bo=true,zo=false;}configure(e){e.customRenderer&&(bi=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,Bo=n.resizable??true,zo=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 K);c&&(this.lastSelectedImageNodeKey=c.getKey());});}),o=e.registerCommand(mi,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(f=>{e.update(()=>{let g=$getNodeByKey(u.getKey());g instanceof K&&(g.setSrc(f),g.__uploading=!1);});}).catch(f=>{console.error("Upload failed:",f),e.update(()=>{let g=$getNodeByKey(u.getKey());g instanceof K&&(g.__uploading=!1);});}));let u=Xe(d,l.alt,l.caption,l.linkHref,l.linkTitle,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 f=$createParagraphNode();f.append(u),$getRoot().append(f);}}catch(d){console.error("\u274C Insertion error:",d);}}),true),COMMAND_PRIORITY_EDITOR),i=e.registerCommand(KEY_DELETE_COMMAND,()=>{let l=$getSelection();if($isNodeSelection(l)){let d=l.getNodes();if(d.some(c=>c instanceof K))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 K))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(f=>f.type==="text/html");for(let f of c)if(f.type.startsWith("image/")){if(m)continue;d.preventDefault();let g=f.getAsFile();if(!g)continue;l("\u{1F4CB} Pasting image:",g.name),(this.config.uploadHandler&&this.config.forceUpload?this.config.uploadHandler(g).catch(L=>(console.error("Upload failed:",L),URL.createObjectURL(g))):Promise.resolve(URL.createObjectURL(g))).then(L=>{if(this.recentImages.has(L)){l("\u{1F6AB} Duplicate paste image src detected, skipping:",L);return}this.recentImages.add(L),setTimeout(()=>this.recentImages.delete(L),1e3);let b=false,p;this.config.uploadHandler&&this.config.forceUpload&&g&&(b=true,this.config.uploadHandler(g).then(C=>{e.update(()=>{let S=$getNodeByKey(p.getKey());S instanceof K&&(S.setSrc(C),S.__uploading=false);});}).catch(C=>{console.error("Upload failed:",C),e.update(()=>{let S=$getNodeByKey(p.getKey());S instanceof K&&(S.__uploading=false);});})),e.update(()=>{let C=$getSelection(),S=g.name||"Pasted image";if($isNodeSelection(C)&&this.config.pasteListener?.replace){let y=C.getNodes().find(w=>w instanceof K);if(y){l("\u{1F504} Replacing selected image src"),y.setSrc(L),y.__uploading=b,u=true;return}}this.config.pasteListener?.insert&&(l("\u2795 Inserting new pasted image"),p=Xe(L,S,void 0,void 0,void 0,"none",void 0,void 0,void 0,void 0,b),$isRangeSelection(C)?C.insertNodes([p]):$getRoot().append($createParagraphNode().append(p)),u=true);});});break}return u},COMMAND_PRIORITY_NORMAL);}return ()=>{n(),o(),i(),s(),a();}}getNodes(){return [K]}getCommands(e){return {insertImage:n=>{e.dispatchCommand(mi,n);},setImageAlignment:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();for(let s of i)s instanceof K&&s.setAlignment(n);}});},setImageCaption:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();for(let s of i)s instanceof K&&s.setCaption(n);return}if(this.lastSelectedImageNodeKey){let i=$getNodeByKey(this.lastSelectedImageNodeKey);i instanceof K?i.setCaption(n):this.lastSelectedImageNodeKey=null;}});},getImageCaption:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes().find(s=>s instanceof K);if(i){n(i.__caption??"");return}}if(this.lastSelectedImageNodeKey){let i=$getNodeByKey(this.lastSelectedImageNodeKey);if(i instanceof K){n(i.__caption??"");return}}n("");});}),setImageClassName:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();for(let s of i)s instanceof K&&s.setClassName(n);}});},setImageStyle:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();for(let s of i)s instanceof K&&s.setStyle(n);}});}}}getStateQueries(e){return {imageSelected:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();n(i.length===1&&i[0]instanceof K);}else n(false);});}),isImageAlignedLeft:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();if(i.length===1&&i[0]instanceof K){n(i[0].__alignment==="left");return}}n(false);});}),isImageAlignedCenter:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();if(i.length===1&&i[0]instanceof K){n(i[0].__alignment==="center");return}}n(false);});}),isImageAlignedRight:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();if(i.length===1&&i[0]instanceof K){n(i[0].__alignment==="right");return}}n(false);});}),isImageAlignedNone:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes();if(i.length===1&&i[0]instanceof K){n(i[0].__alignment==="none");return}}n(false);});})}}},Jl=new gn;function Fo(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\]/g,"\\]")}function $o(r){return r.replace(/\\(["\\\]])/g,"$1")}function ql(r){let t=r.trim();if(!t)return null;let e=t.match(/^(<[^>\r\n]+>|[^\s]+)(?:\s+"((?:[^"\\]|\\.)*)")?$/);if(!e||!e[1])return null;let n=e[1].trim(),o=n.startsWith("<")&&n.endsWith(">")?n.slice(1,-1).trim():n;if(!o)return null;let i=typeof e[2]=="string"&&e[2].length>0?$o(e[2]):void 0;return {href:o,...i?{title:i}:{}}}function Xl(r){let t={alignment:"none"},e=r.trim();if(!e)return t;let n=/<!--\s*([a-z-]+)\s*:\s*([\s\S]*?)\s*-->/gi,o=n.exec(e),i=0;for(;o;){if(e.slice(i,o.index).trim().length>0)return null;let l=(o[1]??"").trim().toLowerCase(),d=(o[2]??"").trim();if(l==="align"){let c=d.toLowerCase();(c==="left"||c==="center"||c==="right")&&(t.alignment=c);}if(l==="link"){let c=ql(d);c&&(t.linkHref=c.href,t.linkTitle=c.title);}i=n.lastIndex,o=n.exec(e);}return e.slice(i).trim().length>0?null:t}var yi={dependencies:[K],export:r=>{if(!Gl(r))return null;let t=r,e=t.__src||"",n=t.__alt||"",o=t.__caption||"",i=t.__linkHref?.trim()??"",s=t.__linkTitle?.trim()??"",a=t.__alignment||"none";if(!e)return null;let l=`}"`),l+=")";let d=i?(()=>{let c=s?` "${Fo(s)}"`:"";return `[${l}](${i}${c})`})():l;return a!=="none"&&(d+=` <!-- align:${a} -->`),d},regExp:/^!\[((?:\\.|[^\]])*)\]\(([^)\s]+)(?:\s+"((?:[^"\\]|\\.)*)")?\)(\s*(?:<!--[\s\S]*?-->\s*)*)$/,replace:(r,t,e,n)=>{let[,o,i,s,a]=e;if(!i)return;let l=Xl(String(a??""));if(!l)return;let d=Xe(i,typeof o=="string"?$o(o):"",typeof s=="string"&&s.length>0?$o(s):void 0,l.linkHref,l.linkTitle,l.alignment,void 0,void 0,void 0,void 0,false);r.replace(d);},type:"element"};function Gl(r){return r instanceof K}function jo(r,t,e){return r&&t&&!e}function Ko(r,t,e){return r?t&&!e?"auto":"none":"auto"}function ac(r){let t=r.trim();return /^https?:\/\//i.test(t)?t:`https://${t}`}function xi(r){try{let t=new URL(ac(r.trim()));return t.protocol!=="http:"&&t.protocol!=="https:"||!t.hostname?null:t}catch{return null}}function Pe(r,t,e){return Math.min(e,Math.max(t,Math.round(r)))}function lc(r){return r==="center"?{margin:"1rem auto",width:"fit-content",maxWidth:"100%"}:r==="left"?{margin:"1rem auto 1rem 0",width:"fit-content",maxWidth:"100%"}:{margin:"1rem 0 1rem auto",width:"fit-content",maxWidth:"100%"}}var At=240,It=140,_t=1600,Ot=1200,G=class r extends DecoratorNode{constructor(e,n){super(n);N(this,"__payload");this.__payload=e;}static getType(){return "iframe-embed"}static clone(e){return new r(e.__payload,e.__key)}static importJSON(e){return new r({src:e.src,width:Pe(e.width,At,_t),height:Pe(e.height,It,Ot),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 i=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 r({src:i,width:Pe(s,At,_t),height:Pe(a,It,Ot),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(cc,{nodeKey:this.__key,payload:this.__payload})}isInline(){return false}isKeyboardSelectable(){return true}};function cc({nodeKey:r,payload:t}){let[e]=useLexicalComposerContext(),[n,o]=useState(()=>e.isEditable()),[i,s]=useState(false),[a,l]=useState(false),[d,c]=useState(t.width),[u,m]=useState(t.height),f=useRef(t.width),g=useRef(t.height),x=useRef(null),L=useRef(null),b=useRef(null);useEffect(()=>{c(t.width),m(t.height),f.current=t.width,g.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 T=$getSelection();if(!$isNodeSelection(T)){s(false);return}let k=T.getNodes().some(I=>I.getKey()===r);s(k);});}),[e,r]);let p=E=>{e.update(()=>{let T=$getNodeByKey(r);T instanceof G&&T.setPayload(E);});},C=E=>{E.preventDefault(),E.stopPropagation(),e.update(()=>{let T=$createNodeSelection();T.add(r),$setSelection(T);});},S=E=>T=>{if(T.preventDefault(),T.stopPropagation(),!x.current)return;let I=T.clientX,D=T.clientY,Y=d,ee=u;document.body.style.userSelect="none",document.body.style.cursor=E==="width"?"ew-resize":"ns-resize",l(true);let B=()=>{b.current=null,x.current&&(x.current.style.width=`${f.current}px`),L.current&&(L.current.style.height=`${g.current}px`);},z=j=>{let U=E==="width"?Pe(Y+(j.clientX-I),At,_t):f.current,O=E==="height"?Pe(ee+(j.clientY-D),It,Ot):g.current;f.current=U,g.current=O,b.current==null&&(b.current=window.requestAnimationFrame(B));},W=()=>{b.current!=null&&(window.cancelAnimationFrame(b.current),b.current=null),l(false),c(f.current),m(g.current),p({width:f.current,height:g.current}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",z),document.removeEventListener("mouseup",W);};document.addEventListener("mousemove",z),document.addEventListener("mouseup",W);},h=useMemo(()=>lc(t.alignment),[t.alignment]),y=useMemo(()=>({marginTop:"0.5rem",textAlign:"center",color:"#666",fontSize:"0.9em",fontStyle:"italic"}),[]),w=jo(n,i,a);return jsxs("div",{style:h,children:[jsxs("div",{ref:x,className:`luthor-media-embed-shell${i?" is-selected":""}${a?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{width:d,maxWidth:"100%"},onClick:n?C:void 0,children:[jsx("iframe",{ref:L,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:Ko(n,i,a)}}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize iframe width","aria-hidden":!w,tabIndex:w?0:-1,style:{opacity:w?1:0,pointerEvents:w?"auto":"none"},onMouseDown:S("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize iframe height","aria-hidden":!w,tabIndex:w?0:-1,style:{opacity:w?1:0,pointerEvents:w?"auto":"none"},onMouseDown:S("height")})]}),t.caption?jsx("figcaption",{style:y,children:t.caption}):null]})}var pn=class extends M{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,i)=>{let s=xi(e);s&&t.update(()=>{let a=new G({src:s.toString(),width:Pe(n??this.config.defaultWidth??640,At,_t),height:Pe(o??this.config.defaultHeight??360,It,Ot),alignment:this.config.defaultAlignment??"center",title:i,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(i=>{i instanceof G&&i.setPayload({width:Pe(e,At,_t),height:Pe(n,It,Ot)});});});},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(i=>i instanceof G);e(o?.getPayload().caption??"");});}),updateIframeEmbedUrl:e=>{let n=xi(e);if(!n)return false;let o=false;return t.update(()=>{let i=$getSelection();$isNodeSelection(i)&&i.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(i=>i 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(i=>i 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(i=>i 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(i=>i instanceof G);e(o?.getPayload().alignment==="right");});})}}},dc=new pn;var dt=240,ut=140,mt=1600,gt=1200;function xe(r,t,e){return Math.min(e,Math.max(t,Math.round(r)))}function bc(r){return r==="center"?{margin:"1rem auto",width:"fit-content",maxWidth:"100%"}:r==="left"?{margin:"1rem auto 1rem 0",width:"fit-content",maxWidth:"100%"}:{margin:"1rem 0 1rem auto",width:"fit-content",maxWidth:"100%"}}function yc(r){let t=r.trim();return /^https?:\/\//i.test(t)?t:`https://${t}`}function Uo(r){try{return new URL(yc(r))}catch{return null}}function vi(r){return /^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/.*)?$/i.test(r)}function Le(r){return typeof r=="string"&&/^[A-Za-z0-9_-]{3,}$/.test(r)}function Li(r){let t=r.hostname.toLowerCase(),e=r.pathname;if(t==="youtu.be"){let i=e.split("/").filter(Boolean)[0];return Le(i)?{videoId:i}:null}if(e==="/playlist"){let i=r.searchParams.get("list");return Le(i)?{playlistId:i}:null}if(e.startsWith("/shorts/")){let i=e.split("/")[2];return Le(i)?{videoId:i}:null}if(e.startsWith("/embed/")){let i=e.split("/")[2];if(!i)return null;if(i==="videoseries"){let s=r.searchParams.get("list");return Le(s)?{playlistId:s}:null}return Le(i)?{videoId:i}:null}if(e==="/watch"){let i=r.searchParams.get("list"),s=r.searchParams.get("v"),a={};return Le(s)&&(a.videoId=s),Le(i)&&(a.playlistId=i),a.videoId||a.playlistId?a:null}let n=r.searchParams.get("v"),o=r.searchParams.get("list");return Le(n)||Le(o)?{videoId:Le(n)?n:void 0,playlistId:Le(o)?o:void 0}:null}function Ec(r,t){if(!vi(r))return null;let e=Uo(r);if(!e)return null;if(e.pathname.includes("/embed/"))return e.toString();let n=Li(e);if(!n)return null;let o=t.nocookie?"https://www.youtube-nocookie.com/embed/":"https://www.youtube.com/embed/",i="";if(n.playlistId&&!n.videoId?i=`${o}videoseries?list=${encodeURIComponent(n.playlistId)}`:n.videoId&&(i=`${o}${encodeURIComponent(n.videoId)}`),!i)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 i;let a=i.includes("?")?"&":"?";return `${i}${a}${s.join("&")}`}function Ni(r,t){let e=Uo(r);if(!e||!vi(t))return null;let n=Uo(t);if(!n)return null;let o=Li(n);if(!o||!o.videoId&&!o.playlistId)return null;let i=new URLSearchParams(e.search);i.delete("v"),i.delete("list"),i.delete("index"),o.playlistId&&i.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=i.toString(),d.toString()}var V=class r extends DecoratorNode{constructor(e,n){super(n);N(this,"__payload");this.__payload=e;}static getType(){return "youtube-embed"}static clone(e){return new r(e.__payload,e.__key)}static importJSON(e){return new r({src:e.src,width:xe(e.width,dt,mt),height:xe(e.height,ut,gt),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 i=o.querySelector("iframe");if(!i)return {node:null};let s=i.getAttribute("src")??"",a=Number(i.getAttribute("width")??"640"),l=Number(i.getAttribute("height")??"480"),d=o.getAttribute("data-align")??"center",u=o.querySelector("figcaption")?.textContent??o.getAttribute("data-caption")??"",m=Number(i.getAttribute("data-start")??"0");return {node:new r({src:s,width:xe(a,dt,mt),height:xe(l,ut,gt),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 i=o.querySelector("iframe");if(!i)return {node:null};let s=i.getAttribute("src")??"",a=Number(i.getAttribute("width")??"640"),l=Number(i.getAttribute("height")??"480"),d=o.getAttribute("data-align")??"center",u=o.querySelector("figcaption")?.textContent??o.getAttribute("data-caption")??"",m=Number(i.getAttribute("data-start")??"0");return {node:new r({src:s,width:xe(a,dt,mt),height:xe(l,ut,gt),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(xc,{nodeKey:this.__key,payload:this.__payload})}isInline(){return false}isKeyboardSelectable(){return true}};function xc({nodeKey:r,payload:t}){let[e]=useLexicalComposerContext(),[n,o]=useState(()=>e.isEditable()),[i,s]=useState(false),[a,l]=useState(false),[d,c]=useState(t.width),[u,m]=useState(t.height),f=useRef(t.width),g=useRef(t.height),x=useRef(null),L=useRef(null),b=useRef(null);useEffect(()=>{c(t.width),m(t.height),f.current=t.width,g.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 T=$getSelection();if(!$isNodeSelection(T)){s(false);return}let k=T.getNodes().some(I=>I.getKey()===r);s(k);});}),[e,r]);let p=E=>{e.update(()=>{let T=$getNodeByKey(r);T instanceof V&&T.setPayload(E);});},C=E=>{E.preventDefault(),E.stopPropagation(),e.update(()=>{let T=$createNodeSelection();T.add(r),$setSelection(T);});},S=E=>T=>{if(T.preventDefault(),T.stopPropagation(),!x.current)return;let I=T.clientX,D=T.clientY,Y=d,ee=u;document.body.style.userSelect="none",document.body.style.cursor=E==="width"?"ew-resize":"ns-resize",l(true);let B=()=>{b.current=null,x.current&&(x.current.style.width=`${f.current}px`),L.current&&(L.current.style.height=`${g.current}px`);},z=j=>{let U=E==="width"?xe(Y+(j.clientX-I),dt,mt):f.current,O=E==="height"?xe(ee+(j.clientY-D),ut,gt):g.current;f.current=U,g.current=O,b.current==null&&(b.current=window.requestAnimationFrame(B));},W=()=>{b.current!=null&&(window.cancelAnimationFrame(b.current),b.current=null),l(false),c(f.current),m(g.current),p({width:f.current,height:g.current}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",z),document.removeEventListener("mouseup",W);};document.addEventListener("mousemove",z),document.addEventListener("mouseup",W);},h=useMemo(()=>bc(t.alignment),[t.alignment]),y=jo(n,i,a),w=useMemo(()=>({fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"}),[]);return jsxs("div",{style:h,children:[jsxs("div",{ref:x,className:`luthor-media-embed-shell${i?" is-selected":""}${a?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{width:d,maxWidth:"100%"},onClick:n?C:void 0,children:[jsx("iframe",{ref:L,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:Ko(n,i,a)}}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize YouTube embed width","aria-hidden":!y,tabIndex:y?0:-1,style:{opacity:y?1:0,pointerEvents:y?"auto":"none"},onMouseDown:S("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize YouTube embed height","aria-hidden":!y,tabIndex:y?0:-1,style:{opacity:y?1:0,pointerEvents:y?"auto":"none"},onMouseDown:S("height")})]}),t.caption?jsx("figcaption",{style:w,children:t.caption}):null]})}var bn=class extends M{constructor(e){super("youtubeEmbed",["toolbar"]);N(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 i=o.getNodes().find(s=>s instanceof V);i&&(this.lastSelectedYouTubeNodeKey=i.getKey());});})}getNodes(){return [V]}getPlugins(){return []}getCommands(e){return {insertYouTubeEmbed:(n,o,i,s)=>{let a=Ec(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:xe(o??this.config.defaultWidth??640,dt,mt),height:xe(i??this.config.defaultHeight??480,ut,gt),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(i=>{i instanceof V&&i.setPayload({alignment:n});});});},resizeYouTubeEmbed:(n,o)=>{e.update(()=>{let i=$getSelection();$isNodeSelection(i)&&i.getNodes().forEach(s=>{s instanceof V&&s.setPayload({width:xe(n,dt,mt),height:xe(o,ut,gt)});});});},setYouTubeEmbedCaption:n=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){o.getNodes().forEach(i=>{i instanceof V&&i.setPayload({caption:n});});return}if(this.lastSelectedYouTubeNodeKey){let i=$getNodeByKey(this.lastSelectedYouTubeNodeKey);i instanceof V?i.setPayload({caption:n}):this.lastSelectedYouTubeNodeKey=null;}});},getYouTubeEmbedCaption:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let i=o.getNodes().find(s=>s instanceof V);if(i){n(i.getPayload().caption??"");return}}if(this.lastSelectedYouTubeNodeKey){let i=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(i instanceof V){n(i.getPayload().caption??"");return}}n("");});}),updateYouTubeEmbedUrl:n=>{let o=false;return e.update(()=>{let i=$getSelection();if($isNodeSelection(i)){i.getNodes().forEach(s=>{if(s instanceof V){let a=Ni(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=Ni(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 i=o.getNodes().find(s=>s instanceof V);if(i){n(i.getPayload().src??"");return}}if(this.lastSelectedYouTubeNodeKey){let i=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(i instanceof V){n(i.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(i=>i instanceof V));});}),isYouTubeEmbedAlignedLeft:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){n(false);return}let i=o.getNodes().find(s=>s instanceof V);n(i?.getPayload().alignment==="left");});}),isYouTubeEmbedAlignedCenter:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){n(false);return}let i=o.getNodes().find(s=>s instanceof V);n(i?.getPayload().alignment==="center");});}),isYouTubeEmbedAlignedRight:()=>new Promise(n=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){n(false);return}let i=o.getNodes().find(s=>s instanceof V);n(i?.getPayload().alignment==="right");});})}}},Cc=new bn;var Sc="luthor:meta";var Nc=/<!--\s*luthor:meta\s+v(\d+)\s+({[\s\S]*?})\s*-->/g;function Ae(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function ft(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function Qo(r){return {type:"text",version:1,text:r,detail:0,format:0,mode:"normal",style:""}}function Yo(r){return {type:"paragraph",version:1,format:"",indent:0,direction:null,children:[Qo(r)]}}function Tc(r){return {type:"listitem",version:1,value:1,checked:null,indent:0,direction:null,format:"",children:[Qo(r)]}}function vc(r,t){return `[Unsupported ${t} preserved in ${r} metadata]`}function Vo(r,t,e){let n=t.length>0?t.join("."):"root";return `${r}:${n}:${e}`}function Lc(r,t){return r==="root"||r==="quote"?Yo(t):r==="list"?Tc(t):r==="paragraph"||r==="heading"||r==="listitem"||r==="link"||r==="autolink"||r==="code"||r==="code-highlight"?Qo(t):Yo(t)}function ki(r,t,e,n,o,i){let s=[];for(let[a,l]of r.entries()){if(!Ae(l))continue;let d=[...e,a],c=typeof l.type=="string"?l.type:"";if(!o.has(c)){let m=vc(n,c||"node"),f={id:Vo(c||"node",d,i.length+1),type:c||"node",path:d,node:ft(l),fallback:m};i.push(f),s.push(Lc(t,m));continue}let u={...l};Array.isArray(l.children)&&(u.children=ki(l.children,c,d,n,o,i)),s.push(u);}return s}function wc(){return {type:"root",version:1,format:"",indent:0,direction:null,children:[Yo("")]}}function Ri(r){let t=typeof r=="string"?JSON.parse(r):r;if(!Ae(t)||!Ae(t.root))return {root:wc()};let e=t.root,n=Array.isArray(e.children)?e.children:[];return {root:{...e,type:"root",children:n}}}function kc(r,t,e){if(t.length===0)return false;let n=r;for(let i of t.slice(0,-1)){if(!Array.isArray(n.children)||i<0||i>=n.children.length)return false;let s=n.children[i];if(!Ae(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]=ft(e),true):o===n.children.length?(n.children.push(ft(e)),true):false}function Rc(r,t){if(t.length===0)return r;let e=r;for(let n of t){if(!Array.isArray(e.children)||n<0||n>=e.children.length)return null;let o=e.children[n];if(!Ae(o))return null;e=o;}return e}function Mi(r,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 i=typeof r.format=="number"?r.format:Number(r.format??0);r.format=Number.isFinite(i)?i|o:o;continue}if(Ae(n)&&Ae(r[e])){Mi(r[e],n);continue}r[e]=ft(n);}}function Mc(r,t,e){let n=Rc(r,t);return n?(Mi(n,e),true):false}function zt(r,t){let e=Ri(r),n=Array.isArray(e.root.children)?e.root.children:[],o=[],i=ki(n,"root",[],t.mode,t.supportedNodeTypes,o);return {document:{root:{...e.root,type:"root",children:i}},envelopes:o}}function $t(r,t){if(t.length===0)return r;let n=t.map(o=>{let i=JSON.stringify(o);return `<!-- ${Sc} v1 ${i} -->`}).join(`
|
|
2
2
|
`);return r?`${r}${r.endsWith(`
|
|
3
3
|
`)?"":`
|
|
4
|
-
`}${n}`:n}function jt(r){let t=[],e=[],n=new RegExp(
|
|
5
|
-
`).replace(/\n/g,"<br>")}function
|
|
6
|
-
`)}function
|
|
7
|
-
`)},regExpStart:/^\|.*\|$/,regExpEnd:{optional:true,regExp:/^$/},replace:(r,t,e,n,o,i)=>{let s=e[0];if(!s)return;let l=[s,...o??[]].filter(p=>typeof p=="string").filter(p=>{let
|
|
8
|
-
`)}function
|
|
4
|
+
`}${n}`:n}function jt(r){let t=[],e=[],n=new RegExp(Nc.source,"g");for(let o of r.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(!Ae(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(g=>Number.isInteger(g)&&g>=0).map(g=>Number(g)),f=Ae(s.node)?s.node:null;if(!l||!a||!f){e.push("Ignoring metadata envelope with missing required fields.");continue}t.push({id:l,type:a,path:m,node:f,fallback:d,strategy:c});}catch{e.push("Ignoring malformed metadata envelope payload.");}}return {content:r.replace(n,"").trimEnd(),envelopes:t,warnings:e}}function Kt(r,t){if(t.length===0)return r;let e=ft(r.root);for(let n of t){if(n.strategy==="merge"){Mc(e,n.path,n.node);continue}if(kc(e,n.path,n.node))continue;Array.isArray(e.children)||(e.children=[]),e.children.push(ft(n.node));}return {...r,root:e}}function wi(r){return Object.keys(r).length>0}function yn(r,t){let e=Ri(r),n=Array.isArray(e.root.children)?e.root.children:[],o=[],i=typeof e.root.type=="string"?e.root.type:"root";if(i&&t.supportedNodeTypes.has(i)){let a=t.extractPatch({mode:t.mode,type:i,path:[],node:e.root});a&&wi(a)&&o.push({id:Vo(i,[],o.length+1),type:i,path:[],node:a,fallback:"",strategy:"merge"});}let s=(a,l)=>{for(let[d,c]of a.entries()){if(!Ae(c))continue;let u=[...l,d],m=typeof c.type=="string"?c.type:"";if(!m||!t.supportedNodeTypes.has(m))continue;let f=t.extractPatch({mode:t.mode,type:m,path:u,node:c});f&&wi(f)&&o.push({id:Vo(m,u,o.length+1),type:m,path:u,node:f,fallback:"",strategy:"merge"}),Array.isArray(c.children)&&s(c.children,u);}};return s(n,[]),o}var Pi=["root","paragraph","text","linebreak","tab","heading","quote","list","listitem","link","autolink","code","code-highlight","horizontalrule","image","iframe-embed","youtube-embed","table","tablerow","tablecell"],En=new Set(Pi),xn=new Set(Pi),Wo=IS_BOLD|IS_ITALIC|IS_STRIKETHROUGH|IS_CODE|IS_HIGHLIGHT|IS_UNDERLINE,Ai={root:new Set(["type","version","children","frontmatter"]),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","linkHref","linkTitle","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","headerState","format","children"])},Ii={root:new Set(["type","version","format","indent","direction","children"]),paragraph:new Set(["type","version","format","indent","direction","textFormat","textStyle","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","textFormat","textStyle","children"]),quote:new Set(["type","version","format","indent","direction","textFormat","textStyle","children"]),list:new Set(["type","version","listType","start","tag","format","indent","direction","textFormat","textStyle","style","children"]),listitem:new Set(["type","version","value","checked","format","indent","direction","textFormat","textStyle","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","textFormat","textStyle","children"]),"code-highlight":new Set(["type","version","text","highlightType"]),horizontalrule:new Set(["type","version"]),image:new Set(["type","version","src","alt","caption","linkHref","linkTitle","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","format","colSpan","rowSpan","width","backgroundColor","verticalAlign","children"])};function Jo(r,t,e){switch(t){case "textFormat":return e===0;case "textStyle":return e==="";case "format":return e===""||e===0;case "indent":return e===0;case "direction":return e===null;case "detail":return e===0;case "mode":return e==="normal";case "style":return e===""||e===null;case "target":case "rel":case "title":case "linkHref":case "linkTitle":return e===""||e===null||e===void 0;case "isUnlinked":return e===false||e===void 0;case "headerState":return e===0;case "className":return e===""||e===null||e===void 0;case "colSpan":case "rowSpan":return e===1;case "width":case "height":return e==null;case "backgroundColor":return e===null||e==="";case "verticalAlign":return e==null||e==="";case "rowStriping":return e===false;case "frozenColumnCount":case "frozenRowCount":return e===0;case "colWidths":return Array.isArray(e)&&e.length===0;case "uploading":return e===false||e===void 0;default:return false}}function Hc(r,t,e){if(Jo(r,t,e))return true;if(r==="iframe-embed"){if(t==="width")return e===640;if(t==="height")return e===360;if(t==="alignment")return e==="center"}if(r==="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 Fc(r,t,e,n){if(r==="list"&&t==="tag"){let o=typeof n?.node?.listType=="string"?n.node.listType:"";if(o==="number")return e==="ol";if(o==="bullet"||o==="check")return e==="ul"}return false}function _i(r,t,e,n){let o=Ai[r];return o?r==="text"&&t==="format"&&typeof e=="number"?(e&~Wo)===0:o.has(t)||Fc(r,t,e,n)?true:Hc(r,t,e):false}function Oi(r,t,e){let n=Ii[r];return n?n.has(t)?true:Jo(r,t,e):false}function Bc(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function zc(r){return Object.keys(r).length>0}function Di(r,t,e){let n={};for(let[o,i]of Object.entries(t)){if(o==="children"||o==="type"||i===void 0)continue;if(r==="markdown"&&e==="text"&&o==="format"&&typeof i=="number"){let a=i&~Wo;a!==0&&(n.__luthorTextFormatExtra=a);continue}(r==="markdown"?_i(e,o,i,{node:t}):Oi(e,o,i))||(n[o]=Bc(i));}return zc(n)?n:null}function qo(r,t){return Di("markdown",r,t)}function Xo(r,t){return Di("html",r,t)}var Jc={dependencies:[HorizontalRuleNode],export:r=>$isHorizontalRuleNode(r)?"---":null,regExp:/^(?:---|___)\s*$/,replace:(r,t,e)=>{r.replace($createHorizontalRuleNode());},type:"element"},qc={format:["underline"],tag:"++",type:"text-format"};function et(r){return r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Wt(r){return r.replace(/\\(["\\])/g,"$1")}function as(r){try{let t=JSON.parse(r);if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t}catch{return null}return null}var Xc={dependencies:[G],export:r=>{if(!(r instanceof G))return null;let t=r.getPayload(),e=t.caption??"",n=e?` "${et(e)}"`:"";return `[iframe](${t.src}${n})`},regExp:/^\[iframe\]\(([^)\s]+)(?:\s+"((?:[^"\\]|\\.)*)")?\)\s*(?:<!--\s*luthor:iframe\s+({[\s\S]*?})\s*-->)?\s*$/,replace:(r,t,e)=>{let[,n,o,i]=e;if(!n)return;let s=typeof o=="string"?Wt(o):"",a=640,l=360,d="center",c;if(typeof i=="string"&&i.length>0){let u=as(i);if(u){let m=Number(u.width);Number.isFinite(m)&&(a=m);let f=Number(u.height);Number.isFinite(f)&&(l=f),(u.alignment==="left"||u.alignment==="center"||u.alignment==="right")&&(d=u.alignment),typeof u.title=="string"&&(c=u.title);}}r.replace(new G({src:n,width:a,height:l,alignment:d,title:c,caption:s}));},type:"element"},Gc={dependencies:[V],export:r=>{if(!(r instanceof V))return null;let t=r.getPayload(),e=t.caption??"",n=e?` "${et(e)}"`:"";return `[youtube](${t.src}${n})`},regExp:/^\[youtube\]\(([^)\s]+)(?:\s+"((?:[^"\\]|\\.)*)")?\)\s*(?:<!--\s*luthor:youtube\s+({[\s\S]*?})\s*-->)?\s*$/,replace:(r,t,e)=>{let[,n,o,i]=e;if(!n)return;let s=typeof o=="string"?Wt(o):"",a=640,l=360,d="center",c=0;if(typeof i=="string"&&i.length>0){let u=as(i);if(u){let m=Number(u.width);Number.isFinite(m)&&(a=m);let f=Number(u.height);Number.isFinite(f)&&(l=f),(u.alignment==="left"||u.alignment==="center"||u.alignment==="right")&&(d=u.alignment);let g=Number(u.start);Number.isFinite(g)&&(c=g);}}r.replace(new V({src:n,width:a,height:l,alignment:d,caption:s,start:c}));},type:"element"};function Zc(r){return r.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\r\n?/g,`
|
|
5
|
+
`).replace(/\n/g,"<br>")}function $i(r){return r.replace(/\\\|/g,"|").replace(/<br\s*\/?>/gi,`
|
|
6
|
+
`)}function ed(r){let t=r.trim();if(!t||!/^:?-{3,}:?$/.test(t))return;let e=t.startsWith(":"),n=t.endsWith(":");return e&&n?"center":e?"left":n?"right":null}function td(r){return r==="left"?":---":r==="center"?":---:":r==="right"?"---:":"---"}function nd(r){let t=r.trim();if(!t.includes("|"))return [];let e=t;e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1));let n=[],o="",i=false;for(let s of e){if(i){o+=s,i=false;continue}if(s==="\\"){o+=s,i=true;continue}if(s==="|"){n.push($i(o.trim())),o="";continue}o+=s;}return n.push($i(o.trim())),n}function od(r){let t=r.getFormatType();return t==="left"||t==="center"||t==="right"?t:null}function rd(r,t){for(let e of r){let n=e[t];if(!n)continue;let o=od(n);if(o)return o}return null}var id={dependencies:[TableNode,TableRowNode,TableCellNode],export:r=>{if(!$isTableNode(r))return null;let t=r.getChildren();if(t.length===0)return null;let e=[];if(t.forEach(s=>{if(!$isTableRowNode(s))return;let a=[];s.getChildren().forEach(l=>{$isTableCellNode(l)&&a.push(l);}),e.push(a);}),e.length===0||!e[0])return null;let n=Math.max(...e.map(s=>s.length));if(!Number.isFinite(n)||n<1)return null;let o=s=>`| ${Array.from({length:n},(l,d)=>{let c=s[d]?.getTextContent().trim()??"";return Zc(c)}).join(" | ")} |`,i=[];i.push(o(e[0])),i.push(`| ${Array.from({length:n},(s,a)=>td(rd(e,a))).join(" | ")} |`);for(let s=1;s<e.length;s+=1)i.push(o(e[s]??[]));return i.join(`
|
|
7
|
+
`)},regExpStart:/^\|.*\|$/,regExpEnd:{optional:true,regExp:/^$/},replace:(r,t,e,n,o,i)=>{let s=e[0];if(!s)return;let l=[s,...o??[]].filter(p=>typeof p=="string").filter(p=>{let C=p.trim();return C.length>0&&C.includes("|")&&C.split("|").length>1});if(l.length<2)return;let d=l.map(p=>nd(p)).filter(p=>p.length>0);if(d.length<2||!d[0])return;let c=d[0],u=d[1]??[],m=u.map(p=>ed(p));if(!(m.length>0&&m.every(p=>p!==void 0)))return;let g=[c,...d.slice(2)],x=Math.max(c.length,u.length,...g.map(p=>p.length));if(!Number.isFinite(x)||x<1)return;let L=$createTableNodeWithDimensions(Math.max(g.length,1),x,true),b=L.getChildren();g.forEach((p,C)=>{let S=b[C];if(!$isTableRowNode(S))return;let h=S.getChildren();p.forEach((y,w)=>{let E=h[w];if(!$isTableCellNode(E))return;E.clear();let T=$createParagraphNode();y&&T.append($createTextNode(y)),E.append(T);let k=m[w]??null;(k==="left"||k==="center"||k==="right")&&E.setFormat(k);});}),r.append(L);},type:"multiline-element"};function sd(r){let t=[],e=false;for(let n of r)n!==CHECK_LIST&&(n===UNORDERED_LIST&&!e&&(t.push(CHECK_LIST),e=true),t.push(n));return e||t.push(CHECK_LIST),t}var ls=[...sd(TRANSFORMERS),qc,Jc,id,yi,Xc,Gc],cs=[...TRANSFORMERS];function ad(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function ld(r){return yn(r,{mode:"markdown",supportedNodeTypes:En,extractPatch:({node:t,type:e})=>qo(t,e)})}function ds(){return createEditor({namespace:"luthor-markdown-converter",onError:r=>{throw r},nodes:[ParagraphNode,TextNode,LineBreakNode,TabNode,HeadingNode,QuoteNode,ListNode,ListItemNode,LinkNode,AutoLinkNode,CodeNode,CodeHighlightNode,HorizontalRuleNode,K,G,V,TableNode,TableRowNode,TableCellNode]})}function us(){return createEditor({namespace:"luthor-lexical-markdown-converter",onError:r=>{throw r},nodes:[ParagraphNode,TextNode,LineBreakNode,TabNode,HeadingNode,QuoteNode,ListNode,ListItemNode,LinkNode,AutoLinkNode,CodeNode]})}function ji(r,t){let e=typeof t=="string"?t:JSON.stringify(t??{});return r.parseEditorState(e)}var cd="[[LUTHORALIGNSTART:",dd="]]",Zo="[[LUTHORALIGNEND]]",Ut=null,Cn=null;function ce(r){return r.replace(/\r\n?/g,`
|
|
8
|
+
`)}function vn(r){return r.trim().toLowerCase().replace(/^:+|:+$/g,"")}function ud(r){return Array.isArray(r)?r.map(t=>typeof t=="string"?vn(t):"").filter(t=>t.length>0):typeof r=="string"?r.split(/[,\s]+/).map(t=>vn(t)).filter(t=>t.length>0):[]}function md(r){if(typeof r.native=="string"&&r.native.length>0)return r.native;if(!Array.isArray(r.skins))return null;for(let t of r.skins){if(typeof t!="object"||t===null||Array.isArray(t))continue;let e=t;if(typeof e.native=="string"&&e.native.length>0)return e.native}return null}function Nn(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let t=r;if(!t.emojis||typeof t.emojis!="object"||Array.isArray(t.emojis))return null;let e=new Map;for(let[n,o]of Object.entries(t.emojis)){if(typeof o!="object"||o===null||Array.isArray(o))continue;let i=o,s=md(i);if(!s)continue;let a=Array.from(new Set([vn(n),...ud(i.shortcodes)].filter(l=>l.length>0)));for(let l of a)e.has(l)||e.set(l,s);}return e.size>0?e:null}function gd(){let r=globalThis.__EMOJI_MART_DATA__??globalThis.EmojiMart?.data;return Nn(r)}function fd(){try{let r=new Function("return typeof require === 'function' ? require : null;")();if(!r)return null;let t=r("@emoji-mart/data");return Nn(t.default)??Nn(t.data)??Nn(t)}catch{return null}}function pd(){let r=gd();if(r)return Ut=r,Cn="global",r;if(Cn==="global"&&(Ut=null,Cn=null),Ut)return Ut;let t=fd();return t?(Ut=t,Cn="module",t):null}function Vt(r){let t=pd();return t?r.replace(/:([a-z0-9_+-]+):/gi,(e,n)=>{let o=vn(String(n));return t.get(o)??e}):r}function Qt(r){let t=(e,n)=>{let o=e.trim();if(!o)return "";let i=n&&n.trim().length>0?` "${et(n.trim())}"`:"";return ` <!-- link:${o}${i} -->`};return r.replace(/\[!\[((?:\\.|[^\]])*)\]\(([^)\s]+)(?:\s+"((?:[^"\\]|\\.)*)")?\)\]\((<[^>\r\n]+>|[^)\s]+)(?:\s+"((?:[^"\\]|\\.)*)")?\)/g,(e,n,o,i,s,a)=>{let l=String(s??"").trim(),d=l.startsWith("<")&&l.endsWith(">")?l.slice(1,-1).trim():l;if(!d)return e;let c=`}`;return typeof i=="string"&&i.length>0&&(c+=` "${et(Wt(i))}"`),c+=")",c+=t(d,typeof a=="string"&&a.length>0?Wt(a):void 0),c})}function hd(r){let t=ce(r).split(`
|
|
9
9
|
`),e=[],n=null;for(let o of t){let i=we(o);if(i){n&&i.marker===n.marker&&i.length>=n.length?n=null:n||(n=i),e.push(o);continue}if(n){e.push(o);continue}e.push(Qt(o));}return e.join(`
|
|
10
|
-
`)}function
|
|
11
|
-
`).replace(/</gi,"<").replace(/>/gi,">").replace(/&/gi,"&").replace(/"/gi,'"').replace(/'/gi,"'").replace(/<\/?[^>]+>/g,"")}function
|
|
12
|
-
`),e=new Map,n=[],o=null;for(let a of t){let l=we(a);if(l){o&&l.marker===o.marker&&l.length>=o.length?o=null:o||(o=l),n.push(a);continue}if(o){n.push(a);continue}let d=
|
|
13
|
-
`);let i=(a,l)=>{let d=a.trim().length>0?a:l??"";return e.get(
|
|
14
|
-
`)}function
|
|
15
|
-
`),e=[],n=null;for(let o of t){let i=we(o);if(i){n&&i.marker===n.marker&&i.length>=n.length?n=null:n||(n=i),e.push(o);continue}if(n){e.push(o);continue}let s=o.match(/^(\s*(?:>\s*)+)\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*(.*)$/i);if(!s||!s[1]||!s[2]){e.push(o);continue}let a=s[2].toUpperCase(),l=
|
|
16
|
-
`)}function
|
|
10
|
+
`)}function Tn(r){return r.replace(/<strong\b[^>]*>([\s\S]*?)<\/strong>/gi,"**$1**").replace(/<b\b[^>]*>([\s\S]*?)<\/b>/gi,"**$1**").replace(/<em\b[^>]*>([\s\S]*?)<\/em>/gi,"*$1*").replace(/<i\b[^>]*>([\s\S]*?)<\/i>/gi,"*$1*").replace(/<code\b[^>]*>([\s\S]*?)<\/code>/gi,"`$1`").replace(/<\/?span\b[^>]*>/gi,"").replace(/<br\s*\/?>/gi,`
|
|
11
|
+
`).replace(/</gi,"<").replace(/>/gi,">").replace(/&/gi,"&").replace(/"/gi,'"').replace(/'/gi,"'").replace(/<\/?[^>]+>/g,"")}function or(r){return r==="left"||r==="center"||r==="right"||r==="justify"}function ms(r){let t={},e=/([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/g,n=e.exec(r);for(;n;){let o=(n[1]??"").trim().toLowerCase(),i=(n[2]??n[3]??n[4]??"").trim();o&&(t[o]=i),n=e.exec(r);}return t}function gs(r){let t=r.align?.trim().toLowerCase();if(t&&or(t))return t;let e=r.style?.toLowerCase()??"";if(e){let i=e.match(/text-align\s*:\s*(left|center|right|justify)\b/)?.[1]?.toLowerCase();if(i&&or(i))return i;let a=e.match(/float\s*:\s*(left|right)\b/)?.[1]?.toLowerCase();if(a==="left"||a==="right")return a}let n=r.class?.toLowerCase()??"";return n.includes("align-center")?"center":n.includes("align-left")?"left":n.includes("align-right")?"right":null}function Sn(r){return gs(ms(r))}function fs(r){return r.replace(/\\/g,"\\\\").replace(/\]/g,"\\]")}function ps(r){return r==="left"||r==="center"||r==="right"?r:r==="justify"?"center":null}function er(r){return r.replace(/<figcaption\b[^>]*>[\s\S]*?<\/figcaption>/gi,"")}function tr(r){let t=r.match(/<figcaption\b[^>]*>([\s\S]*?)<\/figcaption>/i);if(!t)return null;let e=t[1]??"",n=Vt(Tn(e)).replace(/\s+/g," ").trim();return n.length>0?n:null}function Yt(r,t=null,e){let n=r.match(/<img\b[^>]*>/i);if(!n)return null;let o=ms(n[0]),i=o.src?.trim();if(!i)return null;let s=o.alt?.trim()??"",a=e?.trim()||o.title?.trim()||"",l=ps(gs(o)??t),d=`}"`),d+=")",l&&(d+=` <!-- align:${l} -->`),d}function nr(r){return `${cd}${r}${dd}`}var hs={NOTE:"Note",TIP:"Tip",IMPORTANT:"Important",WARNING:"Warning",CAUTION:"Caution"},bd=new Map(Object.entries(hs).map(([r,t])=>[t.toLowerCase(),r]));function we(r){let t=r.match(/^\s{0,3}([`~]{3,})/);if(!t||!t[1])return null;let e=t[1],n=e[0];return n!=="`"&&n!=="~"?null:{marker:n,length:e.length}}function bs(r){return r.trim().replace(/\s+/g," ").toLowerCase()}function yd(r){let t=r.match(/^\s{0,3}\[([^\]]+)\]:\s*(<[^>\r\n]+>|[^\s]+)(?:\s+(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|\(([^)\r\n]*)\)))?\s*$/);if(!t||!t[1]||!t[2])return null;let e=bs(t[1]);if(!e)return null;let n=t[2].trim(),o=n.startsWith("<")&&n.endsWith(">")?n.slice(1,-1).trim():n;if(!o)return null;let i=t[3]??t[4]??t[5]??"",s=i?Wt(i.trim()):void 0;return {id:e,definition:{url:o,...s?{title:s}:{}}}}function Ed(r){let t=ce(r).split(`
|
|
12
|
+
`),e=new Map,n=[],o=null;for(let a of t){let l=we(a);if(l){o&&l.marker===o.marker&&l.length>=o.length?o=null:o||(o=l),n.push(a);continue}if(o){n.push(a);continue}let d=yd(a);if(d){e.set(d.id,d.definition);continue}n.push(a);}if(e.size===0)return n.join(`
|
|
13
|
+
`);let i=(a,l)=>{let d=a.trim().length>0?a:l??"";return e.get(bs(d))},s=[];o=null;for(let a of n){let l=we(a);if(l){o&&l.marker===o.marker&&l.length>=o.length?o=null:o||(o=l),s.push(a);continue}if(o){s.push(a);continue}let d=a;d=d.replace(/!\[([^\]]*)\]\[([^\]]*)\]/g,(c,u,m)=>{let f=String(u??""),g=i(String(m??""),f);if(!g)return c;let x=g.title?` "${et(g.title)}"`:"";return ``}),d=d.replace(/(^|[^!])\[([^\]]+)\]\[([^\]]*)\]/g,(c,u,m,f)=>{let g=String(m??""),x=i(String(f??""),g);if(!x)return c;let L=x.title?` "${et(x.title)}"`:"";return `${String(u??"")}[${g}](${x.url}${L})`}),s.push(d);}return s.join(`
|
|
14
|
+
`)}function xd(r){let t=ce(r).split(`
|
|
15
|
+
`),e=[],n=null;for(let o of t){let i=we(o);if(i){n&&i.marker===n.marker&&i.length>=n.length?n=null:n||(n=i),e.push(o);continue}if(n){e.push(o);continue}let s=o.match(/^(\s*(?:>\s*)+)\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*(.*)$/i);if(!s||!s[1]||!s[2]){e.push(o);continue}let a=s[2].toUpperCase(),l=hs[a]??a,d=(s[3]??"").trim();e.push(d.length>0?`${s[1]}**${l}:** ${d}`:`${s[1]}**${l}:**`);}return e.join(`
|
|
16
|
+
`)}function Cd(r){let t=ce(r).split(`
|
|
17
17
|
`),e=[],n=null;for(let o=0;o<t.length;o+=1){let i=t[o]??"",s=we(i);if(s){n&&s.marker===n.marker&&s.length>=n.length?n=null:n||(n=s),e.push(i);continue}if(n){e.push(i);continue}if(i.trim()!=="$$"){e.push(i);continue}let a=[],l=false;for(;o+1<t.length;){o+=1;let d=t[o]??"";if(d.trim()==="$$"){l=true;break}a.push(d);}if(!l){e.push(i),e.push(...a);continue}e.push("```math"),e.push(...a),e.push("```");}return e.join(`
|
|
18
|
-
`)}function
|
|
18
|
+
`)}function Sd(r){let t=ce(r).split(`
|
|
19
19
|
`),e=[],n=null;for(let o of t){let i=we(o);if(i){n&&i.marker===n.marker&&i.length>=n.length?n=null:n||(n=i),e.push(o);continue}if(n){e.push(o);continue}e.push(o.replace(/^(\s*(?:[-*+]\s+)?\[)X(\]\s+)/,"$1x$2"));}return e.join(`
|
|
20
|
-
`)}function
|
|
20
|
+
`)}function Ln(r){return r.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"footnote"}function Nd(r){let t=ce(r).split(`
|
|
21
21
|
`),e=[],n=[],o=new Map,i=null,s=null;for(let c of t){let u=we(c);if(u){s=null,i&&u.marker===i.marker&&u.length>=i.length?i=null:i||(i=u),e.push(c);continue}if(i){e.push(c);continue}let m=c.match(/^\[\^([^\]]+)\]:\s*(.*)$/);if(m&&m[1]){let f=m[1].trim();if(!f){e.push(c);continue}let g=(m[2]??"").trim();o.has(f)||n.push(f),o.set(f,g),s=f;continue}if(s&&/^( {2,}|\t)/.test(c)){let f=c.replace(/^( {2,}|\t)/,"").trim(),g=o.get(s)??"";o.set(s,f.length>0?`${g}
|
|
22
22
|
${f}`.trim():g);continue}s=null,e.push(c);}if(o.size===0)return e.join(`
|
|
23
|
-
`);let a=[];i=null;for(let c of e){let u=we(c);if(u){i&&u.marker===i.marker&&u.length>=i.length?i=null:i||(i=u),a.push(c);continue}if(i){a.push(c);continue}let m=c.replace(/\[\^([^\]\s]+)\]/g,(f,g)=>{let
|
|
24
|
-
`);let l=n.map((c,u)=>{let m=
|
|
23
|
+
`);let a=[];i=null;for(let c of e){let u=we(c);if(u){i&&u.marker===i.marker&&u.length>=i.length?i=null:i||(i=u),a.push(c);continue}if(i){a.push(c);continue}let m=c.replace(/\[\^([^\]\s]+)\]/g,(f,g)=>{let x=String(g??"").trim();if(!x||!o.has(x))return f;let L=Ln(x);return `[^${x}](#fn-${L})`});a.push(m);}if(n.length===0)return a.join(`
|
|
24
|
+
`);let l=n.map((c,u)=>{let m=Ln(c),g=(o.get(c)??"").trim().replace(/\n+/g," ").trim();return `${u+1}. <a id="fn-${m}"></a> **[^${c}]**${g?` ${g}`:""}`});return `${a.join(`
|
|
25
25
|
`).replace(/\n+$/g,"")}
|
|
26
26
|
|
|
27
27
|
---
|
|
@@ -30,42 +30,42 @@ ${f}`.trim():g);continue}s=null,e.push(c);}if(o.size===0)return e.join(`
|
|
|
30
30
|
|
|
31
31
|
${l.join(`
|
|
32
32
|
`)}
|
|
33
|
-
`}function
|
|
34
|
-
`),e=[],n=null;for(let o of t){let i=we(o);if(i){n&&i.marker===n.marker&&i.length>=n.length?n=null:n||(n=i),e.push(o);continue}if(n){e.push(o);continue}let s=o.match(/^(\s*(?:>\s*)+)\*\*(Note|Tip|Important|Warning|Caution):\*\*(?:\s*(.*))?$/i);if(!s||!s[1]||!s[2]){e.push(o);continue}let a=
|
|
35
|
-
`)}function
|
|
33
|
+
`}function Td(r){let t=ce(r).split(`
|
|
34
|
+
`),e=[],n=null;for(let o of t){let i=we(o);if(i){n&&i.marker===n.marker&&i.length>=n.length?n=null:n||(n=i),e.push(o);continue}if(n){e.push(o);continue}let s=o.match(/^(\s*(?:>\s*)+)\*\*(Note|Tip|Important|Warning|Caution):\*\*(?:\s*(.*))?$/i);if(!s||!s[1]||!s[2]){e.push(o);continue}let a=bd.get(s[2].toLowerCase())??s[2].toUpperCase(),l=(s[3]??"").trim();e.push(l.length>0?`${s[1]}[!${a}] ${l}`:`${s[1]}[!${a}]`);}return e.join(`
|
|
35
|
+
`)}function vd(r){let t=r.body.split(`
|
|
36
36
|
`).map(o=>o.trim()).filter(o=>o.length>0);if(t.length===0)return `[^${r.id}]:`;let[e,...n]=t;return n.length===0?`[^${r.id}]: ${e}`:`[^${r.id}]: ${e}
|
|
37
37
|
${n.map(o=>` ${o}`).join(`
|
|
38
|
-
`)}`}function
|
|
39
|
-
`),e=-1,n=null;for(let g=0;g<t.length;g+=1){let
|
|
40
|
-
`);let o=e+1;for(;o<t.length&&(t[o]??"").trim()==="";)o+=1;let i=[],s=o;for(;s<t.length;){let g=t[s]??"";if(g.trim()===""){s+=1;continue}let
|
|
38
|
+
`)}`}function Ld(r){let t=ce(r).split(`
|
|
39
|
+
`),e=-1,n=null;for(let g=0;g<t.length;g+=1){let x=t[g]??"",L=we(x);if(L){n&&L.marker===n.marker&&L.length>=n.length?n=null:n||(n=L);continue}n||x.trim().toLowerCase()==="### footnotes"&&(e=g);}if(e<0)return t.join(`
|
|
40
|
+
`);let o=e+1;for(;o<t.length&&(t[o]??"").trim()==="";)o+=1;let i=[],s=o;for(;s<t.length;){let g=t[s]??"";if(g.trim()===""){s+=1;continue}let x=g.match(/^\s*\d+\.\s*<a id="fn-([^"]+)"><\/a>\s+\*\*\[\^([^\]]+)\]\*\*(?:\s*(.*))?$/);if(!x||!x[1]||!x[2])break;let L=x[2].trim();if(!L)break;let b=Ln(L);if(x[1].trim()!==b)break;let C=[],S=(x[3]??"").trim();for(S.length>0&&C.push(S),s+=1;s<t.length;){let h=t[s]??"";if(/^( {2,}|\t)/.test(h)){C.push(h.replace(/^( {2,}|\t)/,"").trim()),s+=1;continue}break}i.push({id:L,body:C.join(`
|
|
41
41
|
`).trim()});}if(i.length===0||t.slice(s).some(g=>g.trim().length>0))return t.join(`
|
|
42
42
|
`);let l=e;for(;l>0&&(t[l-1]??"").trim()==="";)l-=1;if(l>0&&(t[l-1]??"").trim()==="---")for(l-=1;l>0&&(t[l-1]??"").trim()==="";)l-=1;let d=t.slice(0,l);for(;d.length>0&&(d[d.length-1]??"").trim()==="";)d.pop();let c=new Set(i.map(g=>g.id)),u=d.join(`
|
|
43
|
-
`).replace(/\[\^([^\]\s]+)\]\(#fn-([a-z0-9_-]+)\)/gi,(g,
|
|
43
|
+
`).replace(/\[\^([^\]\s]+)\]\(#fn-([a-z0-9_-]+)\)/gi,(g,x,L)=>{let b=String(x??"").trim(),p=String(L??"").trim().toLowerCase();if(!b||!c.has(b))return g;let C=Ln(b);return p!==C?g:`[^${b}]`}),m=i.map(g=>vd(g)).join(`
|
|
44
44
|
`),f=u.trimEnd();return f?`${f}
|
|
45
45
|
|
|
46
46
|
${m}
|
|
47
47
|
`:`${m}
|
|
48
|
-
`}function
|
|
49
|
-
`).filter(n=>{let o=
|
|
50
|
-
`)}var
|
|
51
|
-
`),e=[],n=null;for(let o of t){let i=we(o);if(i){n&&i.marker===n.marker&&i.length>=n.length?n=null:n||(n=i),e.push(o);continue}if(n){e.push(o);continue}let s=o.match(/^(\s*)(.*\S)\s*<!--\s*align\s*:\s*(left|center|right)\s*-->\s*$/i);if(!s||!s[2]||!s[3]){e.push(o);continue}let a=s[1]??"",l=s[2].trim(),d=s[3].toLowerCase();if(d!=="left"&&d!=="center"&&d!=="right"||!
|
|
52
|
-
`)}function
|
|
48
|
+
`}function wd(r){return ce(r).split(`
|
|
49
|
+
`).filter(n=>{let o=rr(n);return o.length===0?true:sr(o)?false:ir(o)===null}).join(`
|
|
50
|
+
`)}var kd=/^!\[((?:\\.|[^\]])*)\]\(([^)\s]+)(?:\s+"((?:[^"\\]|\\.)*)")?\)$/,Rd=/^\[!\[((?:\\.|[^\]])*)\]\(([^)\s]+)(?:\s+"((?:[^"\\]|\\.)*)")?\)\]\((<[^>\r\n]+>|[^)\s]+)(?:\s+"((?:[^"\\]|\\.)*)")?\)$/;function Md(r){let t=r.trim();return t.length===0?false:kd.test(t)||Rd.test(t)}function Pd(r){let t=ce(r).split(`
|
|
51
|
+
`),e=[],n=null;for(let o of t){let i=we(o);if(i){n&&i.marker===n.marker&&i.length>=n.length?n=null:n||(n=i),e.push(o);continue}if(n){e.push(o);continue}let s=o.match(/^(\s*)(.*\S)\s*<!--\s*align\s*:\s*(left|center|right)\s*-->\s*$/i);if(!s||!s[2]||!s[3]){e.push(o);continue}let a=s[1]??"",l=s[2].trim(),d=s[3].toLowerCase();if(d!=="left"&&d!=="center"&&d!=="right"||!Md(l)){e.push(o);continue}e.push(`${a}<p align="${d}">`),e.push(`${a}${l}`),e.push(`${a}</p>`);}return e.join(`
|
|
52
|
+
`)}function Ad(r,t,e){let n=Td(r),o=Ld(n),i=wd(o);return t==="github"&&e==="none"?Pd(i):i}function Id(r){let t=ce(r),e=t.split(`
|
|
53
53
|
`);if(e.length<3)return {frontmatter:null,content:t};if((e[0]??"").replace(/^\uFEFF/,"").trim()!=="---")return {frontmatter:null,content:t};let o=-1;for(let l=1;l<e.length;l+=1){let d=(e[l]??"").trim();if(d==="---"||d==="..."){o=l;break}}if(o<2)return {frontmatter:null,content:t};let i=e.slice(1,o).join(`
|
|
54
54
|
`);if(!/^[^#\n]*:/m.test(i))return {frontmatter:null,content:t};let s=e.slice(0,o+1).join(`
|
|
55
55
|
`).trim(),a=e.slice(o+1).join(`
|
|
56
|
-
`);return {frontmatter:s,content:a}}function
|
|
56
|
+
`);return {frontmatter:s,content:a}}function _d(r){let t=Id(r),e=hd(t.content),n=Sd(e),o=Ed(n),i=xd(o),s=Cd(i),a=Nd(s);return {frontmatter:t.frontmatter,content:a}}function Od(r,t){return !t||!Ze(r.root)||(r.root.frontmatter=t),r}function Dd(r){if(!Ze(r)||!Ze(r.root))return {document:r,frontmatter:null};let t=ad(r);if(!Ze(t.root))return {document:t,frontmatter:null};let e=typeof t.root.frontmatter=="string"?ce(t.root.frontmatter).trim():"";return delete t.root.frontmatter,{document:t,frontmatter:e.length>0?e:null}}function Ki(r,t){if(!t)return r;let e=ce(t).trim(),n=ce(r).trim();return n?`${e}
|
|
57
57
|
|
|
58
58
|
${n}`:`${e}
|
|
59
|
-
`}function
|
|
60
|
-
`),e=[];for(let n=0;n<t.length;n+=1){let o=t[n]??"",i=o.trim();if(i.length===0){e.push(o);continue}let s=i.match(/^<(div|p|figure)\b([^>]*)>([\s\S]*?)<\/\1>$/i);if(s){let c=
|
|
61
|
-
`),m=
|
|
62
|
-
`));u&&e.push(u);continue}if(/^<source\b/i.test(i)||/^<\/?picture\b/i.test(i)||/^<\/?figcaption\b/i.test(i)||/^<\/?figure\b/i.test(i))continue;if(i.match(/^<(div|p)\b([^>]*)>$/i)){let c=
|
|
63
|
-
`)}function
|
|
64
|
-
`;continue}if(e.type==="tab"){t+=" ";continue}return null}return t}function
|
|
65
|
-
`),e=[];return t.forEach((n,o)=>{n.length>0&&e.push({type:"text",version:1,text:n,detail:0,format:0,mode:"normal",style:""}),o<t.length-1&&e.push({type:"linebreak",version:1});}),e}function
|
|
66
|
-
`),o=[],i=false,s=null;for(let a of n){let l=
|
|
67
|
-
`)),{keepNode:true,consumedMarker:true,alignmentForNode:s})}function nu(r,t){let e=typeof r.type=="string"?r.type:"";if(e==="image"){let n=ws(t);if(!n)return;let o=r.alignment;(o==null||o===""||o==="none")&&(r.alignment=n);return}(e==="paragraph"||e==="heading"||e==="quote"||e==="list"||e==="table"||e==="code")&&(r.format=t);}function ou(r){if(!et(r.root)||!Array.isArray(r.root.children))return r;let t=[],e=[];for(let n of r.root.children){if(!et(n)){e.push(n);continue}let o=tu(n,t);if(!o.keepNode)continue;let i=eu(n);if(i){i.type==="start"?t.push(i.alignment):t.pop();continue}let s=o.alignmentForNode??t[t.length-1];s&&nu(n,s),e.push(n);}return r.root.children=e,r}function Ps(r){return r!=="none"}function As(r){let t=r?.bridgeFlavor??"github";return t==="luthor"?"github":t}function ru(r,t){if(As(t)==="lexical-native"){let f=Ns();return f.update(()=>{$convertFromMarkdownString(ce(r),Cs);},{discrete:true}),f.getEditorState().toJSON()}let n=Ps(t?.metadataMode),{content:o,envelopes:i,warnings:s}=n?jt(r):{content:r,envelopes:[],warnings:[]};if(n)for(let f of s)console.warn(`[luthor-headless] ${f}`);let a=qd(o),l=n?a.content:Xd(a.content),d=Ss();d.update(()=>{$convertFromMarkdownString(l,xs);},{discrete:true});let c=d.getEditorState().toJSON(),u=n?c:ou(c),m=Ut(u,i);return Jd(m,a.frontmatter)}function iu(r,t){let e=As(t);if(e==="lexical-native"){let f=Ns(),g=es(f,r);return f.setEditorState(g,{tag:"history-merge"}),g.read(()=>$convertToMarkdownString(Cs))}let{document:n,frontmatter:o}=Gd(r),i=Ps(t?.metadataMode),s=zt(n,{mode:"markdown",supportedNodeTypes:Cn}),a=i?Nd(n):[],l=Ss(),d=es(l,s.document);l.setEditorState(d,{tag:"history-merge"});let c=d.read(()=>$convertToMarkdownString(xs)),u=Qd(c,e,t?.metadataMode);if(!i)return ts(u,o);let m=$t(u,[...s.envelopes,...a]);return ts(m,o)}function vu(r){return xn(r,{mode:"html",supportedNodeTypes:Sn,extractPatch:({node:t,type:e})=>rr(t,e)})}var wu=new Set(["pre","script","style","textarea"]);function Ds(){return createEditor({namespace:"luthor-html-converter",onError:r=>{throw r},nodes:[ParagraphNode,TextNode,LineBreakNode,TabNode,HeadingNode,QuoteNode,ListNode,ListItemNode,LinkNode,AutoLinkNode,CodeNode,CodeHighlightNode,HorizontalRuleNode,U,X,V,TableNode,TableRowNode,TableCellNode]})}function ku(r,t){let e=typeof t=="string"?t:JSON.stringify(t??{});return r.parseEditorState(e)}function Hs(){if(typeof document>"u"||typeof window>"u"||typeof DOMParser>"u")throw new Error("HTML conversion requires browser DOM APIs (document/window/DOMParser).")}function Is(r){if(!r)return false;let t=r.getAttribute("style");return t?/\bwhite-space\s*:\s*(pre|pre-wrap|pre-line)\b/i.test(t):false}function Ru(r){let t=r.parentElement;for(;t;){if(wu.has(t.tagName.toLowerCase()))return true;t=t.parentElement;}return false}function _s(r,t){let e=t==="previous"?r.previousSibling:r.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 Mu(r,t){if(!r||!t||/\s$/.test(r)||/^\s/.test(t))return false;let e=r.at(-1)??"",n=t[0]??"";return !(!e||!n||/^[,.;:!?)]$/.test(n)||/^[([{"']$/.test(e))}var Pu=new Set(["p","h1","h2","h3","h4","h5","h6","blockquote","li","td","th","pre","code"]),Au=new Set(["div","section","article","main","header","footer","aside","nav"]);function Iu(r){return r==="left"||r==="center"||r==="right"||r==="justify"}function Rn(r,t){let e=r.getAttribute("style")?.trim()??"";if(!e){r.setAttribute("style",t);return}let n=e.endsWith(";")?e:`${e};`;r.setAttribute("style",`${n} ${t}`);}function Os(r,t){if(t==="center"){Rn(r,"display:block; margin-left:auto; margin-right:auto;");return}if(t==="left"||t==="right"){Rn(r,`float:${t};`);return}}function _u(r){let t=Array.from(r.querySelectorAll("[align]"));for(let e of t){let n=e.getAttribute("align")?.trim().toLowerCase()??"";if(!Iu(n))continue;let o=e.tagName.toLowerCase();if(o==="img"){Os(e,n),e.removeAttribute("align");continue}if(Rn(e,`text-align:${n};`),Au.has(o))for(let i of Array.from(e.children)){if(!(i instanceof HTMLElement))continue;let s=i.tagName.toLowerCase();if(Pu.has(s)){Rn(i,`text-align:${n};`);continue}s==="img"&&Os(i,n);}e.removeAttribute("align");}}function Ou(r){let t=Array.from(r.querySelectorAll("picture"));for(let e of t){let n=e.querySelector("img");if(!n){e.remove();continue}e.replaceWith(n.cloneNode(true));}}function Du(r){let t=Array.from(r.querySelectorAll("[style]"));for(let i of t){if(!Is(i)||i.childNodes.length!==1||i.firstChild?.nodeType!==Node.TEXT_NODE)continue;let s=i.firstChild;/[\r\n]/.test(s.data)&&(s.data=s.data.replace(/^\s*\r?\n\s*/,"").replace(/\r?\n\s*$/,""));}let e=r.createTreeWalker(r.body,NodeFilter.SHOW_TEXT),n=[],o=e.nextNode();for(;o;){let i=o,s=i.data,a=i.parentElement;if(!/^[\s\r\n\t]+$/.test(s)||!/[\r\n]/.test(s)||Ru(i)||Is(a)){o=e.nextNode();continue}let l=_s(i,"previous"),d=_s(i,"next"),c=l?.textContent??"",u=d?.textContent??"";Mu(c,u)?n.push({node:i,replacement:" "}):n.push({node:i,replacement:null}),o=e.nextNode();}for(let i of n)if(i.node.parentNode){if(i.replacement===null){i.node.parentNode.removeChild(i.node);continue}i.node.data=i.replacement;}}function Fs(r){return r!=="none"}function Hu(r,t){Hs();let e=Fs(t?.metadataMode),{content:n,envelopes:o,warnings:i}=e?jt(r):{content:r,envelopes:[],warnings:[]};if(e)for(let l of i)console.warn(`[luthor-headless] ${l}`);let s=Ds();s.update(()=>{let l=new DOMParser().parseFromString(n,"text/html");Ou(l),_u(l),Du(l);let d=$generateNodesFromDOM(s,l),c=$getRoot();c.clear(),c.append(...d);},{discrete:true});let a=s.getEditorState().toJSON();return Ut(a,o)}function Fu(r,t){Hs();let e=Fs(t?.metadataMode),n=zt(r,{mode:"html",supportedNodeTypes:Sn}),o=e?vu(r):[],i=Ds(),s=ku(i,n.document);i.setEditorState(s,{tag:"history-merge"});let a=s.read(()=>$generateHtmlFromNodes(i,null));return e?$t(a,[...n.envelopes,...o]):a}var Mn=class extends ae{constructor(){super("bold");}},Bu=new Mn;var Pn=class extends ae{constructor(){super("italic");}},zu=new Pn;var $u={format:["underline"],tag:"++",type:"text-format"},An=class extends ae{constructor(){super("underline");}getMarkdownTransformers(){return [$u]}},ju=new An;var In=class extends ae{constructor(){super("strikethrough");}},Uu=new In;var _n=class extends M{constructor(){super("link",["toolbar"]);T(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,i=>{let s=i.clipboardData;if(!s)return false;let a=s.getData("text/plain");return a&&this.config.validateUrl(a)&&this.config.autoLinkUrls?(i.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:i})=>{i.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),i=(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){i(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}i(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(),i=e.getNodes(),s=[n,o,...i];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);});})}}},Xu=new _n;var am={dependencies:[HorizontalRuleNode],export:r=>$isHorizontalRuleNode(r)?"---":null,regExp:/^(?:---|___)\s*$/,replace:(r,t,e,n)=>{let o=$createHorizontalRuleNode();r.replace(o),n||dm(o);},type:"element"},lm=[am],cm=/^(?:---|___)$/;function dm(r){let t=r.getNextSibling();if(t&&$isParagraphNode(t)){t.selectStart();return}let e=$createParagraphNode();r.insertAfter(e),e.selectStart();}var On=class extends M{constructor(){super("horizontalRule",["toolbar"]);}register(t){let e=registerMarkdownShortcuts(t,lm),n=t.registerCommand(KEY_ENTER_COMMAND,o=>{if(o?.shiftKey)return false;let i=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(!cm.test(c))return;i=true;let u=$createHorizontalRuleNode();l.replace(u),u.selectNext();}),i},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 i=n.getNodes().some(s=>$isHorizontalRuleNode(s));e(i);}else e(false);});})}}},um=new On;var Qs=[{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"}],fm={value:"default",label:"Default",fontFamily:"inherit"};function Vs(r){return r.trim().toLowerCase()}function pm(r){return /^[a-z0-9][a-z0-9-]*$/i.test(r)}function hm(r){let t=new Set,e=[];for(let o of r){let i=o.value.trim(),s=o.label.trim(),a=o.fontFamily.trim();if(!i||!s||!a||!pm(i))continue;let l=Vs(i);t.has(l)||(t.add(l),e.push({value:i,label:s,fontFamily:a,cssImportUrl:o.cssImportUrl?.trim()||void 0}));}return e.length===0?Qs:e.some(o=>Vs(o.value)==="default")?e:[fm,...e]}var Dn=class extends M{constructor(){super("fontFamily",["toolbar"]);T(this,"loadedFontUrls",new Set);this.config={options:Qs,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=hm(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 i=$getSelectionStyleValueForProperty(o,"font-family","");n=this.normalizeFontValue(i).length>0;}),n}getCurrentFontFamilyValue(e){let n=null;return e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let i=$getSelectionStyleValueForProperty(o,"font-family","");if(!i){n="default";return}let s=this.normalizeFontValue(i);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);}},bm=new Dn;var Js=[{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"}],Em={value:"default",label:"Default",fontSize:"inherit"};function qs(r){return r.trim().toLowerCase()}function xm(r){return /^[a-z0-9][a-z0-9-]*$/i.test(r)}function Cm(r){let t=new Set,e=[];for(let o of r){let i=String(o.value).trim(),s=String(o.label).trim(),a=String(o.fontSize).trim();if(!i||!s||!a||!xm(i))continue;let l=qs(i);t.has(l)||(t.add(l),e.push({value:i,label:s,fontSize:a}));}return e.length===0?Js:e.some(o=>qs(o.value)==="default")?e:[Em,...e]}var Hn=class extends M{constructor(){super("fontSize",["toolbar"]),this.config={options:Js,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}configure(t){let e={...t};return t.options&&(e.options=Cm(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",""),i=this.normalizeValue(o);e=i.length>0&&i!=="inherit";}),e}getCurrentFontSizeValue(t){let e=null;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"font-size",""),i=this.normalizeValue(o);if(!i||i==="inherit"){e="default";return}e=this.config.options.find(a=>this.normalizeValue(a.value)===i?true:this.normalizeValue(a.fontSize)===i)?.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,"")}},Sm=new Hn;var Xs=[{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"}],Nr={value:"default",label:"Default",lineHeight:"1.5"},Lm=1;function Sr(r){return r.trim().toLowerCase()}function vm(r){return Sr(r)==="default"?true:Bn(r)!==null}function Bn(r){let t=r.trim();if(!/^\d*\.?\d+$/.test(t))return null;let e=Number(t);return !Number.isFinite(e)||e<Lm?null:e.toString()}function wm(r,t){let e=new Set,n=[];for(let i of r){let s=i.value.trim(),a=i.label.trim(),l=Sr(s);if(!s||!a||!vm(s)||e.has(l))continue;if(l==="default"){e.add(l),n.push({value:s,label:a,lineHeight:t});continue}let d=Bn(String(i.lineHeight));d&&(e.add(l),n.push({value:s,label:a,lineHeight:d}));}return n.length===0?Xs:n.some(i=>Sr(i.value)==="default")?n:[{...Nr,lineHeight:t},...n]}function km(r){return Bn(r)??Nr.lineHeight}var Fn=class extends M{constructor(){super("lineHeight",["toolbar"]),this.config={options:Xs,defaultLineHeight:Nr.lineHeight,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}configure(t){let e={...t},n=km(String(t.defaultLineHeight??this.config.defaultLineHeight));return e.defaultLineHeight=n,t.options&&(e.options=wm(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 i of o){let s=this.withStyleProperty(i.getStyle(),"line-height",e);i.setStyle(s);for(let a of i.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"),i=t.split(";").map(a=>a.trim()).filter(a=>a.length>0).filter(a=>!o.test(a)),s=n.trim();return s.length>0&&i.push(`${e}: ${s}`),i.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 i=o??$getSelectionStyleValueForProperty(n,"line-height",""),s=this.normalizeValue(i);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 i=o??$getSelectionStyleValueForProperty(n,"line-height",""),s=this.normalizeValue(i);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 i of e){let s=this.readStyleProperty(i.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()??""}},Rm=new Fn;var Pm=[{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"}],zn=class extends M{constructor(){super("textColor",["toolbar"]),this.config={options:Pm,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 i=this.normalizeValue(o);e=this.config.options.find(a=>this.normalizeValue(a.value)===i?true:this.normalizeValue(a.color)===i)?.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}},Am=new zn;var _m=[{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"}],$n=class extends M{constructor(){super("textHighlight",["toolbar"]),this.config={options:_m,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",""),i=this.normalizeValue(o);e=i.length>0&&i!=="transparent";}),e}getCurrentTextHighlightValue(t){let e=null;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"background-color",""),i=this.normalizeValue(o);if(!i||i==="transparent"){e="default";return}e=this.config.options.find(a=>this.normalizeValue(a.value)===i?true:this.normalizeValue(a.backgroundColor)===i)?.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}},Om=new $n;var jn=class extends ae{constructor(){super("subscript");}},Dm=new jn;var Un=class extends ae{constructor(){super("superscript");}},Hm=new Un;function Kn(r,t,e){return r<t?t:r>e?e:r}function jm({items:r,position:t,onClose:e,className:n,style:o,itemClassName:i,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:r.map((d,c)=>d.separator?jsx("div",{className:"h-px bg-border my-1"},c):jsxs("div",{className:d.disabled?a:i,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 Yn=class{constructor(t,e={}){T(this,"providers",new Map);T(this,"currentMenu",null);T(this,"listeners",new Set);T(this,"editor");T(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((i,s)=>(s.priority||0)-(i.priority||0));for(let i of o){let s={editor:this.editor,target:e,selection:n,event:t};if(i.canHandle(s)){this.config.preventDefault!==false&&t.preventDefault();let a=i.getItems(s);if(a.length>0){let l=e.getBoundingClientRect();this.showMenu({items:a,position:{x:t.clientX,y:t.clientY},renderer:i.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,i=e.getBoundingClientRect();return {...t,position:{x:i.left+n,y:i.top+o}}}};function Um({extension:r}){let{config:t}=Oe(),[e,n]=useState(null),o=t?.theme?.contextMenu||{},i=r.config,s={container:i?.theme?.container||o.container||"luthor-context-menu",item:i?.theme?.item||o.item||"luthor-context-menu-item",itemDisabled:i?.theme?.itemDisabled||o.itemDisabled||"luthor-context-menu-item-disabled"},a={container:{...i?.styles?.container,...o.styles?.container},item:{...i?.styles?.item,...o.styles?.item},itemDisabled:{...i?.styles?.itemDisabled,...o.styles?.itemDisabled}};if(useEffect(()=>r.subscribe(n),[r]),!e)return null;let l=e.renderer||r.config.defaultRenderer,d=r.manager?.getPortalContainer()??null,c=220,u=Math.min(420,18+e.items.length*34),m=8,f=(()=>{if(!d){let b=typeof window>"u"?0:window.innerWidth,E=typeof window>"u"?0:window.innerHeight;return {width:b,height:E}}let N=d.getBoundingClientRect();return {width:N.width,height:N.height}})(),g=Math.max(0,f.width-m*2),y=Math.max(0,f.height-m*2),C=Math.min(c,g||c),h=Math.min(u,y||u),p=(()=>{if(!d){let I=Math.max(m,f.width-C-m),D=Math.max(m,f.height-h-m);return {x:Kn(e.position.x,m,I),y:Kn(e.position.y,m,D)}}let N=d.getBoundingClientRect(),b=e.position.x-N.left+d.scrollLeft,E=e.position.y-N.top+d.scrollTop,w=d.scrollLeft+m,x=d.scrollTop+m,L=Math.max(w,d.scrollLeft+N.width-C-m),k=Math.max(x,d.scrollTop+N.height-h-m);return {x:Kn(b,w,L),y:Kn(E,x,k)}})(),S=d?{position:"absolute",...a.container,maxWidth:g>0?g:void 0,maxHeight:y>0?y:void 0,overflowY:"auto",overscrollBehavior:"contain"}:{...a.container,maxWidth:g>0?g:void 0,maxHeight:y>0?y:void 0,overflowY:"auto",overscrollBehavior:"contain"};return createPortal(jsx(l,{items:e.items,position:p,onClose:()=>r.manager?.hideMenu(),className:s.container,style:S,itemClassName:s.item,itemStyle:a.item,disabledItemClassName:s.itemDisabled,disabledItemStyle:a.itemDisabled}),d??document.body)}var Vn=class extends M{constructor(e={}){super("contextMenu",["toolbar"]);T(this,"manager",null);T(this,"pendingListeners",new Set);this.config={defaultRenderer:jm,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 Yn(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();},i=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",i),window.addEventListener("scroll",s,true),window.addEventListener("resize",s),()=>{a.removeEventListener("contextmenu",n),document.removeEventListener("mousedown",o),document.removeEventListener("keydown",i),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 Yn(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(Um,{extension:this},"context-menu")]}subscribe(e){return this.manager?this.manager.subscribe(e):(this.pendingListeners.add(e),()=>{this.pendingListeners.delete(e);})}},kr=new Vn;function oa(r,t,e){return r<t?t:r>e?e:r}function Jn(){let r=$getSelection();if($isTableSelection(r)){let t=r.getNodes().find(e=>$isTableCellNode(e));if($isTableCellNode(t))return t}if($isRangeSelection(r)){let t=r.anchor.getNode(),e=$findCellNode(t);if($isTableCellNode(e))return e}return null}function og({headersEnabled:r,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:r,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 rg({extension:r}){let{editor:t}=Oe(),[e,n]=useState(()=>t?.isEditable()??true),[o,i]=useState(null),[s,a]=useState(false),[l,d]=useState(false),[c,u]=useState(null),m=useRef(null),f=useRef(null),g=p=>{!t||!t.isEditable()||t.update(()=>{let S=Jn();S&&(S.selectStart(),p(S));});},y=p=>{g(S=>{$getTableNodeFromLexicalNodeOrThrow(S).getChildren().filter(E=>$isTableRowNode(E)).forEach((E,w)=>{E.getChildren().filter(L=>$isTableCellNode(L)).forEach(L=>{let k=p&&w===0?TableCellHeaderStates.ROW:TableCellHeaderStates.NO_STATUS;L.setHeaderStyles(k,TableCellHeaderStates.ROW);});});});};if(useEffect(()=>{if(t)return t.registerEditableListener(p=>{n(p),p||(a(false),u(null));})},[t]),useEffect(()=>{if(!t)return;let p=t.getRootElement(),S=p?.closest(".luthor-editor-wrapper")||p?.parentElement||null;i(S);let N=()=>{t.getEditorState().read(()=>{if(!t.isEditable()){a(false),u(null);return}let w=$getSelection();if($isRangeSelection(w)&&!w.isCollapsed()){a(false),u(null);return}let x=Jn();if(!x){a(false),u(null);return}let k=t.getElementByKey(x.getKey())?.closest("table");if(!k||!S){a(false),u(null);return}let Y=$getTableNodeFromLexicalNodeOrThrow(x).getChildren().filter(Ye=>$isTableRowNode(Ye))[0]?.getChildren().filter(Ye=>$isTableCellNode(Ye))||[],ee=Y.length>0&&Y.every(Ye=>Ye.hasHeaderState(TableCellHeaderStates.ROW));d(ee);let B=S.getBoundingClientRect(),z=k.getBoundingClientRect(),W=m.current?.getBoundingClientRect(),j=W?.width??520,K=W?.height??44,O=12,J=Math.max(0,B.width-O*2),Z=Math.min(j,J||j)/2,ge=z.left-B.left+z.width/2,be=O+Z,$e=Math.max(be,B.width-O-Z),Te=oa(ge,be,$e),je=z.top-B.top,Ue=B.bottom-z.bottom,fe=je>=K+O,re=Ue>=K+O,_e=fe||!re?z.top-B.top-12-K:z.bottom-B.top+12,Ke=O,Fo=Math.max(Ke,B.height-K-O),Bo=oa(_e,Ke,Fo);u({x:Te,y:Bo,maxWidth:J}),a(true);});};N();let b=t.registerUpdateListener(()=>{N();}),E=()=>{f.current===null&&(f.current=window.requestAnimationFrame(()=>{f.current=null,N();}));};return window.addEventListener("scroll",E,true),window.addEventListener("resize",E),()=>{b(),window.removeEventListener("scroll",E,true),window.removeEventListener("resize",E),f.current!==null&&(cancelAnimationFrame(f.current),f.current=null);}},[t]),!e||!o||!s||!c||typeof document>"u")return null;let C={insertRowAbove:()=>g(()=>$insertTableRowAtSelection(false)),insertRowBelow:()=>g(()=>$insertTableRowAtSelection(true)),insertColumnLeft:()=>g(()=>$insertTableColumnAtSelection(false)),insertColumnRight:()=>g(()=>$insertTableColumnAtSelection(true)),deleteSelectedColumn:()=>g(()=>$deleteTableColumnAtSelection()),deleteSelectedRow:()=>g(()=>$deleteTableRowAtSelection()),deleteTable:()=>g(p=>{$getTableNodeFromLexicalNodeOrThrow(p).remove();})},h=r.config.tableBubbleRenderer?r.config.tableBubbleRenderer({headersEnabled:l,setHeadersEnabled:p=>{d(p),y(p);},actions:C}):jsx(og,{headersEnabled:l,setHeadersEnabled:p=>{d(p),y(p);},actions:C});return createPortal(jsx("div",{ref:m,className:"luthor-table-bubble-menu",style:{position:"absolute",left:c.x,top:c.y,transform:"translateX(-50%)",maxWidth:c.maxWidth>0?c.maxWidth:void 0,overflowX:"auto",zIndex:"var(--luthor-z-menu, 460)"},onMouseDown:p=>p.preventDefault(),children:h}),o)}var Gn=class extends M{constructor(e){super("table",["toolbar"]);T(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||kr;if(o){let i={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(i),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:i=3,includeHeaders:s=false}=n;e.update(()=>{let a=$getSelection();if($isRangeSelection(a)){let l=$createTableNodeWithDimensions(o,i,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=Jn();if(!n)return;let o=$getTableNodeFromLexicalNodeOrThrow(n),i=$getTableRowIndexFromTableCellNode(n),s=o.getChildren()[i];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=Jn();if(!n)return;let o=$getTableNodeFromLexicalNodeOrThrow(n),i=$getTableColumnIndexFromTableCellNode(n),a=o.getChildren().filter(c=>$isTableRowNode(c)).map(c=>c.getChildren()[i]).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(i=>$isTableCellNode(i));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(),i=n.focus.getNode();return $isTableCellNode(o)||$isTableCellNode(i)}catch{return false}})}}getPlugins(){return [jsx(TablePlugin,{},"table-plugin"),jsx(rg,{extension:this},"table-quick-actions-plugin")]}},ig=new Gn;var ma=9,yt={"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"]},tn={"disc-circle-square":["disc","circle","square"],"arrow-diamond-disc":['"\u25B8"','"\u25C6"',"disc"],"square-square-square":["square","square","square"],"arrow-circle-square":['"\u25B8"',"circle","square"]},Et="decimal-alpha-roman",ga="disc-circle-square",io="--luthor-checklist-variant",Fe="--luthor-unordered-pattern",Ca="--luthor-unordered-pattern-token",He="--luthor-unordered-marker-kind",Ne="--luthor-ordered-marker-content",fa={"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 Sa(r){let t=new Map;for(let e of r.split(";")){let n=e.trim();if(!n)continue;let o=n.indexOf(":");if(o<=0)continue;let i=n.slice(0,o).trim(),s=n.slice(o+1).trim();i&&t.set(i,s);}return t}function mg(r){return Array.from(r.entries()).map(([t,e])=>`${t}: ${e}`).join("; ")}function oe(r,t){let e=r.getStyle(),n=Sa(e),o=false;for(let[i,s]of Object.entries(t)){let a=n.get(i);if(s===null||s===""){n.delete(i)&&(o=true);continue}a!==s&&(n.set(i,s),o=true);}o&&r.setStyle(mg(n));}function he(r,t){return Sa(r.getStyle()).get(t)??null}function Ct(r,t){let e=[...r];for(let n=0;n<e.length;n+=1){let o=e[n],i=t(o);if(i==="stop")break;i!=="skip-children"&&typeof o?.getChildren=="function"&&e.push(...o.getChildren());}}function so(r){let t=r;for(;t;){if($isListNode(t))return t;t=t.getParent();}return null}function gg(r){let t=r;for(;t;){if($isListItemNode(t))return t;t=t.getParent();}return null}function nn(r){let t=r;for(;;){let e=t.getParent();if(!$isListItemNode(e))return t;let n=e.getParent();if(!$isListNode(n))return t;t=n;}}function to(r,t){let e=$getListDepth(r),n=$getListDepth(t);return e-n}function no(r,t){let e=t%r.length;return r[e]??r[0]??"disc"}function pa(r,t){let e=r,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 ha(r,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(r)),o="";for(let[i,s]of e)for(;n>=i;)o+=s,n-=i;return t?o:o.toLowerCase()}function ba(r,t,e,n){let o=e==="paren"?")":".";return `"${n?n.join("."):r==="decimal-leading-zero"?t<10?`0${t}`:`${t}`:r==="lower-alpha"?pa(t,false):r==="upper-alpha"?pa(t,true):r==="lower-roman"?ha(t,false):r==="upper-roman"?ha(t,true):`${t}`}${o}"`}function fg(r,t){let e=0;for(let n of r.getChildren())if($isListItemNode(n)&&(Zt(n)&&(e+=1),n.getKey()===t.getKey()))return Math.max(1,e);return Math.max(1,e)}function ya(r,t){let e=[],n=r;for(;n.getKey()!==t.getKey();){let o=n.getParent();if(!$isListItemNode(o))break;let i=o.getParent();if(!$isListNode(i))break;e.push(fg(i,o)),n=i;}return e.reverse()}function lo(r){return r&&Object.hasOwn(tn,r)?r:r&&Object.hasOwn(fa,r)?fa[r]??ga:ga}function pg(r){return r.startsWith('"')&&r.endsWith('"')}function Hr(r){if(pg(r)){let t=r.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(r){case "disc":return "disc";case "circle":return "circle";case "square":return "square";default:return "disc"}}function hg(r){let t=r.trim();if(!t)return null;let e=t.match(/^(\d+)([.)])$/);if(e){let i=e[1]??"",s=e[2]??".";return {pattern:i.length>1&&i.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 xt(r){let t=new Map,e=r.getNodes();for(let n of e){let o=so(n);if(!o)continue;let i=nn(o);t.set(i.getKey(),i);}if(t.size===0){let n=so(r.anchor.getNode());if(n){let o=nn(n);t.set(o.getKey(),o);}}return [...t.values()]}function oo(r,t){let e=Math.max(0,t-1),n=r.anchor.getNode(),o=gg(n);if(o){let s=o.getIndent();if(typeof s=="number")return s>=e}let i=so(n);return i?$getListDepth(i)-1>=e:false}function Fr(r){let t=[];return Ct(r.getChildren(),e=>{if($isListNode(e))return "skip-children";$isTextNode(e)&&t.push(e);}),t}function it(r){let t=[];return Ct(r.getChildren(),e=>{if($isListNode(e))return t.push(e),"skip-children"}),t}function Zt(r){let t=false,e=false;return Ct(r.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 en(r){oe(r,{"--luthor-unordered-marker-content":null,[He]:null});}function Ir(r,t){Ct(r.getChildren(),e=>{if($isListNode(e))return "skip-children";typeof e.getStyle=="function"&&typeof e.setStyle=="function"&&oe(e,{[Ca]:t});});}function bg(r){let t=null;return Ct(r.getChildren(),e=>{if($isListNode(e))return "skip-children";if(typeof e.getStyle=="function"){let n=he(e,Ca);if(n)return t=lo(n),"stop"}}),t}function yg(r){let t=[r];for(;t.length>0;){let e=t.pop();if(e.getListType()==="check")for(let n of e.getChildren()){if(!$isListItemNode(n))continue;let o=Fr(n);for(let i of o)if(he(i,io)==="plain")return "plain";t.push(...it(n));}}return null}function Eg(r){let t=[r];for(;t.length>0;){let e=t.pop();if(e.getListType()==="bullet")for(let n of e.getChildren()){if(!$isListItemNode(n))continue;let o=he(n,Fe),i=lo(o);if(o&&Object.hasOwn(tn,i))return i;let s=bg(n);if(s)return s;t.push(...it(n));}}return null}function _r(r){let t=Eg(r);if(t)return t;let e=he(r,Fe);return lo(e)}function Or(r){return he(r,io)==="plain"?"plain":yg(r)??"strikethrough"}function ro(r){let t=r.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?nn(e):null;return {listNode:e,listItemNode:n,topListNode:o}}function Br(r){let t=r.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 i=e.getBoundingClientRect(),s=r.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 r?r.pointerType:"")==="touch"?32:0;return (e.dir==="rtl"?s<i.right+c&&s>i.right-l-c:s>i.left-c&&s<i.left+l+c)?e:null}var ao=class extends M{constructor(t={}){super("list",["toolbar"]),this.config=t;}getMaxListDepth(){let t=this.config.maxDepth;if(!Number.isFinite(t))return ma;let e=Math.floor(t);return e>=1?e:ma}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),i=t.registerCommand(INDENT_CONTENT_COMMAND,()=>{let d=$getSelection();return !$isRangeSelection(d)||!ro(d).listNode?false:oo(d,this.getMaxListDepth())},COMMAND_PRIORITY_EDITOR),s=d=>{t.isEditable()||Br(d)&&(d.preventDefault(),d.stopPropagation());},a=d=>{if(t.isEditable())return;let c=Br(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(),i(),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=ro(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=ro(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=ro(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)&&(oo(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)||oo(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)||oo(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 i=xt(o);for(let s of i)this.applyOrderedPattern(s,e);});},setOrderedListSuffix:e=>{t.update(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=xt(n);for(let i of o)i.getListType()==="number"&&this.applyOrderedSuffix(i,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 i=xt(o);for(let s of i)this.applyUnorderedPattern(s,e);});},setCheckListVariant:e=>{let n=false;t.update(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let i=xt(o);if(i.length===0){n=true;return}for(let s of i)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 i=xt(o);for(let s of i)s.getListType()!=="check"&&this.convertTopListType(s,"check"),this.applyCheckListVariant(s,e);}));},rehydrateListStyles:()=>{t.update(()=>{let e=$getRoot(),n=new Map;Ct(e.getChildren(),o=>{if($isListNode(o)){let i=nn(o);n.set(i.getKey(),i);}});for(let o of n.values()){if(o.getListType()==="number"){let i=he(o,"--luthor-ordered-pattern")??Et,s=Object.hasOwn(yt,i)?i:Et,a=he(o,"--luthor-ordered-suffix")==="paren"?"paren":"dot";this.applyOrderedPattern(o,s),this.applyOrderedSuffix(o,a);continue}if(o.getListType()==="bullet"){let i=_r(o);this.applyUnorderedPattern(o,i);continue}if(o.getListType()==="check"){let i=Or(o);this.applyCheckListVariant(o,i);}}});}}}applyOrderedPattern(t,e){if(t.getListType()!=="number")return;let n=yt[e],o=he(t,"--luthor-ordered-suffix")??"dot";oe(t,{"--luthor-ordered-pattern":e,"--luthor-ordered-suffix":o});let i=[t];for(;i.length>0;){let s=i.pop();if(s.getListType()!=="number")continue;let a=to(s,t),l=no(n,a),d=e==="decimal-hierarchical";en(s),oe(s,{"--luthor-ordered-pattern":e,"--luthor-ordered-suffix":o,"list-style-type":"none",[Ne]:null});let c=d?ya(s,t):null,u=0;for(let m of s.getChildren()){if(!$isListItemNode(m))continue;let f=Zt(m);f&&(u+=1);let g=ba(l,Math.max(1,u),o==="paren"?"paren":"dot",d?[...c??[],Math.max(1,u)]:null);en(m),oe(m,{[Ne]:f?g:null}),i.push(...it(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(...it(a));}}let o=he(t,"--luthor-ordered-pattern")??Et,i=Object.hasOwn(yt,o)?o:Et;this.applyOrderedPattern(t,i);}applyUnorderedPattern(t,e){if(t.getListType()!=="bullet")return;let n=tn[e];oe(t,{[Fe]:e});let o=[t];for(;o.length>0;){let i=o.pop();if(i.getListType()!=="bullet")continue;let s=to(i,t),a=no(n,s),l=Hr(a);oe(i,{[Fe]:e,"list-style-type":"none","--luthor-unordered-marker-content":null,[He]:null,[Ne]:null});for(let d of i.getChildren())$isListItemNode(d)&&(oe(d,{[Fe]:e,"--luthor-unordered-marker-content":null,[He]:Zt(d)?l:null,[Ne]:null}),Ir(d,e),o.push(...it(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,[He]:null,[Ne]:null,"--luthor-unordered-pattern":null,"--luthor-ordered-pattern":null,"--luthor-ordered-suffix":null,"list-style-type":null});for(let i of o.getChildren()){if(!$isListItemNode(i))continue;oe(i,{"--luthor-checklist-variant":e,[Fe]:null,"--luthor-unordered-marker-content":null,[He]:null,[Ne]:null}),Ir(i,null);let s=Fr(i);for(let a of s)oe(a,{[io]:e==="plain"?"plain":null});n.push(...it(i));}}}}syncListNodeStyles(t){let e=nn(t);if(e.getListType()==="number"){let n=he(e,"--luthor-ordered-pattern")??Et;if(!Object.hasOwn(yt,n))return;let o=yt[n],i=to(t,e),s=no(o,i),a=n==="decimal-hierarchical",l=he(e,"--luthor-ordered-suffix")??"dot";en(t),oe(t,{"--luthor-ordered-pattern":n,"--luthor-ordered-suffix":l,"list-style-type":"none",[Ne]:null});let d=a?ya(t,e):null,c=0;for(let u of t.getChildren()){if(!$isListItemNode(u))continue;let m=Zt(u);m&&(c+=1);let f=ba(s,Math.max(1,c),l==="paren"?"paren":"dot",a?[...d??[],Math.max(1,c)]:null);en(u),oe(u,{[Ne]:m?f:null});}return}if(e.getListType()==="bullet"){let n=_r(e),o=tn[n],i=to(t,e),s=no(o,i),a=Hr(s);oe(t,{[Fe]:n,"list-style-type":"none","--luthor-unordered-marker-content":null,[He]:null,[Ne]:null});for(let l of t.getChildren())$isListItemNode(l)&&(oe(l,{[Fe]:n,"--luthor-unordered-marker-content":null,[He]:Zt(l)?a:null,[Ne]:null}),Ir(l,n));return}if(e.getListType()==="check"){let n=Or(e);oe(t,{"--luthor-checklist-variant":n,"--luthor-unordered-marker-content":null,[He]:null,[Ne]: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,[Fe]:null,"--luthor-unordered-marker-content":null,[He]:null,[Ne]:null});let i=Fr(o);for(let s of i)oe(s,{[io]:n==="plain"?"plain":null});}}}convertTopListType(t,e){let n=[t];for(;n.length>0;){let i=n.pop();i.setListType(e);for(let s of i.getChildren())$isListItemNode(s)&&n.push(...it(s));}if(e==="number"){let i=he(t,"--luthor-ordered-pattern"),s=i&&Object.hasOwn(yt,i)?i:Et,a=he(t,"--luthor-ordered-suffix")==="paren"?"paren":"dot";this.applyOrderedPattern(t,s),this.applyOrderedSuffix(t,a);return}if(e==="bullet"){let i=_r(t);this.applyUnorderedPattern(t,i);return}let o=Or(t);this.applyCheckListVariant(t,o);}handleOrderedListShortcut(t){let e=$getSelection();if(!$isRangeSelection(e)||!e.isCollapsed())return false;let n=e.anchor.getNode();if(so(n))return false;let o=n;for(;o&&!$isParagraphNode(o);)o=o.getParent();if(!$isParagraphNode(o))return false;let i=o,s=hg(i.getTextContent());if(!s)return false;i.clear(),t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);let a=$getSelection();if(!$isRangeSelection(a))return true;let l=xt(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);});})}}},xg=new ao;var Sg="plain";function on(){return Sg}function Na(){return PrismTokenizer}async function Ta(r){return r?.provider?r.provider:r?.loadProvider?r.loadProvider():null}async function La(r){return r?r.tokenizer?r.tokenizer:r.getTokenizer?r.getTokenizer():null:null}var va={csharp:"csharp",cs:"csharp",dockerfile:"docker",golang:"go",js:"javascript",jsx:"jsx",json:"json",kt:"kotlin",py:"python",rb:"ruby",sh:"bash",shell:"bash",ts:"typescript",tsx:"tsx",yml:"yaml"},zr=["bash","csharp","dart","docker","go","graphql","javascript","json","jsx","kotlin","lua","perl","php","r","ruby","scala","toml","tsx","yaml"],Lg=new Set(zr),rn=null;function Be(r){if(!r)return null;let t=r.trim().toLowerCase();if(!t||t==="auto")return null;let e=va[t]??t,n=normalizeCodeLang(e);return !n||n==="auto"?null:va[n]??n}function wa(){return new Set(getCodeLanguages().map(r=>Be(r)).filter(r=>!!r))}function vg(){return rn||(rn=wa()),rn}function $r(){return rn=wa(),new Set(rn)}function co(r){let t=r.trim().toLowerCase();return t?vg().has(t):false}function wg(r){let t=Be(r);return t?co(t):false}function kg(r){let t=Be(r);return t?Lg.has(t):false}function Rg(r){return wg(r)||kg(r)}function ka(r){let t=Be(r);return t&&Rg(t)?t:null}var Ma={bash:()=>import('prismjs/components/prism-bash.js'),csharp:()=>import('prismjs/components/prism-csharp.js'),dart:()=>import('prismjs/components/prism-dart.js'),docker:()=>import('prismjs/components/prism-docker.js'),go:()=>import('prismjs/components/prism-go.js'),graphql:()=>import('prismjs/components/prism-graphql.js'),javascript:()=>import('prismjs/components/prism-javascript.js'),json:()=>import('prismjs/components/prism-json.js'),jsx:()=>import('prismjs/components/prism-jsx.js'),kotlin:()=>import('prismjs/components/prism-kotlin.js'),lua:()=>import('prismjs/components/prism-lua.js'),perl:()=>import('prismjs/components/prism-perl.js'),php:()=>import('prismjs/components/prism-php.js'),r:()=>import('prismjs/components/prism-r.js'),ruby:()=>import('prismjs/components/prism-ruby.js'),scala:()=>import('prismjs/components/prism-scala.js'),toml:()=>import('prismjs/components/prism-toml.js'),tsx:()=>import('prismjs/components/prism-tsx.js'),yaml:()=>import('prismjs/components/prism-yaml.js')},Pa=zr,uo=null,sn=null,jr=new Map;function mo(r){if(!r||typeof r!="object")return false;let t=r;return !!(t.languages&&typeof t.languages=="object")}function Ra(){let r=globalThis.Prism;return mo(r)?r:null}function Mg(r){if(!r||typeof r!="object")return null;let t=r;return mo(t.default)?t.default:mo(t.Prism)?t.Prism:mo(r)?r:null}async function Aa(){if(Ra())return true;if(sn)return sn;sn=(async()=>{let t;try{t=await import('prismjs');}catch{return false}let e=Mg(t);return e?(globalThis.Prism=e,Ra()!==null):false})();let r=await sn;return r||(sn=null),r}async function Pg(r){if(!await Aa()||co(r))return false;let t=jr.get(r);if(t)return t;let e=Ma[r];if(!e)return false;let n=(async()=>{try{await e();}catch{return false}return $r().has(r)})();jr.set(r,n);try{return await n}finally{jr.delete(r);}}function Ag(){return [...Pa]}async function go(r){if(!await Aa())return [];let t=[],e=[],n=new Set;$r();for(let o of r){let i=Be(o);i&&(n.has(i)||(n.add(i),!co(i)&&Ma[i]&&e.push(i)));}for(let o of e)await Pg(o)&&t.push(o);return t}async function Ur(){return uo||(uo=go(Pa),uo)}var yo=class yo extends M{constructor(){super("code",["toolbar"]);T(this,"codeHighlightProviderPromise",null);T(this,"lineNumberTextCache",new Map);T(this,"appliedLineNumberNodeKeys",new Set);this.config={syntaxHighlighting:"auto",showLineNumbers:true,grammarPreloadMode:"lazy"};}register(e){let n=()=>{},o=false,i=null,s=false,a=null,l=()=>{o||this.ensureCodeBlockLineNumbers(e);},d=y=>{i=y,n(),n=registerCodeHighlighting(e,y);},c=()=>{o||!i||(d(i),e.update(()=>{$nodesOfType(CodeNode).forEach(y=>{let C=y.getLanguage();typeof C=="string"&&C.trim().length>0&&y.setLanguage(C);});}));},u=async()=>{let y=e.getEditorState().read(()=>$nodesOfType(CodeNode).map(h=>h.getLanguage()).filter(h=>typeof h=="string"));if(y.length===0)return;let C=await go(y);o||C.length===0||c();},m=()=>{o||s||(s=true,queueMicrotask(()=>{s=false,!o&&u();}));};if(this.config.syntaxHighlighting!=="disabled"){d(this.config.tokenizer??Na()),this.resolveConfiguredTokenizer().then(h=>{o||!h||(d(h),m());});let y=$g(this.config.grammarPreloadMode),C=async()=>{let h=await Ur();o||h.length===0||c();};y==="eager"?C():y==="idle"&&(a=jg(()=>{C();})),m();}let f=e.registerUpdateListener(({dirtyElements:y,dirtyLeaves:C})=>{(y.size>0||C.size>0)&&(l(),this.config.syntaxHighlighting!=="disabled"&&this.hasCodeNodeMutations(e,y,C)&&m());});queueMicrotask(()=>{l();});let g=e.registerCommand(KEY_TAB_COMMAND,y=>{let C=false;return e.update(()=>{let h=$getSelection();if(!$isRangeSelection(h))return;let p=h.anchor.getNode();this.getBlockNode(p)&&(C=true,!this.hasReachedCodeTabLimit(h)&&h.insertText(" "));}),C?(y?.preventDefault(),true):false},COMMAND_PRIORITY_LOW);return ()=>{o=true,n(),f(),g(),a?.(),a=null,this.appliedLineNumberNodeKeys.clear();}}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 i=$createCodeNode();return i.setTheme?.(on()),i});}});}async resolveConfiguredTokenizer(){if(this.config.tokenizer)return this.config.tokenizer;let e=await this.loadCodeHighlightProvider();return La(e)}async loadCodeHighlightProvider(){return this.config.provider?this.config.provider:this.codeHighlightProviderPromise?this.codeHighlightProviderPromise:(this.codeHighlightProviderPromise=Ta(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 i=$getSelection();if(!$isRangeSelection(i)){o=false;return}let s=i.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}hasCodeNodeMutations(e,n,o){let i=new Set;return n.forEach((s,a)=>{i.add(a);}),o.forEach(s=>{i.add(s);}),i.size===0?false:e.getEditorState().read(()=>{for(let s of i){let a=$getNodeByKey(s);for(;a;){if($isCodeNode(a))return true;a=a.getParent();}}return false})}hasReachedCodeTabLimit(e){let n=e.anchor,o=n.getNode();if(typeof o.getTextContent!="function")return false;let i=o.getTextContent(),s=typeof n.offset=="number"?n.offset:i.length,a=Math.max(0,Math.min(i.length,s)),l=i.lastIndexOf(`
|
|
68
|
-
`,a-1)+1;return (i.slice(l,a).match(/^\t*/)?.[0].length??0)>=
|
|
59
|
+
`}function Hd(r){let t=ce(r).split(`
|
|
60
|
+
`),e=[];for(let n=0;n<t.length;n+=1){let o=t[n]??"",i=o.trim();if(i.length===0){e.push(o);continue}let s=i.match(/^<(div|p|figure)\b([^>]*)>([\s\S]*?)<\/\1>$/i);if(s){let c=Sn(i),u=s[3]??"",m=tr(u);c&&e.push(nr(c));let f=Yt(u,c,m);if(f)e.push(f);else {let g=Vt(Qt(Tn(er(u))));g.trim().length>0&&e.push(g);}c&&e.push(Zo);continue}if(/^<figure\b/i.test(i)){let c=[o];for(;n+1<t.length;){n+=1;let L=t[n]??"";if(c.push(L),/<\/figure>/i.test(L))break}let u=c.join(`
|
|
61
|
+
`),m=Sn(u),f=tr(u),g=Yt(u,m,f);if(g){e.push(g);continue}let x=Vt(Qt(Tn(er(u))));x.trim().length>0&&e.push(x);continue}if(/^<picture\b/i.test(i)){let c=[o];for(;n+1<t.length;){n+=1;let m=t[n]??"";if(c.push(m),/<\/picture>/i.test(m))break}let u=Yt(c.join(`
|
|
62
|
+
`));u&&e.push(u);continue}if(/^<source\b/i.test(i)||/^<\/?picture\b/i.test(i)||/^<\/?figcaption\b/i.test(i)||/^<\/?figure\b/i.test(i))continue;if(i.match(/^<(div|p)\b([^>]*)>$/i)){let c=Sn(i);c&&e.push(nr(c));continue}if(/^<\/(div|p)>$/i.test(i)){e.push(Zo);continue}if(/^<img\b[\s\S]*\/?>$/i.test(i)){let c=Yt(i);if(c){e.push(c);continue}}let l=i.match(/^<p\b[^>]*>([\s\S]*?)<\/p>$/i);if(l){let c=Sn(i),u=l[1]??"",m=tr(u);c&&e.push(nr(c));let f=Yt(u,c,m);if(f)e.push(f);else {let g=Vt(Qt(Tn(er(u))));g.trim().length>0&&e.push(g);}c&&e.push(Zo);continue}let d=Vt(Qt(o));e.push(d);}return e.join(`
|
|
63
|
+
`)}function Ze(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function ys(r){if(r.type!=="paragraph"||!Array.isArray(r.children))return null;let t="";for(let e of r.children){if(!Ze(e))return null;if(e.type==="text"){t+=typeof e.text=="string"?e.text:"";continue}if(e.type==="linebreak"){t+=`
|
|
64
|
+
`;continue}if(e.type==="tab"){t+=" ";continue}return null}return t}function Fd(r){if(r.length===0)return [];let t=r.split(`
|
|
65
|
+
`),e=[];return t.forEach((n,o)=>{n.length>0&&e.push({type:"text",version:1,text:n,detail:0,format:0,mode:"normal",style:""}),o<t.length-1&&e.push({type:"linebreak",version:1});}),e}function rr(r){return r.trim().replace(/\\+/g,"").replace(/\s+/g,"")}function ir(r){let t=rr(r),e=[t.match(/^\[\[LUTHORALIGNSTART:(left|center|right|justify)\]\]$/i),t.match(/^\[\[LUTHOR_ALIGN_START:(left|center|right|justify)\]\]$/i),t.match(/^\[\[LUTHOR-ALIGN-START:(left|center|right|justify)\]\]$/i)];for(let n of e){let o=n?.[1]?.toLowerCase();if(o&&or(o))return o}return null}function sr(r){let t=rr(r);return t==="[[LUTHORALIGNEND]]"||t==="[[LUTHOR_ALIGN_END]]"||t==="[[LUTHOR-ALIGN-END]]"}function Bd(r){let t=ys(r);if(t===null)return null;if(sr(t))return {type:"end"};let e=ir(t);return e?{type:"start",alignment:e}:null}function zd(r,t){let e=ys(r);if(e===null)return {keepNode:true,consumedMarker:false,alignmentForNode:null};let n=e.split(`
|
|
66
|
+
`),o=[],i=false,s=null;for(let a of n){let l=ir(a);if(l){t.push(l),i=true;continue}if(sr(a)){t.pop(),i=true;continue}s===null&&(s=t[t.length-1]??null),o.push(a);}if(!i)return {keepNode:true,consumedMarker:false,alignmentForNode:s};for(;o.length>0&&(o[0]??"").trim().length===0;)o.shift();for(;o.length>0&&(o[o.length-1]??"").trim().length===0;)o.pop();return o.length===0?(r.children=[],{keepNode:false,consumedMarker:true,alignmentForNode:null}):(r.children=Fd(o.join(`
|
|
67
|
+
`)),{keepNode:true,consumedMarker:true,alignmentForNode:s})}function $d(r,t){let e=typeof r.type=="string"?r.type:"";if(e==="image"){let n=ps(t);if(!n)return;let o=r.alignment;(o==null||o===""||o==="none")&&(r.alignment=n);return}(e==="paragraph"||e==="heading"||e==="quote"||e==="list"||e==="table"||e==="code")&&(r.format=t);}function jd(r){if(!Ze(r.root)||!Array.isArray(r.root.children))return r;let t=[],e=[];for(let n of r.root.children){if(!Ze(n)){e.push(n);continue}let o=zd(n,t);if(!o.keepNode)continue;let i=Bd(n);if(i){i.type==="start"?t.push(i.alignment):t.pop();continue}let s=o.alignmentForNode??t[t.length-1];s&&$d(n,s),e.push(n);}return r.root.children=e,r}function Es(r){return r!=="none"}function xs(r){let t=r?.bridgeFlavor??"github";return t==="luthor"?"github":t}function Kd(r,t){if(xs(t)==="lexical-native"){let f=us();return f.update(()=>{$convertFromMarkdownString(ce(r),cs);},{discrete:true}),f.getEditorState().toJSON()}let n=Es(t?.metadataMode),{content:o,envelopes:i,warnings:s}=n?jt(r):{content:r,envelopes:[],warnings:[]};if(n)for(let f of s)console.warn(`[luthor-headless] ${f}`);let a=_d(o),l=n?a.content:Hd(a.content),d=ds();d.update(()=>{$convertFromMarkdownString(l,ls);},{discrete:true});let c=d.getEditorState().toJSON(),u=n?c:jd(c),m=Kt(u,i);return Od(m,a.frontmatter)}function Ud(r,t){let e=xs(t);if(e==="lexical-native"){let f=us(),g=ji(f,r);return f.setEditorState(g,{tag:"history-merge"}),g.read(()=>$convertToMarkdownString(cs))}let{document:n,frontmatter:o}=Dd(r),i=Es(t?.metadataMode),s=zt(n,{mode:"markdown",supportedNodeTypes:En}),a=i?ld(n):[],l=ds(),d=ji(l,s.document);l.setEditorState(d,{tag:"history-merge"});let c=d.read(()=>$convertToMarkdownString(ls)),u=Ad(c,e,t?.metadataMode);if(!i)return Ki(u,o);let m=$t(u,[...s.envelopes,...a]);return Ki(m,o)}function uu(r){return yn(r,{mode:"html",supportedNodeTypes:xn,extractPatch:({node:t,type:e})=>Xo(t,e)})}var mu=new Set(["pre","script","style","textarea"]);function Ts(){return createEditor({namespace:"luthor-html-converter",onError:r=>{throw r},nodes:[ParagraphNode,TextNode,LineBreakNode,TabNode,HeadingNode,QuoteNode,ListNode,ListItemNode,LinkNode,AutoLinkNode,CodeNode,CodeHighlightNode,HorizontalRuleNode,K,G,V,TableNode,TableRowNode,TableCellNode]})}function gu(r,t){let e=typeof t=="string"?t:JSON.stringify(t??{});return r.parseEditorState(e)}function vs(){if(typeof document>"u"||typeof window>"u"||typeof DOMParser>"u")throw new Error("HTML conversion requires browser DOM APIs (document/window/DOMParser).")}function Cs(r){if(!r)return false;let t=r.getAttribute("style");return t?/\bwhite-space\s*:\s*(pre|pre-wrap|pre-line)\b/i.test(t):false}function fu(r){let t=r.parentElement;for(;t;){if(mu.has(t.tagName.toLowerCase()))return true;t=t.parentElement;}return false}function Ss(r,t){let e=t==="previous"?r.previousSibling:r.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 pu(r,t){if(!r||!t||/\s$/.test(r)||/^\s/.test(t))return false;let e=r.at(-1)??"",n=t[0]??"";return !(!e||!n||/^[,.;:!?)]$/.test(n)||/^[([{"']$/.test(e))}var hu=new Set(["p","h1","h2","h3","h4","h5","h6","blockquote","li","td","th","pre","code"]),bu=new Set(["div","section","article","main","header","footer","aside","nav"]);function yu(r){return r==="left"||r==="center"||r==="right"||r==="justify"}function wn(r,t){let e=r.getAttribute("style")?.trim()??"";if(!e){r.setAttribute("style",t);return}let n=e.endsWith(";")?e:`${e};`;r.setAttribute("style",`${n} ${t}`);}function Ns(r,t){if(t==="center"){wn(r,"display:block; margin-left:auto; margin-right:auto;");return}if(t==="left"||t==="right"){wn(r,`float:${t};`);return}}function Eu(r){let t=Array.from(r.querySelectorAll("[align]"));for(let e of t){let n=e.getAttribute("align")?.trim().toLowerCase()??"";if(!yu(n))continue;let o=e.tagName.toLowerCase();if(o==="img"){Ns(e,n),e.removeAttribute("align");continue}if(wn(e,`text-align:${n};`),bu.has(o))for(let i of Array.from(e.children)){if(!(i instanceof HTMLElement))continue;let s=i.tagName.toLowerCase();if(hu.has(s)){wn(i,`text-align:${n};`);continue}s==="img"&&Ns(i,n);}e.removeAttribute("align");}}function xu(r){let t=Array.from(r.querySelectorAll("picture"));for(let e of t){let n=e.querySelector("img");if(!n){e.remove();continue}e.replaceWith(n.cloneNode(true));}}function Cu(r){let t=Array.from(r.querySelectorAll("[style]"));for(let i of t){if(!Cs(i)||i.childNodes.length!==1||i.firstChild?.nodeType!==Node.TEXT_NODE)continue;let s=i.firstChild;/[\r\n]/.test(s.data)&&(s.data=s.data.replace(/^\s*\r?\n\s*/,"").replace(/\r?\n\s*$/,""));}let e=r.createTreeWalker(r.body,NodeFilter.SHOW_TEXT),n=[],o=e.nextNode();for(;o;){let i=o,s=i.data,a=i.parentElement;if(!/^[\s\r\n\t]+$/.test(s)||!/[\r\n]/.test(s)||fu(i)||Cs(a)){o=e.nextNode();continue}let l=Ss(i,"previous"),d=Ss(i,"next"),c=l?.textContent??"",u=d?.textContent??"";pu(c,u)?n.push({node:i,replacement:" "}):n.push({node:i,replacement:null}),o=e.nextNode();}for(let i of n)if(i.node.parentNode){if(i.replacement===null){i.node.parentNode.removeChild(i.node);continue}i.node.data=i.replacement;}}function Ls(r){return r!=="none"}function Su(r,t){vs();let e=Ls(t?.metadataMode),{content:n,envelopes:o,warnings:i}=e?jt(r):{content:r,envelopes:[],warnings:[]};if(e)for(let l of i)console.warn(`[luthor-headless] ${l}`);let s=Ts();s.update(()=>{let l=new DOMParser().parseFromString(n,"text/html");xu(l),Eu(l),Cu(l);let d=$generateNodesFromDOM(s,l),c=$getRoot();c.clear(),c.append(...d);},{discrete:true});let a=s.getEditorState().toJSON();return Kt(a,o)}function Nu(r,t){vs();let e=Ls(t?.metadataMode),n=zt(r,{mode:"html",supportedNodeTypes:xn}),o=e?uu(r):[],i=Ts(),s=gu(i,n.document);i.setEditorState(s,{tag:"history-merge"});let a=s.read(()=>$generateHtmlFromNodes(i,null));return e?$t(a,[...n.envelopes,...o]):a}var kn=class extends ae{constructor(){super("bold");}},Tu=new kn;var Rn=class extends ae{constructor(){super("italic");}},vu=new Rn;var Lu={format:["underline"],tag:"++",type:"text-format"},Mn=class extends ae{constructor(){super("underline");}getMarkdownTransformers(){return [Lu]}},wu=new Mn;var Pn=class extends ae{constructor(){super("strikethrough");}},ku=new Pn;var An=class extends M{constructor(){super("link",["toolbar"]);N(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,i=>{let s=i.clipboardData;if(!s)return false;let a=s.getData("text/plain");return a&&this.config.validateUrl(a)&&this.config.autoLinkUrls?(i.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:i})=>{i.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),i=(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){i(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}i(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(),i=e.getNodes(),s=[n,o,...i];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);});})}}},Hu=new An;var Vu={dependencies:[HorizontalRuleNode],export:r=>$isHorizontalRuleNode(r)?"---":null,regExp:/^(?:---|___)\s*$/,replace:(r,t,e,n)=>{let o=$createHorizontalRuleNode();r.replace(o),n||Ju(o);},type:"element"},Qu=[Vu],Wu=/^(?:---|___)$/;function Ju(r){let t=r.getNextSibling();if(t&&$isParagraphNode(t)){t.selectStart();return}let e=$createParagraphNode();r.insertAfter(e),e.selectStart();}var In=class extends M{constructor(){super("horizontalRule",["toolbar"]);}register(t){let e=registerMarkdownShortcuts(t,Qu),n=t.registerCommand(KEY_ENTER_COMMAND,o=>{if(o?.shiftKey)return false;let i=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(!Wu.test(c))return;i=true;let u=$createHorizontalRuleNode();l.replace(u),u.selectNext();}),i},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 i=n.getNodes().some(s=>$isHorizontalRuleNode(s));e(i);}else e(false);});})}}},qu=new In;var Os=[{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"}],Zu={value:"default",label:"Default",fontFamily:"inherit"};function _s(r){return r.trim().toLowerCase()}function em(r){return /^[a-z0-9][a-z0-9-]*$/i.test(r)}function tm(r){let t=new Set,e=[];for(let o of r){let i=o.value.trim(),s=o.label.trim(),a=o.fontFamily.trim();if(!i||!s||!a||!em(i))continue;let l=_s(i);t.has(l)||(t.add(l),e.push({value:i,label:s,fontFamily:a,cssImportUrl:o.cssImportUrl?.trim()||void 0}));}return e.length===0?Os:e.some(o=>_s(o.value)==="default")?e:[Zu,...e]}var _n=class extends M{constructor(){super("fontFamily",["toolbar"]);N(this,"loadedFontUrls",new Set);this.config={options:Os,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=tm(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 i=$getSelectionStyleValueForProperty(o,"font-family","");n=this.normalizeFontValue(i).length>0;}),n}getCurrentFontFamilyValue(e){let n=null;return e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let i=$getSelectionStyleValueForProperty(o,"font-family","");if(!i){n="default";return}let s=this.normalizeFontValue(i);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);}},nm=new _n;var Fs=[{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"}],rm={value:"default",label:"Default",fontSize:"inherit"};function Hs(r){return r.trim().toLowerCase()}function im(r){return /^[a-z0-9][a-z0-9-]*$/i.test(r)}function sm(r){let t=new Set,e=[];for(let o of r){let i=String(o.value).trim(),s=String(o.label).trim(),a=String(o.fontSize).trim();if(!i||!s||!a||!im(i))continue;let l=Hs(i);t.has(l)||(t.add(l),e.push({value:i,label:s,fontSize:a}));}return e.length===0?Fs:e.some(o=>Hs(o.value)==="default")?e:[rm,...e]}var On=class extends M{constructor(){super("fontSize",["toolbar"]),this.config={options:Fs,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}configure(t){let e={...t};return t.options&&(e.options=sm(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",""),i=this.normalizeValue(o);e=i.length>0&&i!=="inherit";}),e}getCurrentFontSizeValue(t){let e=null;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"font-size",""),i=this.normalizeValue(o);if(!i||i==="inherit"){e="default";return}e=this.config.options.find(a=>this.normalizeValue(a.value)===i?true:this.normalizeValue(a.fontSize)===i)?.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,"")}},am=new On;var zs=[{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"}],hr={value:"default",label:"Default",lineHeight:"1.5"},dm=1;function pr(r){return r.trim().toLowerCase()}function um(r){return pr(r)==="default"?true:Hn(r)!==null}function Hn(r){let t=r.trim();if(!/^\d*\.?\d+$/.test(t))return null;let e=Number(t);return !Number.isFinite(e)||e<dm?null:e.toString()}function mm(r,t){let e=new Set,n=[];for(let i of r){let s=i.value.trim(),a=i.label.trim(),l=pr(s);if(!s||!a||!um(s)||e.has(l))continue;if(l==="default"){e.add(l),n.push({value:s,label:a,lineHeight:t});continue}let d=Hn(String(i.lineHeight));d&&(e.add(l),n.push({value:s,label:a,lineHeight:d}));}return n.length===0?zs:n.some(i=>pr(i.value)==="default")?n:[{...hr,lineHeight:t},...n]}function gm(r){return Hn(r)??hr.lineHeight}var Dn=class extends M{constructor(){super("lineHeight",["toolbar"]),this.config={options:zs,defaultLineHeight:hr.lineHeight,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}configure(t){let e={...t},n=gm(String(t.defaultLineHeight??this.config.defaultLineHeight));return e.defaultLineHeight=n,t.options&&(e.options=mm(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 i of o){let s=this.withStyleProperty(i.getStyle(),"line-height",e);i.setStyle(s);for(let a of i.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"),i=t.split(";").map(a=>a.trim()).filter(a=>a.length>0).filter(a=>!o.test(a)),s=n.trim();return s.length>0&&i.push(`${e}: ${s}`),i.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 i=o??$getSelectionStyleValueForProperty(n,"line-height",""),s=this.normalizeValue(i);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 i=o??$getSelectionStyleValueForProperty(n,"line-height",""),s=this.normalizeValue(i);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 i of e){let s=this.readStyleProperty(i.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 Hn(e)??e}readStyleProperty(t,e){let n=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return t.match(new RegExp(`(?:^|;)\\s*${n}\\s*:\\s*([^;]+)`,"i"))?.[1]?.trim()??""}},fm=new Dn;var hm=[{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"}],Fn=class extends M{constructor(){super("textColor",["toolbar"]),this.config={options:hm,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 i=this.normalizeValue(o);e=this.config.options.find(a=>this.normalizeValue(a.value)===i?true:this.normalizeValue(a.color)===i)?.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}},bm=new Fn;var Em=[{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"}],Bn=class extends M{constructor(){super("textHighlight",["toolbar"]),this.config={options:Em,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",""),i=this.normalizeValue(o);e=i.length>0&&i!=="transparent";}),e}getCurrentTextHighlightValue(t){let e=null;return t.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=$getSelectionStyleValueForProperty(n,"background-color",""),i=this.normalizeValue(o);if(!i||i==="transparent"){e="default";return}e=this.config.options.find(a=>this.normalizeValue(a.value)===i?true:this.normalizeValue(a.backgroundColor)===i)?.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}},xm=new Bn;var zn=class extends ae{constructor(){super("subscript");}},Cm=new zn;var $n=class extends ae{constructor(){super("superscript");}},Sm=new $n;function jn(r,t,e){return r<t?t:r>e?e:r}function wm({items:r,position:t,onClose:e,className:n,style:o,itemClassName:i,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:r.map((d,c)=>d.separator?jsx("div",{className:"h-px bg-border my-1"},c):jsxs("div",{className:d.disabled?a:i,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 Kn=class{constructor(t,e={}){N(this,"providers",new Map);N(this,"currentMenu",null);N(this,"listeners",new Set);N(this,"editor");N(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((i,s)=>(s.priority||0)-(i.priority||0));for(let i of o){let s={editor:this.editor,target:e,selection:n,event:t};if(i.canHandle(s)){this.config.preventDefault!==false&&t.preventDefault();let a=i.getItems(s);if(a.length>0){let l=e.getBoundingClientRect();this.showMenu({items:a,position:{x:t.clientX,y:t.clientY},renderer:i.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,i=e.getBoundingClientRect();return {...t,position:{x:i.left+n,y:i.top+o}}}};function km({extension:r}){let{config:t}=Oe(),[e,n]=useState(null),o=t?.theme?.contextMenu||{},i=r.config,s={container:i?.theme?.container||o.container||"luthor-context-menu",item:i?.theme?.item||o.item||"luthor-context-menu-item",itemDisabled:i?.theme?.itemDisabled||o.itemDisabled||"luthor-context-menu-item-disabled"},a={container:{...i?.styles?.container,...o.styles?.container},item:{...i?.styles?.item,...o.styles?.item},itemDisabled:{...i?.styles?.itemDisabled,...o.styles?.itemDisabled}};if(useEffect(()=>r.subscribe(n),[r]),!e)return null;let l=e.renderer||r.config.defaultRenderer,d=r.manager?.getPortalContainer()??null,c=220,u=Math.min(420,18+e.items.length*34),m=8,f=(()=>{if(!d){let h=typeof window>"u"?0:window.innerWidth,y=typeof window>"u"?0:window.innerHeight;return {width:h,height:y}}let S=d.getBoundingClientRect();return {width:S.width,height:S.height}})(),g=Math.max(0,f.width-m*2),x=Math.max(0,f.height-m*2),L=Math.min(c,g||c),b=Math.min(u,x||u),p=(()=>{if(!d){let I=Math.max(m,f.width-L-m),D=Math.max(m,f.height-b-m);return {x:jn(e.position.x,m,I),y:jn(e.position.y,m,D)}}let S=d.getBoundingClientRect(),h=e.position.x-S.left+d.scrollLeft,y=e.position.y-S.top+d.scrollTop,w=d.scrollLeft+m,E=d.scrollTop+m,T=Math.max(w,d.scrollLeft+S.width-L-m),k=Math.max(E,d.scrollTop+S.height-b-m);return {x:jn(h,w,T),y:jn(y,E,k)}})(),C=d?{position:"absolute",...a.container,maxWidth:g>0?g:void 0,maxHeight:x>0?x:void 0,overflowY:"auto",overscrollBehavior:"contain"}:{...a.container,maxWidth:g>0?g:void 0,maxHeight:x>0?x:void 0,overflowY:"auto",overscrollBehavior:"contain"};return createPortal(jsx(l,{items:e.items,position:p,onClose:()=>r.manager?.hideMenu(),className:s.container,style:C,itemClassName:s.item,itemStyle:a.item,disabledItemClassName:s.itemDisabled,disabledItemStyle:a.itemDisabled}),d??document.body)}var Un=class extends M{constructor(e={}){super("contextMenu",["toolbar"]);N(this,"manager",null);N(this,"pendingListeners",new Set);this.config={defaultRenderer:wm,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 Kn(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();},i=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",i),window.addEventListener("scroll",s,true),window.addEventListener("resize",s),()=>{a.removeEventListener("contextmenu",n),document.removeEventListener("mousedown",o),document.removeEventListener("keydown",i),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 Kn(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(km,{extension:this},"context-menu")]}subscribe(e){return this.manager?this.manager.subscribe(e):(this.pendingListeners.add(e),()=>{this.pendingListeners.delete(e);})}},Cr=new Un;function Ys(r,t,e){return r<t?t:r>e?e:r}function Wn(){let r=$getSelection();if($isTableSelection(r)){let t=r.getNodes().find(e=>$isTableCellNode(e));if($isTableCellNode(t))return t}if($isRangeSelection(r)){let t=r.anchor.getNode(),e=$findCellNode(t);if($isTableCellNode(e))return e}return null}function jm({headersEnabled:r,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:r,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 Km({extension:r}){let{editor:t}=Oe(),[e,n]=useState(()=>t?.isEditable()??true),[o,i]=useState(null),[s,a]=useState(false),[l,d]=useState(false),[c,u]=useState(null),m=useRef(null),f=useRef(null),g=p=>{!t||!t.isEditable()||t.update(()=>{let C=Wn();C&&(C.selectStart(),p(C));});},x=p=>{g(C=>{$getTableNodeFromLexicalNodeOrThrow(C).getChildren().filter(y=>$isTableRowNode(y)).forEach((y,w)=>{y.getChildren().filter(T=>$isTableCellNode(T)).forEach(T=>{let k=p&&w===0?TableCellHeaderStates.ROW:TableCellHeaderStates.NO_STATUS;T.setHeaderStyles(k,TableCellHeaderStates.ROW);});});});};if(useEffect(()=>{if(t)return t.registerEditableListener(p=>{n(p),p||(a(false),u(null));})},[t]),useEffect(()=>{if(!t)return;let p=t.getRootElement(),C=p?.closest(".luthor-editor-wrapper")||p?.parentElement||null;i(C);let S=()=>{t.getEditorState().read(()=>{if(!t.isEditable()){a(false),u(null);return}let w=$getSelection();if($isRangeSelection(w)&&!w.isCollapsed()){a(false),u(null);return}let E=Wn();if(!E){a(false),u(null);return}let k=t.getElementByKey(E.getKey())?.closest("table");if(!k||!C){a(false),u(null);return}let Y=$getTableNodeFromLexicalNodeOrThrow(E).getChildren().filter(Ue=>$isTableRowNode(Ue))[0]?.getChildren().filter(Ue=>$isTableCellNode(Ue))||[],ee=Y.length>0&&Y.every(Ue=>Ue.hasHeaderState(TableCellHeaderStates.ROW));d(ee);let B=C.getBoundingClientRect(),z=k.getBoundingClientRect(),W=m.current?.getBoundingClientRect(),j=W?.width??520,U=W?.height??44,O=12,q=Math.max(0,B.width-O*2),Z=Math.min(j,q||j)/2,ge=z.left-B.left+z.width/2,be=O+Z,ze=Math.max(be,B.width-O-Z),Te=Ys(ge,be,ze),$e=z.top-B.top,je=B.bottom-z.bottom,fe=$e>=U+O,re=je>=U+O,_e=fe||!re?z.top-B.top-12-U:z.bottom-B.top+12,Ke=O,Po=Math.max(Ke,B.height-U-O),Ao=Ys(_e,Ke,Po);u({x:Te,y:Ao,maxWidth:q}),a(true);});};S();let h=t.registerUpdateListener(()=>{S();}),y=()=>{f.current===null&&(f.current=window.requestAnimationFrame(()=>{f.current=null,S();}));};return window.addEventListener("scroll",y,true),window.addEventListener("resize",y),()=>{h(),window.removeEventListener("scroll",y,true),window.removeEventListener("resize",y),f.current!==null&&(cancelAnimationFrame(f.current),f.current=null);}},[t]),!e||!o||!s||!c||typeof document>"u")return null;let L={insertRowAbove:()=>g(()=>$insertTableRowAtSelection(false)),insertRowBelow:()=>g(()=>$insertTableRowAtSelection(true)),insertColumnLeft:()=>g(()=>$insertTableColumnAtSelection(false)),insertColumnRight:()=>g(()=>$insertTableColumnAtSelection(true)),deleteSelectedColumn:()=>g(()=>$deleteTableColumnAtSelection()),deleteSelectedRow:()=>g(()=>$deleteTableRowAtSelection()),deleteTable:()=>g(p=>{$getTableNodeFromLexicalNodeOrThrow(p).remove();})},b=r.config.tableBubbleRenderer?r.config.tableBubbleRenderer({headersEnabled:l,setHeadersEnabled:p=>{d(p),x(p);},actions:L}):jsx(jm,{headersEnabled:l,setHeadersEnabled:p=>{d(p),x(p);},actions:L});return createPortal(jsx("div",{ref:m,className:"luthor-table-bubble-menu",style:{position:"absolute",left:c.x,top:c.y,transform:"translateX(-50%)",maxWidth:c.maxWidth>0?c.maxWidth:void 0,overflowX:"auto",zIndex:"var(--luthor-z-menu, 460)"},onMouseDown:p=>p.preventDefault(),children:b}),o)}var Jn=class extends M{constructor(e){super("table",["toolbar"]);N(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||Cr;if(o){let i={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(i),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:i=3,includeHeaders:s=false}=n;e.update(()=>{let a=$getSelection();if($isRangeSelection(a)){let l=$createTableNodeWithDimensions(o,i,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=Wn();if(!n)return;let o=$getTableNodeFromLexicalNodeOrThrow(n),i=$getTableRowIndexFromTableCellNode(n),s=o.getChildren()[i];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=Wn();if(!n)return;let o=$getTableNodeFromLexicalNodeOrThrow(n),i=$getTableColumnIndexFromTableCellNode(n),a=o.getChildren().filter(c=>$isTableRowNode(c)).map(c=>c.getChildren()[i]).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(i=>$isTableCellNode(i));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(),i=n.focus.getNode();return $isTableCellNode(o)||$isTableCellNode(i)}catch{return false}})}}getPlugins(){return [jsx(TablePlugin,{},"table-plugin"),jsx(Km,{extension:this},"table-quick-actions-plugin")]}},Um=new Jn;var ea=9,bt={"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"]},tn={"disc-circle-square":["disc","circle","square"],"arrow-diamond-disc":['"\u25B8"','"\u25C6"',"disc"],"square-square-square":["square","square","square"],"arrow-circle-square":['"\u25B8"',"circle","square"]},yt="decimal-alpha-roman",ta="disc-circle-square",oo="--luthor-checklist-variant",Fe="--luthor-unordered-pattern",ca="--luthor-unordered-pattern-token",He="--luthor-unordered-marker-kind",Ne="--luthor-ordered-marker-content",na={"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 da(r){let t=new Map;for(let e of r.split(";")){let n=e.trim();if(!n)continue;let o=n.indexOf(":");if(o<=0)continue;let i=n.slice(0,o).trim(),s=n.slice(o+1).trim();i&&t.set(i,s);}return t}function Xm(r){return Array.from(r.entries()).map(([t,e])=>`${t}: ${e}`).join("; ")}function oe(r,t){let e=r.getStyle(),n=da(e),o=false;for(let[i,s]of Object.entries(t)){let a=n.get(i);if(s===null||s===""){n.delete(i)&&(o=true);continue}a!==s&&(n.set(i,s),o=true);}o&&r.setStyle(Xm(n));}function he(r,t){return da(r.getStyle()).get(t)??null}function xt(r,t){let e=[...r];for(let n=0;n<e.length;n+=1){let o=e[n],i=t(o);if(i==="stop")break;i!=="skip-children"&&typeof o?.getChildren=="function"&&e.push(...o.getChildren());}}function ro(r){let t=r;for(;t;){if($isListNode(t))return t;t=t.getParent();}return null}function Gm(r){let t=r;for(;t;){if($isListItemNode(t))return t;t=t.getParent();}return null}function nn(r){let t=r;for(;;){let e=t.getParent();if(!$isListItemNode(e))return t;let n=e.getParent();if(!$isListNode(n))return t;t=n;}}function Zn(r,t){let e=$getListDepth(r),n=$getListDepth(t);return e-n}function eo(r,t){let e=t%r.length;return r[e]??r[0]??"disc"}function oa(r,t){let e=r,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 ra(r,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(r)),o="";for(let[i,s]of e)for(;n>=i;)o+=s,n-=i;return t?o:o.toLowerCase()}function ia(r,t,e,n){let o=e==="paren"?")":".";return `"${n?n.join("."):r==="decimal-leading-zero"?t<10?`0${t}`:`${t}`:r==="lower-alpha"?oa(t,false):r==="upper-alpha"?oa(t,true):r==="lower-roman"?ra(t,false):r==="upper-roman"?ra(t,true):`${t}`}${o}"`}function Zm(r,t){let e=0;for(let n of r.getChildren())if($isListItemNode(n)&&(Zt(n)&&(e+=1),n.getKey()===t.getKey()))return Math.max(1,e);return Math.max(1,e)}function sa(r,t){let e=[],n=r;for(;n.getKey()!==t.getKey();){let o=n.getParent();if(!$isListItemNode(o))break;let i=o.getParent();if(!$isListNode(i))break;e.push(Zm(i,o)),n=i;}return e.reverse()}function so(r){return r&&Object.hasOwn(tn,r)?r:r&&Object.hasOwn(na,r)?na[r]??ta:ta}function eg(r){return r.startsWith('"')&&r.endsWith('"')}function Mr(r){if(eg(r)){let t=r.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(r){case "disc":return "disc";case "circle":return "circle";case "square":return "square";default:return "disc"}}function tg(r){let t=r.trim();if(!t)return null;let e=t.match(/^(\d+)([.)])$/);if(e){let i=e[1]??"",s=e[2]??".";return {pattern:i.length>1&&i.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 Et(r){let t=new Map,e=r.getNodes();for(let n of e){let o=ro(n);if(!o)continue;let i=nn(o);t.set(i.getKey(),i);}if(t.size===0){let n=ro(r.anchor.getNode());if(n){let o=nn(n);t.set(o.getKey(),o);}}return [...t.values()]}function to(r,t){let e=Math.max(0,t-1),n=r.anchor.getNode(),o=Gm(n);if(o){let s=o.getIndent();if(typeof s=="number")return s>=e}let i=ro(n);return i?$getListDepth(i)-1>=e:false}function Pr(r){let t=[];return xt(r.getChildren(),e=>{if($isListNode(e))return "skip-children";$isTextNode(e)&&t.push(e);}),t}function rt(r){let t=[];return xt(r.getChildren(),e=>{if($isListNode(e))return t.push(e),"skip-children"}),t}function Zt(r){let t=false,e=false;return xt(r.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 en(r){oe(r,{"--luthor-unordered-marker-content":null,[He]:null});}function Lr(r,t){xt(r.getChildren(),e=>{if($isListNode(e))return "skip-children";typeof e.getStyle=="function"&&typeof e.setStyle=="function"&&oe(e,{[ca]:t});});}function ng(r){let t=null;return xt(r.getChildren(),e=>{if($isListNode(e))return "skip-children";if(typeof e.getStyle=="function"){let n=he(e,ca);if(n)return t=so(n),"stop"}}),t}function og(r){let t=[r];for(;t.length>0;){let e=t.pop();if(e.getListType()==="check")for(let n of e.getChildren()){if(!$isListItemNode(n))continue;let o=Pr(n);for(let i of o)if(he(i,oo)==="plain")return "plain";t.push(...rt(n));}}return null}function rg(r){let t=[r];for(;t.length>0;){let e=t.pop();if(e.getListType()==="bullet")for(let n of e.getChildren()){if(!$isListItemNode(n))continue;let o=he(n,Fe),i=so(o);if(o&&Object.hasOwn(tn,i))return i;let s=ng(n);if(s)return s;t.push(...rt(n));}}return null}function wr(r){let t=rg(r);if(t)return t;let e=he(r,Fe);return so(e)}function kr(r){return he(r,oo)==="plain"?"plain":og(r)??"strikethrough"}function no(r){let t=r.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?nn(e):null;return {listNode:e,listItemNode:n,topListNode:o}}function Ar(r){let t=r.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 i=e.getBoundingClientRect(),s=r.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 r?r.pointerType:"")==="touch"?32:0;return (e.dir==="rtl"?s<i.right+c&&s>i.right-l-c:s>i.left-c&&s<i.left+l+c)?e:null}var io=class extends M{constructor(t={}){super("list",["toolbar"]),this.config=t;}getMaxListDepth(){let t=this.config.maxDepth;if(!Number.isFinite(t))return ea;let e=Math.floor(t);return e>=1?e:ea}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),i=t.registerCommand(INDENT_CONTENT_COMMAND,()=>{let d=$getSelection();return !$isRangeSelection(d)||!no(d).listNode?false:to(d,this.getMaxListDepth())},COMMAND_PRIORITY_EDITOR),s=d=>{t.isEditable()||Ar(d)&&(d.preventDefault(),d.stopPropagation());},a=d=>{if(t.isEditable())return;let c=Ar(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(),i(),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=no(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=no(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=no(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)&&(to(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)||to(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)||to(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 i=Et(o);for(let s of i)this.applyOrderedPattern(s,e);});},setOrderedListSuffix:e=>{t.update(()=>{let n=$getSelection();if(!$isRangeSelection(n))return;let o=Et(n);for(let i of o)i.getListType()==="number"&&this.applyOrderedSuffix(i,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 i=Et(o);for(let s of i)this.applyUnorderedPattern(s,e);});},setCheckListVariant:e=>{let n=false;t.update(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let i=Et(o);if(i.length===0){n=true;return}for(let s of i)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 i=Et(o);for(let s of i)s.getListType()!=="check"&&this.convertTopListType(s,"check"),this.applyCheckListVariant(s,e);}));},rehydrateListStyles:()=>{t.update(()=>{let e=$getRoot(),n=new Map;xt(e.getChildren(),o=>{if($isListNode(o)){let i=nn(o);n.set(i.getKey(),i);}});for(let o of n.values()){if(o.getListType()==="number"){let i=he(o,"--luthor-ordered-pattern")??yt,s=Object.hasOwn(bt,i)?i:yt,a=he(o,"--luthor-ordered-suffix")==="paren"?"paren":"dot";this.applyOrderedPattern(o,s),this.applyOrderedSuffix(o,a);continue}if(o.getListType()==="bullet"){let i=wr(o);this.applyUnorderedPattern(o,i);continue}if(o.getListType()==="check"){let i=kr(o);this.applyCheckListVariant(o,i);}}});}}}applyOrderedPattern(t,e){if(t.getListType()!=="number")return;let n=bt[e],o=he(t,"--luthor-ordered-suffix")??"dot";oe(t,{"--luthor-ordered-pattern":e,"--luthor-ordered-suffix":o});let i=[t];for(;i.length>0;){let s=i.pop();if(s.getListType()!=="number")continue;let a=Zn(s,t),l=eo(n,a),d=e==="decimal-hierarchical";en(s),oe(s,{"--luthor-ordered-pattern":e,"--luthor-ordered-suffix":o,"list-style-type":"none",[Ne]:null});let c=d?sa(s,t):null,u=0;for(let m of s.getChildren()){if(!$isListItemNode(m))continue;let f=Zt(m);f&&(u+=1);let g=ia(l,Math.max(1,u),o==="paren"?"paren":"dot",d?[...c??[],Math.max(1,u)]:null);en(m),oe(m,{[Ne]:f?g:null}),i.push(...rt(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(...rt(a));}}let o=he(t,"--luthor-ordered-pattern")??yt,i=Object.hasOwn(bt,o)?o:yt;this.applyOrderedPattern(t,i);}applyUnorderedPattern(t,e){if(t.getListType()!=="bullet")return;let n=tn[e];oe(t,{[Fe]:e});let o=[t];for(;o.length>0;){let i=o.pop();if(i.getListType()!=="bullet")continue;let s=Zn(i,t),a=eo(n,s),l=Mr(a);oe(i,{[Fe]:e,"list-style-type":"none","--luthor-unordered-marker-content":null,[He]:null,[Ne]:null});for(let d of i.getChildren())$isListItemNode(d)&&(oe(d,{[Fe]:e,"--luthor-unordered-marker-content":null,[He]:Zt(d)?l:null,[Ne]:null}),Lr(d,e),o.push(...rt(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,[He]:null,[Ne]:null,"--luthor-unordered-pattern":null,"--luthor-ordered-pattern":null,"--luthor-ordered-suffix":null,"list-style-type":null});for(let i of o.getChildren()){if(!$isListItemNode(i))continue;oe(i,{"--luthor-checklist-variant":e,[Fe]:null,"--luthor-unordered-marker-content":null,[He]:null,[Ne]:null}),Lr(i,null);let s=Pr(i);for(let a of s)oe(a,{[oo]:e==="plain"?"plain":null});n.push(...rt(i));}}}}syncListNodeStyles(t){let e=nn(t);if(e.getListType()==="number"){let n=he(e,"--luthor-ordered-pattern")??yt;if(!Object.hasOwn(bt,n))return;let o=bt[n],i=Zn(t,e),s=eo(o,i),a=n==="decimal-hierarchical",l=he(e,"--luthor-ordered-suffix")??"dot";en(t),oe(t,{"--luthor-ordered-pattern":n,"--luthor-ordered-suffix":l,"list-style-type":"none",[Ne]:null});let d=a?sa(t,e):null,c=0;for(let u of t.getChildren()){if(!$isListItemNode(u))continue;let m=Zt(u);m&&(c+=1);let f=ia(s,Math.max(1,c),l==="paren"?"paren":"dot",a?[...d??[],Math.max(1,c)]:null);en(u),oe(u,{[Ne]:m?f:null});}return}if(e.getListType()==="bullet"){let n=wr(e),o=tn[n],i=Zn(t,e),s=eo(o,i),a=Mr(s);oe(t,{[Fe]:n,"list-style-type":"none","--luthor-unordered-marker-content":null,[He]:null,[Ne]:null});for(let l of t.getChildren())$isListItemNode(l)&&(oe(l,{[Fe]:n,"--luthor-unordered-marker-content":null,[He]:Zt(l)?a:null,[Ne]:null}),Lr(l,n));return}if(e.getListType()==="check"){let n=kr(e);oe(t,{"--luthor-checklist-variant":n,"--luthor-unordered-marker-content":null,[He]:null,[Ne]: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,[Fe]:null,"--luthor-unordered-marker-content":null,[He]:null,[Ne]:null});let i=Pr(o);for(let s of i)oe(s,{[oo]:n==="plain"?"plain":null});}}}convertTopListType(t,e){let n=[t];for(;n.length>0;){let i=n.pop();i.setListType(e);for(let s of i.getChildren())$isListItemNode(s)&&n.push(...rt(s));}if(e==="number"){let i=he(t,"--luthor-ordered-pattern"),s=i&&Object.hasOwn(bt,i)?i:yt,a=he(t,"--luthor-ordered-suffix")==="paren"?"paren":"dot";this.applyOrderedPattern(t,s),this.applyOrderedSuffix(t,a);return}if(e==="bullet"){let i=wr(t);this.applyUnorderedPattern(t,i);return}let o=kr(t);this.applyCheckListVariant(t,o);}handleOrderedListShortcut(t){let e=$getSelection();if(!$isRangeSelection(e)||!e.isCollapsed())return false;let n=e.anchor.getNode();if(ro(n))return false;let o=n;for(;o&&!$isParagraphNode(o);)o=o.getParent();if(!$isParagraphNode(o))return false;let i=o,s=tg(i.getTextContent());if(!s)return false;i.clear(),t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);let a=$getSelection();if(!$isRangeSelection(a))return true;let l=Et(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);});})}}},ig=new io;var ag="plain";function on(){return ag}function ua(){return PrismTokenizer}async function ma(r){return r?.provider?r.provider:r?.loadProvider?r.loadProvider():null}async function ga(r){return r?r.tokenizer?r.tokenizer:r.getTokenizer?r.getTokenizer():null:null}var uo=class uo extends M{constructor(){super("code",["toolbar"]);N(this,"codeHighlightProviderPromise",null);N(this,"lineNumberTextCache",new Map);N(this,"appliedLineNumberNodeKeys",new Set);this.config={syntaxHighlighting:"auto",showLineNumbers:true};}register(e){let n=()=>{},o=false,i=()=>{o||this.ensureCodeBlockLineNumbers(e);},s=d=>{n(),n=registerCodeHighlighting(e,d);};this.config.syntaxHighlighting!=="disabled"&&(s(this.config.tokenizer??ua()),this.resolveConfiguredTokenizer().then(d=>{o||!d||s(d);}));let a=e.registerUpdateListener(({dirtyElements:d,dirtyLeaves:c})=>{(d.size>0||c.size>0)&&i();});queueMicrotask(()=>{i();});let l=e.registerCommand(KEY_TAB_COMMAND,d=>{let c=false;return e.update(()=>{let u=$getSelection();if(!$isRangeSelection(u))return;let m=u.anchor.getNode();this.getBlockNode(m)&&(c=true,!this.hasReachedCodeTabLimit(u)&&u.insertText(" "));}),c?(d?.preventDefault(),true):false},COMMAND_PRIORITY_LOW);return ()=>{o=true,n(),a(),l(),this.appliedLineNumberNodeKeys.clear();}}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 i=$createCodeNode();return i.setTheme?.(on()),i});}});}async resolveConfiguredTokenizer(){if(this.config.tokenizer)return this.config.tokenizer;let e=await this.loadCodeHighlightProvider();return ga(e)}async loadCodeHighlightProvider(){return this.config.provider?this.config.provider:this.codeHighlightProviderPromise?this.codeHighlightProviderPromise:(this.codeHighlightProviderPromise=ma(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 i=$getSelection();if(!$isRangeSelection(i)){o=false;return}let s=i.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 i=o.getTextContent(),s=typeof n.offset=="number"?n.offset:i.length,a=Math.max(0,Math.min(i.length,s)),l=i.lastIndexOf(`
|
|
68
|
+
`,a-1)+1;return (i.slice(l,a).match(/^\t*/)?.[0].length??0)>=uo.MAX_CODE_TAB_DEPTH}ensureCodeBlockLineNumbers(e){let n=this.config.showLineNumbers!==false,o=e.getEditorState().read(()=>$nodesOfType(CodeNode).map(s=>({key:s.getKey(),lineCount:this.getCodeBlockLineCount(s.getTextContent())}))),i=new Set;o.forEach(({key:s,lineCount:a})=>{i.add(s);let l=e.getElementByKey(s);if(!l)return;if(!n){this.clearCodeBlockLineNumberAttributes(l),this.appliedLineNumberNodeKeys.delete(s);return}let d=Math.max(1,a),c=String(d);(l.getAttribute("data-luthor-line-number-count")!==c||!l.hasAttribute("data-luthor-line-numbers"))&&(l.setAttribute("data-luthor-line-number-count",c),l.setAttribute("data-luthor-line-numbers",this.getCodeBlockLineNumberText(d)),l.style.setProperty("--luthor-code-line-number-gutter-width",`${Math.max(2,c.length)}ch`)),l.classList.add("luthor-code-block--line-numbers"),this.appliedLineNumberNodeKeys.add(s);}),Array.from(this.appliedLineNumberNodeKeys).forEach(s=>{if(n&&i.has(s))return;let a=e.getElementByKey(s);a&&this.clearCodeBlockLineNumberAttributes(a),this.appliedLineNumberNodeKeys.delete(s);});}clearCodeBlockLineNumberAttributes(e){e.classList.remove("luthor-code-block--line-numbers"),e.removeAttribute("data-luthor-line-numbers"),e.removeAttribute("data-luthor-line-number-count"),e.style.removeProperty("--luthor-code-line-number-gutter-width");}getCodeBlockLineCount(e){if(!e)return 1;let n=1;for(let o=0;o<e.length;o+=1)e[o]===`
|
|
69
69
|
`&&(n+=1);return Math.max(1,n)}getCodeBlockLineNumberText(e){let n=this.lineNumberTextCache.get(e);if(n)return n;let o=Array.from({length:e},(i,s)=>String(s+1)).join(`
|
|
70
|
-
`);return this.lineNumberTextCache.set(e,o),o}};T(yo,"MAX_CODE_TAB_DEPTH",8);var bo=yo,zg=new bo;function $g(r){return r??"lazy"}function jg(r){if(typeof window<"u"){let e=window.requestIdleCallback,n=window.cancelIdleCallback;if(typeof e=="function"){let o=e(r,{timeout:500});return ()=>{typeof n=="function"&&n(o);}}}let t=setTimeout(r,16);return ()=>clearTimeout(t)}var Jg='<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>',Gg='<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>',Xg=["plaintext","typescript","javascript","jsx","tsx","json","markdown","html","css","python","bash","yaml","sql","graphql","java","c","cpp","csharp","go","docker","rust","php","ruby","perl","lua","r","scala","dart","toml","kotlin","swift","powershell","xml"],Zg={atom:"Atom",bash:"Bash",c:"C",csharp:"C#",clike:"C-like",cpp:"C++",css:"CSS",dart:"Dart",diff:"Diff",docker:"Dockerfile",dockerfile:"Dockerfile",go:"Go",graphql:"GraphQL",html:"HTML",java:"Java",javascript:"JavaScript",json:"JSON",js:"JavaScript",jsx:"JSX",kotlin:"Kotlin",lua:"Lua",markup:"Markup",markdown:"Markdown",mathml:"MathML",objc:"Objective-C",objectivec:"Objective-C",perl:"Perl",plain:"Plain Text",php:"PHP",powershell:"PowerShell",py:"Python",r:"R",ruby:"Ruby",rss:"RSS",rust:"Rust",scala:"Scala",sql:"SQL",ssml:"SSML",svg:"SVG",swift:"Swift",toml:"TOML",tsx:"TSX",txt:"Plain Text",typescript:"TypeScript",yaml:"YAML",xml:"XML"},xo=class extends M{constructor(){super("codeIntelligence"),this.config={isCopyAllowed:true};}register(t){let e=of(t,TRANSFORMERS),n=registerMarkdownShortcuts(t,e),o=t.registerUpdateListener(({dirtyElements:i,dirtyLeaves:s})=>{(i.size>0||s.size>0)&&this.ensureCodeBlockThemes(t);});return queueMicrotask(()=>{this.ensureCodeBlockThemes(t);}),()=>{n(),o();}}getPlugins(){return [createElement(tf,{key:"code-intelligence-controls",extension:this})]}getCommands(t){return {setCodeLanguage:e=>{let n=We(e)??"plain",o=this.getThemeForLanguage(n);t.update(()=>{this.getSelectionCodeNodes().forEach(i=>{i.setLanguage(n),i.setTheme(o);});});},autoDetectCodeLanguage:async()=>null,getCurrentCodeLanguage:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=this.getSelectionCodeNodes();e(n[0]?.getLanguage()??null);});}),getCodeLanguageOptions:()=>this.getLanguageOptions(),copySelectedCodeBlock:async()=>{if(!this.isCopyAllowed())return false;let e=await this.getPrimaryCodeBlockText(t);return !e||!e.text.trim()?false:Fa(e.text)}}}isCopyAllowed(){return this.config.isCopyAllowed!==false}getLanguageOptionsSnapshot(){return this.getLanguageOptions()}getCodeBlocksSnapshot(t){return t.getEditorState().read(()=>$nodesOfType(CodeNode).map(e=>{let n=We(e.getLanguage());return {key:e.getKey(),language:n??"plain",text:e.getTextContent()}}))}setCodeBlockLanguage(t,e,n){t.isEditable()&&t.update(()=>{let o=$getNodeByKey(e);if(!o||!$isCodeNode(o))return;let i=We(n)??"plain";o.setLanguage(i),o.setTheme(this.getThemeForLanguage(i));});}getCodeBlockText(t,e){return t.getEditorState().read(()=>{let n=$getNodeByKey(e);return !n||!$isCodeNode(n)?"":n.getTextContent()})}getThemeForLanguage(t){let e=We(t);return !e||e==="plain"?on():"hljs"}ensureCodeBlockThemes(t){let e=t.getEditorState().read(()=>$nodesOfType(CodeNode).map(n=>{let o=n.getLanguage(),i=We(o),s=typeof o=="string"&&o.trim().length>0&&!i,a=n.getTheme?.()??"",l=this.getThemeForLanguage(s?"plain":i);return {key:n.getKey(),nextLanguage:s?"plain":null,nextTheme:l??on(),currentTheme:a}}).filter(n=>n.nextLanguage!==null||n.currentTheme!==n.nextTheme));e.length!==0&&t.update(()=>{e.forEach(n=>{let o=$getNodeByKey(n.key);!o||!$isCodeNode(o)||(n.nextLanguage&&o.setLanguage(n.nextLanguage),o.setTheme(n.nextTheme));});});}getSelectionCodeNodes(){let t=$getSelection();if(!$isRangeSelection(t))return [];let e=t.getNodes(),n=new Map;return e.forEach(o=>{let i=this.getNearestCodeNode(o);i&&n.set(i.getKey(),i);}),Array.from(n.values())}getNearestCodeNode(t){let e=t;for(;e;){if($isCodeNode(e))return e;e=e.getParent();}return null}getLanguageOptions(){let t=Xg.map(o=>We(o)).filter(o=>!!o),e=sf(this.config.languageOptions);if(!e)return qr(t);let n=af(e.values);return e.mode==="replace"?qr(n):qr([...t,...n])}async getPrimaryCodeBlockText(t){return new Promise(e=>{t.getEditorState().read(()=>{let o=this.getSelectionCodeNodes()[0];if(!o){e(null);return}let i=o.getTextContent().trim();if(!i){e(null);return}e({key:o.getKey(),text:i});});})}},ef=34;function tf({extension:r}){let[t]=useLexicalComposerContext(),[e,n]=useState(()=>t.isEditable()),[o,i]=useState([]),[s,a]=useState({}),l=useRef(null),d=useRef(new Map),c=r.getLanguageOptionsSnapshot(),u=useMemo(()=>c.map(b=>({id:b,label:lf(b)})),[c]),m=useCallback(()=>{let b=Ha(t);if(!b)return [];let E=b.getBoundingClientRect(),w=r.getCodeBlocksSnapshot(t),x=[];return w.forEach(L=>{let k=t.getElementByKey(L.key);if(!k||!k.isConnected)return;k.classList.add("luthor-code-block--interactive");let I=k.getBoundingClientRect(),D=Math.max(120,Math.round(I.width)),Y=Math.max(0,Math.round(I.top-E.top-ef)),ee=Math.max(0,Math.round(I.left-E.left));x.push({key:L.key,language:L.language,top:Y,left:ee,width:D});}),x},[t,r]),f=useCallback(()=>{let b=m();i(E=>nf(E,b)?E:b);},[m]),g=useCallback(()=>{l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null,f();}));},[f]),y=useCallback(b=>{let E=d.current.get(b);E&&(clearTimeout(E),d.current.delete(b));},[]),C=useCallback((b,E)=>{y(b),a(x=>({...x,[b]:E}));let w=setTimeout(()=>{a(x=>{if(!(b in x))return x;let L={...x};return delete L[b],L}),d.current.delete(b);},1200);d.current.set(b,w);},[y]),h=useCallback((b,E)=>{e&&(r.setCodeBlockLanguage(t,b,E),g());},[t,r,e,g]),p=r.isCopyAllowed(),S=useCallback(async b=>{if(!p)return;let E=r.getCodeBlockText(t,b);if(!E.trim())return;if(await Fa(E)){C(b,"copied");return}C(b,"error");},[p,t,r,C]);if(useEffect(()=>t.registerEditableListener(n),[t]),useEffect(()=>{g();let b=0,E=null,w=()=>{g(),b+=1,!(b>=20)&&(E=requestAnimationFrame(w));};E=requestAnimationFrame(w);let x=t.registerUpdateListener(()=>{g();}),L=()=>{g();},k=d.current;return window.addEventListener("scroll",L,true),window.addEventListener("resize",L,{passive:true}),()=>{x(),window.removeEventListener("scroll",L,true),window.removeEventListener("resize",L),E!==null&&cancelAnimationFrame(E),l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),k.forEach(I=>clearTimeout(I)),k.clear();}},[t,g]),useEffect(()=>{let b=new Set(o.map(E=>E.key));a(E=>{let w=false,x={};return Object.entries(E).forEach(([L,k])=>{if(b.has(L)){x[L]=k;return}w=true,y(L);}),w?x:E});},[y,o]),typeof document>"u"||o.length===0)return null;let N=Ha(t);return N?createPortal(createElement("div",{className:"luthor-codeblock-controls-layer","aria-hidden":false},o.map(b=>{let E=s[b.key],w=["luthor-codeblock-copy",E==="copied"?"is-copied":"",E==="error"?"is-copy-error":""].filter(Boolean).join(" "),x=E==="copied"?"Copied":E==="error"?"Copy failed":"Copy to clipboard";return createElement("div",{key:b.key,className:"luthor-codeblock-controls","data-code-node-key":b.key,style:{position:"absolute",top:`${b.top}px`,left:`${b.left}px`,width:`${b.width}px`}},createElement("span",{className:"luthor-codeblock-controls-left"},createElement("select",{className:"luthor-codeblock-language",value:b.language,"aria-label":"Code language",disabled:!e,"aria-disabled":!e,onChange:L=>{let k=L.target;h(b.key,k.value);}},u.map(L=>createElement("option",{key:L.id,value:L.id},L.label)))),createElement("span",{className:"luthor-codeblock-controls-right"},p?createElement("button",{className:w,type:"button","aria-label":"Copy code",title:x,"data-tooltip":x,onMouseDown:L=>{L.preventDefault();},onClick:()=>{S(b.key);},dangerouslySetInnerHTML:{__html:E==="copied"?Gg:Jg}}):null))})),N):null}function nf(r,t){if(r.length!==t.length)return false;for(let e=0;e<r.length;e+=1){let n=r[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 Fa(r){if(typeof navigator<"u"&&navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(r),!0}catch{}if(typeof document>"u")return false;let t=document.createElement("textarea");t.value=r,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 Ha(r){let t=r.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 We(r){let t=Be(r);return t?ka(t):null}function of(r,t){return t.filter(e=>{let n=e.dependencies;return !n||n.length===0?true:r.hasNodes([...n])})}var rf=new xo;function sf(r){if(!r)return null;if(Array.isArray(r))return {mode:"append",values:r};let t=r;return {mode:t.mode??"append",values:Array.isArray(t.values)?t.values:[]}}function af(r){let t=[],e=new Set;for(let n of r){let o=n.trim();if(!o)continue;let i=We(o);if(!i)throw new Error(`[CodeIntelligenceExtension] Invalid language option "${n}". Use a supported language ID or alias (excluding "auto").`);if(e.has(i))throw new Error(`[CodeIntelligenceExtension] Duplicate language option "${n}". It resolves to "${i}", which is already configured.`);e.add(i),t.push(i);}return t}function qr(r){return Array.from(new Set(r)).sort((t,e)=>t.localeCompare(e))}function lf(r){let t=We(r)??Be(r)??r.trim().toLowerCase();return t?Zg[t]??cf(t):"Plain Text"}function cf(r){let t=r.trim();return t?t.split(/[-_]+/).filter(e=>e.length>0).map(e=>e.length<=2?e.toUpperCase():`${e[0]?.toUpperCase()??""}${e.slice(1)}`).join(" "):"Plain Text"}var Co=class extends ae{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},i=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=i(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(),f=Math.max(4,Math.min(8,m.width/2)),g=null,y=0;a.clientX<=m.left+f?(g=o(u),y=0):a.clientX>=m.right-f&&(g=i(u),y=g?.data.length??0),g&&(a.preventDefault(),t.focus(()=>{let C=window.getSelection();if(!C)return;let h=document.createRange();h.setStart(g,y),h.collapse(true),C.removeAllRanges(),C.addRange(h);}));};return n.addEventListener("click",s,true),()=>{n.removeEventListener("click",s,true),e();}}},df=new Co;var No=class extends M{constructor(){super("blockFormat",["toolbar"]);}register(t){let e=t.registerCommand(INSERT_PARAGRAPH_COMMAND,()=>{let o=$getSelection();if($isRangeSelection(o)){let i=o.anchor.getNode(),s=this.getBlockNode(i);if(s&&($isHeadingNode(s)||$isQuoteNode(s)))return false}return false},COMMAND_PRIORITY_NORMAL),n=t.registerCommand(KEY_ENTER_COMMAND,o=>{let i=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"),i=true);}),i&&o?.preventDefault(),i},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 i=o.getNodes();for(let s of i){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 i=o.getNodes();for(let s of i){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(),i=this.getBlockNode(o);i&&(e=this.getNodeFormat(i));}}),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}},Cf=new No;var To=class extends M{constructor(){super("history",["toolbar"]);T(this,"canUndoState",false);T(this,"canRedoState",false);}register(e){let n=e.registerCommand(CAN_UNDO_COMMAND,i=>(this.canUndoState=i,false),COMMAND_PRIORITY_LOW),o=e.registerCommand(CAN_REDO_COMMAND,i=>(this.canRedoState=i,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}}},kf=new To;var ko=class extends M{constructor(e){super("draggableBlock",["floating"]);T(this,"isDraggingState",false);T(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(If,{config:this.config,extension:this},"draggable-block")]}getCommands(e){return {moveBlock:(n,o,i)=>{e.isEditable()&&e.update(()=>{let s=$getNodeByKey(n),a=$getNodeByKey(o);s&&a&&(s.remove(),i?a.insertAfter(s):a.insertBefore(s));});},moveCurrentBlockUp:()=>{e.isEditable()&&e.update(()=>{let n=$getSelection();if($isRangeSelection(n)){let o=n.anchor.getNode(),i=$isElementNode(o)?o:o.getParent();if(i&&$isElementNode(i)){let s=i.getPreviousSibling();s&&(i.remove(),s.insertBefore(i));}}});},moveCurrentBlockDown:()=>{e.isEditable()&&e.update(()=>{let n=$getSelection();if($isRangeSelection(n)){let o=n.anchor.getNode(),i=$isElementNode(o)?o:o.getParent();if(i&&$isElementNode(i)){let s=i.getNextSibling();s&&(i.remove(),s.insertAfter(i));}}});}}}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)}},Af=new ko;function If({config:r,extension:t}){let[e]=useLexicalComposerContext(),{config:n,extensions:o}=Oe(),s=o.find(v=>v.name==="draggableBlock")?.config,a=useMemo(()=>n?.theme?.draggable||{},[n?.theme?.draggable]),[l,d]=useState(null),[c,u]=useState(false),[m,f]=useState(()=>e.isEditable()),[g,y]=useState(null),[C,h]=useState(false),p=useRef(null),S=useRef(null),N=useRef(null),b=useRef(null),E=useRef(null),w=useRef(null),x=useRef(null),L=useRef(null),[k,I]=useState(null);useEffect(()=>{t.setIsDragging(c);},[c,t]);let D=typeof document<"u"&&typeof window<"u",Y=e.getRootElement(),ee=D?Y?.closest?.(".luthor-editor")||Y?.parentElement||document.body:null,B=s?.anchorElem||r.anchorElem||ee,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:{}}),[]),W=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]),j=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(v=>{if(!v||!j.blockDragging)return;(j.blockDragging.includes(" ")?j.blockDragging.split(" ").filter(Boolean):[j.blockDragging]).forEach(A=>v.classList.remove(A)),v.style.opacity="";},[j]),O=useCallback(v=>{if(!v||!j.blockDragging)return;(j.blockDragging.includes(" ")?j.blockDragging.split(" ").filter(Boolean):[j.blockDragging]).forEach(A=>v.classList.add(A)),Object.assign(v.style,W.blockDragging);},[j,W.blockDragging]);useEffect(()=>e.registerEditableListener(v=>{f(v),!v&&(u(false),y(null),d(null),h(false),p.current&&K(p.current),p.current=null,S.current=null);}),[e,K]);let J=useCallback(()=>{let v=e.getRootElement();if(v)try{v.focus({preventScroll:!0});}catch{v.focus();}},[e]),G=useCallback(()=>{p.current&&K(p.current),u(false),y(null),J(),setTimeout(()=>{p.current=null,S.current=null;},100);},[K,J]);useEffect(()=>()=>{p.current&&K(p.current),b.current&&clearTimeout(b.current),E.current!==null&&window.cancelAnimationFrame(E.current),x.current!==null&&window.cancelAnimationFrame(x.current);},[K]),useEffect(()=>{N.current=l;},[l]);let Z=useCallback(v=>{w.current=v,E.current===null&&(E.current=window.requestAnimationFrame(()=>{E.current=null;let P=w.current;d(A=>A===P?A:P);}));},[]),ge=useCallback(v=>{L.current=v,x.current===null&&(x.current=window.requestAnimationFrame(()=>{x.current=null;let P=L.current;P!=null&&I(A=>A!=null&&Math.abs(A-P)<.5?A:P);}));},[]),be=useCallback(v=>{let P=null;e.update(()=>{let A=$createParagraphNode(),H=$getNearestNodeFromDOMNode(v);if(H)try{H.getTopLevelElementOrThrow().insertAfter(A);}catch{$getRoot().append(A);}else $getRoot().append(A);A.selectStart(),P=A.getKey();}),P&&setTimeout(()=>{let A=e.getElementByKey(P);if(A&&A instanceof HTMLElement&&typeof A.getBoundingClientRect=="function"){Z(A);let H=A.getBoundingClientRect();ge(H.top+window.scrollY+H.height/2);}},0),J();},[e,J,Z,ge]);useEffect(()=>{if(l||p.current)h(true);else {let v=setTimeout(()=>h(false),300);return ()=>clearTimeout(v)}},[l]),useEffect(()=>{let v=A=>{if(!m){Z(null);return}if(c)return;let H=e.getRootElement();if(!H)return;let _=A.target;ge(A.clientY+window.scrollY);let R=_&&_.closest&&(_.closest(".drag-handle-area")||_.closest('[draggable="true"]')||_.closest(".luthor-drag-button")||_.closest(".luthor-draggable-button-stack")),se=window.getSelection(),Q=se&&se.rangeCount>0&&!se.isCollapsed,$=null,F=_;for(;F&&F!==H&&F!==document.body;){if(F.parentElement===H){$=F;break}F=F.parentElement;}b.current&&(clearTimeout(b.current),b.current=null),($||R)&&!Q&&!c?$&&Z($):b.current=setTimeout(()=>{Z(null),b.current=null;},500);},P=()=>{c||(b.current&&(clearTimeout(b.current),b.current=null),b.current=setTimeout(()=>{Z(null),b.current=null;},300));};return document.addEventListener("mousemove",v),document.addEventListener("mouseleave",P),()=>{document.removeEventListener("mousemove",v),document.removeEventListener("mouseleave",P),b.current&&(clearTimeout(b.current),b.current=null),E.current!==null&&(window.cancelAnimationFrame(E.current),E.current=null),x.current!==null&&(window.cancelAnimationFrame(x.current),x.current=null);}},[e,c,m,Z,ge]);let $e=useCallback((v,P)=>{if(!e.isEditable()){v.preventDefault();return}v.stopPropagation(),u(true),y(null),p.current=P,O(P);let A=e.read(()=>{let _=$getNearestNodeFromDOMNode(P);return _?_.getKey():null});A&&(S.current=A,v.dataTransfer?.setData("application/x-lexical-drag",JSON.stringify({key:A}))),v.dataTransfer.effectAllowed="move";let H=P.cloneNode(true);H.style.opacity="0.6",H.style.position="absolute",H.style.top="-9999px",H.style.left="-9999px",document.body.appendChild(H),v.dataTransfer.setDragImage(H,0,0),setTimeout(()=>document.body.removeChild(H),0);},[e,O]),Te=useCallback((v,P)=>{if(!e.isEditable())return;v.preventDefault(),u(true),p.current=P,O(P);let A=e.read(()=>{let H=$getNearestNodeFromDOMNode(P);return H?H.getKey():null});A&&(S.current=A);},[e,O]),je=useCallback(v=>{if(!e.isEditable()||!c||!p.current)return;v.preventDefault();let P=v.touches[0];if(!P)return;let A=e.getRootElement();if(!A)return;let H=null,_=document.elementFromPoint(P.clientX,P.clientY);if(_){let R=_;for(;R&&R!==A;){if(R.parentElement===A){H=R;break}R=R.parentElement;}}if(H&&H!==p.current){let R=H.getBoundingClientRect(),se=P.clientY<R.top+R.height/2;y({top:se?R.top+window.scrollY:R.bottom+window.scrollY,left:R.left+window.scrollX,width:R.width});}else y(null);},[e,c]),Ue=useCallback(v=>{if(!e.isEditable()){G();return}if(!c||!S.current)return;v.preventDefault();let P=v.changedTouches[0];if(!P)return;let A=e.getRootElement();if(!A)return;let H=null,_=document.elementFromPoint(P.clientX,P.clientY);if(_){let R=_;for(;R&&R!==A;){if(R.parentElement===A){H=R;break}R=R.parentElement;}}H&&H!==p.current&&(e.update(()=>{let R=$getNodeByKey(S.current),se=$getNearestNodeFromDOMNode(H);if(R&&se){let Q=H.getBoundingClientRect(),$=P.clientY>=Q.top+Q.height/2;R.remove(),$?se.insertAfter(R):se.insertBefore(R);}}),setTimeout(()=>{if(S.current)try{let R=e.getElementByKey(S.current);R&&R instanceof HTMLElement&&typeof R.getBoundingClientRect=="function"&&d(R);}catch(R){console.warn("Error finding moved element:",R);}},50)),G();},[e,c,G]);useEffect(()=>{let v=e.getRootElement();if(!v)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 Q=window.getSelection();if(!Q||Q.isCollapsed||!(s?.enableTextSelectionDrag??r.enableTextSelectionDrag)){_.preventDefault();return}let $=Q.anchorNode;$?.nodeType===Node.TEXT_NODE&&($=$.parentNode);let F=null;for(;$&&$!==v;){if($.parentNode===v){F=$;break}$=$.parentNode;}if(!F){_.preventDefault();return}Q.collapse(Q.anchorNode,Q.anchorOffset);let ie=e.read(()=>$getNearestNodeFromDOMNode(F)?.getKey()??null);if(!ie){_.preventDefault();return}_.dataTransfer.clearData(),_.dataTransfer.setData("application/x-lexical-drag",JSON.stringify({key:ie})),_.dataTransfer.effectAllowed="move";let q=F.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),y(null),p.current=F,O(F),S.current=ie;},A=_=>{if(!e.isEditable())return;let R=_.target;if(R.nodeType!==Node.ELEMENT_NODE&&(R=R.parentNode),!R||!(R instanceof HTMLElement))return;let se=R;_.preventDefault(),_.dataTransfer.dropEffect="move";let Q=null,$=se;for(;$&&$!==v;){if($.parentElement===v){Q=$;break}$=$.parentElement;}if(Q&&Q!==p.current){let F=Q.getBoundingClientRect(),ie=_.clientY<F.top+F.height/2;y({top:ie?F.top+window.scrollY:F.bottom+window.scrollY,left:F.left+window.scrollX,width:F.width});}else y(null);},H=_=>{if(!e.isEditable())return;let R=_.target;if(R.nodeType!==Node.ELEMENT_NODE&&(R=R.parentNode),!R||!(R instanceof HTMLElement))return;let se=R;_.preventDefault(),y(null);let Q=_.dataTransfer?.getData("application/x-lexical-drag");if(!Q){G();return}let{key:$}=JSON.parse(Q);if(!$){G();return}let F=null,ie=se;for(;ie&&ie!==v;){if(ie.parentElement===v){F=ie;break}ie=ie.parentElement;}F&&F!==p.current&&(e.update(()=>{let q=$getNodeByKey($),Me=$getNearestNodeFromDOMNode(F);if(q&&Me){let dt=F.getBoundingClientRect(),mn=_.clientY>=dt.top+dt.height/2;q.remove(),mn?Me.insertAfter(q):Me.insertBefore(q);}}),setTimeout(()=>{if(S.current)try{let q=e.getElementByKey(S.current);q&&q instanceof HTMLElement&&typeof q.getBoundingClientRect=="function"&&d(q);}catch(q){console.warn("Error finding moved element:",q);}J();},50)),G();};return v.addEventListener("dragstart",P),v.addEventListener("dragover",A),v.addEventListener("drop",H),v.addEventListener("dragend",G),()=>{v.removeEventListener("dragstart",P),v.removeEventListener("dragover",A),v.removeEventListener("drop",H),v.removeEventListener("dragend",G);}},[e,G,O,J,s?.enableTextSelectionDrag,r.enableTextSelectionDrag]),useEffect(()=>{if(!c)return;let v=()=>{G();},P=H=>{H.key==="Escape"&&G();},A=()=>{document.hidden&&G();};return window.addEventListener("dragend",v),window.addEventListener("drop",v),window.addEventListener("blur",v),document.addEventListener("keydown",P),document.addEventListener("visibilitychange",A),()=>{window.removeEventListener("dragend",v),window.removeEventListener("drop",v),window.removeEventListener("blur",v),document.removeEventListener("keydown",P),document.removeEventListener("visibilitychange",A);}},[c,G]),useEffect(()=>{let v=e.getRootElement();if(!v)return;let P=null,A=0,H=0,_=Q=>{if(!e.isEditable()||Q.touches.length!==1||!(s?.enableTextSelectionDrag??r.enableTextSelectionDrag))return;let $=Q.touches[0];if(!$)return;let F=Q.target;if(F.nodeType!==Node.ELEMENT_NODE&&(F=F.parentNode),!F||!(F instanceof HTMLElement))return;let ie=F;ie.closest('[draggable="true"]')||(A=$.clientX,H=$.clientY,P=setTimeout(()=>{P=null;let q=null,Me=ie;for(;Me&&Me!==v;){if(Me.parentElement===v){q=Me;break}Me=Me.parentElement;}if(!q)return;let dt=window.getSelection();dt&&!dt.isCollapsed&&dt.collapseToStart(),u(true),p.current=q,O(q);let mn=e.read(()=>$getNearestNodeFromDOMNode(q)?.getKey()??null);mn&&(S.current=mn);},500));},R=Q=>{if(P&&Q.touches.length===1){let $=Q.touches[0];if(!$)return;let F=$.clientX-A,ie=$.clientY-H;Math.sqrt(F*F+ie*ie)>10&&(clearTimeout(P),P=null);}},se=()=>{P&&(clearTimeout(P),P=null);};return v.addEventListener("touchstart",_,{passive:false}),v.addEventListener("touchmove",R,{passive:false}),v.addEventListener("touchend",se,{passive:false}),document.addEventListener("touchmove",je,{passive:false}),document.addEventListener("touchend",Ue,{passive:false}),()=>{v.removeEventListener("touchstart",_),v.removeEventListener("touchmove",R),v.removeEventListener("touchend",se),document.removeEventListener("touchmove",je),document.removeEventListener("touchend",Ue);}},[e,O,G,c,je,Ue,s?.enableTextSelectionDrag,r.enableTextSelectionDrag]);let fe=l||p.current;if(!m||!D||!B||!fe||typeof fe.getBoundingClientRect!="function")return null;let re=fe.getBoundingClientRect();if(!re.width||!re.height)return null;let Tt=Y?.closest?.(".luthor-editor")||null,_e=Tt||Y;if(!_e)return null;let Ke=_e.getBoundingClientRect(),Fo=window.getComputedStyle(_e),Bo=Number.parseFloat(Fo.getPropertyValue("--luthor-drag-gutter-width"))||40,Ye=m&&(s?.showAddButton??r.showAddButton)!==false,pl=Ye?52:24,hl=Ke.left+window.scrollX+Math.max(0,(Bo-pl)/2),bl=(s?.buttonStackPosition||r.buttonStackPosition)==="right"?re.right+window.scrollX+(s?.offsetRight||r.offsetRight||10):Tt?hl:re.left+window.scrollX+(s?.offsetLeft||r.offsetLeft||-40),un=24,ii=un/2,zo=re.top+window.scrollY,si=re.bottom+window.scrollY,yl=zo+re.height/2,El=k??yl,xl=zo+un/2,Cl=si-un/2,Sl=Math.min(Cl,Math.max(xl,El)),ai=zo,Nl=Math.max(ai,si-(ii+un/2)),Tl=Math.min(Nl,Math.max(ai,Sl-ii)),li=B.getBoundingClientRect(),ci=B===document.body?0:li.left+window.scrollX,di=B===document.body?0:li.top+window.scrollY,Ll=bl-ci,vl=Tl-di;return jsxs(Fragment,{children:[createPortal(jsx("div",{className:`luthor-draggable-button-stack ${j.buttonStack} ${C?"":"fade-out"}`,style:{position:"absolute",left:0,top:0,transform:`translate3d(${Ll}px, ${vl}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",...W.buttonStack},children:jsxs("div",{style:{display:"flex",flexDirection:"row",alignItems:"center",gap:"4px"},children:[Ye&&jsx("button",{type:"button","aria-label":"Add block",title:"Add",className:`luthor-drag-button ${j.addButton}`,onMouseDown:v=>{v.preventDefault(),v.stopPropagation();},onClick:v=>{v.preventDefault(),v.stopPropagation(),!(!fe||c)&&be(fe);},style:W.addButton,children:"+"}),s?.handleRenderer||r.handleRenderer?(s?.handleRenderer||r.handleRenderer)({rect:re,isDragging:c,onDragStart:v=>$e(v,fe),className:`luthor-drag-button ${j.handle} ${c?j.handleActive:""}`.trim()}):jsx("div",{className:`luthor-drag-button ${j.handle} ${c?j.handleActive:""}`.trim(),draggable:true,onDragStart:v=>$e(v,fe),onDragEnd:G,onTouchStart:v=>Te(v,fe),style:c?W.handleActive:W.handle,children:"\u22EE\u22EE"})]})}),B),g&&(s?.dropIndicatorRenderer||r.dropIndicatorRenderer?createPortal((s?.dropIndicatorRenderer||r.dropIndicatorRenderer)({...g,className:j.dropIndicator}),B):createPortal(jsx("div",{className:j.dropIndicator,style:{position:"absolute",top:g.top-4-di,left:g.left-ci,width:g.width,height:"8px",pointerEvents:"none",zIndex:9997,...W.dropIndicator}}),B))]})}function qa(r){let t=renderToStaticMarkup(r),e=document.createElement("div");e.innerHTML=t;let n=e.firstElementChild;return e.remove(),n}function Kf(r){let t=r.isContainer??false,e=createCommand("insert-custom-node");function n({node:l,payload:d,nodeKey:c,children:u}){let[m]=useLexicalComposerContext(),[f,g]=useState(false);useEffect(()=>m.registerUpdateListener(({editorState:C})=>{C.read(()=>{let h=$getSelection();g($isNodeSelection(h)&&h.getNodes().some(p=>p.__key===c));});}),[m,c]);let y=C=>{m.update(()=>{let h=l.getWritable();h.__payload={...h.__payload,...C};});};return r.render?r.render({node:l,payload:d,children:u,nodeKey:c,isSelected:f,updatePayload:y}):null}class o extends ElementNode{constructor(c={},u,m){super(m);T(this,"__payload");T(this,"__nodeType");this.__payload=c,this.__nodeType=u;}static getType(){return r.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 r.importDOM?r.importDOM():{}}static exportDOM(c,{node:u}){if(r.exportDOM){let f=document.createElement("div");return r.exportDOM(c,{element:f,node:u})}let m=document.createElement("div");return m.setAttribute("data-custom-node-type",r.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(r.createDOM){let m=r.createDOM(c,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m.setAttribute("data-lexical-key",this.getKey()),m}if(r.jsx){let m=r.jsx({node:this,payload:this.__payload,nodeKey:this.getKey(),isSelected:false,updatePayload:g=>{this.setPayload(g);}}),f=qa(m);return f.setAttribute("data-custom-node-type",this.__nodeType),f.setAttribute("data-lexical-key",this.getKey()),f}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 r.updateDOM?r.updateDOM(c,u,m):false}getPayload(){return this.__payload}setPayload(c){let u=this.getWritable();u.__payload={...this.__payload,...c};}}class i extends DecoratorNode{constructor(c={},u,m){super(m);T(this,"__payload");T(this,"__nodeType");this.__payload=c,this.__nodeType=u;}static getType(){return r.nodeType}static clone(c){return new i(c.__payload,c.__nodeType,c.__key)}isSelectable(){return true}static importJSON(c){let{payload:u}=c;return new i(u,c.type)}static importDOM(){return r.importDOM?r.importDOM():{}}static exportDOM(c,{node:u}){if(r.exportDOM){let f=document.createElement("span");return r.exportDOM(c,{element:f,node:u})}let m=document.createElement("span");return m.setAttribute("data-custom-node-type",r.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),r.createDOM){let m=r.createDOM(c,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m}return u}updateDOM(c,u,m){return r.updateDOM?r.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=r.defaultPayload||{}){if(t){let d=new o(l,r.nodeType);if(r.initialChildren)r.initialChildren().forEach(u=>{if(u.type==="paragraph"){let m=$createParagraphNode();u.children&&u.children.forEach(f=>{f.type==="text"&&m.append($createTextNode(f.text||""));}),d.append(m);}});else {let c=$createParagraphNode();c.append($createTextNode("")),d.append(c);}return d}else return new i(l,r.nodeType)}class a extends M{constructor(){super(r.nodeType,["toolbar"]);}register(d){let c=d.registerCommand(e,m=>(d.update(()=>{let f=s(m),g=$getSelection();$isRangeSelection(g)?g.insertNodes([f]):$getRoot().append($createParagraphNode().append(f));}),true),COMMAND_PRIORITY_EDITOR),u=d.registerUpdateListener(({editorState:m})=>{t&&m.read(()=>{let f=$getSelection(),g=$isNodeSelection(f)?f.getNodes():[];d.getEditorState().read(()=>{let y=$getRoot(),C=h=>{if(h.getType()===r.nodeType){let p=g.some(N=>N.__key===h.__key),S=document.querySelector(`[data-lexical-key="${h.__key}"]`);S&&(S.setAttribute("data-selected",p.toString()),S.style.borderColor=p?"#007ACC":"#ccc",S.style.backgroundColor=p?"#f0f8ff":"transparent");}"getChildren"in h&&h.getChildren().forEach(C);};C(y);});});});return ()=>{c(),u();}}getNodes(){return t?[o]:[i]}getCommands(d){return {...{insertCustomNode:u=>d.dispatchCommand(e,u)},...r.commands?r.commands(d):{}}}getStateQueries(d){return {...{isCustomNodeActive:()=>new Promise(u=>{d.getEditorState().read(()=>{let m=$getSelection();u(!!m&&$isNodeSelection(m)&&m.getNodes().some(f=>f.getType()===r.nodeType));});})},...r.stateQueries?r.stateQueries(d):{}}}}return {extension:new a,$createCustomNode:s,jsxToDOM:qa}}function Ja(r,t,e){return e<=t?t:Math.min(e,Math.max(t,r))}function Wf(r,t,e,n){let o=r.getBoundingClientRect(),i=t.getBoundingClientRect(),s=Ja(e,o.left+1,o.right-1),a=Ja(n,i.top+1,i.bottom-1);return {x:s,y:a}}function qf(r,t){let e=document,n=window.getSelection();if(!n)return;let o=e.caretPositionFromPoint?.(r,t);if(o){let s=document.createRange();s.setStart(o.offsetNode,o.offset),s.collapse(true),n.removeAllRanges(),n.addRange(s);return}let i=e.caretRangeFromPoint?.(r,t);i&&(i.collapse(true),n.removeAllRanges(),n.addRange(i));}function Ga(r,t,e){let i=Array.from(r.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(),f=m.top+m.height/2;return Math.abs(u-e)<Math.abs(f-e)?d:l},null)??r.firstElementChild??r,{x:s,y:a}=Wf(r,i,t,e);r.focus(),qf(s,a);}function Jf(r){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(()=>r());return}globalThis.setTimeout(r,0);}function Xa(r){return !!r.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 Za=r=>{let{contentEditable:t,placeholder:e,className:n,nonEditableVisualMode:o=false,onEditIntent:i,classNames:s,styles:a,errorBoundary:l}=r,d=ln.useContext(Lt),c=d?.lexical??null,[u,m]=ln.useState(!o),f=ln.useRef(null),g=d?.config,y=typeof g?.placeholder=="string"?g.placeholder:void 0,C=g?.classNames,h=g?.styles,p=e??y??"Start writing...",S=s?.placeholder||C?.placeholder||Je.richText?.placeholder||"luthor-placeholder",N={position:"absolute",pointerEvents:"none",zIndex:1,...h?.placeholder,...a?.placeholder};return ln.useEffect(()=>{m(!o);},[o]),ln.useEffect(()=>{c?.setEditable(u);},[u,c]),jsx("div",{className:s?.container||C?.container||n||Je.container||"luthor-editor-container",onMouseDown:b=>{if(b.button!==0)return;let E=b.target;if(!E||Xa(E))return;let w=b.currentTarget,x=b.clientX,L=b.clientY;if(o&&!u){if(i){f.current={clientX:x,clientY:L};return}let I=w.querySelector("[contenteditable]");if(!I)return;b.preventDefault(),c?.setEditable(true),m(true),Jf(()=>{let D=w.querySelector("[contenteditable='true']")??I;Ga(D,x,L);});return}let k=w.querySelector("[contenteditable='true']");!k||k.contains(E)||(b.preventDefault(),Ga(k,x,L));},onMouseUp:b=>{if(b.button!==0||!i||!o||u){f.current=null;return}let E=b.target;if(!E||Xa(E)){f.current=null;return}let w=f.current;if(f.current=null,!w)return;let x=Math.abs(b.clientX-w.clientX),L=Math.abs(b.clientY-w.clientY);if(x>4||L>4)return;let k=window.getSelection();k&&!k.isCollapsed||i({clientX:b.clientX,clientY:b.clientY});},style:{position:"relative",cursor:o?"default":"text",...h?.container,...a?.container},children:jsx(RichTextPlugin,{contentEditable:t||jsx("div",{style:{display:"block"},children:jsx(ContentEditable,{className:s?.contentEditable||C?.contentEditable||Je.richText?.contentEditable||"luthor-content-editable",style:{...o?{cursor:"default",caretColor:"transparent",userSelect:"text",WebkitUserSelect:"text"}:{},...h?.contentEditable,...a?.contentEditable}})}),placeholder:typeof p=="string"?jsx("div",{className:S,style:N,children:p}):p||jsx("div",{className:S,style:N,children:"Start writing..."}),ErrorBoundary:l||Zf})})},ei=class extends M{constructor(t={}){super("richText",["floating"]),this.config={showInToolbar:false,position:"after",...t};}register(t){return ()=>{}}getPlugins(){return [jsx(Za,{...this.config},"rich-text")]}},Gf=new ei,Xf=r=>jsx(Za,{...r}),Zf=({children:r,onError:t})=>{try{return jsx(Fragment,{children:r})}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 sl=8,cp=9,Mo=class extends M{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 i=o.anchor.getNode();if(this.isInCodeBlock(i))return false;n.preventDefault();let s=this.resolveTabContext(i);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(i)||t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),true):s==="heading"?n.shiftKey?(t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0),true):(this.isBlockAtMaxIndent(i)||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)):cp,o=Math.max(0,n-1),i=this.findNearestListItemNode(t);if(i&&typeof i.getIndent=="function"){let a=i.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>=sl}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(),i=typeof e.offset=="number"?e.offset:o.length,s=Math.max(0,Math.min(o.length,i)),a=o.lastIndexOf(`
|
|
71
|
-
`,s-1)+1;return (o.slice(a,s).match(/^\t*/)?.[0].length??0)>=sl}},dp=new Mo;var dl=[{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"]}],ll=dl,Ao={":)":"\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 fp(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dn(r){return r.trim().toLowerCase().replace(/^:+|:+$/g,"")}function cl(r){return r.toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}function oi(r){let t=r.map(o=>({...o,shortcodes:[...o.shortcodes],keywords:o.keywords?[...o.keywords]:void 0})),e=new Map,n=t.map(o=>{let i=(o.shortcodes||[]).map(a=>dn(a)).filter(Boolean);for(let a of i)e.has(a)||e.set(a,o);let s=cl([o.label,...i,...o.keywords||[]].join(" "));return {item:o,searchable:s}});return {getAll:()=>[...t],resolveShortcode:o=>e.get(dn(o))??null,search:(o,i)=>{let s=Math.max(0,i?.limit??t.length);if(s===0)return [];let a=cl(o);return a?n.filter(l=>l.searchable.includes(a)).slice(0,s).map(l=>l.item):t.slice(0,s)}}}function ul(r){return Array.isArray(r)?r.map(t=>typeof t=="string"?t.trim():"").filter(t=>t.length>0):[]}function pp(r){let t=ul(r.shortcodes);return t.length>0?t.map(e=>dn(e)):typeof r.shortcodes=="string"?r.shortcodes.split(/[,\s]+/).map(e=>dn(e)).filter(Boolean):[]}function ni(r){if(!r||typeof r!="object")return null;let t=r;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 i=o,s=typeof i.name=="string"&&i.name.trim().length>0?i.name.trim():n,l=(Array.isArray(i.skins)?i.skins:[])[0],d=typeof l?.native=="string"?l.native:"";if(!d)continue;let c=Array.from(new Set([dn(n),...pp(i)].filter(Boolean)));c.length!==0&&e.push({emoji:d,label:s,shortcodes:c,keywords:ul(i.keywords)});}return e.length===0?null:oi(e)}async function hp(r){return new Function("name","return import(name);")(r)}var Io=class extends M{constructor(e={}){super("emoji",["toolbar"]);T(this,"listeners",[]);T(this,"isOpen",false);T(this,"query","");T(this,"position",null);T(this,"suggestions",[]);T(this,"activeMatch",null);T(this,"viewportRafId",null);T(this,"applyingAutoReplace",false);T(this,"catalogAdapter",oi(ll));T(this,"hasExplicitCatalogConfig",false);T(this,"hasExplicitAdapterConfig",false);T(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:Ao,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||Ao,...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 f=$getSelection();$isRangeSelection(f)&&f.insertText(m);}),true)},COMMAND_PRIORITY_EDITOR),i=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",i),document.addEventListener("pointerdown",s),window.addEventListener("scroll",a,true),window.addEventListener("resize",a),()=>{n(),o(),document.removeEventListener("keydown",i),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:oi(e.catalog||ll)}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=ni(e);if(n){this.catalogAdapter=n,this.refreshSuggestionsIfOpen();return}try{let i=await hp("@emoji-mart/data"),s=ni(i.default)||ni(i.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 i=o.anchor.getNode();if(!$isTextNode(i)){this.closeIfNeeded();return}let s=o.anchor.offset,a=i.getTextContent(),l=a.slice(0,s);if(this.config.autoReplaceSymbols&&!this.applyingAutoReplace){let C=this.detectSymbolReplacement(a,l,s);C&&(n={nodeKey:i.getKey(),startOffset:C.startOffset,endOffset:C.endOffset,emoji:C.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 f=l.slice(c+d.length);if(/\s/.test(f)||f.length>(this.config.maxQueryLength??32)){this.closeIfNeeded();return}let g=this.getSuggestions(f),y=this.getCaretPosition();this.query=f,this.position=y,this.suggestions=g,this.isOpen=g.length>0,this.activeMatch={nodeKey:i.getKey(),startOffset:c,endOffset:s},this.notifyListeners();}),n!==null){let o=n;this.applyingAutoReplace=true,e.update(()=>{let i=$getNodeByKey(o.nodeKey);if(!$isTextNode(i))return;let s=Math.max(0,o.endOffset-o.startOffset);i.spliceText(o.startOffset,s,o.emoji,true);let a=o.startOffset+o.emoji.length;i.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 i=Object.entries(this.config.symbolReplacements||Ao).sort((s,a)=>a[0].length-s[0].length);for(let[s,a]of i){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||Ao),o=e;for(let[i,s]of n){let a=fp(i),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 i=$getNodeByKey(o.nodeKey);if(!$isTextNode(i))return;let s=Math.max(0,o.endOffset-o.startOffset);i.spliceText(o.startOffset,s,n,true);let a=o.startOffset+n.length;i.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));}},bp=new Io;var _o=class extends M{constructor(){super("floatingToolbar",["floating"]);T(this,"isVisible",false);T(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(Lp,{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;}},Tp=new _o;function Lp({extension:r,config:t}){let[n]=useLexicalComposerContext(),{config:o}=Oe(),[i,s]=useState(false),[a,l]=useState(null),[d,c]=useState(null),u=useRef(null),m=N=>(N.querySelector('[data-luthor-selection-anchor="true"]')??N).getBoundingClientRect(),f=(N,b)=>{let E;return (...w)=>{clearTimeout(E),E=setTimeout(()=>N(()=>w),b);}},g=useCallback((N,b)=>{if(typeof window>"u"||b===document.body)return N;let E=window.pageXOffset||document.documentElement.scrollLeft||0,w=window.pageYOffset||document.documentElement.scrollTop||0,x=b.getBoundingClientRect(),L=x.left+E,k=x.top+w,I=t.toolbarDimensions?.width||420,D=t.toolbarDimensions?.height||40,Y=N.x-L,ee=N.y-k,B=Math.max(20,Math.min(Y,Math.max(20,x.width-I-20))),z=Math.max(20,Math.min(ee,Math.max(20,x.height-D-20)));return {...N,x:B,y:z,top:N.top-k,left:N.left-L,bottom:N.bottom-k,right:N.right-L,positionFromRight:N.positionFromRight}},[t.toolbarDimensions?.height,t.toolbarDimensions?.width,20]),y=useCallback(N=>{let b=t.offset||{y:8},E=t.positionStrategy||"below",w=window.pageXOffset||document.documentElement.scrollLeft||0,x=window.pageYOffset||document.documentElement.scrollTop||0,L=window.innerWidth,k=window.innerHeight,I=N.bottom+x+b.y;E==="above"?I=N.top+x-b.y:E==="auto"&&(I=k-N.bottom>60?N.bottom+x+b.y:N.top+x-b.y);let D=t.getActiveStates?.(),Y=!!D?.isIframeEmbedSelected||!!D?.isYouTubeEmbedSelected,ee=t.toolbarDimensions?.width||(Y?132:420),B=t.toolbarDimensions?.height||40,z=20,W=N.left+N.width/2,j=W+w,K,O,J=W-z,G=L-W-z,Z=ee/2,ge=W-Z,be=W+Z,$e=ge<z,Te=be>L-z;return !$e&&!Te?(K=j-Z,O=false):$e||J<Z?(K=w+z,O=false):Te||G<Z?(K=w+L-ee-z,O=true):(K=j-Z,O=false),I-B<x?I=N.bottom+x+b.y:I+B>x+k&&(I=N.top+x-b.y-B),{x:K,y:I,width:N.width,height:N.height,top:N.top+x,left:N.left+w,bottom:N.bottom+x,right:N.right+w,positionFromRight:O}},[t,20]);useEffect(()=>{r.setVisible(i);},[i,r]),useEffect(()=>{let N=()=>{n.getEditorState().read(()=>{let L=$getSelection(),k=null,I=null;if($isRangeSelection(L)&&!L.isCollapsed()){let D=window.getSelection();D&&D.rangeCount>0&&(k=D.getRangeAt(0).getBoundingClientRect(),I=L);}else if($isNodeSelection(L)){let D=L.getNodes();if(D.length>0){let Y=D[0];if(Y){let ee=Y.getKey(),B=n.getElementByKey(ee);B&&(k=m(B));}}}if(k&&k.width>0&&k.height>0){let D=y(k);l(D),c(I),s(true),r.setSelectionRect(D);}else l(null),c(null),s(false),r.setSelectionRect(null);});},b=f(N,t.debounceMs||100),E=n.registerUpdateListener(()=>{b();}),w=()=>{b();},x=()=>{u.current===null&&(u.current=window.requestAnimationFrame(()=>{u.current=null,N();}));};return document.addEventListener("selectionchange",w),window.addEventListener("scroll",x,true),window.addEventListener("resize",x),()=>{E(),document.removeEventListener("selectionchange",w),window.removeEventListener("scroll",x,true),window.removeEventListener("resize",x),u.current!==null&&(cancelAnimationFrame(u.current),u.current=null);}},[n,t.debounceMs,y,r]);let C=()=>{s(false),l(null),c(null);};if(!t.render)return console.warn("FloatingToolbarExtension: No render function provided in config."),null;if(typeof document>"u")return null;let h=n.getRootElement()?.closest(".luthor-editor-wrapper"),p=t.anchorElem||h||document.body,S=a&&p?g(a,p):a;return createPortal(t.render({isVisible:i,selectionRect:S,selection:d,editor:n,commands:t.getCommands?.()||{},activeStates:t.getActiveStates?.()||{},hide:C,theme:o?.theme?.floatingToolbar||t.theme||{}}),p)}var Oo=class extends M{constructor(){super("commandPalette",["toolbar"]);T(this,"isOpen",false);T(this,"commands",new Map);T(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())}},wp=new Oo;var Pp=new Set(["paragraph","heading"]),Do=class extends M{constructor(e={}){super("slashCommand",["toolbar"]);T(this,"commands",new Map);T(this,"listeners",[]);T(this,"isOpen",false);T(this,"query","");T(this,"position",null);T(this,"activeMatch",null);T(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 i=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",i),window.addEventListener("scroll",s,true),window.addEventListener("resize",s),()=>{n(),document.removeEventListener("keydown",o),document.removeEventListener("pointerdown",i),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 i=this.activeMatch;e.update(()=>{let s=$getNodeByKey(i.nodeKey);if(!$isTextNode(s))return;let a=Math.max(0,Math.min(i.endOffset,s.getTextContentSize()));s.select(a,a);let l=Math.max(0,i.endOffset-i.startOffset);l>0&&s.spliceText(i.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 i=Ip(o);if(!Pp.has(i)){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}if(c!==0){this.closeIfNeeded();return}if(_p(o,c)){this.closeIfNeeded();return}let u=l.slice(c+d.length);if(/\s/.test(u)){this.closeIfNeeded();return}let m=this.getCaretPosition();this.isOpen=true,this.query=u,this.position=m,this.activeMatch={nodeKey:o.getKey(),startOffset:c,endOffset:s,query:u},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));}},Ap=new Do;function Ip(r){try{return r.getTopLevelElementOrThrow?.()?.getType?.()??""}catch{return ""}}function _p(r,t){if(t>0)return true;let e=Op(r);if(!e)return false;let n=r;for(;n&&n!==e;){let o=n.getPreviousSibling?.()??null;for(;o;){if((o.getTextContent?.()??"").length>0)return true;o=o.getPreviousSibling?.()??null;}n=n.getParent?.()??null;}return false}function Op(r){try{return r.getTopLevelElementOrThrow?.()??null}catch{return null}}var Ho=class extends M{constructor(){super("enterKeyBehavior",["floating"]),this.config={...this.config||{},showInToolbar:false,initPriority:100};}register(t){let e,n=i=>{if(i.key!=="Enter")return;let s=false;t.update(()=>{let a=$getSelection();if(!$isRangeSelection(a))return;let l=a.anchor.getNode();if(i.shiftKey){let y=$findCellNode(l);if($isTableCellNode(y)){let p=$getTableNodeFromLexicalNodeOrThrow(y),S=$createParagraphNode();p.insertAfter(S),S.selectStart(),s=true;return}let C=this.findQuoteNode(l);if(C){let p=$createParagraphNode();C.insertAfter(p),p.selectStart(),s=true;return}let h=this.findCodeNode(l);if(h){let p=$createParagraphNode();h.insertAfter(p),p.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 y=$createParagraphNode();d.append(y),y.selectStart(),s=true;return}let u=this.isEmptyQuoteLine(c),m=c.getPreviousSibling(),f=this.isEmptyQuoteLine(m);if(u&&f){let y=c,C=m;y.remove(),C?.remove();let h=$createParagraphNode();d.insertAfter(h),h.selectStart(),s=true;return}let g=$createParagraphNode();c.insertAfter(g),g.selectStart(),s=true;}),s&&(i.preventDefault(),i.stopPropagation());},o=t.registerRootListener((i,s)=>{e?.(),e=void 0,s&&s.removeEventListener("keydown",n,true),i&&(i.addEventListener("keydown",n,true),e=()=>{i.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}},Kp=new Ho;export{M as BaseExtension,Kl as BaseProvider,No as BlockFormatExtension,Mn as BoldExtension,bo as CodeExtension,Co as CodeFormatExtension,xo as CodeIntelligenceExtension,Oo as CommandPaletteExtension,Vn as ContextMenuExtension,ko as DraggableBlockExtension,Io as EmojiExtension,Ho as EnterKeyBehaviorExtension,Vl as ExtensionCategory,_o as FloatingToolbarExtension,Dn as FontFamilyExtension,Hn as FontSizeExtension,Yi as HTML_NATIVE_KEY_MAP,Sn as HTML_SUPPORTED_NODE_TYPES,To as HistoryExtension,On as HorizontalRuleExtension,bn as IframeEmbedExtension,pn as ImageExtension,Pn as ItalicExtension,dl as LIGHTWEIGHT_EMOJI_CATALOG,ui as LUTHOR_EDITOR_THEME_TOKENS,Fn as LineHeightExtension,_n as LinkExtension,ao as ListExtension,Ki as MARKDOWN_NATIVE_KEY_MAP,Cn as MARKDOWN_SUPPORTED_NODE_TYPES,tr as MARKDOWN_TEXT_NATIVE_FORMAT_MASK,Xf as RichText,Do as SlashCommandExtension,In as StrikethroughExtension,jn as SubscriptExtension,Un as SuperscriptExtension,Mo as TabIndentExtension,Gn as TableExtension,zn as TextColorExtension,ae as TextFormatExtension,$n as TextHighlightExtension,An as UnderlineExtension,En as YouTubeEmbedExtension,$t as appendMetadataEnvelopes,Cf as blockFormatExtension,Bu as boldExtension,ql as clearLexicalSelection,zg as codeExtension,df as codeFormatExtension,rf as codeIntelligenceExtension,wp as commandPaletteExtension,kr as contextMenuExtension,Kf as createCustomNodeExtension,hi as createEditorSystem,Ml as createEditorThemeStyleVars,Ql as createExtension,Je as defaultLuthorTheme,Af as draggableBlockExtension,bp as emojiExtension,Kp as enterKeyBehaviorExtension,rr as extractHTMLMetadataPatch,or as extractMarkdownMetadataPatch,jt as extractMetadataEnvelopes,Tp as floatingToolbarExtension,bm as fontFamilyExtension,Sm as fontSizeExtension,Ag as getDefaultPopularPrismLanguages,kf as historyExtension,um as horizontalRuleExtension,Hu as htmlToJSON,Lc as iframeEmbedExtension,dc as imageExtension,nr as isDefaultBridgeValue,Qi as isHTMLRepresentable,Al as isLuthorTheme,Vi as isMarkdownRepresentable,zu as italicExtension,Fu as jsonToHTML,iu as jsonToMarkdown,Rm as lineHeightExtension,Xu as linkExtension,xg as listExtension,Ur as loadPopularPrismLanguages,go as loadPrismLanguages,ru as markdownToJSON,Pl as mergeThemes,zt as prepareDocumentForBridge,Ut as rehydrateDocumentFromEnvelopes,Jl as resolveLinkNodeKeyFromAnchor,Gf as richTextExtension,Ap as slashCommandExtension,Uu as strikethroughExtension,Dm as subscriptExtension,Hm as superscriptExtension,dp as tabIndentExtension,ig as tableExtension,Am as textColorExtension,Om as textHighlightExtension,ju as underlineExtension,Oe as useBaseEditor,Dc as youTubeEmbedExtension};
|
|
70
|
+
`);return this.lineNumberTextCache.set(e,o),o}};N(uo,"MAX_CODE_TAB_DEPTH",8);var co=uo,pg=new co;var ba={js:"javascript",py:"python",ts:"typescript"},Ir=null;function Ct(r){if(!r)return null;let t=r.trim().toLowerCase();if(!t||t==="auto")return null;let e=ba[t]??t,n=normalizeCodeLang(e);return !n||n==="auto"?null:ba[n]??n}function yg(){return new Set(getCodeLanguages().map(r=>Ct(r)).filter(r=>!!r))}function Eg(){return Ir||(Ir=yg()),Ir}function xg(r){let t=r.trim().toLowerCase();return t?Eg().has(t):false}function Cg(r){let t=Ct(r);return t?xg(t):false}function Sg(r){return Cg(r)}function ya(r){let t=Ct(r);return t&&Sg(t)?t:null}var Mg='<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>',Pg='<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>',Ag=["plaintext","typescript","javascript","markdown","html","css","python","sql","java","c","cpp","rust","swift","powershell","xml"],Ig={atom:"Atom",bash:"Bash",c:"C",csharp:"C#",clike:"C-like",cpp:"C++",css:"CSS",dart:"Dart",diff:"Diff",docker:"Dockerfile",dockerfile:"Dockerfile",go:"Go",graphql:"GraphQL",html:"HTML",java:"Java",javascript:"JavaScript",json:"JSON",js:"JavaScript",jsx:"JSX",kotlin:"Kotlin",lua:"Lua",markup:"Markup",markdown:"Markdown",mathml:"MathML",objc:"Objective-C",objectivec:"Objective-C",perl:"Perl",plain:"Plain Text",php:"PHP",powershell:"PowerShell",py:"Python",r:"R",ruby:"Ruby",rss:"RSS",rust:"Rust",scala:"Scala",sql:"SQL",ssml:"SSML",svg:"SVG",swift:"Swift",toml:"TOML",tsx:"TSX",txt:"Plain Text",typescript:"TypeScript",yaml:"YAML",xml:"XML"},go=class extends M{constructor(){super("codeIntelligence"),this.config={isCopyAllowed:true};}register(t){let e=Hg(t,TRANSFORMERS),n=registerMarkdownShortcuts(t,e),o=t.registerUpdateListener(({dirtyElements:i,dirtyLeaves:s})=>{(i.size>0||s.size>0)&&this.ensureCodeBlockThemes(t);});return queueMicrotask(()=>{this.ensureCodeBlockThemes(t);}),()=>{n(),o();}}getPlugins(){return [createElement(Og,{key:"code-intelligence-controls",extension:this})]}getCommands(t){return {setCodeLanguage:e=>{let n=Qe(e)??"plain",o=this.getThemeForLanguage(n);t.update(()=>{this.getSelectionCodeNodes().forEach(i=>{i.setLanguage(n),i.setTheme(o);});});},autoDetectCodeLanguage:async()=>null,getCurrentCodeLanguage:()=>new Promise(e=>{t.getEditorState().read(()=>{let n=this.getSelectionCodeNodes();e(n[0]?.getLanguage()??null);});}),getCodeLanguageOptions:()=>this.getLanguageOptions(),copySelectedCodeBlock:async()=>{if(!this.isCopyAllowed())return false;let e=await this.getPrimaryCodeBlockText(t);return !e||!e.text.trim()?false:Na(e.text)}}}isCopyAllowed(){return this.config.isCopyAllowed!==false}getLanguageOptionsSnapshot(){return this.getLanguageOptions()}getCodeBlocksSnapshot(t){return t.getEditorState().read(()=>$nodesOfType(CodeNode).map(e=>{let n=Qe(e.getLanguage());return {key:e.getKey(),language:n??"plain",text:e.getTextContent()}}))}setCodeBlockLanguage(t,e,n){t.isEditable()&&t.update(()=>{let o=$getNodeByKey(e);if(!o||!$isCodeNode(o))return;let i=Qe(n)??"plain";o.setLanguage(i),o.setTheme(this.getThemeForLanguage(i));});}getCodeBlockText(t,e){return t.getEditorState().read(()=>{let n=$getNodeByKey(e);return !n||!$isCodeNode(n)?"":n.getTextContent()})}getThemeForLanguage(t){let e=Qe(t);return !e||e==="plain"?on():"hljs"}ensureCodeBlockThemes(t){let e=t.getEditorState().read(()=>$nodesOfType(CodeNode).map(n=>{let o=n.getLanguage(),i=Qe(o),s=typeof o=="string"&&o.trim().length>0&&!i,a=n.getTheme?.()??"",l=this.getThemeForLanguage(s?"plain":i);return {key:n.getKey(),nextLanguage:s?"plain":null,nextTheme:l??on(),currentTheme:a}}).filter(n=>n.nextLanguage!==null||n.currentTheme!==n.nextTheme));e.length!==0&&t.update(()=>{e.forEach(n=>{let o=$getNodeByKey(n.key);!o||!$isCodeNode(o)||(n.nextLanguage&&o.setLanguage(n.nextLanguage),o.setTheme(n.nextTheme));});});}getSelectionCodeNodes(){let t=$getSelection();if(!$isRangeSelection(t))return [];let e=t.getNodes(),n=new Map;return e.forEach(o=>{let i=this.getNearestCodeNode(o);i&&n.set(i.getKey(),i);}),Array.from(n.values())}getNearestCodeNode(t){let e=t;for(;e;){if($isCodeNode(e))return e;e=e.getParent();}return null}getLanguageOptions(){let t=Ag.map(o=>Qe(o)).filter(o=>!!o),e=Bg(this.config.languageOptions);if(!e)return Hr(t);let n=zg(e.values);return e.mode==="replace"?Hr(n):Hr([...t,...n])}async getPrimaryCodeBlockText(t){return new Promise(e=>{t.getEditorState().read(()=>{let o=this.getSelectionCodeNodes()[0];if(!o){e(null);return}let i=o.getTextContent().trim();if(!i){e(null);return}e({key:o.getKey(),text:i});});})}},_g=34;function Og({extension:r}){let[t]=useLexicalComposerContext(),[e,n]=useState(()=>t.isEditable()),[o,i]=useState([]),[s,a]=useState({}),l=useRef(null),d=useRef(new Map),c=r.getLanguageOptionsSnapshot(),u=useMemo(()=>c.map(h=>({id:h,label:$g(h)})),[c]),m=useCallback(()=>{let h=Sa(t);if(!h)return [];let y=h.getBoundingClientRect(),w=r.getCodeBlocksSnapshot(t),E=[];return w.forEach(T=>{let k=t.getElementByKey(T.key);if(!k||!k.isConnected)return;k.classList.add("luthor-code-block--interactive");let I=k.getBoundingClientRect(),D=Math.max(120,Math.round(I.width)),Y=Math.max(0,Math.round(I.top-y.top-_g)),ee=Math.max(0,Math.round(I.left-y.left));E.push({key:T.key,language:T.language,top:Y,left:ee,width:D});}),E},[t,r]),f=useCallback(()=>{let h=m();i(y=>Dg(y,h)?y:h);},[m]),g=useCallback(()=>{l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null,f();}));},[f]),x=useCallback(h=>{let y=d.current.get(h);y&&(clearTimeout(y),d.current.delete(h));},[]),L=useCallback((h,y)=>{x(h),a(E=>({...E,[h]:y}));let w=setTimeout(()=>{a(E=>{if(!(h in E))return E;let T={...E};return delete T[h],T}),d.current.delete(h);},1200);d.current.set(h,w);},[x]),b=useCallback((h,y)=>{e&&(r.setCodeBlockLanguage(t,h,y),g());},[t,r,e,g]),p=r.isCopyAllowed(),C=useCallback(async h=>{if(!p)return;let y=r.getCodeBlockText(t,h);if(!y.trim())return;if(await Na(y)){L(h,"copied");return}L(h,"error");},[p,t,r,L]);if(useEffect(()=>t.registerEditableListener(n),[t]),useEffect(()=>{g();let h=0,y=null,w=()=>{g(),h+=1,!(h>=20)&&(y=requestAnimationFrame(w));};y=requestAnimationFrame(w);let E=t.registerUpdateListener(()=>{g();}),T=()=>{g();},k=d.current;return window.addEventListener("scroll",T,true),window.addEventListener("resize",T,{passive:true}),()=>{E(),window.removeEventListener("scroll",T,true),window.removeEventListener("resize",T),y!==null&&cancelAnimationFrame(y),l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),k.forEach(I=>clearTimeout(I)),k.clear();}},[t,g]),useEffect(()=>{let h=new Set(o.map(y=>y.key));a(y=>{let w=false,E={};return Object.entries(y).forEach(([T,k])=>{if(h.has(T)){E[T]=k;return}w=true,x(T);}),w?E:y});},[x,o]),typeof document>"u"||o.length===0)return null;let S=Sa(t);return S?createPortal(createElement("div",{className:"luthor-codeblock-controls-layer","aria-hidden":false},o.map(h=>{let y=s[h.key],w=["luthor-codeblock-copy",y==="copied"?"is-copied":"",y==="error"?"is-copy-error":""].filter(Boolean).join(" "),E=y==="copied"?"Copied":y==="error"?"Copy failed":"Copy to clipboard";return createElement("div",{key:h.key,className:"luthor-codeblock-controls","data-code-node-key":h.key,style:{position:"absolute",top:`${h.top}px`,left:`${h.left}px`,width:`${h.width}px`}},createElement("span",{className:"luthor-codeblock-controls-left"},createElement("select",{className:"luthor-codeblock-language",value:h.language,"aria-label":"Code language",disabled:!e,"aria-disabled":!e,onChange:T=>{let k=T.target;b(h.key,k.value);}},u.map(T=>createElement("option",{key:T.id,value:T.id},T.label)))),createElement("span",{className:"luthor-codeblock-controls-right"},p?createElement("button",{className:w,type:"button","aria-label":"Copy code",title:E,"data-tooltip":E,onMouseDown:T=>{T.preventDefault();},onClick:()=>{C(h.key);},dangerouslySetInnerHTML:{__html:y==="copied"?Pg:Mg}}):null))})),S):null}function Dg(r,t){if(r.length!==t.length)return false;for(let e=0;e<r.length;e+=1){let n=r[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 Na(r){if(typeof navigator<"u"&&navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(r),!0}catch{}if(typeof document>"u")return false;let t=document.createElement("textarea");t.value=r,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 Sa(r){let t=r.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 Qe(r){let t=Ct(r);return t?ya(t):null}function Hg(r,t){return t.filter(e=>{let n=e.dependencies;return !n||n.length===0?true:r.hasNodes([...n])})}var Fg=new go;function Bg(r){if(!r)return null;if(Array.isArray(r))return {mode:"append",values:r};let t=r;return {mode:t.mode??"append",values:Array.isArray(t.values)?t.values:[]}}function zg(r){let t=[],e=new Set;for(let n of r){let o=n.trim();if(!o)continue;let i=Qe(o);if(!i)throw new Error(`[CodeIntelligenceExtension] Invalid language option "${n}". Use a supported language ID or alias (excluding "auto").`);if(e.has(i))throw new Error(`[CodeIntelligenceExtension] Duplicate language option "${n}". It resolves to "${i}", which is already configured.`);e.add(i),t.push(i);}return t}function Hr(r){return Array.from(new Set(r)).sort((t,e)=>t.localeCompare(e))}function $g(r){let t=Qe(r)??Ct(r)??r.trim().toLowerCase();return t?Ig[t]??jg(t):"Plain Text"}function jg(r){let t=r.trim();return t?t.split(/[-_]+/).filter(e=>e.length>0).map(e=>e.length<=2?e.toUpperCase():`${e[0]?.toUpperCase()??""}${e.slice(1)}`).join(" "):"Plain Text"}var fo=class extends ae{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},i=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=i(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(),f=Math.max(4,Math.min(8,m.width/2)),g=null,x=0;a.clientX<=m.left+f?(g=o(u),x=0):a.clientX>=m.right-f&&(g=i(u),x=g?.data.length??0),g&&(a.preventDefault(),t.focus(()=>{let L=window.getSelection();if(!L)return;let b=document.createRange();b.setStart(g,x),b.collapse(true),L.removeAllRanges(),L.addRange(b);}));};return n.addEventListener("click",s,true),()=>{n.removeEventListener("click",s,true),e();}}},Kg=new fo;var ho=class extends M{constructor(){super("blockFormat",["toolbar"]);}register(t){let e=t.registerCommand(INSERT_PARAGRAPH_COMMAND,()=>{let o=$getSelection();if($isRangeSelection(o)){let i=o.anchor.getNode(),s=this.getBlockNode(i);if(s&&($isHeadingNode(s)||$isQuoteNode(s)))return false}return false},COMMAND_PRIORITY_NORMAL),n=t.registerCommand(KEY_ENTER_COMMAND,o=>{let i=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"),i=true);}),i&&o?.preventDefault(),i},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 i=o.getNodes();for(let s of i){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 i=o.getNodes();for(let s of i){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(),i=this.getBlockNode(o);i&&(e=this.getNodeFormat(i));}}),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}},ef=new ho;var bo=class extends M{constructor(){super("history",["toolbar"]);N(this,"canUndoState",false);N(this,"canRedoState",false);}register(e){let n=e.registerCommand(CAN_UNDO_COMMAND,i=>(this.canUndoState=i,false),COMMAND_PRIORITY_LOW),o=e.registerCommand(CAN_REDO_COMMAND,i=>(this.canRedoState=i,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}}},lf=new bo;var Co=class extends M{constructor(e){super("draggableBlock",["floating"]);N(this,"isDraggingState",false);N(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(gf,{config:this.config,extension:this},"draggable-block")]}getCommands(e){return {moveBlock:(n,o,i)=>{e.isEditable()&&e.update(()=>{let s=$getNodeByKey(n),a=$getNodeByKey(o);s&&a&&(s.remove(),i?a.insertAfter(s):a.insertBefore(s));});},moveCurrentBlockUp:()=>{e.isEditable()&&e.update(()=>{let n=$getSelection();if($isRangeSelection(n)){let o=n.anchor.getNode(),i=$isElementNode(o)?o:o.getParent();if(i&&$isElementNode(i)){let s=i.getPreviousSibling();s&&(i.remove(),s.insertBefore(i));}}});},moveCurrentBlockDown:()=>{e.isEditable()&&e.update(()=>{let n=$getSelection();if($isRangeSelection(n)){let o=n.anchor.getNode(),i=$isElementNode(o)?o:o.getParent();if(i&&$isElementNode(i)){let s=i.getNextSibling();s&&(i.remove(),s.insertAfter(i));}}});}}}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)}},mf=new Co;function gf({config:r,extension:t}){let[e]=useLexicalComposerContext(),{config:n,extensions:o}=Oe(),s=o.find(v=>v.name==="draggableBlock")?.config,a=useMemo(()=>n?.theme?.draggable||{},[n?.theme?.draggable]),[l,d]=useState(null),[c,u]=useState(false),[m,f]=useState(()=>e.isEditable()),[g,x]=useState(null),[L,b]=useState(false),p=useRef(null),C=useRef(null),S=useRef(null),h=useRef(null),y=useRef(null),w=useRef(null),E=useRef(null),T=useRef(null),[k,I]=useState(null);useEffect(()=>{t.setIsDragging(c);},[c,t]);let D=typeof document<"u"&&typeof window<"u",Y=e.getRootElement(),ee=D?Y?.closest?.(".luthor-editor")||Y?.parentElement||document.body:null,B=s?.anchorElem||r.anchorElem||ee,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:{}}),[]),W=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]),j=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]),U=useCallback(v=>{if(!v||!j.blockDragging)return;(j.blockDragging.includes(" ")?j.blockDragging.split(" ").filter(Boolean):[j.blockDragging]).forEach(A=>v.classList.remove(A)),v.style.opacity="";},[j]),O=useCallback(v=>{if(!v||!j.blockDragging)return;(j.blockDragging.includes(" ")?j.blockDragging.split(" ").filter(Boolean):[j.blockDragging]).forEach(A=>v.classList.add(A)),Object.assign(v.style,W.blockDragging);},[j,W.blockDragging]);useEffect(()=>e.registerEditableListener(v=>{f(v),!v&&(u(false),x(null),d(null),b(false),p.current&&U(p.current),p.current=null,C.current=null);}),[e,U]);let q=useCallback(()=>{let v=e.getRootElement();if(v)try{v.focus({preventScroll:!0});}catch{v.focus();}},[e]),X=useCallback(()=>{p.current&&U(p.current),u(false),x(null),q(),setTimeout(()=>{p.current=null,C.current=null;},100);},[U,q]);useEffect(()=>()=>{p.current&&U(p.current),h.current&&clearTimeout(h.current),y.current!==null&&window.cancelAnimationFrame(y.current),E.current!==null&&window.cancelAnimationFrame(E.current);},[U]),useEffect(()=>{S.current=l;},[l]);let Z=useCallback(v=>{w.current=v,y.current===null&&(y.current=window.requestAnimationFrame(()=>{y.current=null;let P=w.current;d(A=>A===P?A:P);}));},[]),ge=useCallback(v=>{T.current=v,E.current===null&&(E.current=window.requestAnimationFrame(()=>{E.current=null;let P=T.current;P!=null&&I(A=>A!=null&&Math.abs(A-P)<.5?A:P);}));},[]),be=useCallback(v=>{let P=null;e.update(()=>{let A=$createParagraphNode(),H=$getNearestNodeFromDOMNode(v);if(H)try{H.getTopLevelElementOrThrow().insertAfter(A);}catch{$getRoot().append(A);}else $getRoot().append(A);A.selectStart(),P=A.getKey();}),P&&setTimeout(()=>{let A=e.getElementByKey(P);if(A&&A instanceof HTMLElement&&typeof A.getBoundingClientRect=="function"){Z(A);let H=A.getBoundingClientRect();ge(H.top+window.scrollY+H.height/2);}},0),q();},[e,q,Z,ge]);useEffect(()=>{if(l||p.current)b(true);else {let v=setTimeout(()=>b(false),300);return ()=>clearTimeout(v)}},[l]),useEffect(()=>{let v=A=>{if(!m){Z(null);return}if(c)return;let H=e.getRootElement();if(!H)return;let _=A.target;ge(A.clientY+window.scrollY);let R=_&&_.closest&&(_.closest(".drag-handle-area")||_.closest('[draggable="true"]')||_.closest(".luthor-drag-button")||_.closest(".luthor-draggable-button-stack")),se=window.getSelection(),Q=se&&se.rangeCount>0&&!se.isCollapsed,$=null,F=_;for(;F&&F!==H&&F!==document.body;){if(F.parentElement===H){$=F;break}F=F.parentElement;}h.current&&(clearTimeout(h.current),h.current=null),($||R)&&!Q&&!c?$&&Z($):h.current=setTimeout(()=>{Z(null),h.current=null;},500);},P=()=>{c||(h.current&&(clearTimeout(h.current),h.current=null),h.current=setTimeout(()=>{Z(null),h.current=null;},300));};return document.addEventListener("mousemove",v),document.addEventListener("mouseleave",P),()=>{document.removeEventListener("mousemove",v),document.removeEventListener("mouseleave",P),h.current&&(clearTimeout(h.current),h.current=null),y.current!==null&&(window.cancelAnimationFrame(y.current),y.current=null),E.current!==null&&(window.cancelAnimationFrame(E.current),E.current=null);}},[e,c,m,Z,ge]);let ze=useCallback((v,P)=>{if(!e.isEditable()){v.preventDefault();return}v.stopPropagation(),u(true),x(null),p.current=P,O(P);let A=e.read(()=>{let _=$getNearestNodeFromDOMNode(P);return _?_.getKey():null});A&&(C.current=A,v.dataTransfer?.setData("application/x-lexical-drag",JSON.stringify({key:A}))),v.dataTransfer.effectAllowed="move";let H=P.cloneNode(true);H.style.opacity="0.6",H.style.position="absolute",H.style.top="-9999px",H.style.left="-9999px",document.body.appendChild(H),v.dataTransfer.setDragImage(H,0,0),setTimeout(()=>document.body.removeChild(H),0);},[e,O]),Te=useCallback((v,P)=>{if(!e.isEditable())return;v.preventDefault(),u(true),p.current=P,O(P);let A=e.read(()=>{let H=$getNearestNodeFromDOMNode(P);return H?H.getKey():null});A&&(C.current=A);},[e,O]),$e=useCallback(v=>{if(!e.isEditable()||!c||!p.current)return;v.preventDefault();let P=v.touches[0];if(!P)return;let A=e.getRootElement();if(!A)return;let H=null,_=document.elementFromPoint(P.clientX,P.clientY);if(_){let R=_;for(;R&&R!==A;){if(R.parentElement===A){H=R;break}R=R.parentElement;}}if(H&&H!==p.current){let R=H.getBoundingClientRect(),se=P.clientY<R.top+R.height/2;x({top:se?R.top+window.scrollY:R.bottom+window.scrollY,left:R.left+window.scrollX,width:R.width});}else x(null);},[e,c]),je=useCallback(v=>{if(!e.isEditable()){X();return}if(!c||!C.current)return;v.preventDefault();let P=v.changedTouches[0];if(!P)return;let A=e.getRootElement();if(!A)return;let H=null,_=document.elementFromPoint(P.clientX,P.clientY);if(_){let R=_;for(;R&&R!==A;){if(R.parentElement===A){H=R;break}R=R.parentElement;}}H&&H!==p.current&&(e.update(()=>{let R=$getNodeByKey(C.current),se=$getNearestNodeFromDOMNode(H);if(R&&se){let Q=H.getBoundingClientRect(),$=P.clientY>=Q.top+Q.height/2;R.remove(),$?se.insertAfter(R):se.insertBefore(R);}}),setTimeout(()=>{if(C.current)try{let R=e.getElementByKey(C.current);R&&R instanceof HTMLElement&&typeof R.getBoundingClientRect=="function"&&d(R);}catch(R){console.warn("Error finding moved element:",R);}},50)),X();},[e,c,X]);useEffect(()=>{let v=e.getRootElement();if(!v)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 Q=window.getSelection();if(!Q||Q.isCollapsed||!(s?.enableTextSelectionDrag??r.enableTextSelectionDrag)){_.preventDefault();return}let $=Q.anchorNode;$?.nodeType===Node.TEXT_NODE&&($=$.parentNode);let F=null;for(;$&&$!==v;){if($.parentNode===v){F=$;break}$=$.parentNode;}if(!F){_.preventDefault();return}Q.collapse(Q.anchorNode,Q.anchorOffset);let ie=e.read(()=>$getNearestNodeFromDOMNode(F)?.getKey()??null);if(!ie){_.preventDefault();return}_.dataTransfer.clearData(),_.dataTransfer.setData("application/x-lexical-drag",JSON.stringify({key:ie})),_.dataTransfer.effectAllowed="move";let J=F.cloneNode(true);J.style.opacity="0.6",J.style.position="absolute",J.style.top="-9999px",J.style.left="-9999px",document.body.appendChild(J),_.dataTransfer.setDragImage(J,0,0),setTimeout(()=>document.body.removeChild(J),0),u(true),x(null),p.current=F,O(F),C.current=ie;},A=_=>{if(!e.isEditable())return;let R=_.target;if(R.nodeType!==Node.ELEMENT_NODE&&(R=R.parentNode),!R||!(R instanceof HTMLElement))return;let se=R;_.preventDefault(),_.dataTransfer.dropEffect="move";let Q=null,$=se;for(;$&&$!==v;){if($.parentElement===v){Q=$;break}$=$.parentElement;}if(Q&&Q!==p.current){let F=Q.getBoundingClientRect(),ie=_.clientY<F.top+F.height/2;x({top:ie?F.top+window.scrollY:F.bottom+window.scrollY,left:F.left+window.scrollX,width:F.width});}else x(null);},H=_=>{if(!e.isEditable())return;let R=_.target;if(R.nodeType!==Node.ELEMENT_NODE&&(R=R.parentNode),!R||!(R instanceof HTMLElement))return;let se=R;_.preventDefault(),x(null);let Q=_.dataTransfer?.getData("application/x-lexical-drag");if(!Q){X();return}let{key:$}=JSON.parse(Q);if(!$){X();return}let F=null,ie=se;for(;ie&&ie!==v;){if(ie.parentElement===v){F=ie;break}ie=ie.parentElement;}F&&F!==p.current&&(e.update(()=>{let J=$getNodeByKey($),Me=$getNearestNodeFromDOMNode(F);if(J&&Me){let ct=F.getBoundingClientRect(),dn=_.clientY>=ct.top+ct.height/2;J.remove(),dn?Me.insertAfter(J):Me.insertBefore(J);}}),setTimeout(()=>{if(C.current)try{let J=e.getElementByKey(C.current);J&&J instanceof HTMLElement&&typeof J.getBoundingClientRect=="function"&&d(J);}catch(J){console.warn("Error finding moved element:",J);}q();},50)),X();};return v.addEventListener("dragstart",P),v.addEventListener("dragover",A),v.addEventListener("drop",H),v.addEventListener("dragend",X),()=>{v.removeEventListener("dragstart",P),v.removeEventListener("dragover",A),v.removeEventListener("drop",H),v.removeEventListener("dragend",X);}},[e,X,O,q,s?.enableTextSelectionDrag,r.enableTextSelectionDrag]),useEffect(()=>{if(!c)return;let v=()=>{X();},P=H=>{H.key==="Escape"&&X();},A=()=>{document.hidden&&X();};return window.addEventListener("dragend",v),window.addEventListener("drop",v),window.addEventListener("blur",v),document.addEventListener("keydown",P),document.addEventListener("visibilitychange",A),()=>{window.removeEventListener("dragend",v),window.removeEventListener("drop",v),window.removeEventListener("blur",v),document.removeEventListener("keydown",P),document.removeEventListener("visibilitychange",A);}},[c,X]),useEffect(()=>{let v=e.getRootElement();if(!v)return;let P=null,A=0,H=0,_=Q=>{if(!e.isEditable()||Q.touches.length!==1||!(s?.enableTextSelectionDrag??r.enableTextSelectionDrag))return;let $=Q.touches[0];if(!$)return;let F=Q.target;if(F.nodeType!==Node.ELEMENT_NODE&&(F=F.parentNode),!F||!(F instanceof HTMLElement))return;let ie=F;ie.closest('[draggable="true"]')||(A=$.clientX,H=$.clientY,P=setTimeout(()=>{P=null;let J=null,Me=ie;for(;Me&&Me!==v;){if(Me.parentElement===v){J=Me;break}Me=Me.parentElement;}if(!J)return;let ct=window.getSelection();ct&&!ct.isCollapsed&&ct.collapseToStart(),u(true),p.current=J,O(J);let dn=e.read(()=>$getNearestNodeFromDOMNode(J)?.getKey()??null);dn&&(C.current=dn);},500));},R=Q=>{if(P&&Q.touches.length===1){let $=Q.touches[0];if(!$)return;let F=$.clientX-A,ie=$.clientY-H;Math.sqrt(F*F+ie*ie)>10&&(clearTimeout(P),P=null);}},se=()=>{P&&(clearTimeout(P),P=null);};return v.addEventListener("touchstart",_,{passive:false}),v.addEventListener("touchmove",R,{passive:false}),v.addEventListener("touchend",se,{passive:false}),document.addEventListener("touchmove",$e,{passive:false}),document.addEventListener("touchend",je,{passive:false}),()=>{v.removeEventListener("touchstart",_),v.removeEventListener("touchmove",R),v.removeEventListener("touchend",se),document.removeEventListener("touchmove",$e),document.removeEventListener("touchend",je);}},[e,O,X,c,$e,je,s?.enableTextSelectionDrag,r.enableTextSelectionDrag]);let fe=l||p.current;if(!m||!D||!B||!fe||typeof fe.getBoundingClientRect!="function")return null;let re=fe.getBoundingClientRect();if(!re.width||!re.height)return null;let Tt=Y?.closest?.(".luthor-editor")||null,_e=Tt||Y;if(!_e)return null;let Ke=_e.getBoundingClientRect(),Po=window.getComputedStyle(_e),Ao=Number.parseFloat(Po.getPropertyValue("--luthor-drag-gutter-width"))||40,Ue=m&&(s?.showAddButton??r.showAddButton)!==false,el=Ue?52:24,tl=Ke.left+window.scrollX+Math.max(0,(Ao-el)/2),nl=(s?.buttonStackPosition||r.buttonStackPosition)==="right"?re.right+window.scrollX+(s?.offsetRight||r.offsetRight||10):Tt?tl:re.left+window.scrollX+(s?.offsetLeft||r.offsetLeft||-40),cn=24,Qr=cn/2,Io=re.top+window.scrollY,Wr=re.bottom+window.scrollY,ol=Io+re.height/2,rl=k??ol,il=Io+cn/2,sl=Wr-cn/2,al=Math.min(sl,Math.max(il,rl)),Jr=Io,ll=Math.max(Jr,Wr-(Qr+cn/2)),cl=Math.min(ll,Math.max(Jr,al-Qr)),qr=B.getBoundingClientRect(),Xr=B===document.body?0:qr.left+window.scrollX,Gr=B===document.body?0:qr.top+window.scrollY,dl=nl-Xr,ul=cl-Gr;return jsxs(Fragment,{children:[createPortal(jsx("div",{className:`luthor-draggable-button-stack ${j.buttonStack} ${L?"":"fade-out"}`,style:{position:"absolute",left:0,top:0,transform:`translate3d(${dl}px, ${ul}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",...W.buttonStack},children:jsxs("div",{style:{display:"flex",flexDirection:"row",alignItems:"center",gap:"4px"},children:[Ue&&jsx("button",{type:"button","aria-label":"Add block",title:"Add",className:`luthor-drag-button ${j.addButton}`,onMouseDown:v=>{v.preventDefault(),v.stopPropagation();},onClick:v=>{v.preventDefault(),v.stopPropagation(),!(!fe||c)&&be(fe);},style:W.addButton,children:"+"}),s?.handleRenderer||r.handleRenderer?(s?.handleRenderer||r.handleRenderer)({rect:re,isDragging:c,onDragStart:v=>ze(v,fe),className:`luthor-drag-button ${j.handle} ${c?j.handleActive:""}`.trim()}):jsx("div",{className:`luthor-drag-button ${j.handle} ${c?j.handleActive:""}`.trim(),draggable:true,onDragStart:v=>ze(v,fe),onDragEnd:X,onTouchStart:v=>Te(v,fe),style:c?W.handleActive:W.handle,children:"\u22EE\u22EE"})]})}),B),g&&(s?.dropIndicatorRenderer||r.dropIndicatorRenderer?createPortal((s?.dropIndicatorRenderer||r.dropIndicatorRenderer)({...g,className:j.dropIndicator}),B):createPortal(jsx("div",{className:j.dropIndicator,style:{position:"absolute",top:g.top-4-Gr,left:g.left-Xr,width:g.width,height:"8px",pointerEvents:"none",zIndex:9997,...W.dropIndicator}}),B))]})}function _a(r){let t=renderToStaticMarkup(r),e=document.createElement("div");e.innerHTML=t;let n=e.firstElementChild;return e.remove(),n}function Tf(r){let t=r.isContainer??false,e=createCommand("insert-custom-node");function n({node:l,payload:d,nodeKey:c,children:u}){let[m]=useLexicalComposerContext(),[f,g]=useState(false);useEffect(()=>m.registerUpdateListener(({editorState:L})=>{L.read(()=>{let b=$getSelection();g($isNodeSelection(b)&&b.getNodes().some(p=>p.__key===c));});}),[m,c]);let x=L=>{m.update(()=>{let b=l.getWritable();b.__payload={...b.__payload,...L};});};return r.render?r.render({node:l,payload:d,children:u,nodeKey:c,isSelected:f,updatePayload:x}):null}class o extends ElementNode{constructor(c={},u,m){super(m);N(this,"__payload");N(this,"__nodeType");this.__payload=c,this.__nodeType=u;}static getType(){return r.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 r.importDOM?r.importDOM():{}}static exportDOM(c,{node:u}){if(r.exportDOM){let f=document.createElement("div");return r.exportDOM(c,{element:f,node:u})}let m=document.createElement("div");return m.setAttribute("data-custom-node-type",r.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(r.createDOM){let m=r.createDOM(c,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m.setAttribute("data-lexical-key",this.getKey()),m}if(r.jsx){let m=r.jsx({node:this,payload:this.__payload,nodeKey:this.getKey(),isSelected:false,updatePayload:g=>{this.setPayload(g);}}),f=_a(m);return f.setAttribute("data-custom-node-type",this.__nodeType),f.setAttribute("data-lexical-key",this.getKey()),f}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 r.updateDOM?r.updateDOM(c,u,m):false}getPayload(){return this.__payload}setPayload(c){let u=this.getWritable();u.__payload={...this.__payload,...c};}}class i extends DecoratorNode{constructor(c={},u,m){super(m);N(this,"__payload");N(this,"__nodeType");this.__payload=c,this.__nodeType=u;}static getType(){return r.nodeType}static clone(c){return new i(c.__payload,c.__nodeType,c.__key)}isSelectable(){return true}static importJSON(c){let{payload:u}=c;return new i(u,c.type)}static importDOM(){return r.importDOM?r.importDOM():{}}static exportDOM(c,{node:u}){if(r.exportDOM){let f=document.createElement("span");return r.exportDOM(c,{element:f,node:u})}let m=document.createElement("span");return m.setAttribute("data-custom-node-type",r.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),r.createDOM){let m=r.createDOM(c,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m}return u}updateDOM(c,u,m){return r.updateDOM?r.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=r.defaultPayload||{}){if(t){let d=new o(l,r.nodeType);if(r.initialChildren)r.initialChildren().forEach(u=>{if(u.type==="paragraph"){let m=$createParagraphNode();u.children&&u.children.forEach(f=>{f.type==="text"&&m.append($createTextNode(f.text||""));}),d.append(m);}});else {let c=$createParagraphNode();c.append($createTextNode("")),d.append(c);}return d}else return new i(l,r.nodeType)}class a extends M{constructor(){super(r.nodeType,["toolbar"]);}register(d){let c=d.registerCommand(e,m=>(d.update(()=>{let f=s(m),g=$getSelection();$isRangeSelection(g)?g.insertNodes([f]):$getRoot().append($createParagraphNode().append(f));}),true),COMMAND_PRIORITY_EDITOR),u=d.registerUpdateListener(({editorState:m})=>{t&&m.read(()=>{let f=$getSelection(),g=$isNodeSelection(f)?f.getNodes():[];d.getEditorState().read(()=>{let x=$getRoot(),L=b=>{if(b.getType()===r.nodeType){let p=g.some(S=>S.__key===b.__key),C=document.querySelector(`[data-lexical-key="${b.__key}"]`);C&&(C.setAttribute("data-selected",p.toString()),C.style.borderColor=p?"#007ACC":"#ccc",C.style.backgroundColor=p?"#f0f8ff":"transparent");}"getChildren"in b&&b.getChildren().forEach(L);};L(x);});});});return ()=>{c(),u();}}getNodes(){return t?[o]:[i]}getCommands(d){return {...{insertCustomNode:u=>d.dispatchCommand(e,u)},...r.commands?r.commands(d):{}}}getStateQueries(d){return {...{isCustomNodeActive:()=>new Promise(u=>{d.getEditorState().read(()=>{let m=$getSelection();u(!!m&&$isNodeSelection(m)&&m.getNodes().some(f=>f.getType()===r.nodeType));});})},...r.stateQueries?r.stateQueries(d):{}}}}return {extension:new a,$createCustomNode:s,jsxToDOM:_a}}function Oa(r,t,e){return e<=t?t:Math.min(e,Math.max(t,r))}function kf(r,t,e,n){let o=r.getBoundingClientRect(),i=t.getBoundingClientRect(),s=Oa(e,o.left+1,o.right-1),a=Oa(n,i.top+1,i.bottom-1);return {x:s,y:a}}function Rf(r,t){let e=document,n=window.getSelection();if(!n)return;let o=e.caretPositionFromPoint?.(r,t);if(o){let s=document.createRange();s.setStart(o.offsetNode,o.offset),s.collapse(true),n.removeAllRanges(),n.addRange(s);return}let i=e.caretRangeFromPoint?.(r,t);i&&(i.collapse(true),n.removeAllRanges(),n.addRange(i));}function Da(r,t,e){let i=Array.from(r.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(),f=m.top+m.height/2;return Math.abs(u-e)<Math.abs(f-e)?d:l},null)??r.firstElementChild??r,{x:s,y:a}=kf(r,i,t,e);r.focus(),Rf(s,a);}function Mf(r){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(()=>r());return}globalThis.setTimeout(r,0);}function Ha(r){return !!r.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 Fa=r=>{let{contentEditable:t,placeholder:e,className:n,nonEditableVisualMode:o=false,onEditIntent:i,classNames:s,styles:a,errorBoundary:l}=r,d=sn.useContext(vt),c=d?.lexical??null,[u,m]=sn.useState(!o),f=sn.useRef(null),g=d?.config,x=typeof g?.placeholder=="string"?g.placeholder:void 0,L=g?.classNames,b=g?.styles,p=e??x??"Start writing...",C=s?.placeholder||L?.placeholder||Je.richText?.placeholder||"luthor-placeholder",S={position:"absolute",pointerEvents:"none",zIndex:1,...b?.placeholder,...a?.placeholder};return sn.useEffect(()=>{m(!o);},[o]),sn.useEffect(()=>{c?.setEditable(u);},[u,c]),jsx("div",{className:s?.container||L?.container||n||Je.container||"luthor-editor-container",onMouseDown:h=>{if(h.button!==0)return;let y=h.target;if(!y||Ha(y))return;let w=h.currentTarget,E=h.clientX,T=h.clientY;if(o&&!u){if(i){f.current={clientX:E,clientY:T};return}let I=w.querySelector("[contenteditable]");if(!I)return;h.preventDefault(),c?.setEditable(true),m(true),Mf(()=>{let D=w.querySelector("[contenteditable='true']")??I;Da(D,E,T);});return}let k=w.querySelector("[contenteditable='true']");!k||k.contains(y)||(h.preventDefault(),Da(k,E,T));},onMouseUp:h=>{if(h.button!==0||!i||!o||u){f.current=null;return}let y=h.target;if(!y||Ha(y)){f.current=null;return}let w=f.current;if(f.current=null,!w)return;let E=Math.abs(h.clientX-w.clientX),T=Math.abs(h.clientY-w.clientY);if(E>4||T>4)return;let k=window.getSelection();k&&!k.isCollapsed||i({clientX:h.clientX,clientY:h.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||L?.contentEditable||Je.richText?.contentEditable||"luthor-content-editable",style:{...o?{cursor:"default",caretColor:"transparent",userSelect:"text",WebkitUserSelect:"text"}:{},...b?.contentEditable,...a?.contentEditable}})}),placeholder:typeof p=="string"?jsx("div",{className:C,style:S,children:p}):p||jsx("div",{className:C,style:S,children:"Start writing..."}),ErrorBoundary:l||If})})},jr=class extends M{constructor(t={}){super("richText",["floating"]),this.config={showInToolbar:false,position:"after",...t};}register(t){return ()=>{}}getPlugins(){return [jsx(Fa,{...this.config},"rich-text")]}},Pf=new jr,Af=r=>jsx(Fa,{...r}),If=({children:r,onError:t})=>{try{return jsx(Fragment,{children:r})}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 Ya=8,Kf=9,No=class extends M{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 i=o.anchor.getNode();if(this.isInCodeBlock(i))return false;n.preventDefault();let s=this.resolveTabContext(i);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(i)||t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),true):s==="heading"?n.shiftKey?(t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0),true):(this.isBlockAtMaxIndent(i)||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)):Kf,o=Math.max(0,n-1),i=this.findNearestListItemNode(t);if(i&&typeof i.getIndent=="function"){let a=i.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>=Ya}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(),i=typeof e.offset=="number"?e.offset:o.length,s=Math.max(0,Math.min(o.length,i)),a=o.lastIndexOf(`
|
|
71
|
+
`,s-1)+1;return (o.slice(a,s).match(/^\t*/)?.[0].length??0)>=Ya}},Uf=new No;var Ja=[{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"]}],Qa=Ja,vo={":)":"\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 Wf(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ln(r){return r.trim().toLowerCase().replace(/^:+|:+$/g,"")}function Wa(r){return r.toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}function Yr(r){let t=r.map(o=>({...o,shortcodes:[...o.shortcodes],keywords:o.keywords?[...o.keywords]:void 0})),e=new Map,n=t.map(o=>{let i=(o.shortcodes||[]).map(a=>ln(a)).filter(Boolean);for(let a of i)e.has(a)||e.set(a,o);let s=Wa([o.label,...i,...o.keywords||[]].join(" "));return {item:o,searchable:s}});return {getAll:()=>[...t],resolveShortcode:o=>e.get(ln(o))??null,search:(o,i)=>{let s=Math.max(0,i?.limit??t.length);if(s===0)return [];let a=Wa(o);return a?n.filter(l=>l.searchable.includes(a)).slice(0,s).map(l=>l.item):t.slice(0,s)}}}function qa(r){return Array.isArray(r)?r.map(t=>typeof t=="string"?t.trim():"").filter(t=>t.length>0):[]}function Jf(r){let t=qa(r.shortcodes);return t.length>0?t.map(e=>ln(e)):typeof r.shortcodes=="string"?r.shortcodes.split(/[,\s]+/).map(e=>ln(e)).filter(Boolean):[]}function Ur(r){if(!r||typeof r!="object")return null;let t=r;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 i=o,s=typeof i.name=="string"&&i.name.trim().length>0?i.name.trim():n,l=(Array.isArray(i.skins)?i.skins:[])[0],d=typeof l?.native=="string"?l.native:"";if(!d)continue;let c=Array.from(new Set([ln(n),...Jf(i)].filter(Boolean)));c.length!==0&&e.push({emoji:d,label:s,shortcodes:c,keywords:qa(i.keywords)});}return e.length===0?null:Yr(e)}async function qf(r){return new Function("name","return import(name);")(r)}var Lo=class extends M{constructor(e={}){super("emoji",["toolbar"]);N(this,"listeners",[]);N(this,"isOpen",false);N(this,"query","");N(this,"position",null);N(this,"suggestions",[]);N(this,"activeMatch",null);N(this,"viewportRafId",null);N(this,"applyingAutoReplace",false);N(this,"catalogAdapter",Yr(Qa));N(this,"hasExplicitCatalogConfig",false);N(this,"hasExplicitAdapterConfig",false);N(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:vo,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||vo,...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 f=$getSelection();$isRangeSelection(f)&&f.insertText(m);}),true)},COMMAND_PRIORITY_EDITOR),i=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",i),document.addEventListener("pointerdown",s),window.addEventListener("scroll",a,true),window.addEventListener("resize",a),()=>{n(),o(),document.removeEventListener("keydown",i),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:Yr(e.catalog||Qa)}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=Ur(e);if(n){this.catalogAdapter=n,this.refreshSuggestionsIfOpen();return}try{let i=await qf("@emoji-mart/data"),s=Ur(i.default)||Ur(i.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 i=o.anchor.getNode();if(!$isTextNode(i)){this.closeIfNeeded();return}let s=o.anchor.offset,a=i.getTextContent(),l=a.slice(0,s);if(this.config.autoReplaceSymbols&&!this.applyingAutoReplace){let L=this.detectSymbolReplacement(a,l,s);L&&(n={nodeKey:i.getKey(),startOffset:L.startOffset,endOffset:L.endOffset,emoji:L.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 f=l.slice(c+d.length);if(/\s/.test(f)||f.length>(this.config.maxQueryLength??32)){this.closeIfNeeded();return}let g=this.getSuggestions(f),x=this.getCaretPosition();this.query=f,this.position=x,this.suggestions=g,this.isOpen=g.length>0,this.activeMatch={nodeKey:i.getKey(),startOffset:c,endOffset:s},this.notifyListeners();}),n!==null){let o=n;this.applyingAutoReplace=true,e.update(()=>{let i=$getNodeByKey(o.nodeKey);if(!$isTextNode(i))return;let s=Math.max(0,o.endOffset-o.startOffset);i.spliceText(o.startOffset,s,o.emoji,true);let a=o.startOffset+o.emoji.length;i.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 i=Object.entries(this.config.symbolReplacements||vo).sort((s,a)=>a[0].length-s[0].length);for(let[s,a]of i){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||vo),o=e;for(let[i,s]of n){let a=Wf(i),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 i=$getNodeByKey(o.nodeKey);if(!$isTextNode(i))return;let s=Math.max(0,o.endOffset-o.startOffset);i.spliceText(o.startOffset,s,n,true);let a=o.startOffset+n.length;i.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));}},Xf=new Lo;var wo=class extends M{constructor(){super("floatingToolbar",["floating"]);N(this,"isVisible",false);N(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(ip,{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;}},rp=new wo;function ip({extension:r,config:t}){let[n]=useLexicalComposerContext(),{config:o}=Oe(),[i,s]=useState(false),[a,l]=useState(null),[d,c]=useState(null),u=useRef(null),m=S=>(S.querySelector('[data-luthor-selection-anchor="true"]')??S).getBoundingClientRect(),f=(S,h)=>{let y;return (...w)=>{clearTimeout(y),y=setTimeout(()=>S(()=>w),h);}},g=useCallback((S,h)=>{if(typeof window>"u"||h===document.body)return S;let y=window.pageXOffset||document.documentElement.scrollLeft||0,w=window.pageYOffset||document.documentElement.scrollTop||0,E=h.getBoundingClientRect(),T=E.left+y,k=E.top+w,I=t.toolbarDimensions?.width||420,D=t.toolbarDimensions?.height||40,Y=S.x-T,ee=S.y-k,B=Math.max(20,Math.min(Y,Math.max(20,E.width-I-20))),z=Math.max(20,Math.min(ee,Math.max(20,E.height-D-20)));return {...S,x:B,y:z,top:S.top-k,left:S.left-T,bottom:S.bottom-k,right:S.right-T,positionFromRight:S.positionFromRight}},[t.toolbarDimensions?.height,t.toolbarDimensions?.width,20]),x=useCallback(S=>{let h=t.offset||{y:8},y=t.positionStrategy||"below",w=window.pageXOffset||document.documentElement.scrollLeft||0,E=window.pageYOffset||document.documentElement.scrollTop||0,T=window.innerWidth,k=window.innerHeight,I=S.bottom+E+h.y;y==="above"?I=S.top+E-h.y:y==="auto"&&(I=k-S.bottom>60?S.bottom+E+h.y:S.top+E-h.y);let D=t.getActiveStates?.(),Y=!!D?.isIframeEmbedSelected||!!D?.isYouTubeEmbedSelected,ee=t.toolbarDimensions?.width||(Y?132:420),B=t.toolbarDimensions?.height||40,z=20,W=S.left+S.width/2,j=W+w,U,O,q=W-z,X=T-W-z,Z=ee/2,ge=W-Z,be=W+Z,ze=ge<z,Te=be>T-z;return !ze&&!Te?(U=j-Z,O=false):ze||q<Z?(U=w+z,O=false):Te||X<Z?(U=w+T-ee-z,O=true):(U=j-Z,O=false),I-B<E?I=S.bottom+E+h.y:I+B>E+k&&(I=S.top+E-h.y-B),{x:U,y:I,width:S.width,height:S.height,top:S.top+E,left:S.left+w,bottom:S.bottom+E,right:S.right+w,positionFromRight:O}},[t,20]);useEffect(()=>{r.setVisible(i);},[i,r]),useEffect(()=>{let S=()=>{n.getEditorState().read(()=>{let T=$getSelection(),k=null,I=null;if($isRangeSelection(T)&&!T.isCollapsed()){let D=window.getSelection();D&&D.rangeCount>0&&(k=D.getRangeAt(0).getBoundingClientRect(),I=T);}else if($isNodeSelection(T)){let D=T.getNodes();if(D.length>0){let Y=D[0];if(Y){let ee=Y.getKey(),B=n.getElementByKey(ee);B&&(k=m(B));}}}if(k&&k.width>0&&k.height>0){let D=x(k);l(D),c(I),s(true),r.setSelectionRect(D);}else l(null),c(null),s(false),r.setSelectionRect(null);});},h=f(S,t.debounceMs||100),y=n.registerUpdateListener(()=>{h();}),w=()=>{h();},E=()=>{u.current===null&&(u.current=window.requestAnimationFrame(()=>{u.current=null,S();}));};return document.addEventListener("selectionchange",w),window.addEventListener("scroll",E,true),window.addEventListener("resize",E),()=>{y(),document.removeEventListener("selectionchange",w),window.removeEventListener("scroll",E,true),window.removeEventListener("resize",E),u.current!==null&&(cancelAnimationFrame(u.current),u.current=null);}},[n,t.debounceMs,x,r]);let L=()=>{s(false),l(null),c(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"),p=t.anchorElem||b||document.body,C=a&&p?g(a,p):a;return createPortal(t.render({isVisible:i,selectionRect:C,selection:d,editor:n,commands:t.getCommands?.()||{},activeStates:t.getActiveStates?.()||{},hide:L,theme:o?.theme?.floatingToolbar||t.theme||{}}),p)}var ko=class extends M{constructor(){super("commandPalette",["toolbar"]);N(this,"isOpen",false);N(this,"commands",new Map);N(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())}},ap=new ko;var up=new Set(["paragraph","heading"]),Ro=class extends M{constructor(e={}){super("slashCommand",["toolbar"]);N(this,"commands",new Map);N(this,"listeners",[]);N(this,"isOpen",false);N(this,"query","");N(this,"position",null);N(this,"activeMatch",null);N(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 i=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",i),window.addEventListener("scroll",s,true),window.addEventListener("resize",s),()=>{n(),document.removeEventListener("keydown",o),document.removeEventListener("pointerdown",i),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 i=this.activeMatch;e.update(()=>{let s=$getNodeByKey(i.nodeKey);if(!$isTextNode(s))return;let a=Math.max(0,Math.min(i.endOffset,s.getTextContentSize()));s.select(a,a);let l=Math.max(0,i.endOffset-i.startOffset);l>0&&s.spliceText(i.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 i=gp(o);if(!up.has(i)){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}if(c!==0){this.closeIfNeeded();return}if(fp(o,c)){this.closeIfNeeded();return}let u=l.slice(c+d.length);if(/\s/.test(u)){this.closeIfNeeded();return}let m=this.getCaretPosition();this.isOpen=true,this.query=u,this.position=m,this.activeMatch={nodeKey:o.getKey(),startOffset:c,endOffset:s,query:u},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));}},mp=new Ro;function gp(r){try{return r.getTopLevelElementOrThrow?.()?.getType?.()??""}catch{return ""}}function fp(r,t){if(t>0)return true;let e=pp(r);if(!e)return false;let n=r;for(;n&&n!==e;){let o=n.getPreviousSibling?.()??null;for(;o;){if((o.getTextContent?.()??"").length>0)return true;o=o.getPreviousSibling?.()??null;}n=n.getParent?.()??null;}return false}function pp(r){try{return r.getTopLevelElementOrThrow?.()??null}catch{return null}}var Mo=class extends M{constructor(){super("enterKeyBehavior",["floating"]),this.config={...this.config||{},showInToolbar:false,initPriority:100};}register(t){let e,n=i=>{if(i.key!=="Enter")return;let s=false;t.update(()=>{let a=$getSelection();if(!$isRangeSelection(a))return;let l=a.anchor.getNode();if(i.shiftKey){let x=$findCellNode(l);if($isTableCellNode(x)){let p=$getTableNodeFromLexicalNodeOrThrow(x),C=$createParagraphNode();p.insertAfter(C),C.selectStart(),s=true;return}let L=this.findQuoteNode(l);if(L){let p=$createParagraphNode();L.insertAfter(p),p.selectStart(),s=true;return}let b=this.findCodeNode(l);if(b){let p=$createParagraphNode();b.insertAfter(p),p.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 x=$createParagraphNode();d.append(x),x.selectStart(),s=true;return}let u=this.isEmptyQuoteLine(c),m=c.getPreviousSibling(),f=this.isEmptyQuoteLine(m);if(u&&f){let x=c,L=m;x.remove(),L?.remove();let b=$createParagraphNode();d.insertAfter(b),b.selectStart(),s=true;return}let g=$createParagraphNode();c.insertAfter(g),g.selectStart(),s=true;}),s&&(i.preventDefault(),i.stopPropagation());},o=t.registerRootListener((i,s)=>{e?.(),e=void 0,s&&s.removeEventListener("keydown",n,true),i&&(i.addEventListener("keydown",n,true),e=()=>{i.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}},Tp=new Mo;export{M as BaseExtension,Rl as BaseProvider,ho as BlockFormatExtension,kn as BoldExtension,co as CodeExtension,fo as CodeFormatExtension,go as CodeIntelligenceExtension,ko as CommandPaletteExtension,Un as ContextMenuExtension,Co as DraggableBlockExtension,Lo as EmojiExtension,Mo as EnterKeyBehaviorExtension,Pl as ExtensionCategory,wo as FloatingToolbarExtension,_n as FontFamilyExtension,On as FontSizeExtension,Ii as HTML_NATIVE_KEY_MAP,xn as HTML_SUPPORTED_NODE_TYPES,bo as HistoryExtension,In as HorizontalRuleExtension,pn as IframeEmbedExtension,gn as ImageExtension,Rn as ItalicExtension,Ja as LIGHTWEIGHT_EMOJI_CATALOG,Zr as LUTHOR_EDITOR_THEME_TOKENS,Dn as LineHeightExtension,An as LinkExtension,io as ListExtension,Ai as MARKDOWN_NATIVE_KEY_MAP,En as MARKDOWN_SUPPORTED_NODE_TYPES,Wo as MARKDOWN_TEXT_NATIVE_FORMAT_MASK,Af as RichText,Ro as SlashCommandExtension,Pn as StrikethroughExtension,zn as SubscriptExtension,$n as SuperscriptExtension,No as TabIndentExtension,Jn as TableExtension,Fn as TextColorExtension,ae as TextFormatExtension,Bn as TextHighlightExtension,Mn as UnderlineExtension,bn as YouTubeEmbedExtension,$t as appendMetadataEnvelopes,ef as blockFormatExtension,Tu as boldExtension,_l as clearLexicalSelection,pg as codeExtension,Kg as codeFormatExtension,Fg as codeIntelligenceExtension,ap as commandPaletteExtension,Cr as contextMenuExtension,Tf as createCustomNodeExtension,ri as createEditorSystem,pl as createEditorThemeStyleVars,Al as createExtension,Je as defaultLuthorTheme,mf as draggableBlockExtension,Xf as emojiExtension,Tp as enterKeyBehaviorExtension,Xo as extractHTMLMetadataPatch,qo as extractMarkdownMetadataPatch,jt as extractMetadataEnvelopes,rp as floatingToolbarExtension,nm as fontFamilyExtension,am as fontSizeExtension,lf as historyExtension,qu as horizontalRuleExtension,Su as htmlToJSON,dc as iframeEmbedExtension,Jl as imageExtension,Jo as isDefaultBridgeValue,Oi as isHTMLRepresentable,bl as isLuthorTheme,_i as isMarkdownRepresentable,vu as italicExtension,Nu as jsonToHTML,Ud as jsonToMarkdown,fm as lineHeightExtension,Hu as linkExtension,ig as listExtension,Kd as markdownToJSON,hl as mergeThemes,zt as prepareDocumentForBridge,Kt as rehydrateDocumentFromEnvelopes,Ol as resolveLinkNodeKeyFromAnchor,Pf as richTextExtension,mp as slashCommandExtension,ku as strikethroughExtension,Cm as subscriptExtension,Sm as superscriptExtension,Uf as tabIndentExtension,Um as tableExtension,bm as textColorExtension,xm as textHighlightExtension,wu as underlineExtension,Oe as useBaseEditor,Cc as youTubeEmbedExtension};
|