@lyfie/luthor-headless 2.2.0 → 2.3.0
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 +590 -174
- package/dist/index.cjs +5 -0
- package/dist/index.d.cts +2531 -0
- package/dist/index.d.ts +735 -515
- package/dist/index.js +5 -3
- package/package.json +37 -18
package/dist/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
import {createContext,useState,useEffect,useRef,useCallback,useContext,useMemo}from'react';import {LexicalComposer}from'@lexical/react/LexicalComposer';import {useLexicalComposerContext}from'@lexical/react/LexicalComposerContext';import {createCommand,PASTE_COMMAND,$getSelection,$isRangeSelection,$createTextNode,INDENT_CONTENT_COMMAND,OUTDENT_CONTENT_COMMAND,$createParagraphNode,INSERT_PARAGRAPH_COMMAND,COMMAND_PRIORITY_NORMAL,KEY_ENTER_COMMAND,COMMAND_PRIORITY_EDITOR,ParagraphNode,$isParagraphNode,CAN_UNDO_COMMAND,COMMAND_PRIORITY_LOW,CAN_REDO_COMMAND,CLEAR_HISTORY_COMMAND,REDO_COMMAND,UNDO_COMMAND,$isElementNode,$getNodeByKey,$getRoot,KEY_DELETE_COMMAND,$isNodeSelection,KEY_BACKSPACE_COMMAND,FORMAT_TEXT_COMMAND,INSERT_LINE_BREAK_COMMAND,$getNearestNodeFromDOMNode,DecoratorNode,$createNodeSelection,$setSelection,ElementNode}from'lexical';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {$createLinkNode,TOGGLE_LINK_COMMAND,LinkNode,AutoLinkNode,$isLinkNode}from'@lexical/link';import {LinkPlugin}from'@lexical/react/LexicalLinkPlugin';import {AutoLinkPlugin}from'@lexical/react/LexicalAutoLinkPlugin';import {HorizontalRuleNode,INSERT_HORIZONTAL_RULE_COMMAND,$isHorizontalRuleNode,$createHorizontalRuleNode}from'@lexical/react/LexicalHorizontalRuleNode';import {HorizontalRulePlugin}from'@lexical/react/LexicalHorizontalRulePlugin';import {TablePlugin}from'@lexical/react/LexicalTablePlugin';import {TRANSFORMERS,$convertToMarkdownString,$convertFromMarkdownString}from'@lexical/markdown';import {TableNode,TableRowNode,TableCellNode,$isTableSelection,$isTableNode,$deleteTableColumnAtSelection,$deleteTableRowAtSelection,$insertTableColumnAtSelection,$insertTableRowAtSelection,$createTableNodeWithDimensions,$isTableCellNode,$isTableRowNode}from'@lexical/table';import {createPortal}from'react-dom';import {ListNode,ListItemNode,INSERT_ORDERED_LIST_COMMAND,INSERT_UNORDERED_LIST_COMMAND,$isListItemNode,$isListNode}from'@lexical/list';import {$setBlocksType}from'@lexical/selection';import {ListPlugin}from'@lexical/react/LexicalListPlugin';import {CodeNode,$createCodeNode,$isCodeNode}from'@lexical/code';import {$isHeadingNode,$isQuoteNode,HeadingNode,QuoteNode,$createQuoteNode,$createHeadingNode}from'@lexical/rich-text';import {HistoryPlugin}from'@lexical/react/LexicalHistoryPlugin';import {$generateNodesFromDOM,$generateHtmlFromNodes}from'@lexical/html';import {renderToStaticMarkup}from'react-dom/server';import {RichTextPlugin}from'@lexical/react/LexicalRichTextPlugin';import {ContentEditable}from'@lexical/react/LexicalContentEditable';var So=Object.defineProperty;var No=(a,t,e)=>t in a?So(a,t,{enumerable:true,configurable:true,writable:true,value:e}):a[t]=e;var y=(a,t,e)=>No(a,typeof t!="symbol"?t+"":t,e);var se={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",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",codeHighlight:{atrule:"luthor-code-atrule",attr:"luthor-code-attr",boolean:"luthor-code-boolean",builtin:"luthor-code-builtin",cdata:"luthor-code-cdata",char:"luthor-code-char",class:"luthor-code-class","class-name":"luthor-code-class-name",comment:"luthor-code-comment",constant:"luthor-code-constant",deleted:"luthor-code-deleted",doctype:"luthor-code-doctype",entity:"luthor-code-entity",function:"luthor-code-function",important:"luthor-code-important",inserted:"luthor-code-inserted",keyword:"luthor-code-keyword",namespace:"luthor-code-namespace",number:"luthor-code-number",operator:"luthor-code-operator",prolog:"luthor-code-prolog",property:"luthor-code-property",punctuation:"luthor-code-punctuation",regex:"luthor-code-regex",selector:"luthor-code-selector",string:"luthor-code-string",symbol:"luthor-code-symbol",tag:"luthor-code-tag",url:"luthor-code-url",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"},htmlEmbed:{container:"luthor-html-embed-container",preview:"luthor-html-embed-preview",editor:"luthor-html-embed-editor",textarea:"luthor-html-embed-textarea",toggle:"luthor-html-embed-toggle",content:"luthor-html-embed-content"},richText:{contentEditable:"luthor-content-editable",placeholder:"luthor-placeholder"}};function To(a,t){return {...a,...t,text:{...a.text,...t.text},list:{...a.list,...t.list,nested:{...a.list?.nested,...t.list?.nested}},heading:{...a.heading,...t.heading},codeHighlight:{...a.codeHighlight,...t.codeHighlight},toolbar:{...a.toolbar,...t.toolbar},draggable:{...a.draggable,...t.draggable,styles:{...a.draggable?.styles,...t.draggable?.styles}},floatingToolbar:{...a.floatingToolbar,...t.floatingToolbar,styles:{...a.floatingToolbar?.styles,...t.floatingToolbar?.styles}},htmlEmbed:{...a.htmlEmbed,...t.htmlEmbed,styles:{...a.htmlEmbed?.styles,...t.htmlEmbed?.styles}},richText:{...a.richText,...t.richText},styles:{toolbar:{...a.styles?.toolbar,...t.styles?.toolbar},draggable:{...a.styles?.draggable,...t.styles?.draggable},floatingToolbar:{...a.styles?.floatingToolbar,...t.styles?.floatingToolbar},htmlEmbed:{...a.styles?.htmlEmbed,...t.styles?.htmlEmbed},...t.styles}}}function vo(a){return a&&typeof a=="object"}var it=createContext(null);function Pt(){function a(){let o=useContext(it);if(!o)throw new Error("useEditor must be used within Provider");return o}function t({children:o,config:n={},extensions:r}){let[i]=useLexicalComposerContext(),s={formatText:(g,b)=>i?.dispatchCommand(FORMAT_TEXT_COMMAND,g)},l=useMemo(()=>r.reduce((g,b)=>({...g,...b.getCommands(i)}),{}),[r,i]),c={...s,...l},d=useMemo(()=>r.flatMap(g=>g.getPlugins?.()||[]),[r]),f=useMemo(()=>r.filter(g=>(g.config?.position||"before")==="before").flatMap(g=>g.getPlugins?.()||[]),[r]),m=useMemo(()=>r.filter(g=>(g.config?.position||"before")==="after").flatMap(g=>g.getPlugins?.()||[]),[r]);useEffect(()=>{if(!i)return;let b=[...r].sort((C,E)=>{let x=C.config?.initPriority??0;return (E.config?.initPriority??0)-x}).map(C=>C.register(i));return ()=>b.forEach(C=>C&&C())},[i,r]);let h=useMemo(()=>r.reduce((g,b)=>({...g,...b.getStateQueries?b.getStateQueries(i):{}}),{}),[r,i]),[N,L]=useState(()=>{let g={};return Object.keys(h).forEach(b=>g[b]=false),g});useEffect(()=>{if(!i)return;let g=async()=>{let E=Object.entries(h).map(([A,O])=>O().then(B=>[A,B])),x=await Promise.all(E),I=Object.fromEntries(x);L(I);};g();let b=i.registerUpdateListener(()=>{g();}),C=r.map(E=>"onStateChange"in E&&typeof E.onStateChange=="function"?E.onStateChange(g):()=>{}).filter(Boolean);return ()=>{b(),C.forEach(E=>E());}},[i,h,r]);let T={editor:i,config:n,extensions:r,commands:c,activeStates:N,stateQueries:h,listeners:{registerUpdate:g=>i?.registerUpdateListener(g)||(()=>{}),registerPaste:g=>i?.registerCommand(PASTE_COMMAND,g,4)||(()=>{})},export:{toHTML:async()=>"",toMarkdown:async()=>"",toJSON:()=>i?.getEditorState().toJSON()},import:{fromHTML:async()=>{},fromMarkdown:async()=>{},fromJSON:g=>i?.setEditorState(i.parseEditorState(g))},lexical:i,extensionsAPI:{add:g=>{},remove:g=>{},reorder:g=>{}},plugins:d,hasExtension:g=>r.some(b=>b.name===g)};return jsxs(it.Provider,{value:T,children:[f,o,m]})}function e(o){let n=useMemo(()=>o.extensions.flatMap(s=>s.getNodes?.()||[]),[o.extensions]),r=useMemo(()=>({namespace:"modern-editor",theme:o.config?.theme||se,onError:i=>{console.error("Lexical error:",i);},nodes:n}),[o.config?.theme,n]);return jsx(LexicalComposer,{initialConfig:r,children:jsx(t,{...o})})}return {Provider:e,useEditor:a}}var ko=Pt(),Do=ko.Provider,Z=()=>{let a=useContext(it);if(!a)throw new Error("useBaseEditor must be used within Provider");return a};var Q=(n=>(n.Toolbar="toolbar",n.Sidebar="sidebar",n.ContextMenu="contextmenu",n.Floating="floating",n))(Q||{});var M=class{constructor(t,e=["toolbar"]){y(this,"name");y(this,"category",["toolbar"]);y(this,"config",{});y(this,"supportedFormats",[]);y(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 Io(a){return new class extends M{constructor(){super(a.name,a.category||["toolbar"]);y(this,"_plugins",[]);y(this,"_nodes",[]);y(this,"_initialize");a.config&&(this.config={...this.config,...a.config}),this._initialize=a.initialize,a.supportedFormats&&(this.supportedFormats=a.supportedFormats),a.nodes&&(this._nodes=a.nodes),a.plugins&&(this._plugins=a.plugins);}register(e){let o=this._initialize?.(e);return ()=>{typeof o=="function"&&o();}}getNodes(){return this._nodes}getPlugins(){return this._plugins}getCommands(e){return a.commands?a.commands(e):{}}getStateQueries(e){return a.stateQueries?a.stateQueries(e):{}}}}var V=class extends M{constructor(t){super(t,["toolbar"]),this.supportedFormats=[t];}register(t){let e=t.registerCommand(INSERT_PARAGRAPH_COMMAND,()=>(t.getEditorState().read(()=>{let n=$getSelection();$isRangeSelection(n)&&n.hasFormat(this.name)&&t.dispatchCommand(FORMAT_TEXT_COMMAND,this.name);}),false),1),o=t.registerCommand(INSERT_LINE_BREAK_COMMAND,()=>false,1);return ()=>{e(),o();}}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 o=$getSelection();$isRangeSelection(o)?e(o.hasFormat(this.name)):e(false);});})}}};var Ne=class extends V{constructor(){super("bold");}},Ao=new Ne;var Te=class extends V{constructor(){super("italic");}},Fo=new Te;var at={format:["underline"],tag:"++",type:"text-format"},ve=class extends V{constructor(){super("underline");}getMarkdownTransformers(){return [at]}},$o=new ve;var Re=class extends V{constructor(){super("strikethrough");}},Qo=new Re;var Le=class extends M{constructor(){super("link",["toolbar"]),this.config={autoLinkText:false,linkSelectedTextOnPaste:true,validateUrl:t=>{try{return new URL(t),!0}catch{return false}}};}register(t){let e=t.registerCommand(PASTE_COMMAND,o=>{let n=o.clipboardData;if(!n)return false;let r=n.getData("text/plain");return r&&this.config.validateUrl(r)&&this.config.autoLinkUrls?(o.preventDefault(),t.update(()=>{let i=$getSelection();if($isRangeSelection(i))if(i.isCollapsed()){let s=$createLinkNode(r);s.append($createTextNode(r)),i.insertNodes([s]);}else if(this.config.linkSelectedTextOnPaste)t.dispatchCommand(TOGGLE_LINK_COMMAND,r);else {i.insertText(r);let s=$getSelection();s&&$isRangeSelection(s)&&s.getNodes()[0]&&t.dispatchCommand(TOGGLE_LINK_COMMAND,r);}}),true):false},3);return ()=>{e();}}getNodes(){let t=[LinkNode];return this.config.autoLinkText&&t.push(AutoLinkNode),t}getPlugins(){let t=[];if(t.push(jsx(LinkPlugin,{validateUrl:this.config.validateUrl},"link-plugin")),this.config.autoLinkText){let e=o=>{let r=/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g.exec(o);return r&&this.config.validateUrl(r[0])?{text:r[0],url:r[0],index:r.index,length:r[0].length}:null};t.push(jsx(AutoLinkPlugin,{matchers:[e]},"auto-link"));}return t}getCommands(t){return {insertLink:(e,o)=>{if(e)o&&t.update(()=>{let n=$getSelection();n&&n.insertText(o);}),t.dispatchCommand(TOGGLE_LINK_COMMAND,e);else {let n=prompt("Enter URL:");n&&t.dispatchCommand(TOGGLE_LINK_COMMAND,n);}},removeLink:()=>{t.dispatchCommand(TOGGLE_LINK_COMMAND,null);}}}getStateQueries(t){return {isLink:()=>new Promise(e=>{t.getEditorState().read(()=>{let o=$getSelection();if(o&&$isRangeSelection(o)){let r=o.getNodes()[0];if(r){let i=r.getParent();e($isLinkNode(i)||$isLinkNode(r));}else e(false);}else e(false);});}),isTextSelected:()=>new Promise(e=>{t.getEditorState().read(()=>{let o=$getSelection();o&&$isRangeSelection(o)?e(!o.isCollapsed()):e(false);});})}}},jo=new Le;var Bt={dependencies:[HorizontalRuleNode],export:a=>$isHorizontalRuleNode(a)?"---":null,regExp:/^(?:---|\*\*\*|___)\s*$/,replace:(a,t,e)=>{let o=$createHorizontalRuleNode();a.replace(o);},type:"element"},Pe=class extends M{constructor(){super("horizontalRule",["toolbar"]);}register(t){return ()=>{}}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 o=$getSelection();if(o&&$isRangeSelection(o)){let r=o.getNodes().some(i=>$isHorizontalRuleNode(i));e(r);}else e(false);});})}}},tn=new Pe;var st=class{constructor(t,e=[]){y(this,"editor");y(this,"extraTransformers",[]);this.editor=t,this.extraTransformers=[...e];}registerTransformer(t){this.extraTransformers.includes(t)||this.extraTransformers.push(t);}getAllTransformers(){return [...this.extraTransformers,...TRANSFORMERS]}export(){return this.editor.getEditorState().read(()=>$convertToMarkdownString(this.getAllTransformers()))}import(t,e,o){this.editor.update(()=>{let n=$getRoot();n.clear();let r=t??"";if(!r.trim()){n.append($createParagraphNode());return}$convertFromMarkdownString(r,this.getAllTransformers()),o||$getRoot().selectEnd();},{discrete:true,onUpdate:e});}},we=class extends M{constructor(){super("markdown",["toolbar"]);y(this,"manager",null);y(this,"pendingTransformers",[]);y(this,"importTimer",null);y(this,"registerTransformer",e=>{this.manager?this.manager.registerTransformer(e):this.pendingTransformers.push(e);});this.config={importDebounce:120,transformers:[]};}configure(e){this.config={...this.config,...e};let o=e.transformers||e.customTransformers||[];return this.manager&&o.length?o.forEach(n=>this.manager?.registerTransformer(n)):o.length&&this.pendingTransformers.push(...o),this}register(e){let o=this.config.transformers||this.config.customTransformers||[];return this.manager=new st(e,[...o,...this.pendingTransformers]),this.pendingTransformers=[],()=>{this.manager=null;}}getCommands(e){return {exportToMarkdown:()=>{if(!this.manager)return "";try{return this.manager.export()}catch(o){return console.error("[MarkdownExtension] export failed",o),""}},importFromMarkdown:(o,n)=>new Promise(r=>{if(!this.manager){r();return}let{immediate:i,preventFocus:s}=n||{},l=i?0:this.config.importDebounce||0;this.importTimer&&clearTimeout(this.importTimer);let c=()=>{this.manager?.import(o,()=>{r();},s);};l>0?this.importTimer=setTimeout(c,l):c();}),registerMarkdownTransformer:o=>{this.registerTransformer(o);}}}getStateQueries(e){return {}}},xe=new we;function un({items:a,position:t,onClose:e,className:o,style:n,itemClassName:r,itemStyle:i,disabledItemClassName:s,disabledItemStyle:l}){return jsx("div",{className:o,style:{position:"fixed",left:t.x,top:t.y,zIndex:1e3,...n},onClick:c=>c.stopPropagation(),children:a.map((c,d)=>c.separator?jsx("div",{className:"h-px bg-border my-1"},d):jsxs("div",{className:c.disabled?s:r,style:c.disabled?l:i,onClick:()=>{!c.disabled&&c.action&&(c.action(),e());},children:[c.icon&&jsx(c.icon,{className:"mr-2 h-4 w-4"}),c.label]},d))})}var _e=class{constructor(t,e={}){y(this,"providers",new Map);y(this,"currentMenu",null);y(this,"listeners",new Set);y(this,"editor");y(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 o=$getSelection(),n=Array.from(this.providers.values()).sort((r,i)=>(i.priority||0)-(r.priority||0));for(let r of n){let i={editor:this.editor,target:e,selection:o,event:t};if(r.canHandle(i)){this.config.preventDefault!==false&&t.preventDefault();let s=r.getItems(i);if(s.length>0){this.showMenu({items:s,position:{x:t.clientX,y:t.clientY},renderer:r.renderer||this.config.defaultRenderer});return}}}});}showMenu(t){this.currentMenu=t,this.notifyListeners();}hideMenu(){this.currentMenu=null,this.notifyListeners();}getCurrentMenu(){return this.currentMenu}subscribe(t){return this.listeners.add(t),t(this.currentMenu),()=>{this.listeners.delete(t);}}notifyListeners(){this.listeners.forEach(t=>t(this.currentMenu));}};function gn({extension:a}){let{config:t}=Z(),[e,o]=useState(null),n=t?.theme?.contextMenu||{},r=a.config,i={container:r?.theme?.container||n.container||"luthor-context-menu",item:r?.theme?.item||n.item||"luthor-context-menu-item",itemDisabled:r?.theme?.itemDisabled||n.itemDisabled||"luthor-context-menu-item-disabled"},s={container:{...r?.styles?.container,...n.styles?.container},item:{...r?.styles?.item,...n.styles?.item},itemDisabled:{...r?.styles?.itemDisabled,...n.styles?.itemDisabled}};if(useEffect(()=>a.subscribe(o),[a]),!e)return null;let l=e.renderer||a.config.defaultRenderer;return createPortal(jsx(l,{items:e.items,position:e.position,onClose:()=>a.manager?.hideMenu(),className:i.container,style:s.container,itemClassName:i.item,itemStyle:s.item,disabledItemClassName:i.itemDisabled,disabledItemStyle:s.itemDisabled}),document.body)}var ke=class extends M{constructor(e={}){super("contextMenu",["toolbar"]);y(this,"manager",null);y(this,"pendingListeners",new Set);this.config={defaultRenderer:un,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 _e(e,this.config),this.pendingListeners.forEach(s=>{this.manager?.subscribe(s);}),this.pendingListeners.clear();let o=s=>{this.manager?.handleContextMenu(s);},n=s=>{s.target.closest(".luthor-context-menu")||this.manager?.hideMenu();},r=s=>{s.key==="Escape"&&this.manager?.hideMenu();},i=e.getRootElement();return i?(i.addEventListener("contextmenu",o),document.addEventListener("mousedown",n),document.addEventListener("keydown",r),()=>{i.removeEventListener("contextmenu",o),document.removeEventListener("mousedown",n),document.removeEventListener("keydown",r),this.manager=null;}):()=>{this.manager=null;}}getCommands(e){return {registerProvider:o=>{this.manager||(this.manager=new _e(e,this.config)),this.manager.registerProvider(o);},unregisterProvider:o=>{this.manager?.unregisterProvider(o);},showContextMenu:o=>{this.manager?.showMenu(o);},hideContextMenu:()=>{this.manager?.hideMenu();}}}getStateQueries(e){return {isContextMenuOpen:()=>Promise.resolve(this.manager?.getCurrentMenu()!==null)}}getPlugins(){return [jsx(gn,{extension:this},"context-menu")]}subscribe(e){return this.manager?this.manager.subscribe(e):(this.pendingListeners.add(e),()=>{this.pendingListeners.delete(e);})}},lt=new ke;var Ie=class extends M{constructor(e){super("table",["toolbar"]);y(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()},{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 o=this.config.markdownExtension||xe;try{o.registerTransformer?.(ct);}catch(n){console.warn("[TableExtension] failed to register table markdown transformer",n);}if(this.config.enableContextMenu){let n=this.config.contextMenuExtension||lt;if(n){let r={id:"table",priority:10,canHandle:({target:s,selection:l})=>{let c=s.closest("td, th, [data-lexical-table-cell]");return c?$isTableSelection(l)?true:c.tagName==="TD"||c.tagName==="TH":false},getItems:({editor:s})=>{let l=this.getCommands(s);return this.getContextMenuItems(l)},renderer:this.config.contextMenuRenderer||n.config?.defaultRenderer};return n.getCommands(e).registerProvider(r),()=>{let s=n.getCommands(e);s&&s.unregisterProvider("table");}}}return ()=>{}}getNodes(){return [TableNode,TableRowNode,TableCellNode]}getCommands(e){return {insertTable:o=>{let{rows:n=3,columns:r=3,includeHeaders:i=false}=o;e.update(()=>{let s=$getSelection();if($isRangeSelection(s)){let l=$createTableNodeWithDimensions(n,r,i);s.insertNodes([l]);}});},insertRowAbove:()=>{e.update(()=>{$insertTableRowAtSelection(false);});},insertRowBelow:()=>{e.update(()=>{$insertTableRowAtSelection(true);});},insertColumnLeft:()=>{e.update(()=>{$insertTableColumnAtSelection(false);});},insertColumnRight:()=>{e.update(()=>{$insertTableColumnAtSelection(true);});},deleteRow:()=>{e.update(()=>{$deleteTableRowAtSelection();});},deleteColumn:()=>{e.update(()=>{$deleteTableColumnAtSelection();});},deleteTable:()=>{e.update(()=>{let o=$getSelection();$isTableSelection(o)&&o.getNodes().forEach(n=>{$isTableNode(n)&&n.remove();});});},showTableContextMenu:o=>{}}}getStateQueries(e){return {isTableSelected:async()=>e.getEditorState().read(()=>{let o=$getSelection();return $isTableSelection(o)}),isInTableCell:async()=>e.getEditorState().read(()=>{let o=$getSelection();if(!o||typeof o!="object"||!("anchor"in o)||!("focus"in o))return false;try{let n=o.anchor.getNode(),r=o.focus.getNode();return $isTableCellNode(n)||$isTableCellNode(r)}catch{return false}})}}getPlugins(){return [jsx(TablePlugin,{},"table-plugin")]}},Cn=new Ie,ct={dependencies:[TableNode,TableRowNode,TableCellNode],export:a=>{if(!$isTableNode(a))return null;let t=a.getChildren();if(t.length===0)return null;let e=[];if(t.forEach(i=>{if(!$isTableRowNode(i))return;let s=i.getChildren(),l=[];s.forEach(c=>{if(!$isTableCellNode(c))return;let d=c.getTextContent().trim();l.push(d);}),l.length>0&&e.push(l);}),e.length===0)return null;let o=[];e[0]&&o.push("| "+e[0].join(" | ")+" |");let n=e[0]?.length||1,r="| "+Array(n).fill("---").join(" | ")+" |";o.push(r);for(let i=1;i<e.length;i++){let l=[...e[i]||[]];for(;l.length<n;)l.push("");o.push("| "+l.join(" | ")+" |");}return o.join(`
|
|
2
|
-
`)},regExpStart:/^\|.*\|$/,regExpEnd:{optional:true,regExp:/^$/},replace:(a,t,e,o,n,r)=>{let s=[e[0],...n||[]].filter(m=>{let h=m.trim();return h&&h.includes("|")&&h.split("|").length>1});if(s.length<2)return;let l=[];if(s.forEach(m=>{let h=m.split("|").slice(1,-1).map(N=>N.trim());h.length>0&&l.push(h);}),l.length===0||!l[0])return;let c=l.filter(m=>!m.every(h=>/^:?-+:?$/.test(h)));if(c.length===0)return;let d=$createTableNodeWithDimensions(c.length,Math.max(...c.map(m=>m.length)),false),f=d.getChildren();c.forEach((m,h)=>{let N=f[h];if($isTableRowNode(N)){let L=N.getChildren();m.forEach((T,g)=>{if(g<L.length){let b=L[g];if($isTableCellNode(b)){b.clear();let C=$createParagraphNode();T&&C.append($createTextNode(T)),b.append(C);}}});}}),a.append(d);},type:"multiline-element"};var Fe=class extends M{constructor(){super("list",["toolbar"]);}register(t){return ()=>{}}getNodes(){return [ListNode,ListItemNode]}getPlugins(){return [jsx(ListPlugin,{},"list-plugin")]}getCommands(t){return {toggleUnorderedList:()=>{t.update(()=>{let e=$getSelection();if($isRangeSelection(e)){let n=e.anchor.getNode().getParent(),r=null,i=null;for(;n;){if($isListItemNode(n)&&(i=n),$isListNode(n)){r=n;break}n=n.getParent();}r?r.getListType()==="bullet"?i&&i.getIndent()>0?t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode):t.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0):t.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0);}});},toggleOrderedList:()=>{t.update(()=>{let e=$getSelection();if($isRangeSelection(e)){let n=e.anchor.getNode().getParent(),r=null,i=null;for(;n;){if($isListItemNode(n)&&(i=n),$isListNode(n)){r=n;break}n=n.getParent();}r?r.getListType()==="number"?i&&i.getIndent()>0?t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode):t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0):t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);}});},indentList:()=>{t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0);},outdentList:()=>{t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0);},insertNestedUnorderedList:()=>{t.update(()=>{t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),t.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0);});},insertNestedOrderedList:()=>{t.update(()=>{t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);});}}}getStateQueries(t){return {unorderedList:()=>new Promise(e=>{t.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o)){e(false);return}let n=o.anchor.getNode();for(;n;){if($isListNode(n)){e(n.getListType()==="bullet");return}n=n.getParent();}e(false);});}),orderedList:()=>new Promise(e=>{t.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o)){e(false);return}let n=o.anchor.getNode();for(;n;){if($isListNode(n)){e(n.getListType()==="number");return}n=n.getParent();}e(false);});})}}},Rn=new Fe;var $e=class extends M{constructor(){super("code",["toolbar"]);}register(t){return ()=>{}}getNodes(){return [CodeNode]}getCommands(t){return {toggleCodeBlock:()=>this.toggleCodeBlock(t)}}toggleCodeBlock(t){t.update(()=>{let e=$getSelection();if($isRangeSelection(e)){if(this.getCurrentFormatSync()==="code"){$setBlocksType(e,()=>$createParagraphNode());return}$setBlocksType(e,()=>$createCodeNode());}});}getStateQueries(t){return {isInCodeBlock:()=>Promise.resolve(this.isFormat("code",t))}}isFormat(t,e){let o=true;return e.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n)){o=false;return}let r=n.getNodes();for(let i of r){let s=this.getBlockNode(i);if(!s){o=false;break}if(this.getNodeFormat(s)!==t){o=false;break}}}),o}getBlockNode(t){let e=t;for(;e;){if($isCodeNode(e))return e;e=e.getParent();}return null}getNodeFormat(t){return $isCodeNode(t)?"code":null}getCurrentFormatSync(){let t=$getSelection();if(!$isRangeSelection(t))return null;let e=t.anchor.getNode(),o=this.getBlockNode(e);return o?this.getNodeFormat(o):null}},_n=new $e;var Qe=class extends V{constructor(){super("code");}},kn=new Qe;var Ke=class extends M{constructor(){super("blockFormat",["toolbar"]);}register(t){let e=t.registerCommand(INSERT_PARAGRAPH_COMMAND,()=>{let n=$getSelection();if($isRangeSelection(n)){let r=n.anchor.getNode(),i=this.getBlockNode(r);if(i&&($isHeadingNode(i)||$isQuoteNode(i)))return false}return false},COMMAND_PRIORITY_NORMAL),o=t.registerCommand(KEY_ENTER_COMMAND,n=>{if(n&&n.shiftKey)return false;let r=$getSelection();if($isRangeSelection(r)){let i=r.anchor.getNode(),s=this.getBlockNode(i);if(s&&($isHeadingNode(s)||$isQuoteNode(s)))return this.toggleBlockFormat(t,"p"),true}return false},COMMAND_PRIORITY_EDITOR);return ()=>{e(),o();}}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"),getCurrentBlockType:()=>this.getCurrentFormat(t)||"p"}}toggleBlockFormat(t,e){t.update(()=>{let o=$getSelection();if($isRangeSelection(o)){if(this.getCurrentFormatSync()===e){$setBlocksType(o,()=>$createParagraphNode());return}$setBlocksType(o,()=>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))}}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 o=true;return e.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n)){o=false;return}let r=n.getNodes();for(let i of r){let s=this.getBlockNode(i);if(!s){o=false;break}if(this.getNodeFormat(s)!==t){o=false;break}}}),o}getNodeFormat(t){return $isParagraphNode(t)?"p":$isHeadingNode(t)?t.getTag():$isQuoteNode(t)?"quote":null}getCurrentFormat(t){let e=null;return t.getEditorState().read(()=>{let o=$getSelection();if($isRangeSelection(o)){let n=o.anchor.getNode(),r=this.getBlockNode(n);r&&(e=this.getNodeFormat(r));}}),e}getCurrentFormatSync(){let t=$getSelection();if(!$isRangeSelection(t))return null;let e=t.anchor.getNode(),o=this.getBlockNode(e);return o?this.getNodeFormat(o):null}},Un=new Ke;var We=class extends M{constructor(){super("history",["toolbar"]);y(this,"canUndoState",false);y(this,"canRedoState",false);}register(e){let o=e.registerCommand(CAN_UNDO_COMMAND,r=>(this.canUndoState=r,false),COMMAND_PRIORITY_LOW),n=e.registerCommand(CAN_REDO_COMMAND,r=>(this.canRedoState=r,false),COMMAND_PRIORITY_LOW);return ()=>{o(),n();}}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}}},jn=new We;var ye=class extends M{constructor(e){super("draggableBlock",["floating"]);y(this,"isDraggingState",false);y(this,"stateChangeCallbacks",new Set);this.config={showInToolbar:false,position:"after",showMoveButtons:true,showUpButton:true,showDownButton:true,buttonStackPosition:"left",enableTextSelectionDrag:true,offsetLeft:-40,offsetRight:10,...e};}register(e){return ()=>{}}getPlugins(){return [jsx(Gn,{config:this.config,extension:this},"draggable-block")]}getCommands(e){return {moveBlock:(o,n,r)=>{e.update(()=>{let i=$getNodeByKey(o),s=$getNodeByKey(n);i&&s&&(i.remove(),r?s.insertAfter(i):s.insertBefore(i));});},moveCurrentBlockUp:()=>{e.update(()=>{let o=$getSelection();if($isRangeSelection(o)){let n=o.anchor.getNode(),r=$isElementNode(n)?n:n.getParent();if(r&&$isElementNode(r)){let i=r.getPreviousSibling();i&&(r.remove(),i.insertBefore(r));}}});},moveCurrentBlockDown:()=>{e.update(()=>{let o=$getSelection();if($isRangeSelection(o)){let n=o.anchor.getNode(),r=$isElementNode(n)?n:n.getParent();if(r&&$isElementNode(r)){let i=r.getNextSibling();i&&(r.remove(),i.insertAfter(r));}}});}}}getStateQueries(e){return {isDragging:async()=>this.isDraggingState}}setIsDragging(e){this.isDraggingState!==e&&(this.isDraggingState=e,this.stateChangeCallbacks.forEach(o=>o()));}onStateChange(e){return this.stateChangeCallbacks.add(e),()=>this.stateChangeCallbacks.delete(e)}},ao=new ye;function Gn({config:a,extension:t}){let[e]=useLexicalComposerContext(),{config:o,extensions:n}=Z(),i=n.find(u=>u.name==="draggableBlock")?.config,s=o?.theme?.draggable||{},[l,c]=useState(null),[d,f]=useState(false),[m,h]=useState(null),[N,L]=useState(false),T=useRef(null),g=useRef(null);if(useEffect(()=>{t.setIsDragging(d);},[d,t]),typeof document>"u")return null;let b=i?.anchorElem||a.anchorElem||document.body,C={handle:{cursor:"grab",userSelect:"none"},handleActive:{cursor:"grabbing"},blockDragging:{opacity:.5},dropIndicator:{backgroundColor:"#3b82f6",borderRadius:"2px"},upButton:{cursor:"pointer"},downButton:{cursor:"pointer"},buttonStack:{}},E={handle:{...C.handle,...s.styles?.handle,...i?.styles?.handle},handleActive:{...C.handleActive,...s.styles?.handleActive,...i?.styles?.handleActive},blockDragging:{...C.blockDragging,...s.styles?.blockDragging,...i?.styles?.blockDragging},dropIndicator:{...C.dropIndicator,...s.styles?.dropIndicator,...i?.styles?.dropIndicator},upButton:{...C.upButton,...s.styles?.upButton,...i?.styles?.upButton},downButton:{...C.downButton,...s.styles?.downButton,...i?.styles?.downButton},buttonStack:{...C.buttonStack,...s.styles?.buttonStack,...i?.styles?.buttonStack}},x={handle:i?.theme?.handle||s.handle||"luthor-draggable-handle",handleActive:i?.theme?.handleActive||s.handleActive||"luthor-draggable-handle-active",blockDragging:i?.theme?.blockDragging||s.blockDragging||"luthor-draggable-block-dragging",dropIndicator:i?.theme?.dropIndicator||s.dropIndicator||"luthor-draggable-drop-indicator",upButton:i?.theme?.upButton||s.upButton||"luthor-draggable-up-button",downButton:i?.theme?.downButton||s.downButton||"luthor-draggable-down-button",buttonStack:i?.theme?.buttonStack||s.buttonStack||"luthor-draggable-button-stack"},I=useCallback(u=>{if(!u||!x.blockDragging)return;(x.blockDragging.includes(" ")?x.blockDragging.split(" ").filter(Boolean):[x.blockDragging]).forEach(w=>u.classList.remove(w)),u.style.opacity="";},[x]),A=useCallback(u=>{if(!u||!x.blockDragging)return;(x.blockDragging.includes(" ")?x.blockDragging.split(" ").filter(Boolean):[x.blockDragging]).forEach(w=>u.classList.add(w)),Object.assign(u.style,E.blockDragging);},[x,E.blockDragging]),O=useCallback(()=>{T.current&&I(T.current),f(false),h(null);let u=e.getRootElement();u&&u.focus(),setTimeout(()=>{T.current=null,g.current=null;},100);},[I,e]);useEffect(()=>()=>{T.current&&I(T.current);},[I]),useEffect(()=>{if(l||T.current)L(true);else {let u=setTimeout(()=>L(false),300);return ()=>clearTimeout(u)}},[l,T.current]),useEffect(()=>{let u,S=P=>{if(d)return;let R=e.getRootElement();if(!R)return;let p=P.target,H=p&&p.closest&&(p.closest(".drag-handle-area")||p.closest('[draggable="true"]')),D=window.getSelection(),_=D&&D.rangeCount>0&&!D.isCollapsed,v=null,k=p;for(;k&&k!==R&&k!==document.body;){if(k.parentElement===R){v=k;break}k=k.parentElement;}u&&clearTimeout(u),(v||H)&&!_&&!d?v&&v!==l&&c(v):u=setTimeout(()=>{c(null);},500);},w=()=>{d||(u&&clearTimeout(u),u=setTimeout(()=>{c(null);},300));};return document.addEventListener("mousemove",S),document.addEventListener("mouseleave",w),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseleave",w),u&&clearTimeout(u);}},[e,d,l]);let B=useCallback((u,S)=>{u.stopPropagation(),f(true),T.current=S,A(S);let w=e.read(()=>{let p=$getNearestNodeFromDOMNode(S);return p?p.getKey():null});w&&(g.current=w,u.dataTransfer?.setData("application/x-lexical-drag",JSON.stringify({key:w}))),u.dataTransfer.effectAllowed="move";let P=S.cloneNode(true);P.style.opacity="0.6",P.style.position="absolute",P.style.top="-9999px",P.style.left="-9999px",document.body.appendChild(P),u.dataTransfer.setDragImage(P,0,0),setTimeout(()=>document.body.removeChild(P),0);let R=e.getRootElement();R&&R.focus();},[e,A]),re=useCallback((u,S)=>{u.preventDefault(),f(true),T.current=S,A(S);let w=e.read(()=>{let P=$getNearestNodeFromDOMNode(S);return P?P.getKey():null});w&&(g.current=w);},[e,A]),J=useCallback(u=>{if(!d||!T.current)return;u.preventDefault();let S=u.touches[0];if(!S)return;let w=e.getRootElement();if(!w)return;let P=null,R=document.elementFromPoint(S.clientX,S.clientY);if(R){let p=R;for(;p&&p!==w;){if(p.parentElement===w){P=p;break}p=p.parentElement;}}if(P&&P!==T.current){let p=P.getBoundingClientRect(),H=S.clientY<p.top+p.height/2;h({top:H?p.top+window.scrollY:p.bottom+window.scrollY,left:p.left+window.scrollX,width:p.width});}else h(null);},[e,d]),X=useCallback(u=>{if(!d||!g.current)return;u.preventDefault();let S=u.changedTouches[0];if(!S)return;let w=e.getRootElement();if(!w)return;let P=null,R=document.elementFromPoint(S.clientX,S.clientY);if(R){let p=R;for(;p&&p!==w;){if(p.parentElement===w){P=p;break}p=p.parentElement;}}P&&P!==T.current&&(e.update(()=>{let p=$getNodeByKey(g.current),H=$getNearestNodeFromDOMNode(P);if(p&&H){let D=P.getBoundingClientRect(),_=S.clientY>=D.top+D.height/2;p.remove(),_?H.insertAfter(p):H.insertBefore(p);}}),setTimeout(()=>{if(g.current)try{let p=e.getElementByKey(g.current);p&&p instanceof HTMLElement&&typeof p.getBoundingClientRect=="function"&&c(p);}catch(p){console.warn("Error finding moved element:",p);}},50)),O();},[e,d,O]),U=useCallback(()=>{l&&e.update(()=>{let u=$getNearestNodeFromDOMNode(l);if(u){let S=u.getPreviousSibling();S&&(u.remove(),S.insertBefore(u));}});},[e,l]),z=useCallback(()=>{l&&e.update(()=>{let u=$getNearestNodeFromDOMNode(l);if(u){let S=u.getNextSibling();S&&(u.remove(),S.insertAfter(u));}});},[e,l]);useEffect(()=>{let u=e.getRootElement();if(!u)return;let S=R=>{let p=R.target;if(p.nodeType!==Node.ELEMENT_NODE&&(p=p.parentNode),!p||!(p instanceof HTMLElement)){R.preventDefault();return}if(p.closest('[draggable="true"]'))return;let D=window.getSelection();if(!D||D.isCollapsed||!(i?.enableTextSelectionDrag??a.enableTextSelectionDrag)){R.preventDefault();return}let _=D.anchorNode;_?.nodeType===Node.TEXT_NODE&&(_=_.parentNode);let v=null;for(;_&&_!==u;){if(_.parentNode===u){v=_;break}_=_.parentNode;}if(!v){R.preventDefault();return}D.collapse(D.anchorNode,D.anchorOffset);let k=e.read(()=>$getNearestNodeFromDOMNode(v)?.getKey()??null);if(!k){R.preventDefault();return}R.dataTransfer.clearData(),R.dataTransfer.setData("application/x-lexical-drag",JSON.stringify({key:k})),R.dataTransfer.effectAllowed="move";let $=v.cloneNode(true);$.style.opacity="0.6",$.style.position="absolute",$.style.top="-9999px",$.style.left="-9999px",document.body.appendChild($),R.dataTransfer.setDragImage($,0,0),setTimeout(()=>document.body.removeChild($),0),f(true),T.current=v,A(v),g.current=k;},w=R=>{let p=R.target;if(p.nodeType!==Node.ELEMENT_NODE&&(p=p.parentNode),!p||!(p instanceof HTMLElement))return;let H=p;R.preventDefault(),R.dataTransfer.dropEffect="move";let D=null,_=H;for(;_&&_!==u;){if(_.parentElement===u){D=_;break}_=_.parentElement;}if(D&&D!==T.current){let v=D.getBoundingClientRect(),k=R.clientY<v.top+v.height/2;h({top:k?v.top+window.scrollY:v.bottom+window.scrollY,left:v.left+window.scrollX,width:v.width});}else h(null);},P=R=>{let p=R.target;if(p.nodeType!==Node.ELEMENT_NODE&&(p=p.parentNode),!p||!(p instanceof HTMLElement))return;let H=p;R.preventDefault(),h(null);let D=R.dataTransfer?.getData("application/x-lexical-drag");if(!D){O();return}let{key:_}=JSON.parse(D);if(!_){O();return}let v=null,k=H;for(;k&&k!==u;){if(k.parentElement===u){v=k;break}k=k.parentElement;}v&&v!==T.current&&(e.update(()=>{let $=$getNodeByKey(_),W=$getNearestNodeFromDOMNode(v);if($&&W){let ce=v.getBoundingClientRect(),Se=R.clientY>=ce.top+ce.height/2;$.remove(),Se?W.insertAfter($):W.insertBefore($);}}),setTimeout(()=>{if(g.current)try{let W=e.getElementByKey(g.current);W&&W instanceof HTMLElement&&typeof W.getBoundingClientRect=="function"&&c(W);}catch(W){console.warn("Error finding moved element:",W);}let $=e.getRootElement();$&&$.focus();},50)),O();};return u.addEventListener("dragstart",S),u.addEventListener("dragover",w),u.addEventListener("drop",P),u.addEventListener("dragend",O),()=>{u.removeEventListener("dragstart",S),u.removeEventListener("dragover",w),u.removeEventListener("drop",P),u.removeEventListener("dragend",O);}},[e,O,A,i?.enableTextSelectionDrag,a.enableTextSelectionDrag]),useEffect(()=>{let u=e.getRootElement();if(!u)return;let S=null,w=0,P=0,R=D=>{if(D.touches.length!==1||!(i?.enableTextSelectionDrag??a.enableTextSelectionDrag))return;let _=D.touches[0];if(!_)return;let v=D.target;if(v.nodeType!==Node.ELEMENT_NODE&&(v=v.parentNode),!v||!(v instanceof HTMLElement))return;let k=v;k.closest('[draggable="true"]')||(w=_.clientX,P=_.clientY,S=setTimeout(()=>{S=null;let $=null,W=k;for(;W&&W!==u;){if(W.parentElement===u){$=W;break}W=W.parentElement;}if(!$)return;let ce=window.getSelection();ce&&!ce.isCollapsed&&ce.collapseToStart(),f(true),T.current=$,A($);let Se=e.read(()=>$getNearestNodeFromDOMNode($)?.getKey()??null);Se&&(g.current=Se);},500));},p=D=>{if(S&&D.touches.length===1){let _=D.touches[0];if(!_)return;let v=_.clientX-w,k=_.clientY-P;Math.sqrt(v*v+k*k)>10&&(clearTimeout(S),S=null);}},H=D=>{S&&(clearTimeout(S),S=null);};return u.addEventListener("touchstart",R,{passive:false}),u.addEventListener("touchmove",p,{passive:false}),u.addEventListener("touchend",H,{passive:false}),document.addEventListener("touchmove",J,{passive:false}),document.addEventListener("touchend",X,{passive:false}),()=>{u.removeEventListener("touchstart",R),u.removeEventListener("touchmove",p),u.removeEventListener("touchend",H),document.removeEventListener("touchmove",J),document.removeEventListener("touchend",X);}},[e,A,O,d,J,X,i?.enableTextSelectionDrag,a.enableTextSelectionDrag]);let K=l||T.current;if(!K||typeof K.getBoundingClientRect!="function")return null;let Y=K.getBoundingClientRect();return !Y.width||!Y.height?null:jsxs(Fragment,{children:[createPortal(jsx("div",{className:`${x.buttonStack} ${N?"":"fade-out"}`,style:{position:"absolute",left:(i?.buttonStackPosition||a.buttonStackPosition)==="right"?Y.right+window.scrollX+(i?.offsetRight||a.offsetRight||10):Y.left+window.scrollX+(i?.offsetLeft||a.offsetLeft||-40),top:Y.top+window.scrollY,zIndex:40,display:"flex",flexDirection:"row",gap:"6px",alignItems:"center",pointerEvents:"auto",willChange:"transform, opacity",backfaceVisibility:"hidden",perspective:"1000px",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",...E.buttonStack},children:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px",alignItems:"center"},children:[(i?.showMoveButtons??a.showMoveButtons)!==false&&(i?.showUpButton??a.showUpButton)!==false&&(i?.buttonsRenderer||a.buttonsRenderer?(i?.buttonsRenderer||a.buttonsRenderer)({rect:Y,onMoveUp:U,onMoveDown:z,showUp:true,showDown:false,upClassName:`luthor-drag-button ${x.upButton}`,downClassName:`luthor-drag-button ${x.downButton}`}):jsx("button",{className:`luthor-drag-button ${x.upButton}`,onClick:U,style:E.upButton,children:"\u2191"})),i?.handleRenderer||a.handleRenderer?(i?.handleRenderer||a.handleRenderer)({rect:Y,isDragging:d,onDragStart:u=>B(u,K),className:`luthor-drag-button ${x.handle} ${d?x.handleActive:""}`.trim()}):jsx("div",{className:`luthor-drag-button ${x.handle} ${d?x.handleActive:""}`.trim(),draggable:true,onDragStart:u=>B(u,K),onTouchStart:u=>re(u,K),style:d?E.handleActive:E.handle,children:"\u22EE\u22EE"}),(i?.showMoveButtons??a.showMoveButtons)!==false&&(i?.showDownButton??a.showDownButton)!==false&&(i?.buttonsRenderer||a.buttonsRenderer?(i?.buttonsRenderer||a.buttonsRenderer)({rect:Y,onMoveUp:U,onMoveDown:z,showUp:false,showDown:true,upClassName:`luthor-drag-button ${x.upButton}`,downClassName:`luthor-drag-button ${x.downButton}`}):jsx("button",{className:`luthor-drag-button ${x.downButton}`,onClick:z,style:E.downButton,children:"\u2193"}))]})}),b),m&&(i?.dropIndicatorRenderer||a.dropIndicatorRenderer?createPortal((i?.dropIndicatorRenderer||a.dropIndicatorRenderer)({...m,className:x.dropIndicator}),b):createPortal(jsx("div",{className:x.dropIndicator,style:{position:"absolute",top:m.top-4,left:m.left,width:m.width,height:"8px",pointerEvents:"none",zIndex:9997,...E.dropIndicator}}),b))]})}var je=class extends M{constructor(){super("html",["toolbar"]);}register(t){return ()=>{}}getCommands(t){return {exportToHTML:()=>t.getEditorState().read(()=>$generateHtmlFromNodes(t)),importFromHTML:(e,o)=>new Promise(n=>{t.update(()=>{try{let r=$getRoot();if(r.clear(),e.trim()){let s=new DOMParser().parseFromString(e,"text/html"),l=$generateNodesFromDOM(t,s);l&&l.length>0?l.forEach(c=>{c&&r.append(c);}):r.append($createParagraphNode());}else r.append($createParagraphNode());o?.preventFocus||$getRoot().selectEnd();}catch(r){console.error("Error importing HTML:",r);let i=$getRoot();i.clear(),i.append($createParagraphNode());}},{discrete:true,onUpdate:n});})}}getStateQueries(t){return {canExportHTML:async()=>true}}},or=new je;var oe=class a extends DecoratorNode{constructor(e,o){super(o);y(this,"__payload");this.__payload=e;}static getType(){return "html-embed"}static clone(e){return new a(e.__payload,e.__key)}createDOM(){let e=document.createElement("div");return e.setAttribute("data-lexical-html-embed","true"),e.className="html-embed-container",e}updateDOM(){return false}static importJSON(e){let o={html:e.html||'<div style="padding: 20px; border-radius: 8px; text-align: center;"><h3>Custom HTML Block</h3><p>Edit this HTML to create your custom embed!</p></div>',preview:e.preview??true};return new a(o)}exportJSON(){return {type:"html-embed",html:this.__payload.html,preview:this.__payload.preview,version:1}}static importDOM(){return {div:e=>e.hasAttribute("data-lexical-html-embed")?{conversion:o=>{let r={html:o.getAttribute("data-html-content")||"",preview:true};return {node:new a(r)}},priority:4}:null,p:e=>e.querySelector('div[data-lexical-html-embed="true"]')?{conversion:n=>{let r=n.querySelector('div[data-lexical-html-embed="true"]');if(r){let s={html:r.getAttribute("data-html-content")||"",preview:true};return {node:new a(s)}}return {node:null}},priority:4}:null}}exportDOM(){let e=document.createElement("div");return e.setAttribute("data-lexical-html-embed","true"),e.setAttribute("data-html-content",this.__payload.html),{element:e}}getPayload(){return this.getLatest().__payload}setPayload(e){let o=this.getWritable();o.__payload={...o.__payload,...e};}decorate(e){return jsx(sr,{nodeKey:this.__key,payload:this.__payload,editor:e})}isInline(){return false}isKeyboardSelectable(){return true}},sr=({nodeKey:a,payload:t,editor:e})=>{let{config:o,extensions:n}=Z(),i=n.find(E=>E.name==="htmlEmbed")?.config,s=o?.theme?.htmlEmbed||{},l=useRef(null),c=E=>{e.update(()=>{let x=$getNodeByKey(a);x&&x.setPayload(E);});},d=()=>{if(!t.preview&&l.current){let E=l.current.value;E!==t.html&&c({html:E});}c({preview:!t.preview});},f=()=>{if(l.current){let E=l.current.value;E!==t.html&&c({html:E});}c({preview:true});},m={container:{...i?.styles?.container,...s.styles?.container},preview:{...i?.styles?.preview,...s.styles?.preview},editor:{...i?.styles?.editor,...s.styles?.editor},textarea:{...i?.styles?.textarea,...s.styles?.textarea},toggle:{...i?.styles?.toggle,...s.styles?.toggle},content:{...i?.styles?.content,...s.styles?.content}},h={container:i?.theme?.container||s.container||"",preview:i?.theme?.preview||s.preview||"",editor:i?.theme?.editor||s.editor||"",textarea:i?.theme?.textarea||s.textarea||"",toggle:i?.theme?.toggle||s.toggle||"",content:i?.theme?.content||s.content||""},N=({children:E,className:x,style:I})=>jsx("div",{className:x,style:I,children:E}),L=({html:E,onToggleEdit:x,className:I,style:A,toggleClassName:O,toggleStyle:B})=>jsxs("div",{className:I,style:A,children:[jsx("div",{className:h.content,style:m.content,dangerouslySetInnerHTML:{__html:E}}),i?.toggleRenderer?i.toggleRenderer({isPreview:true,onClick:x,className:O,style:B}):jsx("button",{className:O,style:B,onClick:x,title:"Edit HTML",type:"button",children:"\u270F\uFE0F Edit"})]}),T=({html:E,onTogglePreview:x,onSave:I,className:A,style:O,textareaClassName:B,textareaStyle:re,toggleClassName:J,toggleStyle:X})=>jsxs("div",{className:A,style:O,children:[jsx("textarea",{ref:l,className:B,style:re,defaultValue:E,placeholder:"Enter HTML here..."}),i?.toggleRenderer?i.toggleRenderer({isPreview:false,onClick:I,className:J,style:X}):jsx("button",{className:J,style:X,onClick:I,title:"Preview HTML",type:"button",children:"\u{1F441}\uFE0F Preview"})]}),g=i?.containerRenderer||N,b=i?.previewRenderer||L,C=i?.editorRenderer||T;return jsx(g,{className:h.container,style:m.container,children:t.preview?jsx(b,{html:t.html,onToggleEdit:d,className:h.preview,style:m.preview,toggleClassName:h.toggle,toggleStyle:m.toggle}):jsx(C,{html:t.html,onTogglePreview:d,onSave:f,className:h.editor,style:m.editor,textareaClassName:h.textarea,textareaStyle:m.textarea,toggleClassName:h.toggle,toggleStyle:m.toggle})})},Ge=class extends M{constructor(t){super("htmlEmbed",["toolbar"]),this.config={defaultHtml:'<div style="padding: 20px; border-radius: 8px; text-align: center;"><h3>Custom HTML Block</h3><p>Edit this HTML to create your custom embed!</p></div>',defaultPreview:false,...t};}register(t){let e=this.config.markdownExtension||xe;try{e.registerTransformer?.(Et);}catch(o){console.warn("[HTMLEmbedExtension] failed to register html embed markdown transformer",o);}return ()=>{}}getNodes(){return [oe]}getPlugins(){return []}getCommands(t){return {insertHTMLEmbed:e=>{t.update(()=>{let o={html:e||this.config.defaultHtml,preview:this.config.defaultPreview},n=new oe(o),r=$getSelection();$isRangeSelection(r)?r.insertNodes([n]):$getRoot().append(n);});},toggleHTMLPreview:()=>{t.update(()=>{let e=$getSelection();$isRangeSelection(e)&&e.getNodes().forEach(n=>{if(n instanceof oe){let r=n.getPayload();n.setPayload({preview:!r.preview});}});});}}}getStateQueries(t){return {isHTMLEmbedSelected:()=>new Promise(e=>{t.getEditorState().read(()=>{let o=$getSelection();if($isRangeSelection(o)){let n=o.getNodes().some(r=>r instanceof oe);e(n);}else e(false);});}),isHTMLPreviewMode:()=>new Promise(e=>{t.getEditorState().read(()=>{let o=$getSelection();if($isRangeSelection(o)){let n=o.getNodes().find(r=>r instanceof oe);e(n?n.getPayload().preview:false);}else e(false);});})}}},Et={dependencies:[oe],export:a=>{if(a&&typeof a.getType=="function"&&a.getType()==="html-embed")try{return "```html-embed\n"+a.getPayload().html+"\n```"}catch(t){return console.error("\u274C Error exporting HTML embed:",t),null}return null},regExpStart:/^```html-embed\s*$/,regExpEnd:{optional:true,regExp:/^```$/},replace:(a,t,e,o,n,r)=>{let i=n.join(`
|
|
3
|
-
`);try{let s={html:i,preview:!0},l=new oe(s);a.append(l);}catch(s){console.error("\u274C Error creating HTML embed node:",s);}},type:"multiline-element"},lr=new Ge;var ae=class{static importDOM(){return {img:()=>({conversion:t=>{try{if(!t||!(t instanceof HTMLImageElement)||!t.src)return null;let e=t,o="none",n=e.style;n.textAlign?o=n.textAlign:n.float&&(o=n.float==="left"?"left":n.float==="right"?"right":"none"),e.classList.contains("align-left")?o="left":e.classList.contains("align-center")?o="center":e.classList.contains("align-right")&&(o="right");let r,i=e.closest("figure");if(i){let s=i.querySelector("figcaption");s&&(r=s.textContent||void 0);}try{return {node:de(e.src,e.alt||"",r,o,e.className||void 0,this.extractStyleObject(e))}}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,o=e.querySelector("img");if(!o||!o.src)return null;let r=e.querySelector("figcaption")?.textContent||void 0;try{return {node:de(o.src,o.alt||"",r,"center",e.className||void 0,this.extractStyleObject(e))}}catch{return null}}catch{return null}},priority:1})}}static exportDOM(t){let{element:e,after:o}=this.createImageElement(t);return {element:e,after:o}}static exportJSON(t){return {type:"image",version:1,src:t.__src,alt:t.__alt,caption:t.__caption,alignment:t.__alignment,className:t.__className,style:t.__style?this.styleObjectToRecord(t.__style):void 0,width:t.__width,height:t.__height,uploading:t.__uploading}}static importJSON(t){let{src:e,alt:o,caption:n,alignment:r,className:i,style:s,width:l,height:c,uploading:d}=t;if(!e||e.length===0)throw new Error("Cannot import ImageNode with empty src");return de(e,o,n,r,i,s?this.recordToStyleObject(s):void 0,l,c,d)}static createImageElement(t){let e=document.createElement("figure"),o=document.createElement("img");switch(o.src=t.__src,o.alt=t.__alt,t.__width&&(o.width=t.__width),t.__height&&(o.height=t.__height),t.__className&&(o.className=t.__className),t.__style&&Object.assign(o.style,t.__style),e.className=`lexical-image align-${t.__alignment}`,t.__alignment){case "left":e.style.textAlign="left";break;case "center":e.style.textAlign="center";break;case "right":e.style.textAlign="right";break;default:e.style.textAlign="left";}if(e.style.margin="1rem 0",e.style.display="block",e.appendChild(o),t.__caption){let n=document.createElement("figcaption");n.textContent=t.__caption,n.style.fontSize="0.9em",n.style.color="#666",n.style.fontStyle="italic",n.style.marginTop="0.5rem",n.style.textAlign="center",e.appendChild(n);}return {element:e,after:n=>n}}static extractStyleObject(t){if(!t||!(t instanceof HTMLElement)||!t.style||!t.style.length)return;let e={};try{for(let o=0;o<t.style.length;o++){let n=t.style.item(o);n&&(e[n]=t.style.getPropertyValue(n));}return Object.keys(e).length>0?e:void 0}catch{return}}static styleObjectToRecord(t){let e={};for(let[o,n]of Object.entries(t))e[o]=String(n);return e}static recordToStyleObject(t){return {...t}}},{importDOM:Rl,exportDOM:Ml,importJSON:Ll,exportJSON:Pl}=ae;var go=createCommand("insert-image"),po=br;function br({src:a,alt:t,caption:e,alignment:o="none",className:n="",style:r,nodeKey:i,width:s,height:l,resizable:c=true,uploading:d=false}){let [f]=useLexicalComposerContext(),m=useRef(null);useRef(null);let [N,L]=useState(false),[T,g]=useState(false),[b,C]=useState(1),[E,x]=useState(s||"auto"),[I,A]=useState(l||"auto");useEffect(()=>{let U=m.current;U&&(U.onload=()=>{C(U.naturalWidth/U.naturalHeight);});},[a]),useEffect(()=>()=>{a&&a.startsWith("blob:")&&URL.revokeObjectURL(a);},[a]),useEffect(()=>{x(s||"auto"),A(l||"auto");},[s,l]),useEffect(()=>{if(i)return f.registerUpdateListener(({editorState:U})=>{U.read(()=>{let z=$getSelection();if($isNodeSelection(z)){let K=z.getNodes();L(K.some(Y=>Y.getKey()===i));}else L(false);});})},[f,i]);let O=U=>{U.preventDefault(),U.stopPropagation(),i&&f.update(()=>{let z=$createNodeSelection();z.add(i),$setSelection(z);});},B=U=>z=>{if(!m.current||!z.target)return;z.preventDefault(),g(true);let K="touches"in z?z.touches?.[0]?.clientX||0:z.clientX,Y="touches"in z?z.touches?.[0]?.clientY||0:z.clientY,u=m.current.clientWidth||100,S=m.current.clientHeight||100,w=u,P=S,R=H=>{let D="touches"in H?H.touches?.[0]?.clientX||0:H.clientX,_="touches"in H?H.touches?.[0]?.clientY||0:H.clientY,v=u,k=S;U.includes("e")&&(v+=D-K),U.includes("w")&&(v+=K-D),U.includes("s")&&(k+=_-Y),U.includes("n")&&(k+=Y-_),H.shiftKey&&(k=v/b),v=Math.max(50,v),k=Math.max(50,k),w=v,P=k,x(v),A(k);},p=()=>{g(false),f.update(()=>{let H=$getNodeByKey(i);H instanceof F&&typeof w=="number"&&typeof P=="number"&&H.setWidthAndHeight(w,P);}),document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",p),document.removeEventListener("touchmove",R),document.removeEventListener("touchend",p);};document.addEventListener("mousemove",R),document.addEventListener("mouseup",p),document.addEventListener("touchmove",R,{passive:false}),document.addEventListener("touchend",p);},re={margin:0,display:"block",position:"relative"},J={maxWidth:"100%",display:"block",borderRadius:"4px",width:typeof E=="number"?"100%":E,height:typeof I=="number"?"100%":I,margin:0},X={fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"};return jsxs("figure",{className:`lexical-image align-${o} ${n} ${N?"selected":""} ${T?"resizing":""} ${d?"uploading":""}`,style:re,children:[jsxs("div",{style:{position:"relative",display:"inline-block",width:E,height:I,cursor:"pointer"},onClick:O,children:[jsx("img",{ref:m,src:a,alt:t,style:J}),N&&c&&jsxs(Fragment,{children:[jsx("div",{className:"resizer ne",onMouseDown:B("ne"),onTouchStart:B("ne"),style:{position:"absolute",top:"-5px",right:"-5px",width:"10px",height:"10px",background:"#007acc",cursor:"ne-resize",borderRadius:"50%"}}),jsx("div",{className:"resizer nw",onMouseDown:B("nw"),onTouchStart:B("nw"),style:{position:"absolute",top:"-5px",left:"-5px",width:"10px",height:"10px",background:"#007acc",cursor:"nw-resize",borderRadius:"50%"}}),jsx("div",{className:"resizer se",onMouseDown:B("se"),onTouchStart:B("se"),style:{position:"absolute",bottom:"-5px",right:"-5px",width:"10px",height:"10px",background:"#007acc",cursor:"se-resize",borderRadius:"50%"}}),jsx("div",{className:"resizer sw",onMouseDown:B("sw"),onTouchStart:B("sw"),style:{position:"absolute",bottom:"-5px",left:"-5px",width:"10px",height:"10px",background:"#007acc",cursor:"sw-resize",borderRadius:"50%"}})]})]}),e&&jsx("figcaption",{style:X,children:e}),jsx("div",{style:{clear:"both",height:0,fontSize:0}})]})}var F=class a extends DecoratorNode{constructor(e="",o="",n,r="none",i,s,l,c,d,f){super(f);y(this,"__src");y(this,"__alt");y(this,"__caption");y(this,"__alignment");y(this,"__className");y(this,"__style");y(this,"__width");y(this,"__height");y(this,"__uploading");this.__src=e&&e.length>0?e:"",this.__alt=o,this.__caption=n,this.__alignment=r,this.__className=i,this.__style=s,this.__width=l,this.__height=c,this.__uploading=d;}static getType(){return "image"}static clone(e){return new a(e.__src,e.__alt,e.__caption,e.__alignment,e.__className,e.__style,e.__width,e.__height,e.__uploading,e.__key)}static importDOM(){return ae.importDOM()}static importJSON(e){return ae.importJSON(e)}createDOM(e){let o=document.createElement("div"),n=e.theme?.image||"",r=this.__alignment;return o.className=`${n} lexical-image-container align-${r}`.trim(),o.style.display=r==="center"?"block":"inline-block",o.style.float=r==="left"?"left":r==="right"?"right":"none",o.style.margin=r==="center"?"1rem auto":r==="left"?"0 1rem 1rem 0":r==="right"?"0 0 1rem 1rem":"1rem 0",o.style.textAlign=r==="center"?"center":"inherit",o.style.position="relative",o}updateDOM(e,o,n){let r=this.__alignment;if(r!==e.__alignment){let i=n.theme?.image||"";o.className=`${i} lexical-image-container align-${r}`.trim();}return o.style.display=r==="center"?"block":"inline-block",o.style.float=r==="left"?"left":r==="right"?"right":"none",o.style.margin=r==="center"?"1rem auto":r==="left"?"0 1rem 1rem 0":r==="right"?"0 0 1rem 1rem":"1rem 0",o.style.textAlign=r==="center"?"center":"inherit",o.style.position="relative",false}exportDOM(){return ae.exportDOM(this)}exportJSON(){return ae.exportJSON(this)}setSrc(e){if(!e||e.length===0){console.warn("Attempted to set empty src on ImageNode");return}let o=this.getWritable();o.__src=e;}setAlt(e){let o=this.getWritable();o.__alt=e;}setCaption(e){let o=this.getWritable();o.__caption=e;}setAlignment(e){let o=this.getWritable();o.__alignment=e;}setClassName(e){let o=this.getWritable();o.__className=e;}setStyle(e){let o=this.getWritable();o.__style=e;}getWidth(){return this.__width}getHeight(){return this.__height}setWidthAndHeight(e,o){let n=this.getWritable();n.__width=e,n.__height=o;}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(po,{src:this.__src,alt:this.__alt,caption:this.__caption,alignment:this.__alignment,className:this.__className,style:this.__style,nodeKey:this.getKey(),width:this.__width,height:this.__height,resizable:!0,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 de(a,t,e,o="none",n,r,i,s,l){if(!a||a.length===0)throw new Error("Cannot create ImageNode with empty src");return new F(a,t,e,o,n,r,i,s,l)}var tt=class extends M{constructor(){super("image",["toolbar"]);y(this,"recentImages",new Set);this.config={...this.config,resizable:true,pasteListener:{insert:true,replace:true},debug:false,forceUpload:false};}configure(e){return e.customRenderer&&(po=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,this.config={...this.config,...e,resizable:e.resizable??true},this}register(e){let o=e.registerCommand(go,s=>(e.update(()=>{try{let l=s.src||(s.file?URL.createObjectURL(s.file):"");if(!l)throw new Error("No src for image");if(this.recentImages.has(l))return !0;this.recentImages.add(l),setTimeout(()=>this.recentImages.delete(l),1e3);let c=!1;s.file&&this.config.uploadHandler&&this.config.forceUpload&&(c=!0,this.config.uploadHandler(s.file).then(m=>{e.update(()=>{let h=$getNodeByKey(d.getKey());h instanceof F&&(h.setSrc(m),h.__uploading=!1);});}).catch(m=>{console.error("Upload failed:",m),e.update(()=>{let h=$getNodeByKey(d.getKey());h instanceof F&&(h.__uploading=!1);});}));let d=de(l,s.alt,s.caption,s.alignment||this.config.defaultAlignment||"none",s.className,s.style,void 0,void 0,c),f=$getSelection();if($isRangeSelection(f))f.insertNodes([d]);else {let m=$createParagraphNode();m.append(d),$getRoot().append(m);}}catch(l){console.error("\u274C Insertion error:",l);}}),true),COMMAND_PRIORITY_EDITOR),n=e.registerCommand(KEY_DELETE_COMMAND,()=>{let s=$getSelection();if($isNodeSelection(s)){let l=s.getNodes();if(l.some(c=>c instanceof F))return e.update(()=>{l.forEach(c=>c.remove());}),true}return false},COMMAND_PRIORITY_EDITOR),r=e.registerCommand(KEY_BACKSPACE_COMMAND,()=>{let s=$getSelection();if($isNodeSelection(s)){let l=s.getNodes();if(l.some(c=>c instanceof F))return e.update(()=>{l.forEach(c=>c.remove());}),true}return false},COMMAND_PRIORITY_EDITOR),i=()=>{};if(this.config.pasteListener?.insert||this.config.pasteListener?.replace){let s=this.config.debug?console.log:()=>{};i=e.registerCommand(PASTE_COMMAND,l=>{let c=l.clipboardData?.items;if(!c)return false;let d=false,f=Array.from(c).some(m=>m.type==="text/html");for(let m of c)if(m.type.startsWith("image/")){if(f)continue;l.preventDefault();let h=m.getAsFile();if(!h)continue;s("\u{1F4CB} Pasting image:",h.name),(this.config.uploadHandler&&this.config.forceUpload?this.config.uploadHandler(h).catch(L=>(console.error("Upload failed:",L),URL.createObjectURL(h))):Promise.resolve(URL.createObjectURL(h))).then(L=>{if(this.recentImages.has(L)){s("\u{1F6AB} Duplicate paste image src detected, skipping:",L);return}this.recentImages.add(L),setTimeout(()=>this.recentImages.delete(L),1e3);let T=false,g;this.config.uploadHandler&&this.config.forceUpload&&h&&(T=true,this.config.uploadHandler(h).then(b=>{e.update(()=>{let C=$getNodeByKey(g.getKey());C instanceof F&&(C.setSrc(b),C.__uploading=false);});}).catch(b=>{console.error("Upload failed:",b),e.update(()=>{let C=$getNodeByKey(g.getKey());C instanceof F&&(C.__uploading=false);});})),e.update(()=>{let b=$getSelection(),C=h.name||"Pasted image";if($isNodeSelection(b)&&this.config.pasteListener?.replace){let x=b.getNodes().find(I=>I instanceof F);if(x){s("\u{1F504} Replacing selected image src"),x.setSrc(L),x.__uploading=T,d=true;return}}this.config.pasteListener?.insert&&(s("\u2795 Inserting new pasted image"),g=de(L,C,void 0,"none",void 0,void 0,void 0,void 0,T),$isRangeSelection(b)?b.insertNodes([g]):$getRoot().append($createParagraphNode().append(g)),d=true);});});break}return d},COMMAND_PRIORITY_NORMAL);}return ()=>{o(),n(),r(),i();}}getNodes(){return [F]}getCommands(e){return {insertImage:o=>{e.dispatchCommand(go,o);},setImageAlignment:o=>{e.update(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();for(let i of r)i instanceof F&&i.setAlignment(o);}});},setImageCaption:o=>{e.update(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();for(let i of r)i instanceof F&&i.setCaption(o);}});},setImageClassName:o=>{e.update(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();for(let i of r)i instanceof F&&i.setClassName(o);}});},setImageStyle:o=>{e.update(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();for(let i of r)i instanceof F&&i.setStyle(o);}});}}}getStateQueries(e){return {imageSelected:()=>new Promise(o=>{e.getEditorState().read(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();o(r.length===1&&r[0]instanceof F);}else o(false);});}),isImageAlignedLeft:()=>new Promise(o=>{e.getEditorState().read(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();if(r.length===1&&r[0]instanceof F){o(r[0].__alignment==="left");return}}o(false);});}),isImageAlignedCenter:()=>new Promise(o=>{e.getEditorState().read(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();if(r.length===1&&r[0]instanceof F){o(r[0].__alignment==="center");return}}o(false);});}),isImageAlignedRight:()=>new Promise(o=>{e.getEditorState().read(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();if(r.length===1&&r[0]instanceof F){o(r[0].__alignment==="right");return}}o(false);});}),isImageAlignedNone:()=>new Promise(o=>{e.getEditorState().read(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();if(r.length===1&&r[0]instanceof F){o(r[0].__alignment==="none");return}}o(false);});})}}},yr=new tt,fo={dependencies:[F],export:a=>{if(!Er(a))return null;let t=a,e=t.__src||"",o=t.__alt||"",n=t.__caption||"",r=t.__alignment||"none";if(!e)return null;let i=`,i+=")",r!=="none"&&(i+=` <!-- align:${r} -->`),i},regExp:/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)(?:\s*<!--\s*align:(left|center|right)\s*-->)?\s*$/,replace:(a,t,e,o)=>{let[,n,r,i,s]=e;if(!r)return;let l=de(r,n||"",i||void 0,s||"none",void 0,void 0,void 0,void 0,false);a.replace(l);},type:"element"};function Er(a){return a instanceof F}function bo(a){let t=renderToStaticMarkup(a),e=document.createElement("div");e.innerHTML=t;let o=e.firstElementChild;return e.remove(),o}function _r(a){let t=a.isContainer??false,e=createCommand("insert-custom-node");function o({node:l,payload:c,nodeKey:d,children:f}){let[m]=useLexicalComposerContext(),[h,N]=useState(false);useEffect(()=>m.registerUpdateListener(({editorState:T})=>{T.read(()=>{let g=$getSelection();N($isNodeSelection(g)&&g.getNodes().some(b=>b.__key===d));});}),[m,d]);let L=T=>{m.update(()=>{let g=l.getWritable();g.__payload={...g.__payload,...T};});};return a.render?a.render({node:l,payload:c,children:f,nodeKey:d,isSelected:h,updatePayload:L}):null}class n extends ElementNode{constructor(d={},f,m){super(m);y(this,"__payload");y(this,"__nodeType");this.__payload=d,this.__nodeType=f;}static getType(){return a.nodeType}static clone(d){return new n(d.__payload,d.__nodeType,d.__key)}isSelectable(){return true}canBeEmpty(){return false}canInsertTextBefore(){return false}canInsertTextAfter(){return false}static importJSON(d){let{payload:f,children:m}=d;return new n(f,d.type)}static importDOM(){return a.importDOM?a.importDOM():{}}static exportDOM(d,{node:f}){if(a.exportDOM){let h=document.createElement("div");return a.exportDOM(d,{element:h,node:f})}let m=document.createElement("div");return m.setAttribute("data-custom-node-type",a.nodeType),{element:m}}exportJSON(){return {type:this.__nodeType,version:1,payload:this.__payload,children:this.getChildren().map(d=>d.exportJSON()),direction:null,format:"",indent:0}}createDOM(d){if(a.createDOM){let m=a.createDOM(d,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m.setAttribute("data-lexical-key",this.getKey()),m}if(a.jsx){let m=a.jsx({node:this,payload:this.__payload,nodeKey:this.getKey(),isSelected:false,updatePayload:N=>{this.setPayload(N);}}),h=bo(m);return h.setAttribute("data-custom-node-type",this.__nodeType),h.setAttribute("data-lexical-key",this.getKey()),h}let f=document.createElement("div");return f.setAttribute("data-custom-node-type",this.__nodeType),f.setAttribute("data-lexical-key",this.getKey()),f.style.border="2px solid #ccc",f.style.borderRadius="8px",f.style.padding="16px",f.style.margin="8px 0",f.style.position="relative",f}updateDOM(d,f,m){return a.updateDOM?a.updateDOM(d,f,m):false}getPayload(){return this.__payload}setPayload(d){let f=this.getWritable();f.__payload={...this.__payload,...d};}}class r extends DecoratorNode{constructor(d={},f,m){super(m);y(this,"__payload");y(this,"__nodeType");this.__payload=d,this.__nodeType=f;}static getType(){return a.nodeType}static clone(d){return new r(d.__payload,d.__nodeType,d.__key)}isSelectable(){return true}static importJSON(d){let{payload:f}=d;return new r(f,d.type)}static importDOM(){return a.importDOM?a.importDOM():{}}static exportDOM(d,{node:f}){if(a.exportDOM){let h=document.createElement("span");return a.exportDOM(d,{element:h,node:f})}let m=document.createElement("span");return m.setAttribute("data-custom-node-type",a.nodeType),{element:m}}exportJSON(){return {type:this.__nodeType,version:1,payload:this.__payload}}createDOM(d){let f=document.createElement("span");if(f.setAttribute("data-custom-node-type",this.__nodeType),a.createDOM){let m=a.createDOM(d,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m}return f}updateDOM(d,f,m){return a.updateDOM?a.updateDOM(d,f,m):false}getPayload(){return this.__payload}setPayload(d){let f=this.getWritable();f.__payload={...this.__payload,...d};}decorate(){return jsx(o,{node:this,payload:this.__payload,nodeKey:this.__key,children:void 0})}}function i(l=a.defaultPayload||{}){if(t){let c=new n(l,a.nodeType);if(a.initialChildren)a.initialChildren().forEach(f=>{if(f.type==="paragraph"){let m=$createParagraphNode();f.children&&f.children.forEach(h=>{h.type==="text"&&m.append($createTextNode(h.text||""));}),c.append(m);}});else {let d=$createParagraphNode();d.append($createTextNode("")),c.append(d);}return c}else return new r(l,a.nodeType)}class s extends M{constructor(){super(a.nodeType,["toolbar"]);}register(c){let d=c.registerCommand(e,m=>(c.update(()=>{let h=i(m),N=$getSelection();$isRangeSelection(N)?N.insertNodes([h]):$getRoot().append($createParagraphNode().append(h));}),true),COMMAND_PRIORITY_EDITOR),f=c.registerUpdateListener(({editorState:m,prevEditorState:h})=>{t&&m.read(()=>{let N=$getSelection(),L=$isNodeSelection(N)?N.getNodes():[];c.getEditorState().read(()=>{let T=$getRoot(),g=b=>{if(b.getType()===a.nodeType){let C=L.some(x=>x.__key===b.__key),E=document.querySelector(`[data-lexical-key="${b.__key}"]`);E&&(E.setAttribute("data-selected",C.toString()),E.style.borderColor=C?"#007ACC":"#ccc",E.style.backgroundColor=C?"#f0f8ff":"transparent");}"getChildren"in b&&b.getChildren().forEach(g);};g(T);});});});return ()=>{d(),f();}}getNodes(){return t?[n]:[r]}getCommands(c){return {...{insertCustomNode:f=>c.dispatchCommand(e,f)},...a.commands?a.commands(c):{}}}getStateQueries(c){return {...{isCustomNodeActive:()=>new Promise(f=>{c.getEditorState().read(()=>{let m=$getSelection();f(!!m&&$isNodeSelection(m)&&m.getNodes().some(h=>h.getType()===a.nodeType));});})},...a.stateQueries?a.stateQueries(c):{}}}}return {extension:new s,$createCustomNode:i,jsxToDOM:bo}}var yo=a=>{let{contentEditable:t,placeholder:e,className:o,classNames:n,styles:r,errorBoundary:i}=a,s=n?.placeholder||se.richText?.placeholder||"luthor-placeholder",l={position:"absolute",top:0,left:0,pointerEvents:"none",color:"#999",zIndex:1,...r?.placeholder};return jsx("div",{className:n?.container||o||se.container||"luthor-editor-container",style:{position:"relative",...r?.container},children:jsx(RichTextPlugin,{contentEditable:t||jsx(ContentEditable,{className:n?.contentEditable||se.richText?.contentEditable||"luthor-content-editable",style:r?.contentEditable}),placeholder:typeof e=="string"?jsx("div",{className:s,style:l,children:e}):e||jsx("div",{className:s,style:l,children:"Start writing..."}),ErrorBoundary:i||Hr})})},Tt=class extends M{constructor(t={}){super("richText",["floating"]),this.config={showInToolbar:false,position:"after",...t};}register(t){return ()=>{}}getPlugins(){return [jsx(yo,{...this.config},"rich-text")]}},Eo=new Tt,Ir=a=>jsx(yo,{...a}),Hr=({children:a,onError:t})=>{try{return jsx(Fragment,{children:a})}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 nt=class extends M{constructor(){super("floatingToolbar",["floating"]);y(this,"isVisible",false);y(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(Wr,{extension:this,config:this.config},"floating-toolbar")]}getCommands(e){return {}}getStateQueries(e){return {isFloatingVisible:async()=>this.isVisible}}updateContext(e,o){this.config&&(this.config.commands=e,this.config.activeStates=o);}getSelectionRect(){return this.selectionRect}getIsVisible(){return this.isVisible}setVisible(e){this.isVisible=e;}setSelectionRect(e){this.selectionRect=e;}},Kr=new nt;function Wr({extension:a,config:t}){let[e]=useLexicalComposerContext(),{config:o}=Z(),[n,r]=useState(false),[i,s]=useState(null),[l,c]=useState(null),d=(N,L)=>{let T;return (...g)=>{clearTimeout(T),T=setTimeout(()=>N(()=>g),L);}},f=N=>{let L=t.offset||{y:8},T=t.positionStrategy||"below",g=window.pageXOffset||document.documentElement.scrollLeft||0,b=window.pageYOffset||document.documentElement.scrollTop||0,C=window.innerWidth,E=window.innerHeight,x=N.bottom+b+L.y;if(T==="above")x=N.top+b-L.y;else if(T==="auto"){let P=E-N.bottom;N.top;x=P>60?N.bottom+b+L.y:N.top+b-L.y;}let I=t.toolbarDimensions?.width||300,A=t.toolbarDimensions?.height||40,O=10,B=N.left+N.width/2,re=B+g,J,X=false,U=B-O,z=C-B-O,K=I/2,Y=B-K,u=B+K,S=Y<O,w=u>C-O;return !S&&!w?(J=re-K,X=false):S||U<K?(J=g+O,X=false):w||z<K?(J=g+C-I-O,X=true):(J=re-K,X=false),x-A<b?x=N.bottom+b+L.y:x+A>b+E&&(x=N.top+b-L.y-A),{x:J,y:x,width:N.width,height:N.height,top:N.top+b,left:N.left+g,bottom:N.bottom+b,right:N.right+g,positionFromRight:X}};useEffect(()=>{a.setVisible(n);},[n,a]),useEffect(()=>{let L=d(()=>{e.getEditorState().read(()=>{let b=$getSelection(),C=null,E=null;if($isRangeSelection(b)&&!b.isCollapsed()){let x=window.getSelection();x&&x.rangeCount>0&&(C=x.getRangeAt(0).getBoundingClientRect(),E=b);}else if($isNodeSelection(b)){let x=b.getNodes();if(x.length>0){let I=x[0];if(I){let A=I.getKey(),O=e.getElementByKey(A);O&&(C=O.getBoundingClientRect());}}}if(C&&C.width>0&&C.height>0){let x=f(C);s(x),c(E),r(true),a.setSelectionRect(x);}else s(null),c(null),r(false),a.setSelectionRect(null);});},t.debounceMs||100),T=e.registerUpdateListener(()=>{L();}),g=()=>{L();};return document.addEventListener("selectionchange",g),()=>{T(),document.removeEventListener("selectionchange",g);}},[e,t.debounceMs]);let m=()=>{r(false),s(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=t.anchorElem||document.body;return createPortal(t.render({isVisible:n,selectionRect:i,selection:l,editor:e,commands:t.getCommands?.()||{},activeStates:t.getActiveStates?.()||{},hide:m,theme:o?.theme?.floatingToolbar||t.theme||{}}),h)}var rt=class extends M{constructor(){super("commandPalette",["toolbar"]);y(this,"isOpen",false);y(this,"commands",new Map);y(this,"listeners",[]);}register(e){let o=n=>{(n.metaKey||n.ctrlKey)&&n.shiftKey&&n.key==="P"&&(n.preventDefault(),this.toggleCommandPalette()),n.key==="Escape"&&this.isOpen&&this.hideCommandPalette();};return document.addEventListener("keydown",o),this.registerTableCommands(e),()=>{document.removeEventListener("keydown",o);}}getCommands(e){return {showCommandPalette:()=>this.showCommandPalette(),hideCommandPalette:()=>this.hideCommandPalette(),registerCommand:o=>this.registerCommand(o),unregisterCommand:o=>this.unregisterCommand(o)}}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(n=>this.registerCommand(n));}notifyListeners(){let e=Array.from(this.commands.values());this.listeners.forEach(o=>o(this.isOpen,e));}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(o=>o!==e);}}getAllCommands(){return Array.from(this.commands.values())}},Jr=new rt;var Xr=[Et,Bt,at,ct,fo];export{Xr as ALL_MARKDOWN_TRANSFORMERS,M as BaseExtension,Do as BaseProvider,Ke as BlockFormatExtension,Ne as BoldExtension,$e as CodeExtension,Qe as CodeFormatExtension,rt as CommandPaletteExtension,ke as ContextMenuExtension,ye as DraggableBlockExtension,Q as ExtensionCategory,nt as FloatingToolbarExtension,Ge as HTMLEmbedExtension,je as HTMLExtension,We as HistoryExtension,Pe as HorizontalRuleExtension,tt as ImageExtension,Te as ItalicExtension,Le as LinkExtension,Fe as ListExtension,we as MarkdownExtension,Ir as RichText,Re as StrikethroughExtension,Ie as TableExtension,V as TextFormatExtension,ve as UnderlineExtension,Un as blockFormatExtension,Ao as boldExtension,_n as codeExtension,kn as codeFormatExtension,Jr as commandPaletteExtension,lt as contextMenuExtension,_r as createCustomNodeExtension,Pt as createEditorSystem,Io as createExtension,se as defaultLuthorTheme,ao as draggableBlockExtension,Kr as floatingToolbarExtension,jn as historyExtension,tn as horizontalRuleExtension,lr as htmlEmbedExtension,or as htmlExtension,yr as imageExtension,vo as isLuthorTheme,Fo as italicExtension,jo as linkExtension,Rn as listExtension,xe as markdownExtension,To as mergeThemes,Eo as richTextExtension,Qo as strikethroughExtension,Cn as tableExtension,$o as underlineExtension,Z as useBaseEditor};
|
|
1
|
+
import Zl,{createContext,createElement,useState,useEffect,useRef,useMemo,useCallback,useContext}from'react';import {LexicalComposer}from'@lexical/react/LexicalComposer';import {useLexicalComposerContext}from'@lexical/react/LexicalComposerContext';import {createCommand,PASTE_COMMAND,$getSelection,$isRangeSelection,$createTextNode,$getNodeByKey,KEY_ENTER_COMMAND,$isTextNode,$isParagraphNode,$isRootOrShadowRoot,COMMAND_PRIORITY_LOW,$isElementNode,INDENT_CONTENT_COMMAND,OUTDENT_CONTENT_COMMAND,$createParagraphNode,KEY_TAB_COMMAND,$nodesOfType,INSERT_PARAGRAPH_COMMAND,COMMAND_PRIORITY_NORMAL,COMMAND_PRIORITY_EDITOR,ParagraphNode,FORMAT_ELEMENT_COMMAND,CAN_UNDO_COMMAND,CAN_REDO_COMMAND,CLEAR_HISTORY_COMMAND,REDO_COMMAND,UNDO_COMMAND,$isNodeSelection,$getRoot,KEY_DELETE_COMMAND,KEY_BACKSPACE_COMMAND,FORMAT_TEXT_COMMAND,INSERT_LINE_BREAK_COMMAND,$getNearestNodeFromDOMNode,DecoratorNode,$createNodeSelection,$setSelection,ElementNode}from'lexical';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {$createLinkNode,TOGGLE_LINK_COMMAND,$isLinkNode,LinkNode,AutoLinkNode}from'@lexical/link';import {LinkPlugin}from'@lexical/react/LexicalLinkPlugin';import {AutoLinkPlugin}from'@lexical/react/LexicalAutoLinkPlugin';import {ClickableLinkPlugin}from'@lexical/react/LexicalClickableLinkPlugin';import {HorizontalRuleNode,$createHorizontalRuleNode,INSERT_HORIZONTAL_RULE_COMMAND,$isHorizontalRuleNode}from'@lexical/react/LexicalHorizontalRuleNode';import {HorizontalRulePlugin}from'@lexical/react/LexicalHorizontalRulePlugin';import {registerMarkdownShortcuts,TRANSFORMERS}from'@lexical/markdown';import {$patchStyleText,$getSelectionStyleValueForProperty,$setBlocksType}from'@lexical/selection';import {createPortal}from'react-dom';import {TablePlugin}from'@lexical/react/LexicalTablePlugin';import {TableNode,TableRowNode,TableCellNode,$isTableSelection,$isTableNode,$deleteTableColumnAtSelection,$deleteTableRowAtSelection,$unmergeCell,$isTableCellNode,$mergeCells,$getTableNodeFromLexicalNodeOrThrow,$getTableColumnIndexFromTableCellNode,$isTableRowNode,TableCellHeaderStates,$getTableRowIndexFromTableCellNode,$insertTableColumnAtSelection,$insertTableRowAtSelection,$createTableNodeWithDimensions,$findCellNode}from'@lexical/table';import {ListNode,ListItemNode,INSERT_ORDERED_LIST_COMMAND,INSERT_UNORDERED_LIST_COMMAND,$isListNode,$isListItemNode,INSERT_CHECK_LIST_COMMAND}from'@lexical/list';import {ListPlugin}from'@lexical/react/LexicalListPlugin';import {CheckListPlugin}from'@lexical/react/LexicalCheckListPlugin';import {CodeNode,CodeHighlightNode,$createCodeNode,$isCodeNode,registerCodeHighlighting,PrismTokenizer,normalizeCodeLang,getCodeLanguageOptions,getCodeLanguages}from'@lexical/code';import {$isHeadingNode,$isQuoteNode,HeadingNode,QuoteNode,$createQuoteNode,$createHeadingNode}from'@lexical/rich-text';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 ai=Object.defineProperty;var li=(s,n,e)=>n in s?ai(s,n,{enumerable:true,configurable:true,writable:true,value:e}):s[n]=e;var x=(s,n,e)=>li(s,typeof n!="symbol"?n+"":n,e);var So=["--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 ci(s){return typeof s=="string"&&s.trim().length>0}function di(s){if(!s)return;let n={};for(let e of So){let t=s[e];ci(t)&&(n[e]=t);}return Object.keys(n).length>0?n:void 0}var we={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 ui(s,n){return {...s,...n,text:{...s.text,...n.text},list:{...s.list,...n.list,nested:{...s.list?.nested,...n.list?.nested}},heading:{...s.heading,...n.heading},codeHighlight:{...s.codeHighlight,...n.codeHighlight},toolbar:{...s.toolbar,...n.toolbar},draggable:{...s.draggable,...n.draggable,styles:{...s.draggable?.styles,...n.draggable?.styles}},floatingToolbar:{...s.floatingToolbar,...n.floatingToolbar,styles:{...s.floatingToolbar?.styles,...n.floatingToolbar?.styles}},richText:{...s.richText,...n.richText},styles:{toolbar:{...s.styles?.toolbar,...n.styles?.toolbar},draggable:{...s.styles?.draggable,...n.styles?.draggable},floatingToolbar:{...s.styles?.floatingToolbar,...n.styles?.floatingToolbar},...n.styles}}}function mi(s){return s&&typeof s=="object"}var Ze=createContext(null);function To(){function s(){let t=useContext(Ze);if(!t)throw new Error("useEditor must be used within Provider");return t}function n({children:t,config:o={},extensions:r}){let[i]=useLexicalComposerContext(),a=useMemo(()=>({formatText:(h,m)=>i?.dispatchCommand(FORMAT_TEXT_COMMAND,h)}),[i]),l=useMemo(()=>{if(!i)return {};let h={};for(let m of r)Object.assign(h,m.getCommands(i));return h},[r,i]),d=useMemo(()=>({...a,...l}),[a,l]),{plugins:c,pluginsBefore:u,pluginsAfter:p}=useMemo(()=>{let h=[],m=[];for(let g of r){let S=g.getPlugins?.()||[];(g.config?.position||"before")==="after"?m.push(...S):h.push(...S);}return {plugins:[...h,...m],pluginsBefore:h,pluginsAfter:m}},[r]);useEffect(()=>{if(!i)return;let m=[...r].sort((g,S)=>{let w=g.config?.initPriority??0;return (S.config?.initPriority??0)-w}).map(g=>g.register(i));return ()=>m.forEach(g=>g&&g())},[i,r]);let b=useMemo(()=>{if(!i)return {};let h={};for(let m of r)m.getStateQueries&&Object.assign(h,m.getStateQueries(i));return h},[r,i]),[v,y]=useState(()=>{let h={};return Object.keys(b).forEach(m=>h[m]=false),h});useEffect(()=>{let h=Object.keys(b);y(m=>{let g={};for(let w of h){let f=m[w];g[w]=f??false;}if(Object.keys(m).length!==h.length)return g;for(let w of h)if(m[w]!==g[w])return g;return m});},[b]),useEffect(()=>{if(!i)return;let h=true,m=0,g=async()=>{let f=++m,F=Object.entries(b).map(async([H,Q])=>{try{let D=await Q();return [H,D]}catch{return [H,false]}}),z=await Promise.all(F);if(!h||f!==m)return;let W=Object.fromEntries(z);y(H=>{let Q=H,D=W,K=Object.keys(Q),A=Object.keys(D);if(K.length!==A.length)return W;for(let M of A)if(Q[M]!==D[M])return W;return H});};g();let S=i.registerUpdateListener(()=>{g();}),w=r.map(f=>{let N=f;if(typeof N.onStateChange=="function")return N.onStateChange(()=>{g();})}).filter(f=>typeof f=="function");return ()=>{h=false,S(),w.forEach(f=>f());}},[i,b,r]);let E={editor:i,config:o,extensions:r,commands:d,activeStates:v,stateQueries:b,listeners:{registerUpdate:h=>i?.registerUpdateListener(h)||(()=>{}),registerPaste:h=>i?.registerCommand(PASTE_COMMAND,h,COMMAND_PRIORITY_EDITOR)||(()=>{})},export:{toJSON:()=>i?.getEditorState().toJSON()},import:{fromJSON:h=>{i&&(typeof h=="string"||typeof h=="object"&&h!==null)&&i.setEditorState(i.parseEditorState(h));}},lexical:i,extensionsAPI:{add:h=>{},remove:h=>{},reorder:h=>{}},plugins:c,hasExtension:h=>r.some(m=>m.name===h)};return jsxs(Ze.Provider,{value:E,children:[u,t,p]})}function e(t){let o=useMemo(()=>t.extensions.flatMap(a=>a.getNodes?.()||[]),[t.extensions]),r=useMemo(()=>({namespace:"modern-editor",theme:t.config?.theme||we,onError:i=>{console.error("Lexical error:",i);},nodes:o}),[t.config?.theme,o]);return jsx(LexicalComposer,{initialConfig:r,children:jsx(n,{...t})})}return {Provider:e,useEditor:s}}var xi=To(),Ei=xi.Provider,xe=()=>{let s=useContext(Ze);if(!s)throw new Error("useBaseEditor must be used within Provider");return s};var vi=(o=>(o.Toolbar="toolbar",o.Sidebar="sidebar",o.ContextMenu="contextmenu",o.Floating="floating",o))(vi||{});var L=class{constructor(n,e=["toolbar"]){x(this,"name");x(this,"category",["toolbar"]);x(this,"config",{});x(this,"supportedFormats",[]);x(this,"nodeOverrides",{});this.name=n,this.category=e;}configure(n){return this.config={...this.config,...n},this}getNodes(){return []}overrideUI(n){return this}overrideNodeRender(n){return this.nodeOverrides={...this.nodeOverrides,...n},this}getPlugins(){return []}getCommands(n){return {}}getStateQueries(n){return {}}getToolbarItems(n){return []}};function Ni(s){return new class extends L{constructor(){super(s.name,s.category||["toolbar"]);x(this,"_plugins",[]);x(this,"_nodes",[]);x(this,"_initialize");s.config&&(this.config={...this.config,...s.config}),this._initialize=s.initialize,s.supportedFormats&&(this.supportedFormats=s.supportedFormats),s.nodes&&(this._nodes=s.nodes),s.plugins&&(this._plugins=s.plugins);}register(e){let t=this._initialize?.(e);return ()=>{typeof t=="function"&&t();}}getNodes(){return this._nodes}getPlugins(){return this._plugins}getCommands(e){return s.commands?s.commands(e):{}}getStateQueries(e){return s.stateQueries?s.stateQueries(e):{}}}}function Li(s){s.update(()=>{$setSelection(null);});}function wi(s,n){let e=n.getAttribute("data-lexical-node-key")?.trim();if(e)return e;let t=null;return s.read(()=>{let o=$getNearestNodeFromDOMNode(n);if($isLinkNode(o)){t=o.getKey();return}let r=n.firstChild;if(!r)return;let i=$getNearestNodeFromDOMNode(r);if($isLinkNode(i)){t=i.getKey();return}let a=i?.getParent();a&&$isLinkNode(a)&&(t=a.getKey());}),t}function Ri(s){return {type:"text",version:1,text:s,detail:0,format:0,mode:"normal",style:""}}function ki(s){return {type:"paragraph",version:1,format:"",indent:0,direction:null,children:[Ri(s)]}}function Pi(s){let n=s.replace(/\r\n?/g,`
|
|
2
|
+
`).trim();return {root:{type:"root",version:1,format:"",indent:0,direction:null,children:(n.length===0?[""]:n.split(/\n{2,}/).map(t=>t.trim())).map(t=>ki(t))}}}function wo(s){return !s||typeof s!="object"?"":"text"in s&&typeof s.text=="string"?s.text:"children"in s&&Array.isArray(s.children)?(s.children??[]).map(n=>wo(n)).join(""):""}function Mi(s){if(!s||typeof s!="object")return "";let n=s.root;return !n||!Array.isArray(n.children)?"":n.children.map(e=>wo(e).trim()).filter(e=>e.length>0).join(`
|
|
3
|
+
|
|
4
|
+
`)}var X=class extends L{constructor(n){super(n,["toolbar"]),this.supportedFormats=[n];}register(n){let e=n.registerCommand(INSERT_PARAGRAPH_COMMAND,()=>(n.getEditorState().read(()=>{let o=$getSelection();$isRangeSelection(o)&&o.hasFormat(this.name)&&n.dispatchCommand(FORMAT_TEXT_COMMAND,this.name);}),false),1),t=n.registerCommand(INSERT_LINE_BREAK_COMMAND,()=>false,1);return ()=>{e(),t();}}getCommands(n){return {[`toggle${this.name.charAt(0).toUpperCase()+this.name.slice(1)}`]:()=>n.dispatchCommand(FORMAT_TEXT_COMMAND,this.name)}}getStateQueries(n){return {[this.name]:()=>new Promise(e=>{n.getEditorState().read(()=>{let t=$getSelection();$isRangeSelection(t)?e(t.hasFormat(this.name)):e(false);});})}}};var St=class extends X{constructor(){super("bold");}},_i=new St;var vt=class extends X{constructor(){super("italic");}},Ai=new vt;var Hi={format:["underline"],tag:"++",type:"text-format"},Nt=class extends X{constructor(){super("underline");}getMarkdownTransformers(){return [Hi]}},Di=new Nt;var Tt=class extends X{constructor(){super("strikethrough");}},Fi=new Tt;var Lt=class extends L{constructor(){super("link",["toolbar"]);x(this,"lastSelectedLinkNodeKey",null);this.config={autoLinkText:false,clickableLinks:true,openLinksInNewTab:true,linkSelectedTextOnPaste:true,validateUrl:e=>{try{return new URL(e),!0}catch{return false}}};}register(e){let t=e.registerCommand(PASTE_COMMAND,r=>{let i=r.clipboardData;if(!i)return false;let a=i.getData("text/plain");return a&&this.config.validateUrl(a)&&this.config.autoLinkUrls?(r.preventDefault(),e.update(()=>{let l=$getSelection();if($isRangeSelection(l))if(l.isCollapsed()){let d=$createLinkNode(a);d.append($createTextNode(a)),l.insertNodes([d]);}else if(this.config.linkSelectedTextOnPaste)e.dispatchCommand(TOGGLE_LINK_COMMAND,a);else {l.insertText(a);let d=$getSelection();d&&$isRangeSelection(d)&&d.getNodes()[0]&&e.dispatchCommand(TOGGLE_LINK_COMMAND,a);}}),true):false},3),o=e.registerUpdateListener(({editorState:r})=>{r.read(()=>{let i=this.getSelectedLinkNode();if(i){this.lastSelectedLinkNodeKey=i.getKey();return}if(this.lastSelectedLinkNodeKey){let a=$getNodeByKey(this.lastSelectedLinkNodeKey);$isLinkNode(a)||(this.lastSelectedLinkNodeKey=null);}});});return ()=>{t(),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 t=o=>{let i=/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_.+~#?&//=]*)/g.exec(o);return i&&this.config.validateUrl(i[0])?{text:i[0],url:i[0],index:i.index,length:i[0].length}:null};e.push(jsx(AutoLinkPlugin,{matchers:[t]},"auto-link"));}return e}getCommands(e){let t=i=>i.trim(),o=i=>i.length>0&&!!this.config.validateUrl?.(i),r=(i,a,l,d)=>{i.setURL(a),typeof l<"u"&&i.setRel(l.trim()||null),typeof d<"u"&&i.setTarget(d.trim()||null);};return {insertLink:(i,a)=>{if(i){let l=t(i);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=t(l);if(!o(d))return;e.dispatchCommand(TOGGLE_LINK_COMMAND,d);}}},updateLink:(i,a,l)=>{let d=t(i);if(!o(d))return false;let c=false;return e.update(()=>{let u=this.getSelectedLinkNode()??this.getCachedLinkNode();if(u){r(u,d,a,l),this.lastSelectedLinkNodeKey=u.getKey(),c=true;return}let p=$getSelection();if(!$isRangeSelection(p)){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 i=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,i=true;return}e.dispatchCommand(TOGGLE_LINK_COMMAND,null);}),i||(this.lastSelectedLinkNodeKey=null);},getCurrentLink:()=>new Promise(i=>{e.getEditorState().read(()=>{let a=this.getSelectedLinkNode()??this.getCachedLinkNode();if(!a){i(null);return}i(this.serializeLinkNode(a));});}),getLinkByKey:i=>new Promise(a=>{e.getEditorState().read(()=>{let l=this.getLinkNodeByKey(i);if(!l){a(null);return}a(this.serializeLinkNode(l));});}),updateLinkByKey:(i,a,l,d)=>{let c=t(a);if(!o(c))return false;let u=false;return e.update(()=>{let p=this.getLinkNodeByKey(i);if(!p){u=false;return}r(p,c,l,d),this.lastSelectedLinkNodeKey=p.getKey(),u=true;}),u},removeLinkByKey:i=>{let a=false;return e.update(()=>{let l=this.getLinkNodeByKey(i);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 t=e.getChildren();for(let o of t)e.insertBefore(o);e.remove();}getLinkNodeByKey(e){let t=e.trim();if(!t)return null;let o=$getNodeByKey(t);return $isLinkNode(o)?o:null}getSelectedLinkNode(){let e=$getSelection();if(!e||!$isRangeSelection(e))return null;let t=e.anchor.getNode(),o=e.focus.getNode(),r=e.getNodes(),i=[t,o,...r];for(let a of i){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(t=>{e.getEditorState().read(()=>{let o=$getSelection();if(o&&$isRangeSelection(o)){let i=o.getNodes()[0];if(i){let a=i.getParent();t($isLinkNode(a)||$isLinkNode(i));}else t(false);}else t(false);});}),isTextSelected:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();o&&$isRangeSelection(o)?t(!o.isCollapsed()):t(false);});})}}},Vi=new Lt;var ns={dependencies:[HorizontalRuleNode],export:s=>$isHorizontalRuleNode(s)?"---":null,regExp:/^(?:---|___)\s*$/,replace:(s,n,e,t)=>{let o=$createHorizontalRuleNode();s.replace(o),t||is(o);},type:"element"},os=[ns],rs=/^(?:---|___)$/;function is(s){let n=s.getNextSibling();if(n&&$isParagraphNode(n)){n.selectStart();return}let e=$createParagraphNode();s.insertAfter(e),e.selectStart();}var wt=class extends L{constructor(){super("horizontalRule",["toolbar"]);}register(n){let e=registerMarkdownShortcuts(n,os),t=n.registerCommand(KEY_ENTER_COMMAND,o=>{if(o?.shiftKey)return false;let r=false;return n.update(()=>{let i=$getSelection();if(!i||!$isRangeSelection(i)||!i.isCollapsed())return;let a=i.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(!rs.test(c))return;r=true;let u=$createHorizontalRuleNode();l.replace(u),u.selectNext();}),r},COMMAND_PRIORITY_LOW);return ()=>{e(),t();}}getNodes(){return [HorizontalRuleNode]}getPlugins(){return [jsx(HorizontalRulePlugin,{},"horizontal-rule")]}getCommands(n){return {insertHorizontalRule:()=>{n.dispatchCommand(INSERT_HORIZONTAL_RULE_COMMAND,void 0);}}}getStateQueries(n){return {isHorizontalRuleSelected:()=>new Promise(e=>{n.getEditorState().read(()=>{let t=$getSelection();if(t&&$isRangeSelection(t)){let r=t.getNodes().some(i=>$isHorizontalRuleNode(i));e(r);}else e(false);});})}}},ss=new wt;var Bo=[{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"}],cs={value:"default",label:"Default",fontFamily:"inherit"};function Fo(s){return s.trim().toLowerCase()}function ds(s){return /^[a-z0-9][a-z0-9-]*$/i.test(s)}function us(s){let n=new Set,e=[];for(let o of s){let r=o.value.trim(),i=o.label.trim(),a=o.fontFamily.trim();if(!r||!i||!a||!ds(r))continue;let l=Fo(r);n.has(l)||(n.add(l),e.push({value:r,label:i,fontFamily:a,cssImportUrl:o.cssImportUrl?.trim()||void 0}));}return e.length===0?Bo:e.some(o=>Fo(o.value)==="default")?e:[cs,...e]}var Rt=class extends L{constructor(){super("fontFamily",["toolbar"]);x(this,"loadedFontUrls",new Set);this.config={options:Bo,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 t={...e};return e.options&&(t.options=us(e.options)),super.configure(t)}getCommands(e){return {setFontFamily:t=>{let o=this.findOption(t);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,t){e.update(()=>{let o=$getSelection();$isRangeSelection(o)&&$patchStyleText(o,{"font-family":t});});}hasCustomFontFamily(e){let t=false;return e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let r=$getSelectionStyleValueForProperty(o,"font-family","");t=this.normalizeFontValue(r).length>0;}),t}getCurrentFontFamilyValue(e){let t=null;return e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let r=$getSelectionStyleValueForProperty(o,"font-family","");if(!r){t="default";return}let i=this.normalizeFontValue(r);t=this.config.options.find(l=>this.normalizeFontValue(l.value)===i?true:this.normalizeFontValue(l.fontFamily)===i)?.value??null;}),t}findOption(e){let t=this.normalizeFontValue(e);return this.config.options.find(o=>this.normalizeFontValue(o.value)===t)}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 t=e.cssImportUrl,o=encodeURIComponent(t);if(this.loadedFontUrls.has(t))return;if(document.querySelector(`link[data-luthor-font-url="${o}"]`)){this.loadedFontUrls.add(t);return}let i=document.createElement("link");i.rel="stylesheet",i.href=t,i.setAttribute("data-luthor-font-url",o),document.head.appendChild(i),this.loadedFontUrls.add(t);}},ms=new Rt;var jo=[{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"}],ps={value:"default",label:"Default",fontSize:"inherit"};function $o(s){return s.trim().toLowerCase()}function hs(s){return /^[a-z0-9][a-z0-9-]*$/i.test(s)}function fs(s){let n=new Set,e=[];for(let o of s){let r=String(o.value).trim(),i=String(o.label).trim(),a=String(o.fontSize).trim();if(!r||!i||!a||!hs(r))continue;let l=$o(r);n.has(l)||(n.add(l),e.push({value:r,label:i,fontSize:a}));}return e.length===0?jo:e.some(o=>$o(o.value)==="default")?e:[ps,...e]}var kt=class extends L{constructor(){super("fontSize",["toolbar"]),this.config={options:jo,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}configure(n){let e={...n};return n.options&&(e.options=fs(n.options)),super.configure(e)}getCommands(n){return {setFontSize:e=>{let t=this.findOption(e);t&&this.applyFontSize(n,t.fontSize);},clearFontSize:()=>{this.applyFontSize(n,"");},getCurrentFontSize:()=>Promise.resolve(this.getCurrentFontSizeValue(n)),getFontSizeOptions:()=>this.config.options}}getStateQueries(n){return {hasCustomFontSize:()=>Promise.resolve(this.hasCustomFontSize(n))}}applyFontSize(n,e){n.update(()=>{let t=$getSelection();$isRangeSelection(t)&&$patchStyleText(t,{"font-size":e});});}hasCustomFontSize(n){let e=false;return n.getEditorState().read(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;let o=$getSelectionStyleValueForProperty(t,"font-size",""),r=this.normalizeValue(o);e=r.length>0&&r!=="inherit";}),e}getCurrentFontSizeValue(n){let e=null;return n.getEditorState().read(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;let o=$getSelectionStyleValueForProperty(t,"font-size",""),r=this.normalizeValue(o);if(!r||r==="inherit"){e="default";return}e=this.config.options.find(a=>this.normalizeValue(a.value)===r?true:this.normalizeValue(a.fontSize)===r)?.value??null;}),e}findOption(n){let e=this.normalizeValue(n);return this.config.options.find(t=>this.normalizeValue(t.value)===e)}normalizeValue(n){return n.trim().toLowerCase().replace(/\s+/g,"")}},bs=new kt;var Uo=[{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"}],Dn={value:"default",label:"Default",lineHeight:"1.5"},xs=1;function Hn(s){return s.trim().toLowerCase()}function Es(s){return Hn(s)==="default"?true:Mt(s)!==null}function Mt(s){let n=s.trim();if(!/^\d*\.?\d+$/.test(n))return null;let e=Number(n);return !Number.isFinite(e)||e<xs?null:e.toString()}function Ss(s,n){let e=new Set,t=[];for(let r of s){let i=r.value.trim(),a=r.label.trim(),l=Hn(i);if(!i||!a||!Es(i)||e.has(l))continue;if(l==="default"){e.add(l),t.push({value:i,label:a,lineHeight:n});continue}let d=Mt(String(r.lineHeight));d&&(e.add(l),t.push({value:i,label:a,lineHeight:d}));}return t.length===0?Uo:t.some(r=>Hn(r.value)==="default")?t:[{...Dn,lineHeight:n},...t]}function vs(s){return Mt(s)??Dn.lineHeight}var Pt=class extends L{constructor(){super("lineHeight",["toolbar"]),this.config={options:Uo,defaultLineHeight:Dn.lineHeight,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}configure(n){let e={...n},t=vs(String(n.defaultLineHeight??this.config.defaultLineHeight));return e.defaultLineHeight=t,n.options&&(e.options=Ss(n.options,t)),super.configure(e)}getCommands(n){return {setLineHeight:e=>{let t=this.findOption(e);t&&this.applyLineHeight(n,t.lineHeight);},clearLineHeight:()=>{this.applyLineHeight(n,"");},getCurrentLineHeight:()=>Promise.resolve(this.getCurrentLineHeightValue(n)),getLineHeightOptions:()=>this.config.options}}getStateQueries(n){return {hasCustomLineHeight:()=>Promise.resolve(this.hasCustomLineHeight(n))}}applyLineHeight(n,e){n.update(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;let o=this.getSelectedTopLevelBlocks(t);for(let r of o){let i=this.withStyleProperty(r.getStyle(),"line-height",e);r.setStyle(i);for(let a of r.getAllTextNodes())$isTextNode(a)&&a.setStyle(this.withStyleProperty(a.getStyle(),"line-height",e));}});}getSelectedTopLevelBlocks(n){let e=new Map;for(let t of n.getNodes()){let o=t.getTopLevelElement();!o||!$isElementNode(o)||o.getType()!=="root"&&e.set(o.getKey(),o);}return [...e.values()]}withStyleProperty(n,e,t){let o=new RegExp(`^${e}\\s*:`,"i"),r=n.split(";").map(a=>a.trim()).filter(a=>a.length>0).filter(a=>!o.test(a)),i=t.trim();return i.length>0&&r.push(`${e}: ${i}`),r.join("; ")}hasCustomLineHeight(n){let e=false;return n.getEditorState().read(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;let o=this.getSelectedBlocksLineHeight(t);if(o==="mixed"){e=true;return}let r=o??$getSelectionStyleValueForProperty(t,"line-height",""),i=this.normalizeValue(r);e=i.length>0&&i!=="normal";}),e}getCurrentLineHeightValue(n){let e=null;return n.getEditorState().read(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;let o=this.getSelectedBlocksLineHeight(t);if(o==="mixed"){e=null;return}let r=o??$getSelectionStyleValueForProperty(t,"line-height",""),i=this.normalizeValue(r);if(!i||i==="normal"){e="default";return}if(i===this.normalizeValue(this.config.defaultLineHeight)){e="default";return}e=this.config.options.find(l=>this.normalizeValue(l.value)===i?true:this.normalizeValue(l.lineHeight)===i)?.value??null;}),e}getSelectedBlocksLineHeight(n){let e=this.getSelectedTopLevelBlocks(n);if(e.length===0)return null;let t=null,o="";for(let r of e){let i=this.readStyleProperty(r.getStyle(),"line-height"),a=this.normalizeValue(i);if(t===null){t=a,o=i;continue}if(t!==a)return "mixed"}return o}findOption(n){let e=this.normalizeValue(n);return this.config.options.find(t=>this.normalizeValue(t.value)===e)}normalizeValue(n){let e=n.trim().toLowerCase().replace(/\s+/g,"");return Mt(e)??e}readStyleProperty(n,e){let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return n.match(new RegExp(`(?:^|;)\\s*${t}\\s*:\\s*([^;]+)`,"i"))?.[1]?.trim()??""}},Ns=new Pt;var Ls=[{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"}],Ot=class extends L{constructor(){super("textColor",["toolbar"]),this.config={options:Ls,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}getCommands(n){return {setTextColor:e=>{let t=this.findOption(e);if(t){this.applyColor(n,t.color);return}this.isValidCssColor(e)&&this.applyColor(n,e);},clearTextColor:()=>{this.applyColor(n,"");},getCurrentTextColor:()=>Promise.resolve(this.getCurrentTextColorValue(n)),getTextColorOptions:()=>this.config.options}}getStateQueries(n){return {hasCustomTextColor:()=>Promise.resolve(this.hasCustomTextColor(n))}}applyColor(n,e){n.update(()=>{let t=$getSelection();$isRangeSelection(t)&&$patchStyleText(t,{color:e});});}hasCustomTextColor(n){let e=false;return n.getEditorState().read(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;let o=$getSelectionStyleValueForProperty(t,"color","");e=this.normalizeValue(o).length>0;}),e}getCurrentTextColorValue(n){let e=null;return n.getEditorState().read(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;let o=$getSelectionStyleValueForProperty(t,"color","");if(!o){e="default";return}let r=this.normalizeValue(o);e=this.config.options.find(a=>this.normalizeValue(a.value)===r?true:this.normalizeValue(a.color)===r)?.value??o;}),e}findOption(n){let e=this.normalizeValue(n);return this.config.options.find(t=>this.normalizeValue(t.value)===e)}normalizeValue(n){return n.trim().toLowerCase().replace(/\s+/g,"")}isValidCssColor(n){let e=n.trim();return e?typeof CSS<"u"&&typeof CSS.supports=="function"?CSS.supports("color",e):/^#([\da-f]{3}|[\da-f]{6})$/i.test(e):false}},ws=new Ot;var ks=[{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"}],It=class extends L{constructor(){super("textHighlight",["toolbar"]),this.config={options:ks,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}getCommands(n){return {setTextHighlight:e=>{let t=this.findOption(e);if(t){this.applyHighlight(n,t.backgroundColor);return}this.isValidCssColor(e)&&this.applyHighlight(n,e);},clearTextHighlight:()=>{this.applyHighlight(n,"");},getCurrentTextHighlight:()=>Promise.resolve(this.getCurrentTextHighlightValue(n)),getTextHighlightOptions:()=>this.config.options}}getStateQueries(n){return {hasTextHighlight:()=>Promise.resolve(this.hasTextHighlight(n))}}applyHighlight(n,e){n.update(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;let o=this.normalizeValue(e).length>0;$patchStyleText(t,{"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(n){let e=false;return n.getEditorState().read(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;let o=$getSelectionStyleValueForProperty(t,"background-color",""),r=this.normalizeValue(o);e=r.length>0&&r!=="transparent";}),e}getCurrentTextHighlightValue(n){let e=null;return n.getEditorState().read(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;let o=$getSelectionStyleValueForProperty(t,"background-color",""),r=this.normalizeValue(o);if(!r||r==="transparent"){e="default";return}e=this.config.options.find(a=>this.normalizeValue(a.value)===r?true:this.normalizeValue(a.backgroundColor)===r)?.value??o;}),e}findOption(n){let e=this.normalizeValue(n);return this.config.options.find(t=>this.normalizeValue(t.value)===e)}normalizeValue(n){return n.trim().toLowerCase().replace(/\s+/g,"")}isValidCssColor(n){let e=n.trim();return e?typeof CSS<"u"&&typeof CSS.supports=="function"?CSS.supports("color",e):/^#([\da-f]{3}|[\da-f]{6})$/i.test(e):false}},Ps=new It;var _t=class extends X{constructor(){super("subscript");}},Ms=new _t;var At=class extends X{constructor(){super("superscript");}},Os=new At;function Ds({items:s,position:n,onClose:e,className:t,style:o,itemClassName:r,itemStyle:i,disabledItemClassName:a,disabledItemStyle:l}){return jsx("div",{className:t,style:{position:"fixed",left:n.x,top:n.y,zIndex:1e3,...o},onClick:d=>d.stopPropagation(),children:s.map((d,c)=>d.separator?jsx("div",{className:"h-px bg-border my-1"},c):jsxs("div",{className:d.disabled?a:r,style:d.disabled?l:i,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 Ht=class{constructor(n,e={}){x(this,"providers",new Map);x(this,"currentMenu",null);x(this,"listeners",new Set);x(this,"editor");x(this,"config");this.editor=n,this.config=e;}registerProvider(n){this.providers.set(n.id,n);}unregisterProvider(n){this.providers.delete(n);}handleContextMenu(n){let e=n.target;this.editor.getEditorState().read(()=>{let t=$getSelection(),o=Array.from(this.providers.values()).sort((r,i)=>(i.priority||0)-(r.priority||0));for(let r of o){let i={editor:this.editor,target:e,selection:t,event:n};if(r.canHandle(i)){this.config.preventDefault!==false&&n.preventDefault();let a=r.getItems(i);if(a.length>0){this.showMenu({items:a,position:{x:n.clientX,y:n.clientY},renderer:r.renderer||this.config.defaultRenderer});return}}}});}showMenu(n){this.currentMenu=n,this.notifyListeners();}hideMenu(){this.currentMenu=null,this.notifyListeners();}getCurrentMenu(){return this.currentMenu}subscribe(n){return this.listeners.add(n),n(this.currentMenu),()=>{this.listeners.delete(n);}}notifyListeners(){this.listeners.forEach(n=>n(this.currentMenu));}};function Fs({extension:s}){let{config:n}=xe(),[e,t]=useState(null),o=n?.theme?.contextMenu||{},r=s.config,i={container:r?.theme?.container||o.container||"luthor-context-menu",item:r?.theme?.item||o.item||"luthor-context-menu-item",itemDisabled:r?.theme?.itemDisabled||o.itemDisabled||"luthor-context-menu-item-disabled"},a={container:{...r?.styles?.container,...o.styles?.container},item:{...r?.styles?.item,...o.styles?.item},itemDisabled:{...r?.styles?.itemDisabled,...o.styles?.itemDisabled}};if(useEffect(()=>s.subscribe(t),[s]),!e)return null;let l=e.renderer||s.config.defaultRenderer;return createPortal(jsx(l,{items:e.items,position:e.position,onClose:()=>s.manager?.hideMenu(),className:i.container,style:a.container,itemClassName:i.item,itemStyle:a.item,disabledItemClassName:i.itemDisabled,disabledItemStyle:a.itemDisabled}),document.body)}var Dt=class extends L{constructor(e={}){super("contextMenu",["toolbar"]);x(this,"manager",null);x(this,"pendingListeners",new Set);this.config={defaultRenderer:Ds,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 Ht(e,this.config),this.pendingListeners.forEach(a=>{this.manager?.subscribe(a);}),this.pendingListeners.clear();let t=a=>{this.manager?.handleContextMenu(a);},o=a=>{a.target.closest(".luthor-context-menu")||this.manager?.hideMenu();},r=a=>{a.key==="Escape"&&this.manager?.hideMenu();},i=e.getRootElement();return i?(i.addEventListener("contextmenu",t),document.addEventListener("mousedown",o),document.addEventListener("keydown",r),()=>{i.removeEventListener("contextmenu",t),document.removeEventListener("mousedown",o),document.removeEventListener("keydown",r),this.manager=null;}):()=>{this.manager=null;}}getCommands(e){return {registerProvider:t=>{this.manager||(this.manager=new Ht(e,this.config)),this.manager.registerProvider(t);},unregisterProvider:t=>{this.manager?.unregisterProvider(t);},showContextMenu:t=>{this.manager?.showMenu(t);},hideContextMenu:()=>{this.manager?.hideMenu();}}}getStateQueries(e){return {isContextMenuOpen:()=>Promise.resolve(this.manager?.getCurrentMenu()!==null)}}getPlugins(){return [jsx(Fs,{extension:this},"context-menu")]}subscribe(e){return this.manager?this.manager.subscribe(e):(this.pendingListeners.add(e),()=>{this.pendingListeners.delete(e);})}},jn=new Dt;function jt(){let s=$getSelection();if($isTableSelection(s)){let n=s.getNodes().find(e=>$isTableCellNode(e));if($isTableCellNode(n))return n}if($isRangeSelection(s)){let n=s.anchor.getNode(),e=$findCellNode(n);if($isTableCellNode(e))return e}return null}function Zs({headersEnabled:s,setHeadersEnabled:n,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:s,onChange:t=>n(t.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 ea({extension:s}){let{editor:n}=xe(),[e,t]=useState(null),[o,r]=useState(false),[i,a]=useState(false),[l,d]=useState(null),c=v=>{n&&n.update(()=>{let y=jt();y&&(y.selectStart(),v(y));});},u=v=>{c(y=>{$getTableNodeFromLexicalNodeOrThrow(y).getChildren().filter(m=>$isTableRowNode(m)).forEach((m,g)=>{m.getChildren().filter(w=>$isTableCellNode(w)).forEach(w=>{let f=v&&g===0?TableCellHeaderStates.ROW:TableCellHeaderStates.NO_STATUS;w.setHeaderStyles(f,TableCellHeaderStates.ROW);});});});};if(useEffect(()=>{if(!n)return;let v=n.getRootElement(),y=v?.closest(".luthor-editor-wrapper")||v?.parentElement||null;t(y);let E=()=>{n.getEditorState().read(()=>{let g=$getSelection();if($isRangeSelection(g)&&!g.isCollapsed()){r(false),d(null);return}let S=jt();if(!S){r(false),d(null);return}let f=n.getElementByKey(S.getKey())?.closest("table");if(!f||!y){r(false),d(null);return}let z=$getTableNodeFromLexicalNodeOrThrow(S).getChildren().filter(D=>$isTableRowNode(D))[0]?.getChildren().filter(D=>$isTableCellNode(D))||[],W=z.length>0&&z.every(D=>D.hasHeaderState(TableCellHeaderStates.ROW));a(W);let H=y.getBoundingClientRect(),Q=f.getBoundingClientRect();d({x:Q.left-H.left+Q.width/2,y:Q.top-H.top-12}),r(true);});};E();let h=n.registerUpdateListener(()=>{E();}),m=()=>{E();};return window.addEventListener("scroll",m,true),window.addEventListener("resize",m),()=>{h(),window.removeEventListener("scroll",m,true),window.removeEventListener("resize",m);}},[n]),!e||!o||!l||typeof document>"u")return null;let p={insertRowAbove:()=>c(()=>$insertTableRowAtSelection(false)),insertRowBelow:()=>c(()=>$insertTableRowAtSelection(true)),insertColumnLeft:()=>c(()=>$insertTableColumnAtSelection(false)),insertColumnRight:()=>c(()=>$insertTableColumnAtSelection(true)),deleteSelectedColumn:()=>c(()=>$deleteTableColumnAtSelection()),deleteSelectedRow:()=>c(()=>$deleteTableRowAtSelection()),deleteTable:()=>c(v=>{$getTableNodeFromLexicalNodeOrThrow(v).remove();})},b=s.config.tableBubbleRenderer?s.config.tableBubbleRenderer({headersEnabled:i,setHeadersEnabled:v=>{a(v),u(v);},actions:p}):jsx(Zs,{headersEnabled:i,setHeadersEnabled:v=>{a(v),u(v);},actions:p});return createPortal(jsx("div",{className:"luthor-table-bubble-menu",style:{position:"absolute",left:l.x,top:l.y,transform:"translate(-50%, -100%)",zIndex:30},onMouseDown:v=>v.preventDefault(),children:b}),e)}var Kt=class extends L{constructor(e){super("table",["toolbar"]);x(this,"defaultContextMenuItems",e=>[{label:"Insert Row Above",action:()=>e.insertRowAbove()},{label:"Insert Row Below",action:()=>e.insertRowBelow()},{label:"Insert Column Left",action:()=>e.insertColumnLeft()},{label:"Insert Column Right",action:()=>e.insertColumnRight()},{separator:true,label:"",action:()=>{}},{label:"Toggle Row Header",action:()=>e.toggleRowHeader()},{label:"Toggle Column Header",action:()=>e.toggleColumnHeader()},{label:"Merge Cells",action:()=>e.mergeSelectedCells()},{label:"Split Cell",action:()=>e.unmergeSelectedCell()},{separator:true,label:"",action:()=>{}},{label:"Delete Row",action:()=>e.deleteRow()},{label:"Delete Column",action:()=>e.deleteColumn()},{label:"Delete Table",action:()=>e.deleteTable()}]);this.config={rows:3,columns:3,includeHeaders:false,enableContextMenu:true,contextMenuItems:this.defaultContextMenuItems,...e};}getContextMenuItems(e){return typeof this.config.contextMenuItems=="function"?this.config.contextMenuItems(e):Array.isArray(this.config.contextMenuItems)?this.config.contextMenuItems:this.defaultContextMenuItems(e)}configure(e){return this.config={...this.config,...e},e.contextMenuItems&&(this.config.contextMenuItems=e.contextMenuItems),this}register(e){let t;if(this.config.enableContextMenu){let o=this.config.contextMenuExtension||jn;if(o){let r={id:"table",priority:10,canHandle:({target:a,selection:l})=>{let d=a.closest("td, th, [data-lexical-table-cell]");return d?$isTableSelection(l)?true:d.tagName==="TD"||d.tagName==="TH":false},getItems:({editor:a})=>{let l=this.getCommands(a);return this.getContextMenuItems(l)},renderer:this.config.contextMenuRenderer||o.config?.defaultRenderer};o.getCommands(e).registerProvider(r),t=()=>{let a=o.getCommands(e);a&&a.unregisterProvider("table");};}}return ()=>{t?.();}}getNodes(){return [TableNode,TableRowNode,TableCellNode]}getCommands(e){return {insertTable:t=>{let{rows:o=3,columns:r=3,includeHeaders:i=false}=t;e.update(()=>{let a=$getSelection();if($isRangeSelection(a)){let l=$createTableNodeWithDimensions(o,r,i);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 t=jt();if(!t)return;let o=$getTableNodeFromLexicalNodeOrThrow(t),r=$getTableRowIndexFromTableCellNode(t),i=o.getChildren()[r];if(!$isTableRowNode(i))return;let a=i.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 t=jt();if(!t)return;let o=$getTableNodeFromLexicalNodeOrThrow(t),r=$getTableColumnIndexFromTableCellNode(t),a=o.getChildren().filter(c=>$isTableRowNode(c)).map(c=>c.getChildren()[r]).filter(c=>$isTableCellNode(c)),d=!a.every(c=>c.hasHeaderState(TableCellHeaderStates.COLUMN))?TableCellHeaderStates.COLUMN:TableCellHeaderStates.NO_STATUS;a.forEach(c=>{c.setHeaderStyles(d,TableCellHeaderStates.COLUMN);});});},mergeSelectedCells:()=>{e.update(()=>{let t=$getSelection();if(!$isTableSelection(t))return;let o=t.getNodes().filter(r=>$isTableCellNode(r));o.length<2||$mergeCells(o);});},unmergeSelectedCell:()=>{e.update(()=>{$unmergeCell();});},deleteRow:()=>{e.update(()=>{$deleteTableRowAtSelection();});},deleteColumn:()=>{e.update(()=>{$deleteTableColumnAtSelection();});},deleteTable:()=>{e.update(()=>{let t=$getSelection();$isTableSelection(t)&&t.getNodes().forEach(o=>{$isTableNode(o)&&o.remove();});});},showTableContextMenu:t=>{}}}getStateQueries(e){return {isTableSelected:async()=>e.getEditorState().read(()=>{let t=$getSelection();return $isTableSelection(t)}),isInTableCell:async()=>e.getEditorState().read(()=>{let t=$getSelection();if(!t||typeof t!="object"||!("anchor"in t)||!("focus"in t))return false;try{let o=t.anchor.getNode(),r=t.focus.getNode();return $isTableCellNode(o)||$isTableCellNode(r)}catch{return false}})}}getPlugins(){return [jsx(TablePlugin,{},"table-plugin"),jsx(ea,{extension:this},"table-quick-actions-plugin")]}},ta=new Kt;var Qt=class extends L{constructor(){super("list",["toolbar"]);}register(n){return ()=>{}}getNodes(){return [ListNode,ListItemNode]}getPlugins(){return [jsx(ListPlugin,{},"list-plugin"),jsx(CheckListPlugin,{},"check-list-plugin")]}getCommands(n){return {toggleUnorderedList:()=>{n.update(()=>{let e=$getSelection();if($isRangeSelection(e)){let o=e.anchor.getNode().getParent(),r=null,i=null;for(;o;){if($isListItemNode(o)&&(i=o),$isListNode(o)){r=o;break}o=o.getParent();}r?r.getListType()==="bullet"?i&&i.getIndent()>0?n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode):n.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0):n.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0);}});},toggleOrderedList:()=>{n.update(()=>{let e=$getSelection();if($isRangeSelection(e)){let o=e.anchor.getNode().getParent(),r=null,i=null;for(;o;){if($isListItemNode(o)&&(i=o),$isListNode(o)){r=o;break}o=o.getParent();}r?r.getListType()==="number"?i&&i.getIndent()>0?n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode):n.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0):n.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);}});},toggleCheckList:()=>{n.update(()=>{let e=$getSelection();if($isRangeSelection(e)){let o=e.anchor.getNode().getParent(),r=null,i=null;for(;o;){if($isListItemNode(o)&&(i=o),$isListNode(o)){r=o;break}o=o.getParent();}r?r.getListType()==="check"?i&&i.getIndent()>0?n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode):n.dispatchCommand(INSERT_CHECK_LIST_COMMAND,void 0):n.dispatchCommand(INSERT_CHECK_LIST_COMMAND,void 0);}});},indentList:()=>{n.update(()=>{let e=$getSelection();if(!$isRangeSelection(e))return;let t=e.anchor.getNode();for(;t;){if($isListNode(t)){if(t.getListType()==="check")return;break}t=t.getParent();}n.dispatchCommand(INDENT_CONTENT_COMMAND,void 0);});},outdentList:()=>{n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0);},insertNestedUnorderedList:()=>{n.update(()=>{n.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),n.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0);});},insertNestedOrderedList:()=>{n.update(()=>{n.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),n.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);});}}}getStateQueries(n){return {unorderedList:()=>new Promise(e=>{n.getEditorState().read(()=>{let t=$getSelection();if(!$isRangeSelection(t)){e(false);return}let o=t.anchor.getNode();for(;o;){if($isListNode(o)){e(o.getListType()==="bullet");return}o=o.getParent();}e(false);});}),orderedList:()=>new Promise(e=>{n.getEditorState().read(()=>{let t=$getSelection();if(!$isRangeSelection(t)){e(false);return}let o=t.anchor.getNode();for(;o;){if($isListNode(o)){e(o.getListType()==="number");return}o=o.getParent();}e(false);});}),checkList:()=>new Promise(e=>{n.getEditorState().read(()=>{let t=$getSelection();if(!$isRangeSelection(t)){e(false);return}let o=t.anchor.getNode();for(;o;){if($isListNode(o)){e(o.getListType()==="check");return}o=o.getParent();}e(false);});})}}},aa=new Qt;var ca="plain";function ot(){return ca}function Xo(){return PrismTokenizer}async function Zo(s){return s?.provider?s.provider:s?.loadProvider?s.loadProvider():null}async function er(s){return s?s.tokenizer?s.tokenizer:s.getTokenizer?s.getTokenizer():null:null}var Wt=class extends L{constructor(){super("code",["toolbar"]);x(this,"codeHighlightProviderPromise",null);this.config={syntaxHighlighting:"auto"};}register(e){let t=()=>{},o=false,r=a=>{t(),t=registerCodeHighlighting(e,a);};this.config.syntaxHighlighting!=="disabled"&&(r(this.config.tokenizer??Xo()),this.resolveConfiguredTokenizer().then(a=>{o||!a||r(a);}));let i=e.registerCommand(KEY_TAB_COMMAND,a=>{let l=false;return e.update(()=>{let d=$getSelection();if(!$isRangeSelection(d))return;let c=d.anchor.getNode();this.getBlockNode(c)&&(l=true,d.insertText(" "));}),l?(a?.preventDefault(),true):false},COMMAND_PRIORITY_LOW);return ()=>{o=true,t(),i();}}getNodes(){return [CodeNode,CodeHighlightNode]}getCommands(e){return {toggleCodeBlock:()=>this.toggleCodeBlock(e)}}toggleCodeBlock(e){e.update(()=>{let t=$getSelection();if($isRangeSelection(t)){if(this.getCurrentFormatSync()==="code"){$setBlocksType(t,()=>$createParagraphNode());return}$setBlocksType(t,()=>{let r=$createCodeNode();return r.setTheme?.(ot()),r});}});}async resolveConfiguredTokenizer(){if(this.config.tokenizer)return this.config.tokenizer;let e=await this.loadCodeHighlightProvider();return er(e)}async loadCodeHighlightProvider(){return this.config.provider?this.config.provider:this.codeHighlightProviderPromise?this.codeHighlightProviderPromise:(this.codeHighlightProviderPromise=Zo(this.config),this.codeHighlightProviderPromise)}getStateQueries(e){return {isInCodeBlock:()=>Promise.resolve(this.isFormat("code",e))}}isFormat(e,t){let o=true;return t.getEditorState().read(()=>{let r=$getSelection();if(!$isRangeSelection(r)){o=false;return}let i=r.getNodes();for(let a of i){let l=this.getBlockNode(a);if(!l){o=false;break}if(this.getNodeFormat(l)!==e){o=false;break}}}),o}getBlockNode(e){let t=e;for(;t;){if($isCodeNode(t))return t;t=t.getParent();}return null}getNodeFormat(e){return $isCodeNode(e)?"code":null}getCurrentFormatSync(){let e=$getSelection();if(!$isRangeSelection(e))return null;let t=e.anchor.getNode(),o=this.getBlockNode(t);return o?this.getNodeFormat(o):null}},ba=new Wt;var wa='<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>',Ra='<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>',ka=["plaintext","typescript","javascript","markdown","html","css","python","sql","java","c","cpp","rust","powershell","xml"],Jt=class extends L{constructor(){super("codeIntelligence");x(this,"languageOptions",[]);this.config={isCopyAllowed:true};}register(e){this.languageOptions=this.getLanguageOptions();let t=registerMarkdownShortcuts(e,TRANSFORMERS),o=e.registerUpdateListener(({dirtyElements:r,dirtyLeaves:i})=>{(r.size>0||i.size>0)&&this.ensureCodeBlockThemes(e);});return queueMicrotask(()=>{this.ensureCodeBlockThemes(e);}),()=>{t(),o(),this.languageOptions=[];}}getPlugins(){return [createElement(Ma,{key:"code-intelligence-controls",extension:this})]}getCommands(e){return {setCodeLanguage:t=>{let o=Ye(t),r=this.getThemeForLanguage(o);e.update(()=>{this.getSelectionCodeNodes().forEach(i=>{i.setLanguage(o??null),i.setTheme(r);});});},autoDetectCodeLanguage:async()=>null,getCurrentCodeLanguage:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=this.getSelectionCodeNodes();t(o[0]?.getLanguage()??null);});}),getCodeLanguageOptions:()=>this.getLanguageOptions(),copySelectedCodeBlock:async()=>{if(!this.isCopyAllowed())return false;let t=await this.getPrimaryCodeBlockText(e);return !t||!t.text.trim()?false:cr(t.text)}}}isCopyAllowed(){return this.config.isCopyAllowed!==false}getLanguageOptionsSnapshot(){return this.languageOptions.length?[...this.languageOptions]:this.getLanguageOptions()}getCodeBlocksSnapshot(e){return e.getEditorState().read(()=>$nodesOfType(CodeNode).map(t=>{let o=Ye(t.getLanguage());return {key:t.getKey(),language:o??"plaintext",text:t.getTextContent()}}))}setCodeBlockLanguage(e,t,o){e.update(()=>{let r=$getNodeByKey(t);if(!r||!$isCodeNode(r))return;let i=Ye(o);r.setLanguage(i??null),r.setTheme(this.getThemeForLanguage(i));});}getCodeBlockText(e,t){return e.getEditorState().read(()=>{let o=$getNodeByKey(t);return !o||!$isCodeNode(o)?"":o.getTextContent()})}getThemeForLanguage(e){let t=Ye(e);return !t||t==="plain"?ot():"hljs"}ensureCodeBlockThemes(e){let t=e.getEditorState().read(()=>$nodesOfType(CodeNode).map(o=>{let r=o.getTheme?.()??"",i=this.getThemeForLanguage(o.getLanguage());return {key:o.getKey(),nextTheme:i??ot(),currentTheme:r}}).filter(o=>o.currentTheme!==o.nextTheme));t.length!==0&&e.update(()=>{t.forEach(o=>{let r=$getNodeByKey(o.key);!r||!$isCodeNode(r)||r.setTheme(o.nextTheme);});});}getSelectionCodeNodes(){let e=$getSelection();if(!$isRangeSelection(e))return [];let t=e.getNodes(),o=new Map;return t.forEach(r=>{let i=this.getNearestCodeNode(r);i&&o.set(i.getKey(),i);}),Array.from(o.values())}getNearestCodeNode(e){let t=e;for(;t;){if($isCodeNode(t))return t;t=t.getParent();}return null}getLanguageOptions(){let e=ka.map(r=>Ye(r)).filter(r=>!!r),t=Aa(this.config.languageOptions);if(!t)return Gn(e);let o=Ha(t.values);return t.mode==="replace"?Gn(o):Gn([...e,...o])}async getPrimaryCodeBlockText(e){return new Promise(t=>{e.getEditorState().read(()=>{let r=this.getSelectionCodeNodes()[0];if(!r){t(null);return}let i=r.getTextContent().trim();if(!i){t(null);return}t({key:r.getKey(),text:i});});})}},Pa=34;function Ma({extension:s}){let[n]=useLexicalComposerContext(),[e,t]=useState([]),[o,r]=useState({}),i=useRef(null),a=useRef(new Map),l=useMemo(()=>s.getLanguageOptionsSnapshot(),[s]),d=useCallback(()=>{let m=lr(n);if(!m)return [];let g=m.getBoundingClientRect(),S=s.getCodeBlocksSnapshot(n),w=[];return S.forEach(f=>{let N=n.getElementByKey(f.key);if(!N||!N.isConnected)return;N.classList.add("luthor-code-block--interactive");let F=N.getBoundingClientRect(),z=Math.max(120,Math.round(F.width)),W=Math.max(0,Math.round(F.top-g.top-Pa)),H=Math.max(0,Math.round(F.left-g.left));w.push({key:f.key,language:f.language,top:W,left:H,width:z});}),w},[n,s]),c=useCallback(()=>{let m=d();t(g=>Oa(g,m)?g:m);},[d]),u=useCallback(()=>{i.current===null&&(i.current=requestAnimationFrame(()=>{i.current=null,c();}));},[c]),p=useCallback(m=>{let g=a.current.get(m);g&&(clearTimeout(g),a.current.delete(m));},[]),b=useCallback((m,g)=>{p(m),r(w=>({...w,[m]:g}));let S=setTimeout(()=>{r(w=>{if(!(m in w))return w;let f={...w};return delete f[m],f}),a.current.delete(m);},1200);a.current.set(m,S);},[p]),v=useCallback((m,g)=>{s.setCodeBlockLanguage(n,m,g),u();},[n,s,u]),y=s.isCopyAllowed(),E=useCallback(async m=>{if(!y)return;let g=s.getCodeBlockText(n,m);if(!g.trim())return;if(await cr(g)){b(m,"copied");return}b(m,"error");},[y,n,s,b]);if(useEffect(()=>{u();let m=0,g=null,S=()=>{u(),m+=1,!(m>=20)&&(g=requestAnimationFrame(S));};g=requestAnimationFrame(S);let w=n.registerUpdateListener(()=>{u();}),f=()=>{u();},N=a.current;return window.addEventListener("resize",f,{passive:true}),()=>{w(),window.removeEventListener("resize",f),g!==null&&cancelAnimationFrame(g),i.current!==null&&(cancelAnimationFrame(i.current),i.current=null),N.forEach(F=>clearTimeout(F)),N.clear();}},[n,u]),useEffect(()=>{let m=new Set(e.map(g=>g.key));r(g=>{let S=false,w={};return Object.entries(g).forEach(([f,N])=>{if(m.has(f)){w[f]=N;return}S=true,p(f);}),S?w:g});},[p,e]),typeof document>"u"||e.length===0)return null;let h=lr(n);return h?createPortal(createElement("div",{className:"luthor-codeblock-controls-layer","aria-hidden":false},e.map(m=>{let g=o[m.key],S=["luthor-codeblock-copy",g==="copied"?"is-copied":"",g==="error"?"is-copy-error":""].filter(Boolean).join(" "),w=g==="copied"?"Copied":g==="error"?"Copy failed":"Copy to clipboard";return createElement("div",{key:m.key,className:"luthor-codeblock-controls","data-code-node-key":m.key,style:{position:"absolute",top:`${m.top}px`,left:`${m.left}px`,width:`${m.width}px`}},createElement("span",{className:"luthor-codeblock-controls-left"},createElement("select",{className:"luthor-codeblock-language",value:m.language,"aria-label":"Code language",onChange:f=>{let N=f.target;v(m.key,N.value);}},l.map(f=>createElement("option",{key:f,value:f},f)))),createElement("span",{className:"luthor-codeblock-controls-right"},y?createElement("button",{className:S,type:"button","aria-label":"Copy code",title:w,"data-tooltip":w,onMouseDown:f=>{f.preventDefault();},onClick:()=>{E(m.key);},dangerouslySetInnerHTML:{__html:g==="copied"?Ra:wa}}):null))})),h):null}function Oa(s,n){if(s.length!==n.length)return false;for(let e=0;e<s.length;e+=1){let t=s[e],o=n[e];if(!t||!o||t.key!==o.key||t.language!==o.language||t.top!==o.top||t.left!==o.left||t.width!==o.width)return false}return true}async function cr(s){if(typeof navigator<"u"&&navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(s),!0}catch{}if(typeof document>"u")return false;let n=document.createElement("textarea");n.value=s,n.setAttribute("readonly","true"),n.style.position="fixed",n.style.opacity="0",n.style.pointerEvents="none",n.style.top="0",n.style.left="0",document.body.appendChild(n),n.select(),n.setSelectionRange(0,n.value.length);try{return document.execCommand("copy")}catch{return false}finally{n.remove();}}function lr(s){let n=s.getRootElement();if(!n)return null;let e=n.closest(".luthor-richtext-container");if(e)return e;let t=n.closest(".luthor-editor-container");return t||n.parentElement}function Ye(s){if(!s)return null;let n=s.trim().toLowerCase();if(!n||n==="auto")return null;let e=normalizeCodeLang(n);return !e||e==="auto"||!Ia(e)?null:e}function Ia(s){let n=s.trim().toLowerCase();if(!n)return false;let e=getCodeLanguageOptions().map(([r])=>normalizeCodeLang(r.trim().toLowerCase())).filter(Boolean),t=getCodeLanguages().map(r=>normalizeCodeLang(r.trim().toLowerCase())).filter(Boolean);return new Set([...e,...t]).has(n)}var _a=new Jt;function Aa(s){if(!s)return null;if(Array.isArray(s))return {mode:"append",values:s};let n=s;return {mode:n.mode??"append",values:Array.isArray(n.values)?n.values:[]}}function Ha(s){let n=[],e=new Set;for(let t of s){let o=t.trim();if(!o)continue;let r=Ye(o);if(!r)throw new Error(`[CodeIntelligenceExtension] Invalid language option "${t}". Use a supported language ID or alias (excluding "auto").`);if(e.has(r))throw new Error(`[CodeIntelligenceExtension] Duplicate language option "${t}". It resolves to "${r}", which is already configured.`);e.add(r),n.push(r);}return n}function Gn(s){return Array.from(new Set(s)).sort((n,e)=>n.localeCompare(e))}var Gt=class extends X{constructor(){super("code");}},Da=new Gt;var Zt=class extends L{constructor(){super("blockFormat",["toolbar"]);}register(n){let e=n.registerCommand(INSERT_PARAGRAPH_COMMAND,()=>{let o=$getSelection();if($isRangeSelection(o)){let r=o.anchor.getNode(),i=this.getBlockNode(r);if(i&&($isHeadingNode(i)||$isQuoteNode(i)))return false}return false},COMMAND_PRIORITY_NORMAL),t=n.registerCommand(KEY_ENTER_COMMAND,o=>{let r=false;return n.update(()=>{let i=$getSelection();if(!$isRangeSelection(i))return;let a=i.anchor.getNode(),l=this.getBlockNode(a);l&&$isHeadingNode(l)&&!o?.shiftKey&&(this.toggleBlockFormat(n,"p"),r=true);}),r&&o?.preventDefault(),r},COMMAND_PRIORITY_EDITOR);return ()=>{e(),t();}}getNodes(){return [ParagraphNode,HeadingNode,QuoteNode]}getCommands(n){return {toggleBlockFormat:e=>this.toggleBlockFormat(n,e),toggleParagraph:()=>this.toggleBlockFormat(n,"p"),toggleHeading:e=>this.toggleBlockFormat(n,e),toggleQuote:()=>this.toggleBlockFormat(n,"quote"),setTextAlignment:e=>this.setTextAlignment(n,e),getCurrentBlockType:()=>this.getCurrentFormat(n)||"p"}}setTextAlignment(n,e){n.dispatchCommand(FORMAT_ELEMENT_COMMAND,e);}toggleBlockFormat(n,e){n.update(()=>{let t=$getSelection();if($isRangeSelection(t)){if(this.getCurrentFormatSync()===e){$setBlocksType(t,()=>$createParagraphNode());return}$setBlocksType(t,()=>e==="p"?$createParagraphNode():e==="quote"?$createQuoteNode():$createHeadingNode(e));}});}getStateQueries(n){return {isParagraph:()=>Promise.resolve(this.isFormat("p",n)),isH1:()=>Promise.resolve(this.isFormat("h1",n)),isH2:()=>Promise.resolve(this.isFormat("h2",n)),isH3:()=>Promise.resolve(this.isFormat("h3",n)),isH4:()=>Promise.resolve(this.isFormat("h4",n)),isH5:()=>Promise.resolve(this.isFormat("h5",n)),isH6:()=>Promise.resolve(this.isFormat("h6",n)),isQuote:()=>Promise.resolve(this.isFormat("quote",n)),isTextAlignedLeft:()=>Promise.resolve(this.isAlignment("left",n)),isTextAlignedCenter:()=>Promise.resolve(this.isAlignment("center",n)),isTextAlignedRight:()=>Promise.resolve(this.isAlignment("right",n)),isTextAlignedJustify:()=>Promise.resolve(this.isAlignment("justify",n))}}isAlignment(n,e){let t=true;return e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o)){t=false;return}let r=o.getNodes();for(let i of r){let a=this.getBlockNode(i);if(!a){t=false;break}if(this.normalizeAlignment(a.getFormatType())!==n){t=false;break}}}),t}normalizeAlignment(n){return n==="center"||n==="right"||n==="justify"?n:"left"}getBlockNode(n){let e=n;for(;e;){if($isParagraphNode(e)||$isHeadingNode(e)||$isQuoteNode(e))return e;e=e.getParent();}return null}isFormat(n,e){let t=true;return e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o)){t=false;return}let r=o.getNodes();for(let i of r){let a=this.getBlockNode(i);if(!a){t=false;break}if(this.getNodeFormat(a)!==n){t=false;break}}}),t}getNodeFormat(n){return $isParagraphNode(n)?"p":$isHeadingNode(n)?n.getTag():$isQuoteNode(n)?"quote":null}getCurrentFormat(n){let e=null;return n.getEditorState().read(()=>{let t=$getSelection();if($isRangeSelection(t)){let o=t.anchor.getNode(),r=this.getBlockNode(o);r&&(e=this.getNodeFormat(r));}}),e}getCurrentFormatSync(){let n=$getSelection();if(!$isRangeSelection(n))return null;let e=n.anchor.getNode(),t=this.getBlockNode(e);return t?this.getNodeFormat(t):null}},Wa=new Zt;var en=class extends L{constructor(){super("history",["toolbar"]);x(this,"canUndoState",false);x(this,"canRedoState",false);}register(e){let t=e.registerCommand(CAN_UNDO_COMMAND,r=>(this.canUndoState=r,false),COMMAND_PRIORITY_LOW),o=e.registerCommand(CAN_REDO_COMMAND,r=>(this.canRedoState=r,false),COMMAND_PRIORITY_LOW);return ()=>{t(),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}}},tl=new en;var rn=class extends L{constructor(e){super("draggableBlock",["floating"]);x(this,"isDraggingState",false);x(this,"stateChangeCallbacks",new Set);this.config={showInToolbar:false,position:"after",showMoveButtons:true,showUpButton:true,showDownButton:true,showAddButton:true,buttonStackPosition:"left",enableTextSelectionDrag:true,offsetLeft:-40,offsetRight:10,...e};}register(e){return ()=>{}}getPlugins(){return [jsx(sl,{config:this.config,extension:this},"draggable-block")]}getCommands(e){return {moveBlock:(t,o,r)=>{e.update(()=>{let i=$getNodeByKey(t),a=$getNodeByKey(o);i&&a&&(i.remove(),r?a.insertAfter(i):a.insertBefore(i));});},moveCurrentBlockUp:()=>{e.update(()=>{let t=$getSelection();if($isRangeSelection(t)){let o=t.anchor.getNode(),r=$isElementNode(o)?o:o.getParent();if(r&&$isElementNode(r)){let i=r.getPreviousSibling();i&&(r.remove(),i.insertBefore(r));}}});},moveCurrentBlockDown:()=>{e.update(()=>{let t=$getSelection();if($isRangeSelection(t)){let o=t.anchor.getNode(),r=$isElementNode(o)?o:o.getParent();if(r&&$isElementNode(r)){let i=r.getNextSibling();i&&(r.remove(),i.insertAfter(r));}}});}}}getStateQueries(e){return {isDragging:async()=>this.isDraggingState}}setIsDragging(e){this.isDraggingState!==e&&(this.isDraggingState=e,this.stateChangeCallbacks.forEach(t=>t()));}onStateChange(e){return this.stateChangeCallbacks.add(e),()=>this.stateChangeCallbacks.delete(e)}},il=new rn;function sl({config:s,extension:n}){let[e]=useLexicalComposerContext(),{config:t,extensions:o}=xe(),i=o.find(C=>C.name==="draggableBlock")?.config,a=useMemo(()=>t?.theme?.draggable||{},[t?.theme?.draggable]),[l,d]=useState(null),[c,u]=useState(false),[p,b]=useState(null),[v,y]=useState(false),E=useRef(null),h=useRef(null),m=useRef(null),g=useRef(null),S=useRef(null),w=useRef(null),f=useRef(null),N=useRef(null),[F,z]=useState(null);useEffect(()=>{n.setIsDragging(c);},[c,n]);let W=typeof document<"u"&&typeof window<"u",H=e.getRootElement(),Q=W?H?.closest?.(".luthor-editor")||H?.parentElement||document.body:null,D=i?.anchorElem||s.anchorElem||Q,K=useMemo(()=>({handle:{cursor:"grab",userSelect:"none"},handleActive:{cursor:"grabbing"},blockDragging:{opacity:.5},dropIndicator:{backgroundColor:"var(--luthor-accent, #3b82f6)",borderRadius:"2px"},addButton:{cursor:"pointer"},buttonStack:{}}),[]),A=useMemo(()=>({handle:{...K.handle,...a.styles?.handle,...i?.styles?.handle},handleActive:{...K.handleActive,...a.styles?.handleActive,...i?.styles?.handleActive},blockDragging:{...K.blockDragging,...a.styles?.blockDragging,...i?.styles?.blockDragging},dropIndicator:{...K.dropIndicator,...a.styles?.dropIndicator,...i?.styles?.dropIndicator},addButton:{...K.addButton,...a.styles?.addButton,...i?.styles?.addButton},buttonStack:{...K.buttonStack,...a.styles?.buttonStack,...i?.styles?.buttonStack}}),[K,i?.styles,a.styles]),M=useMemo(()=>({handle:i?.theme?.handle||a.handle||"luthor-draggable-handle",handleActive:i?.theme?.handleActive||a.handleActive||"luthor-draggable-handle-active",blockDragging:i?.theme?.blockDragging||a.blockDragging||"luthor-draggable-block-dragging",dropIndicator:i?.theme?.dropIndicator||a.dropIndicator||"luthor-draggable-drop-indicator",addButton:i?.theme?.addButton||a.addButton||"luthor-draggable-add-button",buttonStack:i?.theme?.buttonStack||a.buttonStack||"luthor-draggable-button-stack"}),[i?.theme,a]),V=useCallback(C=>{if(!C||!M.blockDragging)return;(M.blockDragging.includes(" ")?M.blockDragging.split(" ").filter(Boolean):[M.blockDragging]).forEach(k=>C.classList.remove(k)),C.style.opacity="";},[M]),U=useCallback(C=>{if(!C||!M.blockDragging)return;(M.blockDragging.includes(" ")?M.blockDragging.split(" ").filter(Boolean):[M.blockDragging]).forEach(k=>C.classList.add(k)),Object.assign(C.style,A.blockDragging);},[M,A.blockDragging]),re=useCallback(()=>{let C=e.getRootElement();if(C)try{C.focus({preventScroll:!0});}catch{C.focus();}},[e]),Y=useCallback(()=>{E.current&&V(E.current),u(false),b(null),re(),setTimeout(()=>{E.current=null,h.current=null;},100);},[V,re]);useEffect(()=>()=>{E.current&&V(E.current),g.current&&clearTimeout(g.current),S.current!==null&&window.cancelAnimationFrame(S.current),f.current!==null&&window.cancelAnimationFrame(f.current);},[V]),useEffect(()=>{m.current=l;},[l]);let ee=useCallback(C=>{w.current=C,S.current===null&&(S.current=window.requestAnimationFrame(()=>{S.current=null;let R=w.current;d(k=>k===R?k:R);}));},[]),Ee=useCallback(C=>{N.current=C,f.current===null&&(f.current=window.requestAnimationFrame(()=>{f.current=null;let R=N.current;R!=null&&z(k=>k!=null&&Math.abs(k-R)<.5?k:R);}));},[]),Le=useCallback(C=>{let R=null;e.update(()=>{let k=$createParagraphNode(),O=$getNearestNodeFromDOMNode(C);if(O)try{O.getTopLevelElementOrThrow().insertAfter(k);}catch{$getRoot().append(k);}else $getRoot().append(k);k.selectStart(),R=k.getKey();}),R&&setTimeout(()=>{let k=e.getElementByKey(R);if(k&&k instanceof HTMLElement&&typeof k.getBoundingClientRect=="function"){ee(k);let O=k.getBoundingClientRect();Ee(O.top+window.scrollY+O.height/2);}},0),re();},[e,re,ee,Ee]);useEffect(()=>{if(l||E.current)y(true);else {let C=setTimeout(()=>y(false),300);return ()=>clearTimeout(C)}},[l]),useEffect(()=>{let C=k=>{if(c)return;let O=e.getRootElement();if(!O)return;let P=k.target;Ee(k.clientY+window.scrollY);let T=P&&P.closest&&(P.closest(".drag-handle-area")||P.closest('[draggable="true"]')||P.closest(".luthor-drag-button")||P.closest(".luthor-draggable-button-stack")),G=window.getSelection(),B=G&&G.rangeCount>0&&!G.isCollapsed,_=null,I=P;for(;I&&I!==O&&I!==document.body;){if(I.parentElement===O){_=I;break}I=I.parentElement;}g.current&&(clearTimeout(g.current),g.current=null),(_||T)&&!B&&!c?_&&ee(_):g.current=setTimeout(()=>{ee(null),g.current=null;},500);},R=()=>{c||(g.current&&(clearTimeout(g.current),g.current=null),g.current=setTimeout(()=>{ee(null),g.current=null;},300));};return document.addEventListener("mousemove",C),document.addEventListener("mouseleave",R),()=>{document.removeEventListener("mousemove",C),document.removeEventListener("mouseleave",R),g.current&&(clearTimeout(g.current),g.current=null),S.current!==null&&(window.cancelAnimationFrame(S.current),S.current=null),f.current!==null&&(window.cancelAnimationFrame(f.current),f.current=null);}},[e,c,ee,Ee]);let yt=useCallback((C,R)=>{C.stopPropagation(),u(true),b(null),E.current=R,U(R);let k=e.read(()=>{let P=$getNearestNodeFromDOMNode(R);return P?P.getKey():null});k&&(h.current=k,C.dataTransfer?.setData("application/x-lexical-drag",JSON.stringify({key:k}))),C.dataTransfer.effectAllowed="move";let O=R.cloneNode(true);O.style.opacity="0.6",O.style.position="absolute",O.style.top="-9999px",O.style.left="-9999px",document.body.appendChild(O),C.dataTransfer.setDragImage(O,0,0),setTimeout(()=>document.body.removeChild(O),0);},[e,U]),Ct=useCallback((C,R)=>{C.preventDefault(),u(true),E.current=R,U(R);let k=e.read(()=>{let O=$getNearestNodeFromDOMNode(R);return O?O.getKey():null});k&&(h.current=k);},[e,U]),$e=useCallback(C=>{if(!c||!E.current)return;C.preventDefault();let R=C.touches[0];if(!R)return;let k=e.getRootElement();if(!k)return;let O=null,P=document.elementFromPoint(R.clientX,R.clientY);if(P){let T=P;for(;T&&T!==k;){if(T.parentElement===k){O=T;break}T=T.parentElement;}}if(O&&O!==E.current){let T=O.getBoundingClientRect(),G=R.clientY<T.top+T.height/2;b({top:G?T.top+window.scrollY:T.bottom+window.scrollY,left:T.left+window.scrollX,width:T.width});}else b(null);},[e,c]),ue=useCallback(C=>{if(!c||!h.current)return;C.preventDefault();let R=C.changedTouches[0];if(!R)return;let k=e.getRootElement();if(!k)return;let O=null,P=document.elementFromPoint(R.clientX,R.clientY);if(P){let T=P;for(;T&&T!==k;){if(T.parentElement===k){O=T;break}T=T.parentElement;}}O&&O!==E.current&&(e.update(()=>{let T=$getNodeByKey(h.current),G=$getNearestNodeFromDOMNode(O);if(T&&G){let B=O.getBoundingClientRect(),_=R.clientY>=B.top+B.height/2;T.remove(),_?G.insertAfter(T):G.insertBefore(T);}}),setTimeout(()=>{if(h.current)try{let T=e.getElementByKey(h.current);T&&T instanceof HTMLElement&&typeof T.getBoundingClientRect=="function"&&d(T);}catch(T){console.warn("Error finding moved element:",T);}},50)),Y();},[e,c,Y]);useEffect(()=>{let C=e.getRootElement();if(!C)return;let R=P=>{let T=P.target;if(T.nodeType!==Node.ELEMENT_NODE&&(T=T.parentNode),!T||!(T instanceof HTMLElement)){P.preventDefault();return}if(T.closest('[draggable="true"]'))return;let B=window.getSelection();if(!B||B.isCollapsed||!(i?.enableTextSelectionDrag??s.enableTextSelectionDrag)){P.preventDefault();return}let _=B.anchorNode;_?.nodeType===Node.TEXT_NODE&&(_=_.parentNode);let I=null;for(;_&&_!==C;){if(_.parentNode===C){I=_;break}_=_.parentNode;}if(!I){P.preventDefault();return}B.collapse(B.anchorNode,B.anchorOffset);let J=e.read(()=>$getNearestNodeFromDOMNode(I)?.getKey()??null);if(!J){P.preventDefault();return}P.dataTransfer.clearData(),P.dataTransfer.setData("application/x-lexical-drag",JSON.stringify({key:J})),P.dataTransfer.effectAllowed="move";let $=I.cloneNode(true);$.style.opacity="0.6",$.style.position="absolute",$.style.top="-9999px",$.style.left="-9999px",document.body.appendChild($),P.dataTransfer.setDragImage($,0,0),setTimeout(()=>document.body.removeChild($),0),u(true),b(null),E.current=I,U(I),h.current=J;},k=P=>{let T=P.target;if(T.nodeType!==Node.ELEMENT_NODE&&(T=T.parentNode),!T||!(T instanceof HTMLElement))return;let G=T;P.preventDefault(),P.dataTransfer.dropEffect="move";let B=null,_=G;for(;_&&_!==C;){if(_.parentElement===C){B=_;break}_=_.parentElement;}if(B&&B!==E.current){let I=B.getBoundingClientRect(),J=P.clientY<I.top+I.height/2;b({top:J?I.top+window.scrollY:I.bottom+window.scrollY,left:I.left+window.scrollX,width:I.width});}else b(null);},O=P=>{let T=P.target;if(T.nodeType!==Node.ELEMENT_NODE&&(T=T.parentNode),!T||!(T instanceof HTMLElement))return;let G=T;P.preventDefault(),b(null);let B=P.dataTransfer?.getData("application/x-lexical-drag");if(!B){Y();return}let{key:_}=JSON.parse(B);if(!_){Y();return}let I=null,J=G;for(;J&&J!==C;){if(J.parentElement===C){I=J;break}J=J.parentElement;}I&&I!==E.current&&(e.update(()=>{let $=$getNodeByKey(_),be=$getNearestNodeFromDOMNode(I);if($&&be){let Ke=I.getBoundingClientRect(),Et=P.clientY>=Ke.top+Ke.height/2;$.remove(),Et?be.insertAfter($):be.insertBefore($);}}),setTimeout(()=>{if(h.current)try{let $=e.getElementByKey(h.current);$&&$ instanceof HTMLElement&&typeof $.getBoundingClientRect=="function"&&d($);}catch($){console.warn("Error finding moved element:",$);}re();},50)),Y();};return C.addEventListener("dragstart",R),C.addEventListener("dragover",k),C.addEventListener("drop",O),C.addEventListener("dragend",Y),()=>{C.removeEventListener("dragstart",R),C.removeEventListener("dragover",k),C.removeEventListener("drop",O),C.removeEventListener("dragend",Y);}},[e,Y,U,re,i?.enableTextSelectionDrag,s.enableTextSelectionDrag]),useEffect(()=>{if(!c)return;let C=()=>{Y();},R=O=>{O.key==="Escape"&&Y();},k=()=>{document.hidden&&Y();};return window.addEventListener("dragend",C),window.addEventListener("drop",C),window.addEventListener("blur",C),document.addEventListener("keydown",R),document.addEventListener("visibilitychange",k),()=>{window.removeEventListener("dragend",C),window.removeEventListener("drop",C),window.removeEventListener("blur",C),document.removeEventListener("keydown",R),document.removeEventListener("visibilitychange",k);}},[c,Y]),useEffect(()=>{let C=e.getRootElement();if(!C)return;let R=null,k=0,O=0,P=B=>{if(B.touches.length!==1||!(i?.enableTextSelectionDrag??s.enableTextSelectionDrag))return;let _=B.touches[0];if(!_)return;let I=B.target;if(I.nodeType!==Node.ELEMENT_NODE&&(I=I.parentNode),!I||!(I instanceof HTMLElement))return;let J=I;J.closest('[draggable="true"]')||(k=_.clientX,O=_.clientY,R=setTimeout(()=>{R=null;let $=null,be=J;for(;be&&be!==C;){if(be.parentElement===C){$=be;break}be=be.parentElement;}if(!$)return;let Ke=window.getSelection();Ke&&!Ke.isCollapsed&&Ke.collapseToStart(),u(true),E.current=$,U($);let Et=e.read(()=>$getNearestNodeFromDOMNode($)?.getKey()??null);Et&&(h.current=Et);},500));},T=B=>{if(R&&B.touches.length===1){let _=B.touches[0];if(!_)return;let I=_.clientX-k,J=_.clientY-O;Math.sqrt(I*I+J*J)>10&&(clearTimeout(R),R=null);}},G=()=>{R&&(clearTimeout(R),R=null);};return C.addEventListener("touchstart",P,{passive:false}),C.addEventListener("touchmove",T,{passive:false}),C.addEventListener("touchend",G,{passive:false}),document.addEventListener("touchmove",$e,{passive:false}),document.addEventListener("touchend",ue,{passive:false}),()=>{C.removeEventListener("touchstart",P),C.removeEventListener("touchmove",T),C.removeEventListener("touchend",G),document.removeEventListener("touchmove",$e),document.removeEventListener("touchend",ue);}},[e,U,Y,c,$e,ue,i?.enableTextSelectionDrag,s.enableTextSelectionDrag]);let fe=l||E.current;if(!W||!D||!fe||typeof fe.getBoundingClientRect!="function")return null;let ie=fe.getBoundingClientRect();if(!ie.width||!ie.height)return null;let je=H?.closest?.(".luthor-editor")||null,Nn=je||H;if(!Nn)return null;let Yr=Nn.getBoundingClientRect(),Vr=window.getComputedStyle(Nn),Wr=Number.parseFloat(Vr.getPropertyValue("--luthor-drag-gutter-width"))||40,ho=(i?.showAddButton??s.showAddButton)!==false,qr=ho?52:24,Jr=Yr.left+window.scrollX+Math.max(0,(Wr-qr)/2),Gr=(i?.buttonStackPosition||s.buttonStackPosition)==="right"?ie.right+window.scrollX+(i?.offsetRight||s.offsetRight||10):je?Jr:ie.left+window.scrollX+(i?.offsetLeft||s.offsetLeft||-40),xt=24,fo=xt/2,Tn=ie.top+window.scrollY,bo=ie.bottom+window.scrollY,Xr=Tn+ie.height/2,Zr=F??Xr,ei=Tn+xt/2,ti=bo-xt/2,ni=Math.min(ti,Math.max(ei,Zr)),yo=Tn,oi=Math.max(yo,bo-(fo+xt/2)),ri=Math.min(oi,Math.max(yo,ni-fo)),Co=D.getBoundingClientRect(),xo=D===document.body?0:Co.left+window.scrollX,Eo=D===document.body?0:Co.top+window.scrollY,ii=Gr-xo,si=ri-Eo;return jsxs(Fragment,{children:[createPortal(jsx("div",{className:`luthor-draggable-button-stack ${M.buttonStack} ${v?"":"fade-out"}`,style:{position:"absolute",left:0,top:0,transform:`translate3d(${ii}px, ${si}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",...A.buttonStack},children:jsxs("div",{style:{display:"flex",flexDirection:"row",alignItems:"center",gap:"4px"},children:[ho&&jsx("button",{type:"button","aria-label":"Add block",title:"Add",className:`luthor-drag-button ${M.addButton}`,onMouseDown:C=>{C.preventDefault(),C.stopPropagation();},onClick:C=>{C.preventDefault(),C.stopPropagation(),!(!fe||c)&&Le(fe);},style:A.addButton,children:"+"}),i?.handleRenderer||s.handleRenderer?(i?.handleRenderer||s.handleRenderer)({rect:ie,isDragging:c,onDragStart:C=>yt(C,fe),className:`luthor-drag-button ${M.handle} ${c?M.handleActive:""}`.trim()}):jsx("div",{className:`luthor-drag-button ${M.handle} ${c?M.handleActive:""}`.trim(),draggable:true,onDragStart:C=>yt(C,fe),onDragEnd:Y,onTouchStart:C=>Ct(C,fe),style:c?A.handleActive:A.handle,children:"\u22EE\u22EE"})]})}),D),p&&(i?.dropIndicatorRenderer||s.dropIndicatorRenderer?createPortal((i?.dropIndicatorRenderer||s.dropIndicatorRenderer)({...p,className:M.dropIndicator}),D):createPortal(jsx("div",{className:M.dropIndicator,style:{position:"absolute",top:p.top-4-Eo,left:p.left-xo,width:p.width,height:"8px",pointerEvents:"none",zIndex:9997,...A.dropIndicator}}),D))]})}function hl(s){let n=s.trim();return /^https?:\/\//i.test(n)?n:`https://${n}`}function Cr(s){try{let n=new URL(hl(s.trim()));return n.protocol!=="http:"&&n.protocol!=="https:"||!n.hostname?null:n}catch{return null}}function Ce(s,n,e){return Math.min(e,Math.max(n,Math.round(s)))}function fl(s){return s==="center"?{margin:"1rem auto",width:"fit-content",maxWidth:"100%"}:s==="left"?{margin:"1rem auto 1rem 0",width:"fit-content",maxWidth:"100%"}:{margin:"1rem 0 1rem auto",width:"fit-content",maxWidth:"100%"}}var lt=240,ct=140,dt=1600,ut=1200,te=class s extends DecoratorNode{constructor(e,t){super(t);x(this,"__payload");this.__payload=e;}static getType(){return "iframe-embed"}static clone(e){return new s(e.__payload,e.__key)}static importJSON(e){return new s({src:e.src,width:Ce(e.width,lt,dt),height:Ce(e.height,ct,ut),alignment:e.alignment,title:e.title,caption:e.caption??""})}static importDOM(){let e=t=>{let o=t.querySelector("iframe");if(!o)return {node:null};let r=o.getAttribute("src")??"",i=Number(o.getAttribute("width")??"640"),a=Number(o.getAttribute("height")??"360"),l=t.getAttribute("data-align")??"center",c=t.querySelector("figcaption")?.textContent??t.getAttribute("data-caption")??"";return {node:new s({src:r,width:Ce(i,lt,dt),height:Ce(a,ct,ut),alignment:l,title:o.getAttribute("title")??void 0,caption:c})}};return {div:t=>t.hasAttribute("data-lexical-iframe-embed")||t.hasAttribute("data-iframe-embed")?{conversion:e,priority:4}:null,figure:t=>t.hasAttribute("data-lexical-iframe-embed")||t.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 t=document.createElement("iframe");if(t.setAttribute("src",this.__payload.src),t.setAttribute("width",String(this.__payload.width)),t.setAttribute("height",String(this.__payload.height)),t.setAttribute("title",this.__payload.title??"Embedded content"),t.setAttribute("loading","lazy"),t.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),t.setAttribute("allowfullscreen","true"),t.style.border="0",e.appendChild(t),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 t=this.getWritable();t.__payload={...t.__payload,...e};}decorate(){return jsx(bl,{nodeKey:this.__key,payload:this.__payload})}isInline(){return false}isKeyboardSelectable(){return true}};function bl({nodeKey:s,payload:n}){let[e]=useLexicalComposerContext(),[t,o]=useState(false),[r,i]=useState(false),[a,l]=useState(n.width),[d,c]=useState(n.height),u=useRef(n.width),p=useRef(n.height),b=useRef(null),v=useRef(null),y=useRef(null);useEffect(()=>{l(n.width),c(n.height),u.current=n.width,p.current=n.height;},[n.width,n.height]),useEffect(()=>()=>{y.current!=null&&window.cancelAnimationFrame(y.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>e.registerUpdateListener(({editorState:f})=>{f.read(()=>{let N=$getSelection();if(!$isNodeSelection(N)){o(false);return}let F=N.getNodes().some(z=>z.getKey()===s);o(F);});}),[e,s]);let E=f=>{e.update(()=>{let N=$getNodeByKey(s);N instanceof te&&N.setPayload(f);});},h=f=>{f.preventDefault(),f.stopPropagation(),e.update(()=>{let N=$createNodeSelection();N.add(s),$setSelection(N);});},m=f=>N=>{if(N.preventDefault(),N.stopPropagation(),!b.current)return;let z=N.clientX,W=N.clientY,H=a,Q=d;document.body.style.userSelect="none",document.body.style.cursor=f==="width"?"ew-resize":"ns-resize",i(true);let D=()=>{y.current=null,b.current&&(b.current.style.width=`${u.current}px`),v.current&&(v.current.style.height=`${p.current}px`);},K=M=>{let V=f==="width"?Ce(H+(M.clientX-z),lt,dt):u.current,U=f==="height"?Ce(Q+(M.clientY-W),ct,ut):p.current;u.current=V,p.current=U,y.current==null&&(y.current=window.requestAnimationFrame(D));},A=()=>{y.current!=null&&(window.cancelAnimationFrame(y.current),y.current=null),i(false),l(u.current),c(p.current),E({width:u.current,height:p.current}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",K),document.removeEventListener("mouseup",A);};document.addEventListener("mousemove",K),document.addEventListener("mouseup",A);},g=useMemo(()=>fl(n.alignment),[n.alignment]),S=useMemo(()=>({marginTop:"0.5rem",textAlign:"center",color:"#666",fontSize:"0.9em",fontStyle:"italic"}),[]),w=t&&!r;return jsxs("div",{style:g,children:[jsxs("div",{ref:b,className:`luthor-media-embed-shell${t?" is-selected":""}${r?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{width:a,maxWidth:"100%"},onClick:h,children:[jsx("iframe",{ref:v,src:n.src,title:n.title??"Embedded content",loading:"lazy",referrerPolicy:"strict-origin-when-cross-origin",allowFullScreen:true,style:{width:"100%",height:`${d}px`,border:"0",display:"block",pointerEvents:t&&!r?"auto":"none"}}),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:m("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:m("height")})]}),n.caption?jsx("figcaption",{style:S,children:n.caption}):null]})}var an=class extends L{constructor(n){super("iframeEmbed",["toolbar"]),this.config={defaultWidth:640,defaultHeight:360,defaultAlignment:"center",...n};}register(n){return ()=>{}}getNodes(){return [te]}getPlugins(){return []}getCommands(n){return {insertIframeEmbed:(e,t,o,r)=>{let i=Cr(e);i&&n.update(()=>{let a=new te({src:i.toString(),width:Ce(t??this.config.defaultWidth??640,lt,dt),height:Ce(o??this.config.defaultHeight??360,ct,ut),alignment:this.config.defaultAlignment??"center",title:r,caption:""}),l=$getSelection();$isRangeSelection(l)?l.insertNodes([a]):$getRoot().append(a);});},setIframeEmbedAlignment:e=>{n.update(()=>{let t=$getSelection();$isNodeSelection(t)&&t.getNodes().forEach(o=>{o instanceof te&&o.setPayload({alignment:e});});});},resizeIframeEmbed:(e,t)=>{n.update(()=>{let o=$getSelection();$isNodeSelection(o)&&o.getNodes().forEach(r=>{r instanceof te&&r.setPayload({width:Ce(e,lt,dt),height:Ce(t,ct,ut)});});});},setIframeEmbedCaption:e=>{n.update(()=>{let t=$getSelection();$isNodeSelection(t)&&t.getNodes().forEach(o=>{o instanceof te&&o.setPayload({caption:e});});});},getIframeEmbedCaption:()=>new Promise(e=>{n.getEditorState().read(()=>{let t=$getSelection();if(!$isNodeSelection(t)){e("");return}let o=t.getNodes().find(r=>r instanceof te);e(o?.getPayload().caption??"");});}),updateIframeEmbedUrl:e=>{let t=Cr(e);if(!t)return false;let o=false;return n.update(()=>{let r=$getSelection();$isNodeSelection(r)&&r.getNodes().forEach(i=>{i instanceof te&&(i.setPayload({src:t.toString()}),o=true);});}),o},getIframeEmbedUrl:()=>new Promise(e=>{n.getEditorState().read(()=>{let t=$getSelection();if(!$isNodeSelection(t)){e("");return}let o=t.getNodes().find(r=>r instanceof te);e(o?.getPayload().src??"");});})}}getStateQueries(n){return {isIframeEmbedSelected:()=>new Promise(e=>{n.getEditorState().read(()=>{let t=$getSelection();if(!$isNodeSelection(t)){e(false);return}e(t.getNodes().some(o=>o instanceof te));});}),isIframeEmbedAlignedLeft:()=>new Promise(e=>{n.getEditorState().read(()=>{let t=$getSelection();if(!$isNodeSelection(t)){e(false);return}let o=t.getNodes().find(r=>r instanceof te);e(o?.getPayload().alignment==="left");});}),isIframeEmbedAlignedCenter:()=>new Promise(e=>{n.getEditorState().read(()=>{let t=$getSelection();if(!$isNodeSelection(t)){e(false);return}let o=t.getNodes().find(r=>r instanceof te);e(o?.getPayload().alignment==="center");});}),isIframeEmbedAlignedRight:()=>new Promise(e=>{n.getEditorState().read(()=>{let t=$getSelection();if(!$isNodeSelection(t)){e(false);return}let o=t.getNodes().find(r=>r instanceof te);e(o?.getPayload().alignment==="right");});})}}},yl=new an;var Ve=240,We=140,qe=1600,Je=1200;function de(s,n,e){return Math.min(e,Math.max(n,Math.round(s)))}function Tl(s){return s==="center"?{margin:"1rem auto",width:"fit-content",maxWidth:"100%"}:s==="left"?{margin:"1rem auto 1rem 0",width:"fit-content",maxWidth:"100%"}:{margin:"1rem 0 1rem auto",width:"fit-content",maxWidth:"100%"}}function Ll(s){let n=s.trim();return /^https?:\/\//i.test(n)?n:`https://${n}`}function oo(s){try{return new URL(Ll(s))}catch{return null}}function Nr(s){return /^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/.*)?$/i.test(s)}function pe(s){return typeof s=="string"&&/^[A-Za-z0-9_-]{3,}$/.test(s)}function Tr(s){let n=s.hostname.toLowerCase(),e=s.pathname;if(n==="youtu.be"){let r=e.split("/").filter(Boolean)[0];return pe(r)?{videoId:r}:null}if(e==="/playlist"){let r=s.searchParams.get("list");return pe(r)?{playlistId:r}:null}if(e.startsWith("/shorts/")){let r=e.split("/")[2];return pe(r)?{videoId:r}:null}if(e.startsWith("/embed/")){let r=e.split("/")[2];if(!r)return null;if(r==="videoseries"){let i=s.searchParams.get("list");return pe(i)?{playlistId:i}:null}return pe(r)?{videoId:r}:null}if(e==="/watch"){let r=s.searchParams.get("list"),i=s.searchParams.get("v"),a={};return pe(i)&&(a.videoId=i),pe(r)&&(a.playlistId=r),a.videoId||a.playlistId?a:null}let t=s.searchParams.get("v"),o=s.searchParams.get("list");return pe(t)||pe(o)?{videoId:pe(t)?t:void 0,playlistId:pe(o)?o:void 0}:null}function wl(s,n){if(!Nr(s))return null;let e=oo(s);if(!e)return null;if(e.pathname.includes("/embed/"))return e.toString();let t=Tr(e);if(!t)return null;let o=n.nocookie?"https://www.youtube-nocookie.com/embed/":"https://www.youtube.com/embed/",r="";if(t.playlistId&&!t.videoId?r=`${o}videoseries?list=${encodeURIComponent(t.playlistId)}`:t.videoId&&(r=`${o}${encodeURIComponent(t.videoId)}`),!r)return null;let i=[];if(n.allowFullscreen||i.push("fs=0"),n.autoplay&&i.push("autoplay=1"),n.controls||i.push("controls=0"),n.rel!==1&&i.push(`rel=${n.rel}`),n.start>0&&i.push(`start=${Math.max(0,Math.floor(n.start))}`),i.length===0)return r;let a=r.includes("?")?"&":"?";return `${r}${a}${i.join("&")}`}function Sr(s,n){let e=oo(s);if(!e||!Nr(n))return null;let t=oo(n);if(!t)return null;let o=Tr(t);if(!o||!o.videoId&&!o.playlistId)return null;let r=new URLSearchParams(e.search);r.delete("v"),r.delete("list"),r.delete("index"),o.playlistId&&r.set("list",o.playlistId);let a=e.hostname.toLowerCase().includes("youtube-nocookie.com")?"https://www.youtube-nocookie.com":"https://www.youtube.com",l=o.videoId?`/embed/${encodeURIComponent(o.videoId)}`:"/embed/videoseries",d=new URL(`${a}${l}`);return d.search=r.toString(),d.toString()}var q=class s extends DecoratorNode{constructor(e,t){super(t);x(this,"__payload");this.__payload=e;}static getType(){return "youtube-embed"}static clone(e){return new s(e.__payload,e.__key)}static importJSON(e){return new s({src:e.src,width:de(e.width,Ve,qe),height:de(e.height,We,Je),alignment:e.alignment,caption:e.caption??"",start:e.start})}static importDOM(){return {div:e=>e.hasAttribute("data-lexical-youtube-embed")||e.hasAttribute("data-youtube-video")?{conversion:o=>{let r=o.querySelector("iframe");if(!r)return {node:null};let i=r.getAttribute("src")??"",a=Number(r.getAttribute("width")??"640"),l=Number(r.getAttribute("height")??"480"),d=o.getAttribute("data-align")??"center",u=o.querySelector("figcaption")?.textContent??o.getAttribute("data-caption")??"",p=Number(r.getAttribute("data-start")??"0");return {node:new s({src:i,width:de(a,Ve,qe),height:de(l,We,Je),alignment:d,caption:u,start:Number.isFinite(p)?p:0})}},priority:4}:null,figure:e=>e.hasAttribute("data-lexical-youtube-embed")||e.hasAttribute("data-youtube-video")?{conversion:o=>{let r=o.querySelector("iframe");if(!r)return {node:null};let i=r.getAttribute("src")??"",a=Number(r.getAttribute("width")??"640"),l=Number(r.getAttribute("height")??"480"),d=o.getAttribute("data-align")??"center",u=o.querySelector("figcaption")?.textContent??o.getAttribute("data-caption")??"",p=Number(r.getAttribute("data-start")??"0");return {node:new s({src:i,width:de(a,Ve,qe),height:de(l,We,Je),alignment:d,caption:u,start:Number.isFinite(p)?p: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 t=document.createElement("iframe");if(t.setAttribute("src",this.__payload.src),t.setAttribute("width",String(this.__payload.width)),t.setAttribute("height",String(this.__payload.height)),t.setAttribute("title","YouTube video player"),t.setAttribute("loading","lazy"),t.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),t.setAttribute("allow","accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"),t.setAttribute("allowfullscreen","true"),t.style.border="0",this.__payload.start&&this.__payload.start>0&&t.setAttribute("data-start",String(this.__payload.start)),e.appendChild(t),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 t=this.getWritable();t.__payload={...t.__payload,...e};}decorate(){return jsx(Rl,{nodeKey:this.__key,payload:this.__payload})}isInline(){return false}isKeyboardSelectable(){return true}};function Rl({nodeKey:s,payload:n}){let[e]=useLexicalComposerContext(),[t,o]=useState(false),[r,i]=useState(false),[a,l]=useState(n.width),[d,c]=useState(n.height),u=useRef(n.width),p=useRef(n.height),b=useRef(null),v=useRef(null),y=useRef(null);useEffect(()=>{l(n.width),c(n.height),u.current=n.width,p.current=n.height;},[n.width,n.height]),useEffect(()=>()=>{y.current!=null&&window.cancelAnimationFrame(y.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>e.registerUpdateListener(({editorState:f})=>{f.read(()=>{let N=$getSelection();if(!$isNodeSelection(N)){o(false);return}let F=N.getNodes().some(z=>z.getKey()===s);o(F);});}),[e,s]);let E=f=>{e.update(()=>{let N=$getNodeByKey(s);N instanceof q&&N.setPayload(f);});},h=f=>{f.preventDefault(),f.stopPropagation(),e.update(()=>{let N=$createNodeSelection();N.add(s),$setSelection(N);});},m=f=>N=>{if(N.preventDefault(),N.stopPropagation(),!b.current)return;let z=N.clientX,W=N.clientY,H=a,Q=d;document.body.style.userSelect="none",document.body.style.cursor=f==="width"?"ew-resize":"ns-resize",i(true);let D=()=>{y.current=null,b.current&&(b.current.style.width=`${u.current}px`),v.current&&(v.current.style.height=`${p.current}px`);},K=M=>{let V=f==="width"?de(H+(M.clientX-z),Ve,qe):u.current,U=f==="height"?de(Q+(M.clientY-W),We,Je):p.current;u.current=V,p.current=U,y.current==null&&(y.current=window.requestAnimationFrame(D));},A=()=>{y.current!=null&&(window.cancelAnimationFrame(y.current),y.current=null),i(false),l(u.current),c(p.current),E({width:u.current,height:p.current}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",K),document.removeEventListener("mouseup",A);};document.addEventListener("mousemove",K),document.addEventListener("mouseup",A);},g=useMemo(()=>Tl(n.alignment),[n.alignment]),S=t&&!r,w=useMemo(()=>({fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"}),[]);return jsxs("div",{style:g,children:[jsxs("div",{ref:b,className:`luthor-media-embed-shell${t?" is-selected":""}${r?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{width:a,maxWidth:"100%"},onClick:h,children:[jsx("iframe",{ref:v,src:n.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:`${d}px`,border:"0",display:"block",pointerEvents:t&&!r?"auto":"none"}}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize YouTube embed width","aria-hidden":!S,tabIndex:S?0:-1,style:{opacity:S?1:0,pointerEvents:S?"auto":"none"},onMouseDown:m("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize YouTube embed height","aria-hidden":!S,tabIndex:S?0:-1,style:{opacity:S?1:0,pointerEvents:S?"auto":"none"},onMouseDown:m("height")})]}),n.caption?jsx("figcaption",{style:w,children:n.caption}):null]})}var cn=class extends L{constructor(e){super("youtubeEmbed",["toolbar"]);x(this,"lastSelectedYouTubeNodeKey",null);this.config={defaultWidth:640,defaultHeight:480,defaultAlignment:"center",allowFullscreen:true,autoplay:false,controls:true,nocookie:true,rel:1,...e};}register(e){return e.registerUpdateListener(({editorState:t})=>{t.read(()=>{let o=$getSelection();if(!$isNodeSelection(o))return;let r=o.getNodes().find(i=>i instanceof q);r&&(this.lastSelectedYouTubeNodeKey=r.getKey());});})}getNodes(){return [q]}getPlugins(){return []}getCommands(e){return {insertYouTubeEmbed:(t,o,r,i)=>{let a=wl(t,{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(i??0))});a&&e.update(()=>{let l=new q({src:a,width:de(o??this.config.defaultWidth??640,Ve,qe),height:de(r??this.config.defaultHeight??480,We,Je),alignment:this.config.defaultAlignment??"center",caption:"",start:i}),d=$getSelection();$isRangeSelection(d)?d.insertNodes([l]):$getRoot().append(l);});},setYouTubeEmbedAlignment:t=>{e.update(()=>{let o=$getSelection();$isNodeSelection(o)&&o.getNodes().forEach(r=>{r instanceof q&&r.setPayload({alignment:t});});});},resizeYouTubeEmbed:(t,o)=>{e.update(()=>{let r=$getSelection();$isNodeSelection(r)&&r.getNodes().forEach(i=>{i instanceof q&&i.setPayload({width:de(t,Ve,qe),height:de(o,We,Je)});});});},setYouTubeEmbedCaption:t=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){o.getNodes().forEach(r=>{r instanceof q&&r.setPayload({caption:t});});return}if(this.lastSelectedYouTubeNodeKey){let r=$getNodeByKey(this.lastSelectedYouTubeNodeKey);r instanceof q?r.setPayload({caption:t}):this.lastSelectedYouTubeNodeKey=null;}});},getYouTubeEmbedCaption:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes().find(i=>i instanceof q);if(r){t(r.getPayload().caption??"");return}}if(this.lastSelectedYouTubeNodeKey){let r=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(r instanceof q){t(r.getPayload().caption??"");return}}t("");});}),updateYouTubeEmbedUrl:t=>{let o=false;return e.update(()=>{let r=$getSelection();if($isNodeSelection(r)){r.getNodes().forEach(i=>{if(i instanceof q){let a=Sr(i.getPayload().src,t);if(!a)return;i.setPayload({src:a}),o=true;}});return}if(this.lastSelectedYouTubeNodeKey){let i=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(i instanceof q){let a=Sr(i.getPayload().src,t);a&&(i.setPayload({src:a}),o=true);}else this.lastSelectedYouTubeNodeKey=null;}}),o},getYouTubeEmbedUrl:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes().find(i=>i instanceof q);if(r){t(r.getPayload().src??"");return}}if(this.lastSelectedYouTubeNodeKey){let r=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(r instanceof q){t(r.getPayload().src??"");return}}t("");});})}}getStateQueries(e){return {isYouTubeEmbedSelected:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){t(false);return}t(o.getNodes().some(r=>r instanceof q));});}),isYouTubeEmbedAlignedLeft:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){t(false);return}let r=o.getNodes().find(i=>i instanceof q);t(r?.getPayload().alignment==="left");});}),isYouTubeEmbedAlignedCenter:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){t(false);return}let r=o.getNodes().find(i=>i instanceof q);t(r?.getPayload().alignment==="center");});}),isYouTubeEmbedAlignedRight:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){t(false);return}let r=o.getNodes().find(i=>i instanceof q);t(r?.getPayload().alignment==="right");});})}}},kl=new cn;var Te=class{static importDOM(){return {img:()=>({conversion:n=>{try{if(!n||!(n instanceof HTMLImageElement)||!n.src)return null;let e=n,t=e.closest("figure"),o=this.resolveAlignment(e,t),r;if(t){let c=t.querySelector("figcaption");c&&(r=c.textContent||void 0);}let i=e.getAttribute("width"),a=e.getAttribute("height"),l=i?Number(i):void 0,d=a?Number(a):void 0;try{return {node:Ge(e.src,e.alt||"",r,o,e.className||void 0,this.extractStyleObject(e),Number.isFinite(l)?l:void 0,Number.isFinite(d)?d:void 0)}}catch{return null}}catch{return null}},priority:0}),figure:()=>({conversion:n=>{try{if(!n||!(n instanceof HTMLElement)||n.tagName!=="FIGURE")return null;let e=n,t=e.querySelector("img");if(!t||!t.src)return null;let r=e.querySelector("figcaption")?.textContent||void 0,i=this.resolveAlignment(t,e),a=t.getAttribute("width"),l=t.getAttribute("height"),d=a?Number(a):void 0,c=l?Number(l):void 0;try{return {node:Ge(t.src,t.alt||"",r,i,t.className||void 0,this.extractStyleObject(t),Number.isFinite(d)?d:void 0,Number.isFinite(c)?c:void 0)}}catch{return null}}catch{return null}},priority:1})}}static exportDOM(n){let{element:e,after:t}=this.createImageElement(n);return {element:e,after:t}}static exportJSON(n){return {type:"image",version:1,src:n.__src,alt:n.__alt,caption:n.__caption,alignment:n.__alignment,className:n.__className,style:n.__style?this.styleObjectToRecord(n.__style):void 0,width:n.__width,height:n.__height,uploading:n.__uploading}}static importJSON(n){let{src:e,alt:t,caption:o,alignment:r,className:i,style:a,width:l,height:d,uploading:c}=n;if(!e||e.length===0)throw new Error("Cannot import ImageNode with empty src");return Ge(e,t,o,r,i,a?this.recordToStyleObject(a):void 0,l,d,c)}static createImageElement(n){let e=document.createElement("figure"),t=document.createElement("img");switch(t.src=n.__src,t.alt=n.__alt,n.__width&&(t.width=n.__width),n.__height&&(t.height=n.__height),n.__className&&(t.className=n.__className),n.__style&&Object.assign(t.style,n.__style),e.className=`lexical-image align-${n.__alignment}`,n.__alignment){case "left":e.style.textAlign="left";break;case "center":e.style.textAlign="center";break;case "right":e.style.textAlign="right";break;default:e.style.textAlign="left";}if(e.style.margin="1rem 0",e.style.display="block",e.appendChild(t),n.__caption){let o=document.createElement("figcaption");o.textContent=n.__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(n){if(!n||!(n instanceof HTMLElement)||!n.style||!n.style.length)return;let e={};try{for(let t=0;t<n.style.length;t++){let o=n.style.item(t);o&&(e[o]=n.style.getPropertyValue(o));}return Object.keys(e).length>0?e:void 0}catch{return}}static resolveAlignment(n,e){let t=[n,e].filter(Boolean);for(let r of t){if(r.classList.contains("align-left"))return "left";if(r.classList.contains("align-center"))return "center";if(r.classList.contains("align-right"))return "right"}let o=e?.getAttribute("data-align");if(o==="left"||o==="center"||o==="right")return o;for(let r of t){if(r.style.textAlign==="left")return "left";if(r.style.textAlign==="center")return "center";if(r.style.textAlign==="right")return "right";if(r.style.float==="left")return "left";if(r.style.float==="right")return "right"}return "none"}static styleObjectToRecord(n){let e={};for(let[t,o]of Object.entries(n))e[t]=String(o);return e}static recordToStyleObject(n){return {...n}}},{importDOM:Jg,exportDOM:Gg,importJSON:Xg,exportJSON:Zg}=Te;var kr=createCommand("insert-image"),_r=Bl,io=true,so=false,Pr=50,Mr=50,Or=2400,Ir=2400;function mn(s,n,e){return Math.min(e,Math.max(n,Math.round(s)))}function Bl({src:s,alt:n,caption:e,alignment:t="none",className:o="",style:r,nodeKey:i,width:a,height:l,resizable:d=true,scaleByRatio:c=false,uploading:u=false}){let[p]=useLexicalComposerContext(),b=useRef(null),v=useRef(null),y=useRef(null),E=useRef(0),h=useRef(0),[m,g]=useState(false),[S,w]=useState(false),[f,N]=useState(a||"auto"),[F,z]=useState(l||"auto");useEffect(()=>()=>{s&&s.startsWith("blob:")&&URL.revokeObjectURL(s);},[s]),useEffect(()=>{N(a||"auto"),z(l||"auto"),E.current=typeof a=="number"?a:0,h.current=typeof l=="number"?l:0;},[a,l]),useEffect(()=>()=>{y.current!=null&&window.cancelAnimationFrame(y.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>{if(i)return p.registerUpdateListener(({editorState:M})=>{M.read(()=>{let V=$getSelection();if($isNodeSelection(V)){let U=V.getNodes();g(U.some(re=>re.getKey()===i));}else g(false);});})},[p,i]);let W=M=>{M.preventDefault(),M.stopPropagation(),i&&p.update(()=>{let V=$createNodeSelection();V.add(i),$setSelection(V);});},H=M=>V=>{if(!b.current||!i)return;V.preventDefault(),V.stopPropagation(),w(true),document.body.style.userSelect="none",document.body.style.cursor=M==="width"?"ew-resize":"ns-resize";let U=V.clientX,re=V.clientY,Y=b.current.clientWidth||(typeof f=="number"?f:100),ee=b.current.clientHeight||(typeof F=="number"?F:100),Le=Number.isFinite(Y)&&Number.isFinite(ee)&&Y>0&&ee>0?Y/ee:null;E.current=Y,h.current=ee;let yt=()=>{y.current=null,v.current&&(v.current.style.width=`${E.current}px`),b.current&&(b.current.style.height=`${h.current}px`);},Ct=ue=>{let fe=!!Le&&(c?!ue.shiftKey:ue.shiftKey),ie=M==="width"?mn(Y+(ue.clientX-U),Pr,Or):E.current,je=M==="height"?mn(ee+(ue.clientY-re),Mr,Ir):h.current;fe&&Le&&(M==="width"?je=mn(ie/Le,Mr,Ir):ie=mn(je*Le,Pr,Or)),E.current=ie,h.current=je,y.current==null&&(y.current=window.requestAnimationFrame(yt));},$e=()=>{y.current!=null&&(window.cancelAnimationFrame(y.current),y.current=null),w(false),N(E.current),z(h.current),p.update(()=>{let ue=$getNodeByKey(i);ue instanceof j&&ue.setWidthAndHeight(E.current,h.current);}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",Ct),document.removeEventListener("mouseup",$e);};document.addEventListener("mousemove",Ct),document.addEventListener("mouseup",$e);},Q={margin:0,display:"block",position:"relative",...r},D={maxWidth:"100%",display:"block",borderRadius:"4px",width:typeof f=="number"?"100%":"auto",height:typeof F=="number"?`${F}px`:F,margin:0},K={fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"},A=m&&d&&!S;return jsxs("figure",{className:`lexical-image align-${t} ${o} ${m?"selected":""} ${S?"resizing":""} ${u?"uploading":""}`,style:Q,children:[jsxs("div",{ref:v,className:`luthor-media-embed-shell${m?" is-selected":""}${S?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{position:"relative",display:"inline-block",width:f,maxWidth:"100%",cursor:"pointer"},onClick:W,children:[jsx("img",{ref:b,src:s,alt:n,style:D}),d?jsxs(Fragment,{children:[jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize image width","aria-hidden":!A,tabIndex:A?0:-1,style:{opacity:A?1:0,pointerEvents:A?"auto":"none"},onMouseDown:H("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize image height","aria-hidden":!A,tabIndex:A?0:-1,style:{opacity:A?1:0,pointerEvents:A?"auto":"none"},onMouseDown:H("height")})]}):null]}),e&&jsx("figcaption",{style:K,children:e}),jsx("div",{style:{clear:"both",height:0,fontSize:0}})]})}var j=class s extends DecoratorNode{constructor(e="",t="",o,r="none",i,a,l,d,c,u){super(u);x(this,"__src");x(this,"__alt");x(this,"__caption");x(this,"__alignment");x(this,"__className");x(this,"__style");x(this,"__width");x(this,"__height");x(this,"__uploading");this.__src=e&&e.length>0?e:"",this.__alt=t,this.__caption=o,this.__alignment=r,this.__className=i,this.__style=a,this.__width=l,this.__height=d,this.__uploading=c;}static getType(){return "image"}static clone(e){return new s(e.__src,e.__alt,e.__caption,e.__alignment,e.__className,e.__style,e.__width,e.__height,e.__uploading,e.__key)}static importDOM(){return Te.importDOM()}static importJSON(e){return Te.importJSON(e)}createDOM(e){let t=document.createElement("div"),o=e.theme?.image||"",r=this.__alignment;return t.className=`${o} lexical-image-container align-${r}`.trim(),t.style.display=r==="center"?"block":"inline-block",t.style.float=r==="left"?"left":r==="right"?"right":"none",t.style.margin=r==="center"?"1rem auto":r==="left"?"0 1rem 1rem 0":r==="right"?"0 0 1rem 1rem":"1rem 0",t.style.textAlign=r==="center"?"center":"inherit",t.style.position="relative",t}updateDOM(e,t,o){let r=this.__alignment;if(r!==e.__alignment){let i=o.theme?.image||"";t.className=`${i} lexical-image-container align-${r}`.trim();}return t.style.display=r==="center"?"block":"inline-block",t.style.float=r==="left"?"left":r==="right"?"right":"none",t.style.margin=r==="center"?"1rem auto":r==="left"?"0 1rem 1rem 0":r==="right"?"0 0 1rem 1rem":"1rem 0",t.style.textAlign=r==="center"?"center":"inherit",t.style.position="relative",false}exportDOM(){return Te.exportDOM(this)}exportJSON(){return Te.exportJSON(this)}setSrc(e){if(!e||e.length===0){console.warn("Attempted to set empty src on ImageNode");return}let t=this.getWritable();t.__src=e;}setAlt(e){let t=this.getWritable();t.__alt=e;}setCaption(e){let t=this.getWritable();t.__caption=e;}setAlignment(e){let t=this.getWritable();t.__alignment=e;}setClassName(e){let t=this.getWritable();t.__className=e;}setStyle(e){let t=this.getWritable();t.__style=e;}getWidth(){return this.__width}getHeight(){return this.__height}setWidthAndHeight(e,t){let o=this.getWritable();o.__width=e,o.__height=t;}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(_r,{src:this.__src,alt:this.__alt,caption:this.__caption,alignment:this.__alignment,className:this.__className,style:this.__style,nodeKey:this.getKey(),width:this.__width,height:this.__height,resizable:io,scaleByRatio:so,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 Ge(s,n,e,t="none",o,r,i,a,l){if(!s||s.length===0)throw new Error("Cannot create ImageNode with empty src");return new j(s,n,e,t,o,r,i,a,l)}var pn=class extends L{constructor(){super("image",["toolbar"]);x(this,"recentImages",new Set);x(this,"lastSelectedImageNodeKey",null);this.config={...this.config,resizable:true,scaleByRatio:false,pasteListener:{insert:true,replace:true},debug:false,forceUpload:false},io=true,so=false;}configure(e){e.customRenderer&&(_r=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 t={...this.config,...e,resizable:e.resizable??this.config.resizable??true,scaleByRatio:e.scaleByRatio??this.config.scaleByRatio??false};return this.config=t,io=t.resizable??true,so=t.scaleByRatio??false,this}register(e){let t=e.registerUpdateListener(({editorState:l})=>{l.read(()=>{let d=$getSelection();if(!$isNodeSelection(d))return;let c=d.getNodes().find(u=>u instanceof j);c&&(this.lastSelectedImageNodeKey=c.getKey());});}),o=e.registerCommand(kr,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(b=>{e.update(()=>{let v=$getNodeByKey(u.getKey());v instanceof j&&(v.setSrc(b),v.__uploading=!1);});}).catch(b=>{console.error("Upload failed:",b),e.update(()=>{let v=$getNodeByKey(u.getKey());v instanceof j&&(v.__uploading=!1);});}));let u=Ge(d,l.alt,l.caption,l.alignment||this.config.defaultAlignment||"none",l.className,l.style,void 0,void 0,c),p=$getSelection();if($isRangeSelection(p))p.insertNodes([u]);else {let b=$createParagraphNode();b.append(u),$getRoot().append(b);}}catch(d){console.error("\u274C Insertion error:",d);}}),true),COMMAND_PRIORITY_EDITOR),r=e.registerCommand(KEY_DELETE_COMMAND,()=>{let l=$getSelection();if($isNodeSelection(l)){let d=l.getNodes();if(d.some(c=>c instanceof j))return e.update(()=>{d.forEach(c=>c.remove());}),true}return false},COMMAND_PRIORITY_EDITOR),i=e.registerCommand(KEY_BACKSPACE_COMMAND,()=>{let l=$getSelection();if($isNodeSelection(l)){let d=l.getNodes();if(d.some(c=>c instanceof j))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,p=Array.from(c).some(b=>b.type==="text/html");for(let b of c)if(b.type.startsWith("image/")){if(p)continue;d.preventDefault();let v=b.getAsFile();if(!v)continue;l("\u{1F4CB} Pasting image:",v.name),(this.config.uploadHandler&&this.config.forceUpload?this.config.uploadHandler(v).catch(E=>(console.error("Upload failed:",E),URL.createObjectURL(v))):Promise.resolve(URL.createObjectURL(v))).then(E=>{if(this.recentImages.has(E)){l("\u{1F6AB} Duplicate paste image src detected, skipping:",E);return}this.recentImages.add(E),setTimeout(()=>this.recentImages.delete(E),1e3);let h=false,m;this.config.uploadHandler&&this.config.forceUpload&&v&&(h=true,this.config.uploadHandler(v).then(g=>{e.update(()=>{let S=$getNodeByKey(m.getKey());S instanceof j&&(S.setSrc(g),S.__uploading=false);});}).catch(g=>{console.error("Upload failed:",g),e.update(()=>{let S=$getNodeByKey(m.getKey());S instanceof j&&(S.__uploading=false);});})),e.update(()=>{let g=$getSelection(),S=v.name||"Pasted image";if($isNodeSelection(g)&&this.config.pasteListener?.replace){let f=g.getNodes().find(N=>N instanceof j);if(f){l("\u{1F504} Replacing selected image src"),f.setSrc(E),f.__uploading=h,u=true;return}}this.config.pasteListener?.insert&&(l("\u2795 Inserting new pasted image"),m=Ge(E,S,void 0,"none",void 0,void 0,void 0,void 0,h),$isRangeSelection(g)?g.insertNodes([m]):$getRoot().append($createParagraphNode().append(m)),u=true);});});break}return u},COMMAND_PRIORITY_NORMAL);}return ()=>{t(),o(),r(),i(),a();}}getNodes(){return [j]}getCommands(e){return {insertImage:t=>{e.dispatchCommand(kr,t);},setImageAlignment:t=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let i of r)i instanceof j&&i.setAlignment(t);}});},setImageCaption:t=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let i of r)i instanceof j&&i.setCaption(t);return}if(this.lastSelectedImageNodeKey){let r=$getNodeByKey(this.lastSelectedImageNodeKey);r instanceof j?r.setCaption(t):this.lastSelectedImageNodeKey=null;}});},getImageCaption:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes().find(i=>i instanceof j);if(r){t(r.__caption??"");return}}if(this.lastSelectedImageNodeKey){let r=$getNodeByKey(this.lastSelectedImageNodeKey);if(r instanceof j){t(r.__caption??"");return}}t("");});}),setImageClassName:t=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let i of r)i instanceof j&&i.setClassName(t);}});},setImageStyle:t=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let i of r)i instanceof j&&i.setStyle(t);}});}}}getStateQueries(e){return {imageSelected:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();t(r.length===1&&r[0]instanceof j);}else t(false);});}),isImageAlignedLeft:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();if(r.length===1&&r[0]instanceof j){t(r[0].__alignment==="left");return}}t(false);});}),isImageAlignedCenter:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();if(r.length===1&&r[0]instanceof j){t(r[0].__alignment==="center");return}}t(false);});}),isImageAlignedRight:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();if(r.length===1&&r[0]instanceof j){t(r[0].__alignment==="right");return}}t(false);});}),isImageAlignedNone:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();if(r.length===1&&r[0]instanceof j){t(r[0].__alignment==="none");return}}t(false);});})}}},zl=new pn;function Dr(s){let n=renderToStaticMarkup(s),e=document.createElement("div");e.innerHTML=n;let t=e.firstElementChild;return e.remove(),t}function Gl(s){let n=s.isContainer??false,e=createCommand("insert-custom-node");function t({node:l,payload:d,nodeKey:c,children:u}){let[p]=useLexicalComposerContext(),[b,v]=useState(false);useEffect(()=>p.registerUpdateListener(({editorState:E})=>{E.read(()=>{let h=$getSelection();v($isNodeSelection(h)&&h.getNodes().some(m=>m.__key===c));});}),[p,c]);let y=E=>{p.update(()=>{let h=l.getWritable();h.__payload={...h.__payload,...E};});};return s.render?s.render({node:l,payload:d,children:u,nodeKey:c,isSelected:b,updatePayload:y}):null}class o extends ElementNode{constructor(c={},u,p){super(p);x(this,"__payload");x(this,"__nodeType");this.__payload=c,this.__nodeType=u;}static getType(){return s.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 s.importDOM?s.importDOM():{}}static exportDOM(c,{node:u}){if(s.exportDOM){let b=document.createElement("div");return s.exportDOM(c,{element:b,node:u})}let p=document.createElement("div");return p.setAttribute("data-custom-node-type",s.nodeType),{element:p}}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(s.createDOM){let p=s.createDOM(c,this);return p.setAttribute("data-custom-node-type",this.__nodeType),p.setAttribute("data-lexical-key",this.getKey()),p}if(s.jsx){let p=s.jsx({node:this,payload:this.__payload,nodeKey:this.getKey(),isSelected:false,updatePayload:v=>{this.setPayload(v);}}),b=Dr(p);return b.setAttribute("data-custom-node-type",this.__nodeType),b.setAttribute("data-lexical-key",this.getKey()),b}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,p){return s.updateDOM?s.updateDOM(c,u,p):false}getPayload(){return this.__payload}setPayload(c){let u=this.getWritable();u.__payload={...this.__payload,...c};}}class r extends DecoratorNode{constructor(c={},u,p){super(p);x(this,"__payload");x(this,"__nodeType");this.__payload=c,this.__nodeType=u;}static getType(){return s.nodeType}static clone(c){return new r(c.__payload,c.__nodeType,c.__key)}isSelectable(){return true}static importJSON(c){let{payload:u}=c;return new r(u,c.type)}static importDOM(){return s.importDOM?s.importDOM():{}}static exportDOM(c,{node:u}){if(s.exportDOM){let b=document.createElement("span");return s.exportDOM(c,{element:b,node:u})}let p=document.createElement("span");return p.setAttribute("data-custom-node-type",s.nodeType),{element:p}}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),s.createDOM){let p=s.createDOM(c,this);return p.setAttribute("data-custom-node-type",this.__nodeType),p}return u}updateDOM(c,u,p){return s.updateDOM?s.updateDOM(c,u,p):false}getPayload(){return this.__payload}setPayload(c){let u=this.getWritable();u.__payload={...this.__payload,...c};}decorate(){return jsx(t,{node:this,payload:this.__payload,nodeKey:this.__key})}}function i(l=s.defaultPayload||{}){if(n){let d=new o(l,s.nodeType);if(s.initialChildren)s.initialChildren().forEach(u=>{if(u.type==="paragraph"){let p=$createParagraphNode();u.children&&u.children.forEach(b=>{b.type==="text"&&p.append($createTextNode(b.text||""));}),d.append(p);}});else {let c=$createParagraphNode();c.append($createTextNode("")),d.append(c);}return d}else return new r(l,s.nodeType)}class a extends L{constructor(){super(s.nodeType,["toolbar"]);}register(d){let c=d.registerCommand(e,p=>(d.update(()=>{let b=i(p),v=$getSelection();$isRangeSelection(v)?v.insertNodes([b]):$getRoot().append($createParagraphNode().append(b));}),true),COMMAND_PRIORITY_EDITOR),u=d.registerUpdateListener(({editorState:p})=>{n&&p.read(()=>{let b=$getSelection(),v=$isNodeSelection(b)?b.getNodes():[];d.getEditorState().read(()=>{let y=$getRoot(),E=h=>{if(h.getType()===s.nodeType){let m=v.some(S=>S.__key===h.__key),g=document.querySelector(`[data-lexical-key="${h.__key}"]`);g&&(g.setAttribute("data-selected",m.toString()),g.style.borderColor=m?"#007ACC":"#ccc",g.style.backgroundColor=m?"#f0f8ff":"transparent");}"getChildren"in h&&h.getChildren().forEach(E);};E(y);});});});return ()=>{c(),u();}}getNodes(){return n?[o]:[r]}getCommands(d){return {...{insertCustomNode:u=>d.dispatchCommand(e,u)},...s.commands?s.commands(d):{}}}getStateQueries(d){return {...{isCustomNodeActive:()=>new Promise(u=>{d.getEditorState().read(()=>{let p=$getSelection();u(!!p&&$isNodeSelection(p)&&p.getNodes().some(b=>b.getType()===s.nodeType));});})},...s.stateQueries?s.stateQueries(d):{}}}}return {extension:new a,$createCustomNode:i,jsxToDOM:Dr}}var Fr=s=>{let{contentEditable:n,placeholder:e,className:t,classNames:o,styles:r,errorBoundary:i}=s,l=Zl.useContext(Ze)?.config,d=typeof l?.placeholder=="string"?l.placeholder:void 0,c=l?.classNames,u=l?.styles,p=e??d??"Start writing...",b=o?.placeholder||c?.placeholder||we.richText?.placeholder||"luthor-placeholder",v={position:"absolute",pointerEvents:"none",zIndex:1,...u?.placeholder,...r?.placeholder};return jsx("div",{className:o?.container||c?.container||t||we.container||"luthor-editor-container",style:{position:"relative",...u?.container,...r?.container},children:jsx(RichTextPlugin,{contentEditable:n||jsx("div",{style:{display:"block"},children:jsx(ContentEditable,{className:o?.contentEditable||c?.contentEditable||we.richText?.contentEditable||"luthor-content-editable",style:{...u?.contentEditable,...r?.contentEditable}})}),placeholder:typeof p=="string"?jsx("div",{className:b,style:v,children:p}):p||jsx("div",{className:b,style:v,children:"Start writing..."}),ErrorBoundary:i||rc})})},co=class extends L{constructor(n={}){super("richText",["floating"]),this.config={showInToolbar:false,position:"after",...n};}register(n){return ()=>{}}getPlugins(){return [jsx(Fr,{...this.config},"rich-text")]}},nc=new co,oc=s=>jsx(Fr,{...s}),rc=({children:s,onError:n})=>{try{return jsx(Fragment,{children:s})}catch(e){return console.error("RichTextPlugin Error:",e),n(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 fn=class extends L{constructor(){super("tabIndent",["toolbar"]);}register(n){let e=n.registerCommand(KEY_TAB_COMMAND,t=>{let o=$getSelection();if(!$isRangeSelection(o))return false;let r=o.anchor.getNode();return this.isInCodeBlock(r)?false:!t.shiftKey&&this.isInCheckList(r)?(t.preventDefault(),true):(t.preventDefault(),t.shiftKey?n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):n.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),true)},COMMAND_PRIORITY_LOW);return ()=>{e();}}isInCodeBlock(n){let e=n;for(;e;){if($isCodeNode(e))return true;e=e.getParent();}return false}isInCheckList(n){let e=n;for(;e;){if($isListNode(e))return e.getListType()==="check";e=e.getParent();}return false}},hc=new fn;var jr=[{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"]}],zr=jr,yn={":)":"\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 Cc(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bt(s){return s.trim().toLowerCase().replace(/^:+|:+$/g,"")}function $r(s){return s.toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}function go(s){let n=s.map(o=>({...o,shortcodes:[...o.shortcodes],keywords:o.keywords?[...o.keywords]:void 0})),e=new Map,t=n.map(o=>{let r=(o.shortcodes||[]).map(a=>bt(a)).filter(Boolean);for(let a of r)e.has(a)||e.set(a,o);let i=$r([o.label,...r,...o.keywords||[]].join(" "));return {item:o,searchable:i}});return {getAll:()=>[...n],resolveShortcode:o=>e.get(bt(o))??null,search:(o,r)=>{let i=Math.max(0,r?.limit??n.length);if(i===0)return [];let a=$r(o);return a?t.filter(l=>l.searchable.includes(a)).slice(0,i).map(l=>l.item):n.slice(0,i)}}}function Kr(s){return Array.isArray(s)?s.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0):[]}function xc(s){let n=Kr(s.shortcodes);return n.length>0?n.map(e=>bt(e)):typeof s.shortcodes=="string"?s.shortcodes.split(/[,\s]+/).map(e=>bt(e)).filter(Boolean):[]}function mo(s){if(!s||typeof s!="object")return null;let n=s;if(!n.emojis||typeof n.emojis!="object")return null;let e=[];for(let[t,o]of Object.entries(n.emojis)){if(!o||typeof o!="object")continue;let r=o,i=typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,l=(Array.isArray(r.skins)?r.skins:[])[0],d=typeof l?.native=="string"?l.native:"";if(!d)continue;let c=Array.from(new Set([bt(t),...xc(r)].filter(Boolean)));c.length!==0&&e.push({emoji:d,label:i,shortcodes:c,keywords:Kr(r.keywords)});}return e.length===0?null:go(e)}async function Ec(s){return new Function("name","return import(name);")(s)}var Cn=class extends L{constructor(e={}){super("emoji",["toolbar"]);x(this,"listeners",[]);x(this,"isOpen",false);x(this,"query","");x(this,"position",null);x(this,"suggestions",[]);x(this,"activeMatch",null);x(this,"applyingAutoReplace",false);x(this,"catalogAdapter",go(zr));x(this,"hasExplicitCatalogConfig",false);x(this,"hasExplicitAdapterConfig",false);x(this,"externalCatalogDetectionStarted",false);this.hasExplicitCatalogConfig=Object.prototype.hasOwnProperty.call(e,"catalog"),this.hasExplicitAdapterConfig=Object.prototype.hasOwnProperty.call(e,"catalogAdapter"),this.config={trigger:":",maxSuggestions:8,maxQueryLength:32,autoReplaceSymbols:true,symbolReplacements:yn,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||yn,...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 t=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 p=this.replaceSymbolsInText(c);return p===c?false:(l.preventDefault(),e.update(()=>{let b=$getSelection();$isRangeSelection(b)&&b.insertText(p);}),true)},COMMAND_PRIORITY_EDITOR),r=l=>{this.isOpen&&l.key==="Escape"&&(l.preventDefault(),this.closeEmojiSuggestions());},i=l=>{l.target?.closest(".luthor-emoji-menu")||this.isOpen&&this.closeEmojiSuggestions();},a=()=>{if(!this.isOpen||!this.activeMatch)return;let l=this.getCaretPosition();if(!l){this.closeEmojiSuggestions();return}this.position=l,this.notifyListeners();};return document.addEventListener("keydown",r),document.addEventListener("pointerdown",i),window.addEventListener("scroll",a,true),window.addEventListener("resize",a),()=>{t(),o(),document.removeEventListener("keydown",r),document.removeEventListener("pointerdown",i),window.removeEventListener("scroll",a,true),window.removeEventListener("resize",a),this.activeMatch=null,this.isOpen=false,this.query="",this.position=null,this.suggestions=[],this.notifyListeners();}}getCommands(e){return {insertEmoji:t=>{e.update(()=>{let o=$getSelection();$isRangeSelection(o)&&o.insertText(t);});},executeEmojiSuggestion:t=>this.executeEmojiSuggestion(e,t),closeEmojiSuggestions:()=>this.closeEmojiSuggestions(),getEmojiSuggestions:(t="")=>this.getSuggestions(t),getEmojiCatalog:()=>this.getCatalog(),resolveEmojiShortcode:t=>this.resolveShortcode(t),setEmojiCatalog:t=>{this.hasExplicitCatalogConfig=true,this.hasExplicitAdapterConfig=false,this.config={...this.config,catalog:[...t],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:t=>{this.hasExplicitAdapterConfig=true,this.config={...this.config,catalogAdapter:t},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(t=>t!==e);}}getCatalog(){return this.catalogAdapter.getAll()}getSuggestions(e){let t=this.config.maxSuggestions??8;return this.catalogAdapter.search(e,{limit:t})}resolveShortcode(e){return this.catalogAdapter.resolveShortcode(e)}resolveCatalogAdapter(e){return e.catalogAdapter?e.catalogAdapter:go(e.catalog||zr)}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,t=mo(e);if(t){this.catalogAdapter=t,this.refreshSuggestionsIfOpen();return}try{let r=await Ec("@emoji-mart/data"),i=mo(r.default)||mo(r.data);i&&(this.catalogAdapter=i,this.refreshSuggestionsIfOpen());}catch{}}refreshSuggestionsIfOpen(){this.isOpen&&(this.suggestions=this.getSuggestions(this.query),this.isOpen=this.suggestions.length>0,this.notifyListeners());}updateFromSelection(e){let t=null;if(e.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o)||!o.isCollapsed()){this.closeIfNeeded();return}if(this.isSelectionInsideCodeBlock(o)){this.closeIfNeeded();return}let r=o.anchor.getNode();if(!$isTextNode(r)){this.closeIfNeeded();return}let i=o.anchor.offset,a=r.getTextContent(),l=a.slice(0,i);if(this.config.autoReplaceSymbols&&!this.applyingAutoReplace){let E=this.detectSymbolReplacement(a,l,i);E&&(t={nodeKey:r.getKey(),startOffset:E.startOffset,endOffset:E.endOffset,emoji:E.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 b=l.slice(c+d.length);if(/\s/.test(b)||b.length>(this.config.maxQueryLength??32)){this.closeIfNeeded();return}let v=this.getSuggestions(b),y=this.getCaretPosition();this.query=b,this.position=y,this.suggestions=v,this.isOpen=v.length>0,this.activeMatch={nodeKey:r.getKey(),startOffset:c,endOffset:i},this.notifyListeners();}),t!==null){let o=t;this.applyingAutoReplace=true,e.update(()=>{let r=$getNodeByKey(o.nodeKey);if(!$isTextNode(r))return;let i=Math.max(0,o.endOffset-o.startOffset);r.spliceText(o.startOffset,i,o.emoji,true);let a=o.startOffset+o.emoji.length;r.select(a,a);}),this.applyingAutoReplace=false;}}isSelectionInsideCodeBlock(e){if(!$isRangeSelection(e))return false;let t=e.anchor.getNode();for(;t;){if($isCodeNode(t))return true;t=t.getParent();}return false}detectSymbolReplacement(e,t,o){let r=Object.entries(this.config.symbolReplacements||yn).sort((i,a)=>a[0].length-i[0].length);for(let[i,a]of r){if(!t.endsWith(i))continue;let l=o-i.length,d=l>0&&e[l-1]||"",c=o<e.length&&e[o]||"",u=l===0||/\s|[([{>"'`]/.test(d),p=o===e.length||/\s|[.,!?;:)\]}"'`]/.test(c);if(u&&p)return {startOffset:l,endOffset:o,emoji:a}}return null}replaceSymbolsInText(e){let t=Object.entries(this.config.symbolReplacements||yn),o=e;for(let[r,i]of t){let a=Cc(r),l=new RegExp(`(^|\\s)${a}(?=$|\\s|[.,!?;:])`,"g");o=o.replace(l,`$1${i}`);}return o}executeEmojiSuggestion(e,t){if(!t)return false;if(this.activeMatch){let o=this.activeMatch;return e.update(()=>{let r=$getNodeByKey(o.nodeKey);if(!$isTextNode(r))return;let i=Math.max(0,o.endOffset-o.startOffset);r.spliceText(o.startOffset,i,t,true);let a=o.startOffset+t.length;r.select(a,a);}),this.closeEmojiSuggestions(),true}return e.update(()=>{let o=$getSelection();$isRangeSelection(o)&&o.insertText(t);}),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 t=e.getRangeAt(0).cloneRange();t.collapse(true);let o=t.getBoundingClientRect(),i=t.getClientRects()[0]||o;return {x:i.left+(this.config.offset?.x??0),y:i.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(t=>t(e));}},Sc=new Cn;var xn=class extends L{constructor(){super("floatingToolbar",["floating"]);x(this,"isVisible",false);x(this,"selectionRect",null);this.config={render:()=>null,debounceMs:100,offset:{x:0,y:8},positionStrategy:"below",theme:{container:"luthor-floating-toolbar",button:"luthor-floating-toolbar-button",buttonActive:"luthor-floating-toolbar-button-active"}};}register(e){return ()=>{}}getPlugins(){return [jsx(Pc,{extension:this,config:this.config},"floating-toolbar")]}getCommands(e){return {}}getStateQueries(e){return {isFloatingVisible:async()=>this.isVisible}}updateContext(e,t){this.config&&(this.config.commands=e,this.config.activeStates=t);}getSelectionRect(){return this.selectionRect}getIsVisible(){return this.isVisible}setVisible(e){this.isVisible=e;}setSelectionRect(e){this.selectionRect=e;}},kc=new xn;function Pc({extension:s,config:n}){let[e]=useLexicalComposerContext(),{config:t}=xe(),[o,r]=useState(false),[i,a]=useState(null),[l,d]=useState(null),c=y=>(y.querySelector('[data-luthor-selection-anchor="true"]')??y).getBoundingClientRect(),u=(y,E)=>{let h;return (...m)=>{clearTimeout(h),h=setTimeout(()=>y(()=>m),E);}},p=useCallback(y=>{let E=n.offset||{y:8},h=n.positionStrategy||"below",m=window.pageXOffset||document.documentElement.scrollLeft||0,g=window.pageYOffset||document.documentElement.scrollTop||0,S=window.innerWidth,w=window.innerHeight,f=y.bottom+g+E.y;h==="above"?f=y.top+g-E.y:h==="auto"&&(f=w-y.bottom>60?y.bottom+g+E.y:y.top+g-E.y);let N=n.getActiveStates?.(),F=!!N?.isIframeEmbedSelected||!!N?.isYouTubeEmbedSelected,z=n.toolbarDimensions?.width||(F?132:300),W=n.toolbarDimensions?.height||40,H=10,Q=y.left+y.width/2,D=Q+m,K,A,M=Q-H,V=S-Q-H,U=z/2,re=Q-U,Y=Q+U,ee=re<H,Ee=Y>S-H;return !ee&&!Ee?(K=D-U,A=false):ee||M<U?(K=m+H,A=false):Ee||V<U?(K=m+S-z-H,A=true):(K=D-U,A=false),f-W<g?f=y.bottom+g+E.y:f+W>g+w&&(f=y.top+g-E.y-W),{x:K,y:f,width:y.width,height:y.height,top:y.top+g,left:y.left+m,bottom:y.bottom+g,right:y.right+m,positionFromRight:A}},[n]);useEffect(()=>{s.setVisible(o);},[o,s]),useEffect(()=>{let E=u(()=>{e.getEditorState().read(()=>{let g=$getSelection(),S=null,w=null;if($isRangeSelection(g)&&!g.isCollapsed()){let f=window.getSelection();f&&f.rangeCount>0&&(S=f.getRangeAt(0).getBoundingClientRect(),w=g);}else if($isNodeSelection(g)){let f=g.getNodes();if(f.length>0){let N=f[0];if(N){let F=N.getKey(),z=e.getElementByKey(F);z&&(S=c(z));}}}if(S&&S.width>0&&S.height>0){let f=p(S);a(f),d(w),r(true),s.setSelectionRect(f);}else a(null),d(null),r(false),s.setSelectionRect(null);});},n.debounceMs||100),h=e.registerUpdateListener(()=>{E();}),m=()=>{E();};return document.addEventListener("selectionchange",m),()=>{h(),document.removeEventListener("selectionchange",m);}},[e,n.debounceMs,p,s]);let b=()=>{r(false),a(null),d(null);};if(!n.render)return console.warn("FloatingToolbarExtension: No render function provided in config."),null;if(typeof document>"u")return null;let v=n.anchorElem||document.body;return createPortal(n.render({isVisible:o,selectionRect:i,selection:l,editor:e,commands:n.getCommands?.()||{},activeStates:n.getActiveStates?.()||{},hide:b,theme:t?.theme?.floatingToolbar||n.theme||{}}),v)}var En=class extends L{constructor(){super("commandPalette",["toolbar"]);x(this,"isOpen",false);x(this,"commands",new Map);x(this,"listeners",[]);}register(e){let t=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",t),this.registerTableCommands(e),()=>{document.removeEventListener("keydown",t);}}getCommands(e){return {showCommandPalette:()=>this.showCommandPalette(),hideCommandPalette:()=>this.hideCommandPalette(),registerCommand:t=>this.registerCommand(t),unregisterCommand:t=>this.unregisterCommand(t)}}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(t=>t(this.isOpen,e));}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(t=>t!==e);}}getAllCommands(){return Array.from(this.commands.values())}},Oc=new En;var Hc=new Set(["paragraph","heading"]),Sn=class extends L{constructor(e={}){super("slashCommand",["toolbar"]);x(this,"commands",new Map);x(this,"listeners",[]);x(this,"isOpen",false);x(this,"query","");x(this,"position",null);x(this,"activeMatch",null);this.config={trigger:"/",offset:{x:0,y:8},...e},this.setSlashCommands(this.config.items??[]);}register(e){let t=e.registerUpdateListener(()=>{this.updateMatchFromSelection(e);}),o=a=>{this.isOpen&&a.key==="Escape"&&(a.preventDefault(),this.closeSlashMenu());};document.addEventListener("keydown",o);let r=a=>{a.target?.closest(".luthor-slash-menu")||this.isOpen&&this.closeSlashMenu();},i=()=>{if(!this.isOpen||!this.activeMatch)return;let a=this.getCaretPosition();if(!a){this.closeSlashMenu();return}this.position=a,this.notifyListeners();};return document.addEventListener("pointerdown",r),window.addEventListener("scroll",i,true),window.addEventListener("resize",i),()=>{t(),document.removeEventListener("keydown",o),document.removeEventListener("pointerdown",r),window.removeEventListener("scroll",i,true),window.removeEventListener("resize",i),this.activeMatch=null,this.isOpen=false,this.query="",this.position=null,this.notifyListeners();}}getCommands(e){return {registerSlashCommand:t=>this.registerSlashCommand(t),unregisterSlashCommand:t=>this.unregisterSlashCommand(t),setSlashCommands:t=>this.setSlashCommands(t),closeSlashMenu:()=>this.closeSlashMenu(),executeSlashCommand:t=>this.executeSlashCommand(e,t)}}getStateQueries(e){return {isSlashMenuOpen:()=>Promise.resolve(this.isOpen)}}subscribe(e){return this.listeners.push(e),e(this.getState()),()=>{this.listeners=this.listeners.filter(t=>t!==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 t=new Map;for(let o of e)!o?.id||t.has(o.id)||t.set(o.id,o);this.commands=t,this.notifyListeners();}closeSlashMenu(){this.isOpen=false,this.query="",this.position=null,this.activeMatch=null,this.notifyListeners();}executeSlashCommand(e,t){let o=this.commands.get(t);if(!o)return false;if(this.activeMatch){let r=this.activeMatch;e.update(()=>{let i=$getNodeByKey(r.nodeKey);if(!$isTextNode(i))return;let a=Math.max(0,Math.min(r.endOffset,i.getTextContentSize()));i.select(a,a);let l=Math.max(0,r.endOffset-r.startOffset);l>0&&i.spliceText(r.startOffset,l,"",true);});}return this.closeSlashMenu(),o.action(),true}updateMatchFromSelection(e){e.getEditorState().read(()=>{let t=$getSelection();if(!$isRangeSelection(t)||!t.isCollapsed()){this.closeIfNeeded();return}let o=t.anchor.getNode();if(!$isTextNode(o)){this.closeIfNeeded();return}let r=Fc(o);if(!Hc.has(r)){this.closeIfNeeded();return}let i=t.anchor.offset,l=o.getTextContent().slice(0,i),d=this.config.trigger||"/",c=l.lastIndexOf(d);if(c<0){this.closeIfNeeded();return}let u=l.slice(0,c);if(!Bc(u)){this.closeIfNeeded();return}let p=l.slice(c+d.length);if(/\s/.test(p)){this.closeIfNeeded();return}let b=this.getCaretPosition();this.isOpen=true,this.query=p,this.position=b,this.activeMatch={nodeKey:o.getKey(),startOffset:c,endOffset:i,query:p},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 t=e.getRangeAt(0).cloneRange();t.collapse(true);let o=t.getBoundingClientRect(),i=t.getClientRects()[0]||o,a=this.config.offset?.x??0,l=this.config.offset?.y??8;return {x:i.left+a,y:i.bottom+l}}getState(){return {isOpen:this.isOpen,query:this.query,position:this.position,commands:this.getAllCommands()}}notifyListeners(){let e=this.getState();this.listeners.forEach(t=>t(e));}},Dc=new Sn;function Fc(s){try{return s.getTopLevelElementOrThrow?.()?.getType?.()??""}catch{return ""}}function Bc(s){return s.trim().length===0}var vn=class extends L{constructor(){super("enterKeyBehavior",["floating"]),this.config={...this.config||{},showInToolbar:false,initPriority:100};}register(n){let e,t=r=>{if(r.key!=="Enter")return;let i=false;n.update(()=>{let a=$getSelection();if(!$isRangeSelection(a))return;let l=a.anchor.getNode();if(r.shiftKey){let y=$findCellNode(l);if($isTableCellNode(y)){let m=$getTableNodeFromLexicalNodeOrThrow(y),g=$createParagraphNode();m.insertAfter(g),g.selectStart(),i=true;return}let E=this.findQuoteNode(l);if(E){let m=$createParagraphNode();E.insertAfter(m),m.selectStart(),i=true;return}let h=this.findCodeNode(l);if(h){let m=$createParagraphNode();h.insertAfter(m),m.selectStart(),i=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(),i=true;return}let u=this.isEmptyQuoteLine(c),p=c.getPreviousSibling(),b=this.isEmptyQuoteLine(p);if(u&&b){let y=c,E=p;y.remove(),E?.remove();let h=$createParagraphNode();d.insertAfter(h),h.selectStart(),i=true;return}let v=$createParagraphNode();c.insertAfter(v),v.selectStart(),i=true;}),i&&(r.preventDefault(),r.stopPropagation());},o=n.registerRootListener((r,i)=>{e?.(),e=void 0,i&&i.removeEventListener("keydown",t,true),r&&(r.addEventListener("keydown",t,true),e=()=>{r.removeEventListener("keydown",t,true);});});return ()=>{e?.(),o();}}findQuoteNode(n){let e=n;for(;e;){if($isQuoteNode(e))return e;e=e.getParent();}return null}findCodeNode(n){let e=n;for(;e;){if($isCodeNode(e))return e;e=e.getParent();}return null}findDirectQuoteChild(n,e){let t=n;for(;t&&t.getParent&&t.getParent()!==e;)t=t.getParent();return t?.getParent&&t.getParent()===e?t:null}isEmptyQuoteLine(n){return n?n.getTextContent().trim()==="":false}},Vc=new vn;
|
|
5
|
+
export{L as BaseExtension,Ei as BaseProvider,Zt as BlockFormatExtension,St as BoldExtension,Wt as CodeExtension,Gt as CodeFormatExtension,Jt as CodeIntelligenceExtension,En as CommandPaletteExtension,Dt as ContextMenuExtension,rn as DraggableBlockExtension,Cn as EmojiExtension,vn as EnterKeyBehaviorExtension,vi as ExtensionCategory,xn as FloatingToolbarExtension,Rt as FontFamilyExtension,kt as FontSizeExtension,en as HistoryExtension,wt as HorizontalRuleExtension,an as IframeEmbedExtension,pn as ImageExtension,vt as ItalicExtension,jr as LIGHTWEIGHT_EMOJI_CATALOG,So as LUTHOR_EDITOR_THEME_TOKENS,Pt as LineHeightExtension,Lt as LinkExtension,Qt as ListExtension,oc as RichText,Sn as SlashCommandExtension,Tt as StrikethroughExtension,_t as SubscriptExtension,At as SuperscriptExtension,fn as TabIndentExtension,Kt as TableExtension,Ot as TextColorExtension,X as TextFormatExtension,It as TextHighlightExtension,Nt as UnderlineExtension,cn as YouTubeEmbedExtension,Wa as blockFormatExtension,_i as boldExtension,Li as clearLexicalSelection,ba as codeExtension,Da as codeFormatExtension,_a as codeIntelligenceExtension,Oc as commandPaletteExtension,jn as contextMenuExtension,Gl as createCustomNodeExtension,To as createEditorSystem,di as createEditorThemeStyleVars,Ni as createExtension,we as defaultLuthorTheme,il as draggableBlockExtension,Sc as emojiExtension,Vc as enterKeyBehaviorExtension,kc as floatingToolbarExtension,ms as fontFamilyExtension,bs as fontSizeExtension,tl as historyExtension,ss as horizontalRuleExtension,yl as iframeEmbedExtension,zl as imageExtension,mi as isLuthorTheme,Ai as italicExtension,Mi as jsonbToMarkdown,Ns as lineHeightExtension,Vi as linkExtension,aa as listExtension,Pi as markdownToJSONB,ui as mergeThemes,wi as resolveLinkNodeKeyFromAnchor,nc as richTextExtension,Dc as slashCommandExtension,Fi as strikethroughExtension,Ms as subscriptExtension,Os as superscriptExtension,hc as tabIndentExtension,ta as tableExtension,ws as textColorExtension,Ps as textHighlightExtension,Di as underlineExtension,xe as useBaseEditor,kl as youTubeEmbedExtension};
|