@lyfie/luthor-headless 2.4.0 → 2.6.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 +1 -1
- package/dist/index.d.ts +18 -1
- package/dist/index.js +4 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
<div align="center">
|
|
8
8
|
|
|
9
|
-
[](https://github.com/lyfie-org/luthor)
|
|
10
10
|
[](https://github.com/lyfie-org/luthor/releases)
|
|
11
11
|
|
|
12
12
|
[](https://www.npmjs.com/package/@lyfie/luthor-headless)
|
package/dist/index.d.ts
CHANGED
|
@@ -2181,6 +2181,20 @@ interface BaseRichTextProps {
|
|
|
2181
2181
|
contentEditable?: React__default.ReactElement;
|
|
2182
2182
|
placeholder?: React__default.ReactElement | string;
|
|
2183
2183
|
className?: string;
|
|
2184
|
+
/**
|
|
2185
|
+
* Starts the visual surface in a non-editable state.
|
|
2186
|
+
* Clicking inside the surface promotes it into editable mode and places the caret
|
|
2187
|
+
* at the clicked coordinate (or nearest line when exact placement is unavailable).
|
|
2188
|
+
*/
|
|
2189
|
+
nonEditableVisualMode?: boolean;
|
|
2190
|
+
/**
|
|
2191
|
+
* Optional callback invoked when a non-editable visual surface receives a click
|
|
2192
|
+
* that indicates edit intent.
|
|
2193
|
+
*/
|
|
2194
|
+
onEditIntent?: (position: {
|
|
2195
|
+
clientX: number;
|
|
2196
|
+
clientY: number;
|
|
2197
|
+
}) => void;
|
|
2184
2198
|
classNames?: {
|
|
2185
2199
|
container?: string;
|
|
2186
2200
|
contentEditable?: string;
|
|
@@ -2588,11 +2602,14 @@ declare class SlashCommandExtension extends BaseExtension<"slashCommand", SlashC
|
|
|
2588
2602
|
}
|
|
2589
2603
|
declare const slashCommandExtension: SlashCommandExtension;
|
|
2590
2604
|
|
|
2591
|
-
type EnterKeyBehaviorCommands =
|
|
2605
|
+
type EnterKeyBehaviorCommands = {
|
|
2606
|
+
insertHardBreak: () => void;
|
|
2607
|
+
};
|
|
2592
2608
|
type EnterKeyBehaviorStateQueries = Record<string, never>;
|
|
2593
2609
|
declare class EnterKeyBehaviorExtension extends BaseExtension<"enterKeyBehavior", BaseExtensionConfig, EnterKeyBehaviorCommands, EnterKeyBehaviorStateQueries> {
|
|
2594
2610
|
constructor();
|
|
2595
2611
|
register(editor: LexicalEditor): () => void;
|
|
2612
|
+
getCommands(editor: LexicalEditor): EnterKeyBehaviorCommands;
|
|
2596
2613
|
private findQuoteNode;
|
|
2597
2614
|
private findCodeNode;
|
|
2598
2615
|
private findDirectQuoteChild;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import bu,{createContext,createElement,useRef,useState,useEffect,useMemo,useCallback,useContext}from'react';import {LexicalComposer}from'@lexical/react/LexicalComposer';import {useLexicalComposerContext}from'@lexical/react/LexicalComposerContext';import {createCommand,$getSelection,$isNodeSelection,$getNodeByKey,$isRangeSelection,$createParagraphNode,$getRoot,COMMAND_PRIORITY_EDITOR,KEY_DELETE_COMMAND,KEY_BACKSPACE_COMMAND,PASTE_COMMAND,COMMAND_PRIORITY_NORMAL,DecoratorNode,$createTextNode,KEY_ENTER_COMMAND,$isTextNode,$isParagraphNode,$isRootOrShadowRoot,COMMAND_PRIORITY_LOW,$isElementNode,KEY_SPACE_COMMAND,INDENT_CONTENT_COMMAND,OUTDENT_CONTENT_COMMAND,KEY_TAB_COMMAND,$nodesOfType,INSERT_PARAGRAPH_COMMAND,ParagraphNode,FORMAT_ELEMENT_COMMAND,CAN_UNDO_COMMAND,CAN_REDO_COMMAND,CLEAR_HISTORY_COMMAND,REDO_COMMAND,UNDO_COMMAND,FORMAT_TEXT_COMMAND,INSERT_LINE_BREAK_COMMAND,$getNearestNodeFromDOMNode,$createNodeSelection,$setSelection,createEditor,TextNode,LineBreakNode,TabNode,ElementNode}from'lexical';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {$createLinkNode,TOGGLE_LINK_COMMAND,$isLinkNode,LinkNode,AutoLinkNode}from'@lexical/link';import {TRANSFORMERS,registerMarkdownShortcuts,$convertFromMarkdownString,$convertToMarkdownString}from'@lexical/markdown';import {ListNode,ListItemNode,$isListNode,INSERT_CHECK_LIST_COMMAND,INSERT_UNORDERED_LIST_COMMAND,INSERT_ORDERED_LIST_COMMAND,$isListItemNode,$getListDepth}from'@lexical/list';import {$isHeadingNode,$isQuoteNode,HeadingNode,QuoteNode,$createQuoteNode,$createHeadingNode}from'@lexical/rich-text';import {CodeNode,CodeHighlightNode,$createCodeNode,$isCodeNode,registerCodeHighlighting,PrismTokenizer,normalizeCodeLang,getCodeLanguageOptions,getCodeLanguages}from'@lexical/code';import {$generateNodesFromDOM,$generateHtmlFromNodes}from'@lexical/html';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 {$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 {ListPlugin}from'@lexical/react/LexicalListPlugin';import {CheckListPlugin}from'@lexical/react/LexicalCheckListPlugin';import {HistoryPlugin}from'@lexical/react/LexicalHistoryPlugin';import {renderToStaticMarkup}from'react-dom/server';import {RichTextPlugin}from'@lexical/react/LexicalRichTextPlugin';import {ContentEditable}from'@lexical/react/LexicalContentEditable';var Es=Object.defineProperty;var Cs=(i,n,e)=>n in i?Es(i,n,{enumerable:true,configurable:true,writable:true,value:e}):i[n]=e;var x=(i,n,e)=>Cs(i,typeof n!="symbol"?n+"":n,e);var rr=["--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 Ss(i){return typeof i=="string"&&i.trim().length>0}function vs(i){if(!i)return;let n={};for(let e of rr){let t=i[e];Ss(t)&&(n[e]=t);}return Object.keys(n).length>0?n:void 0}var Be={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 Ns(i,n){return {...i,...n,text:{...i.text,...n.text},list:{...i.list,...n.list,nested:{...i.list?.nested,...n.list?.nested}},heading:{...i.heading,...n.heading},codeHighlight:{...i.codeHighlight,...n.codeHighlight},toolbar:{...i.toolbar,...n.toolbar},draggable:{...i.draggable,...n.draggable,styles:{...i.draggable?.styles,...n.draggable?.styles}},floatingToolbar:{...i.floatingToolbar,...n.floatingToolbar,styles:{...i.floatingToolbar?.styles,...n.floatingToolbar?.styles}},richText:{...i.richText,...n.richText},styles:{toolbar:{...i.styles?.toolbar,...n.styles?.toolbar},draggable:{...i.styles?.draggable,...n.styles?.draggable},floatingToolbar:{...i.styles?.floatingToolbar,...n.styles?.floatingToolbar},...n.styles}}}function Ts(i){return i&&typeof i=="object"}var gt=createContext(null);function ar(){function i(){let t=useContext(gt);if(!t)throw new Error("useEditor must be used within Provider");return t}function n({children:t,config:o={},extensions:r}){let[s]=useLexicalComposerContext(),a=useMemo(()=>({formatText:(f,p)=>s?.dispatchCommand(FORMAT_TEXT_COMMAND,f)}),[s]),l=useMemo(()=>{if(!s)return {};let f={};for(let p of r)Object.assign(f,p.getCommands(s));return f},[r,s]),d=useMemo(()=>({...a,...l}),[a,l]),{plugins:c,pluginsBefore:u,pluginsAfter:m}=useMemo(()=>{let f=[],p=[];for(let g of r){let E=g.getPlugins?.()||[];(g.config?.position||"before")==="after"?p.push(...E):f.push(...E);}return {plugins:[...f,...p],pluginsBefore:f,pluginsAfter:p}},[r]);useEffect(()=>{if(!s)return;let p=[...r].sort((g,E)=>{let T=g.config?.initPriority??0;return (E.config?.initPriority??0)-T}).map(g=>g.register(s));return ()=>p.forEach(g=>g&&g())},[s,r]);let h=useMemo(()=>{if(!s)return {};let f={};for(let p of r)p.getStateQueries&&Object.assign(f,p.getStateQueries(s));return f},[r,s]),[N,v]=useState(()=>{let f={};return Object.keys(h).forEach(p=>f[p]=false),f});useEffect(()=>{let f=Object.keys(h);v(p=>{let g={};for(let T of f){let b=p[T];g[T]=b??false;}if(Object.keys(p).length!==f.length)return g;for(let T of f)if(p[T]!==g[T])return g;return p});},[h]),useEffect(()=>{if(!s)return;let f=true,p=0,g=async()=>{let b=++p,M=Object.entries(h).map(async([_,q])=>{try{let z=await q();return [_,z]}catch{return [_,false]}}),B=await Promise.all(M);if(!f||b!==p)return;let j=Object.fromEntries(B);v(_=>{let q=_,z=j,F=Object.keys(q),A=Object.keys(z);if(F.length!==A.length)return j;for(let P of A)if(q[P]!==z[P])return j;return _});};g();let E=s.registerUpdateListener(()=>{g();}),T=r.map(b=>{let S=b;if(typeof S.onStateChange=="function")return S.onStateChange(()=>{g();})}).filter(b=>typeof b=="function");return ()=>{f=false,E(),T.forEach(b=>b());}},[s,h,r]);let y={editor:s,config:o,extensions:r,commands:d,activeStates:N,stateQueries:h,listeners:{registerUpdate:f=>s?.registerUpdateListener(f)||(()=>{}),registerPaste:f=>s?.registerCommand(PASTE_COMMAND,f,COMMAND_PRIORITY_EDITOR)||(()=>{})},export:{toJSON:()=>s?.getEditorState().toJSON()},import:{fromJSON:f=>{if(s&&(typeof f=="string"||typeof f=="object"&&f!==null)){s.setEditorState(s.parseEditorState(f));let p=d;typeof p.rehydrateListStyles=="function"&&queueMicrotask(()=>{p.rehydrateListStyles?.();});}}},lexical:s,extensionsAPI:{add:f=>{},remove:f=>{},reorder:f=>{}},plugins:c,hasExtension:f=>r.some(p=>p.name===f)};return jsxs(gt.Provider,{value:y,children:[u,t,m]})}function e(t){let o=useMemo(()=>t.extensions.flatMap(a=>a.getNodes?.()||[]),[t.extensions]),r=useMemo(()=>({namespace:"modern-editor",theme:t.config?.theme||Be,onError:s=>{console.error("Lexical error:",s);},nodes:o}),[t.config?.theme,o]);return jsx(LexicalComposer,{initialConfig:r,children:jsx(n,{...t})})}return {Provider:e,useEditor:i}}var Is=ar(),_s=Is.Provider,Me=()=>{let i=useContext(gt);if(!i)throw new Error("useBaseEditor must be used within Provider");return i};var Ds=(o=>(o.Toolbar="toolbar",o.Sidebar="sidebar",o.ContextMenu="contextmenu",o.Floating="floating",o))(Ds||{});var w=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 Hs(i){return new class extends w{constructor(){super(i.name,i.category||["toolbar"]);x(this,"_plugins",[]);x(this,"_nodes",[]);x(this,"_initialize");i.config&&(this.config={...this.config,...i.config}),this._initialize=i.initialize,i.supportedFormats&&(this.supportedFormats=i.supportedFormats),i.nodes&&(this._nodes=i.nodes),i.plugins&&(this._plugins=i.plugins);}register(e){let t=this._initialize?.(e);return ()=>{typeof t=="function"&&t();}}getNodes(){return this._nodes}getPlugins(){return this._plugins}getCommands(e){return i.commands?i.commands(e):{}}getStateQueries(e){return i.stateQueries?i.stateQueries(e):{}}}}function Bs(i){i.update(()=>{$setSelection(null);});}function zs(i,n){let e=n.getAttribute("data-lexical-node-key")?.trim();if(e)return e;let t=null;return i.read(()=>{let o=$getNearestNodeFromDOMNode(n);if($isLinkNode(o)){t=o.getKey();return}let r=n.firstChild;if(!r)return;let s=$getNearestNodeFromDOMNode(r);if($isLinkNode(s)){t=s.getKey();return}let a=s?.getParent();a&&$isLinkNode(a)&&(t=a.getKey());}),t}var oe=class extends w{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 Ie=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 s=e.getAttribute("width"),a=e.getAttribute("height"),l=s?Number(s):void 0,d=a?Number(a):void 0;try{return {node:$e(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,s=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:$e(t.src,t.alt||"",r,s,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:s,style:a,width:l,height:d,uploading:c}=n;if(!e||e.length===0)throw new Error("Cannot import ImageNode with empty src");return $e(e,t,o,r,s,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:Vm,exportDOM:qm,importJSON:Wm,exportJSON:Jm}=Ie;var pr=createCommand("insert-image"),Er=Gs,so=true,ao=false,hr=50,br=50,yr=2400,xr=2400;function Kt(i,n,e){return Math.min(e,Math.max(n,Math.round(i)))}function Gs({src:i,alt:n,caption:e,alignment:t="none",className:o="",style:r,nodeKey:s,width:a,height:l,resizable:d=true,scaleByRatio:c=false,uploading:u=false}){let[m]=useLexicalComposerContext(),h=useRef(null),N=useRef(null),v=useRef(null),y=useRef(0),f=useRef(0),[p,g]=useState(false),[E,T]=useState(false),[b,S]=useState(a||"auto"),[M,B]=useState(l||"auto");useEffect(()=>()=>{i&&i.startsWith("blob:")&&URL.revokeObjectURL(i);},[i]),useEffect(()=>{S(a||"auto"),B(l||"auto"),y.current=typeof a=="number"?a:0,f.current=typeof l=="number"?l:0;},[a,l]),useEffect(()=>()=>{v.current!=null&&window.cancelAnimationFrame(v.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>{if(s)return m.registerUpdateListener(({editorState:P})=>{P.read(()=>{let Y=$getSelection();if($isNodeSelection(Y)){let K=Y.getNodes();g(K.some(J=>J.getKey()===s));}else g(false);});})},[m,s]);let j=P=>{P.preventDefault(),P.stopPropagation(),s&&m.update(()=>{let Y=$createNodeSelection();Y.add(s),$setSelection(Y);});},_=P=>Y=>{if(!h.current||!s)return;Y.preventDefault(),Y.stopPropagation(),T(true),document.body.style.userSelect="none",document.body.style.cursor=P==="width"?"ew-resize":"ns-resize";let K=Y.clientX,J=Y.clientY,V=h.current.clientWidth||(typeof b=="number"?b:100),te=h.current.clientHeight||(typeof M=="number"?M:100),Te=Number.isFinite(V)&&Number.isFinite(te)&&V>0&&te>0?V/te:null;y.current=V,f.current=te;let Fe=()=>{v.current=null,N.current&&(N.current.style.width=`${y.current}px`),h.current&&(h.current.style.height=`${f.current}px`);},Le=ge=>{let we=!!Te&&(c?!ge.shiftKey:ge.shiftKey),fe=P==="width"?Kt(V+(ge.clientX-K),hr,yr):y.current,Ge=P==="height"?Kt(te+(ge.clientY-J),br,xr):f.current;we&&Te&&(P==="width"?Ge=Kt(fe/Te,br,xr):fe=Kt(Ge*Te,hr,yr)),y.current=fe,f.current=Ge,v.current==null&&(v.current=window.requestAnimationFrame(Fe));},se=()=>{v.current!=null&&(window.cancelAnimationFrame(v.current),v.current=null),T(false),S(y.current),B(f.current),m.update(()=>{let ge=$getNodeByKey(s);ge instanceof $&&ge.setWidthAndHeight(y.current,f.current);}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",Le),document.removeEventListener("mouseup",se);};document.addEventListener("mousemove",Le),document.addEventListener("mouseup",se);},q={margin:0,display:"block",position:"relative",...r},z={maxWidth:"100%",display:"block",borderRadius:"4px",width:typeof b=="number"?"100%":"auto",height:typeof M=="number"?`${M}px`:M,margin:0},F={fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"},A=p&&d&&!E;return jsxs("figure",{className:`lexical-image align-${t} ${o} ${p?"selected":""} ${E?"resizing":""} ${u?"uploading":""}`,style:q,children:[jsxs("div",{ref:N,className:`luthor-media-embed-shell${p?" is-selected":""}${E?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{position:"relative",display:"inline-block",width:b,maxWidth:"100%",cursor:"pointer"},onClick:j,children:[jsx("img",{ref:h,src:i,alt:n,style:z}),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:_("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:_("height")})]}):null]}),e&&jsx("figcaption",{style:F,children:e}),jsx("div",{style:{clear:"both",height:0,fontSize:0}})]})}var $=class i extends DecoratorNode{constructor(e="",t="",o,r="none",s,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=s,this.__style=a,this.__width=l,this.__height=d,this.__uploading=c;}static getType(){return "image"}static clone(e){return new i(e.__src,e.__alt,e.__caption,e.__alignment,e.__className,e.__style,e.__width,e.__height,e.__uploading,e.__key)}static importDOM(){return Ie.importDOM()}static importJSON(e){return Ie.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 s=o.theme?.image||"";t.className=`${s} 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 Ie.exportDOM(this)}exportJSON(){return Ie.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(Er,{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:so,scaleByRatio:ao,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 $e(i,n,e,t="none",o,r,s,a,l){if(!i||i.length===0)throw new Error("Cannot create ImageNode with empty src");return new $(i,n,e,t,o,r,s,a,l)}var Yt=class extends w{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},so=true,ao=false;}configure(e){e.customRenderer&&(Er=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,so=t.resizable??true,ao=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 $);c&&(this.lastSelectedImageNodeKey=c.getKey());});}),o=e.registerCommand(pr,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(h=>{e.update(()=>{let N=$getNodeByKey(u.getKey());N instanceof $&&(N.setSrc(h),N.__uploading=!1);});}).catch(h=>{console.error("Upload failed:",h),e.update(()=>{let N=$getNodeByKey(u.getKey());N instanceof $&&(N.__uploading=!1);});}));let u=$e(d,l.alt,l.caption,l.alignment||this.config.defaultAlignment||"none",l.className,l.style,void 0,void 0,c),m=$getSelection();if($isRangeSelection(m))m.insertNodes([u]);else {let h=$createParagraphNode();h.append(u),$getRoot().append(h);}}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 $))return e.update(()=>{d.forEach(c=>c.remove());}),true}return false},COMMAND_PRIORITY_EDITOR),s=e.registerCommand(KEY_BACKSPACE_COMMAND,()=>{let l=$getSelection();if($isNodeSelection(l)){let d=l.getNodes();if(d.some(c=>c instanceof $))return e.update(()=>{d.forEach(c=>c.remove());}),true}return false},COMMAND_PRIORITY_EDITOR),a=()=>{};if(this.config.pasteListener?.insert||this.config.pasteListener?.replace){let l=this.config.debug?console.log:()=>{};a=e.registerCommand(PASTE_COMMAND,d=>{let c=d.clipboardData?.items;if(!c)return false;let u=false,m=Array.from(c).some(h=>h.type==="text/html");for(let h of c)if(h.type.startsWith("image/")){if(m)continue;d.preventDefault();let N=h.getAsFile();if(!N)continue;l("\u{1F4CB} Pasting image:",N.name),(this.config.uploadHandler&&this.config.forceUpload?this.config.uploadHandler(N).catch(y=>(console.error("Upload failed:",y),URL.createObjectURL(N))):Promise.resolve(URL.createObjectURL(N))).then(y=>{if(this.recentImages.has(y)){l("\u{1F6AB} Duplicate paste image src detected, skipping:",y);return}this.recentImages.add(y),setTimeout(()=>this.recentImages.delete(y),1e3);let f=false,p;this.config.uploadHandler&&this.config.forceUpload&&N&&(f=true,this.config.uploadHandler(N).then(g=>{e.update(()=>{let E=$getNodeByKey(p.getKey());E instanceof $&&(E.setSrc(g),E.__uploading=false);});}).catch(g=>{console.error("Upload failed:",g),e.update(()=>{let E=$getNodeByKey(p.getKey());E instanceof $&&(E.__uploading=false);});})),e.update(()=>{let g=$getSelection(),E=N.name||"Pasted image";if($isNodeSelection(g)&&this.config.pasteListener?.replace){let b=g.getNodes().find(S=>S instanceof $);if(b){l("\u{1F504} Replacing selected image src"),b.setSrc(y),b.__uploading=f,u=true;return}}this.config.pasteListener?.insert&&(l("\u2795 Inserting new pasted image"),p=$e(y,E,void 0,"none",void 0,void 0,void 0,void 0,f),$isRangeSelection(g)?g.insertNodes([p]):$getRoot().append($createParagraphNode().append(p)),u=true);});});break}return u},COMMAND_PRIORITY_NORMAL);}return ()=>{t(),o(),r(),s(),a();}}getNodes(){return [$]}getCommands(e){return {insertImage:t=>{e.dispatchCommand(pr,t);},setImageAlignment:t=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof $&&s.setAlignment(t);}});},setImageCaption:t=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof $&&s.setCaption(t);return}if(this.lastSelectedImageNodeKey){let r=$getNodeByKey(this.lastSelectedImageNodeKey);r instanceof $?r.setCaption(t):this.lastSelectedImageNodeKey=null;}});},getImageCaption:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes().find(s=>s instanceof $);if(r){t(r.__caption??"");return}}if(this.lastSelectedImageNodeKey){let r=$getNodeByKey(this.lastSelectedImageNodeKey);if(r instanceof $){t(r.__caption??"");return}}t("");});}),setImageClassName:t=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof $&&s.setClassName(t);}});},setImageStyle:t=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof $&&s.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 $);}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 $){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 $){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 $){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 $){t(r[0].__alignment==="none");return}}t(false);});})}}},Zs=new Yt,Cr={dependencies:[$],export:i=>{if(!ea(i))return null;let n=i,e=n.__src||"",t=n.__alt||"",o=n.__caption||"",r=n.__alignment||"none";if(!e)return null;let s=`,s+=")",r!=="none"&&(s+=` <!-- align:${r} -->`),s},regExp:/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)(?:\s*<!--\s*align:(left|center|right)\s*-->)?\s*$/,replace:(i,n,e,t)=>{let[,o,r,s,a]=e;if(!r)return;let l=$e(r,o||"",s||void 0,a||"none",void 0,void 0,void 0,void 0,false);i.replace(l);},type:"element"};function ea(i){return i instanceof $}function ca(i){let n=i.trim();return /^https?:\/\//i.test(n)?n:`https://${n}`}function vr(i){try{let n=new URL(ca(i.trim()));return n.protocol!=="http:"&&n.protocol!=="https:"||!n.hostname?null:n}catch{return null}}function ke(i,n,e){return Math.min(e,Math.max(n,Math.round(i)))}function da(i){return i==="center"?{margin:"1rem auto",width:"fit-content",maxWidth:"100%"}:i==="left"?{margin:"1rem auto 1rem 0",width:"fit-content",maxWidth:"100%"}:{margin:"1rem 0 1rem auto",width:"fit-content",maxWidth:"100%"}}var bt=240,yt=140,xt=1600,Et=1200,re=class i extends DecoratorNode{constructor(e,t){super(t);x(this,"__payload");this.__payload=e;}static getType(){return "iframe-embed"}static clone(e){return new i(e.__payload,e.__key)}static importJSON(e){return new i({src:e.src,width:ke(e.width,bt,xt),height:ke(e.height,yt,Et),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")??"",s=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 i({src:r,width:ke(s,bt,xt),height:ke(a,yt,Et),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(ua,{nodeKey:this.__key,payload:this.__payload})}isInline(){return false}isKeyboardSelectable(){return true}};function ua({nodeKey:i,payload:n}){let[e]=useLexicalComposerContext(),[t,o]=useState(false),[r,s]=useState(false),[a,l]=useState(n.width),[d,c]=useState(n.height),u=useRef(n.width),m=useRef(n.height),h=useRef(null),N=useRef(null),v=useRef(null);useEffect(()=>{l(n.width),c(n.height),u.current=n.width,m.current=n.height;},[n.width,n.height]),useEffect(()=>()=>{v.current!=null&&window.cancelAnimationFrame(v.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>e.registerUpdateListener(({editorState:b})=>{b.read(()=>{let S=$getSelection();if(!$isNodeSelection(S)){o(false);return}let M=S.getNodes().some(B=>B.getKey()===i);o(M);});}),[e,i]);let y=b=>{e.update(()=>{let S=$getNodeByKey(i);S instanceof re&&S.setPayload(b);});},f=b=>{b.preventDefault(),b.stopPropagation(),e.update(()=>{let S=$createNodeSelection();S.add(i),$setSelection(S);});},p=b=>S=>{if(S.preventDefault(),S.stopPropagation(),!h.current)return;let B=S.clientX,j=S.clientY,_=a,q=d;document.body.style.userSelect="none",document.body.style.cursor=b==="width"?"ew-resize":"ns-resize",s(true);let z=()=>{v.current=null,h.current&&(h.current.style.width=`${u.current}px`),N.current&&(N.current.style.height=`${m.current}px`);},F=P=>{let Y=b==="width"?ke(_+(P.clientX-B),bt,xt):u.current,K=b==="height"?ke(q+(P.clientY-j),yt,Et):m.current;u.current=Y,m.current=K,v.current==null&&(v.current=window.requestAnimationFrame(z));},A=()=>{v.current!=null&&(window.cancelAnimationFrame(v.current),v.current=null),s(false),l(u.current),c(m.current),y({width:u.current,height:m.current}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",F),document.removeEventListener("mouseup",A);};document.addEventListener("mousemove",F),document.addEventListener("mouseup",A);},g=useMemo(()=>da(n.alignment),[n.alignment]),E=useMemo(()=>({marginTop:"0.5rem",textAlign:"center",color:"#666",fontSize:"0.9em",fontStyle:"italic"}),[]),T=t&&!r;return jsxs("div",{style:g,children:[jsxs("div",{ref:h,className:`luthor-media-embed-shell${t?" is-selected":""}${r?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{width:a,maxWidth:"100%"},onClick:f,children:[jsx("iframe",{ref:N,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":!T,tabIndex:T?0:-1,style:{opacity:T?1:0,pointerEvents:T?"auto":"none"},onMouseDown:p("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize iframe height","aria-hidden":!T,tabIndex:T?0:-1,style:{opacity:T?1:0,pointerEvents:T?"auto":"none"},onMouseDown:p("height")})]}),n.caption?jsx("figcaption",{style:E,children:n.caption}):null]})}var qt=class extends w{constructor(n){super("iframeEmbed",["toolbar"]),this.config={defaultWidth:640,defaultHeight:360,defaultAlignment:"center",...n};}register(n){return ()=>{}}getNodes(){return [re]}getPlugins(){return []}getCommands(n){return {insertIframeEmbed:(e,t,o,r)=>{let s=vr(e);s&&n.update(()=>{let a=new re({src:s.toString(),width:ke(t??this.config.defaultWidth??640,bt,xt),height:ke(o??this.config.defaultHeight??360,yt,Et),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 re&&o.setPayload({alignment:e});});});},resizeIframeEmbed:(e,t)=>{n.update(()=>{let o=$getSelection();$isNodeSelection(o)&&o.getNodes().forEach(r=>{r instanceof re&&r.setPayload({width:ke(e,bt,xt),height:ke(t,yt,Et)});});});},setIframeEmbedCaption:e=>{n.update(()=>{let t=$getSelection();$isNodeSelection(t)&&t.getNodes().forEach(o=>{o instanceof re&&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 re);e(o?.getPayload().caption??"");});}),updateIframeEmbedUrl:e=>{let t=vr(e);if(!t)return false;let o=false;return n.update(()=>{let r=$getSelection();$isNodeSelection(r)&&r.getNodes().forEach(s=>{s instanceof re&&(s.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 re);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 re));});}),isIframeEmbedAlignedLeft:()=>new Promise(e=>{n.getEditorState().read(()=>{let t=$getSelection();if(!$isNodeSelection(t)){e(false);return}let o=t.getNodes().find(r=>r instanceof re);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 re);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 re);e(o?.getPayload().alignment==="right");});})}}},ma=new qt;var et=240,tt=140,nt=1600,ot=1200;function be(i,n,e){return Math.min(e,Math.max(n,Math.round(i)))}function xa(i){return i==="center"?{margin:"1rem auto",width:"fit-content",maxWidth:"100%"}:i==="left"?{margin:"1rem auto 1rem 0",width:"fit-content",maxWidth:"100%"}:{margin:"1rem 0 1rem auto",width:"fit-content",maxWidth:"100%"}}function Ea(i){let n=i.trim();return /^https?:\/\//i.test(n)?n:`https://${n}`}function uo(i){try{return new URL(Ea(i))}catch{return null}}function Rr(i){return /^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/.*)?$/i.test(i)}function Se(i){return typeof i=="string"&&/^[A-Za-z0-9_-]{3,}$/.test(i)}function kr(i){let n=i.hostname.toLowerCase(),e=i.pathname;if(n==="youtu.be"){let r=e.split("/").filter(Boolean)[0];return Se(r)?{videoId:r}:null}if(e==="/playlist"){let r=i.searchParams.get("list");return Se(r)?{playlistId:r}:null}if(e.startsWith("/shorts/")){let r=e.split("/")[2];return Se(r)?{videoId:r}:null}if(e.startsWith("/embed/")){let r=e.split("/")[2];if(!r)return null;if(r==="videoseries"){let s=i.searchParams.get("list");return Se(s)?{playlistId:s}:null}return Se(r)?{videoId:r}:null}if(e==="/watch"){let r=i.searchParams.get("list"),s=i.searchParams.get("v"),a={};return Se(s)&&(a.videoId=s),Se(r)&&(a.playlistId=r),a.videoId||a.playlistId?a:null}let t=i.searchParams.get("v"),o=i.searchParams.get("list");return Se(t)||Se(o)?{videoId:Se(t)?t:void 0,playlistId:Se(o)?o:void 0}:null}function Ca(i,n){if(!Rr(i))return null;let e=uo(i);if(!e)return null;if(e.pathname.includes("/embed/"))return e.toString();let t=kr(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 s=[];if(n.allowFullscreen||s.push("fs=0"),n.autoplay&&s.push("autoplay=1"),n.controls||s.push("controls=0"),n.rel!==1&&s.push(`rel=${n.rel}`),n.start>0&&s.push(`start=${Math.max(0,Math.floor(n.start))}`),s.length===0)return r;let a=r.includes("?")?"&":"?";return `${r}${a}${s.join("&")}`}function Lr(i,n){let e=uo(i);if(!e||!Rr(n))return null;let t=uo(n);if(!t)return null;let o=kr(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 W=class i extends DecoratorNode{constructor(e,t){super(t);x(this,"__payload");this.__payload=e;}static getType(){return "youtube-embed"}static clone(e){return new i(e.__payload,e.__key)}static importJSON(e){return new i({src:e.src,width:be(e.width,et,nt),height:be(e.height,tt,ot),alignment:e.alignment,caption:e.caption??"",start:e.start})}static importDOM(){return {div:e=>e.hasAttribute("data-lexical-youtube-embed")||e.hasAttribute("data-youtube-video")?{conversion:o=>{let r=o.querySelector("iframe");if(!r)return {node:null};let s=r.getAttribute("src")??"",a=Number(r.getAttribute("width")??"640"),l=Number(r.getAttribute("height")??"480"),d=o.getAttribute("data-align")??"center",u=o.querySelector("figcaption")?.textContent??o.getAttribute("data-caption")??"",m=Number(r.getAttribute("data-start")??"0");return {node:new i({src:s,width:be(a,et,nt),height:be(l,tt,ot),alignment:d,caption:u,start:Number.isFinite(m)?m:0})}},priority:4}:null,figure:e=>e.hasAttribute("data-lexical-youtube-embed")||e.hasAttribute("data-youtube-video")?{conversion:o=>{let r=o.querySelector("iframe");if(!r)return {node:null};let s=r.getAttribute("src")??"",a=Number(r.getAttribute("width")??"640"),l=Number(r.getAttribute("height")??"480"),d=o.getAttribute("data-align")??"center",u=o.querySelector("figcaption")?.textContent??o.getAttribute("data-caption")??"",m=Number(r.getAttribute("data-start")??"0");return {node:new i({src:s,width:be(a,et,nt),height:be(l,tt,ot),alignment:d,caption:u,start:Number.isFinite(m)?m:0})}},priority:4}:null}}createDOM(){let e=document.createElement("div");return e.setAttribute("data-lexical-youtube-embed","true"),e}updateDOM(){return false}exportJSON(){return {type:"youtube-embed",version:1,src:this.__payload.src,width:this.__payload.width,height:this.__payload.height,alignment:this.__payload.alignment,caption:this.__payload.caption,start:this.__payload.start}}exportDOM(){let e=document.createElement("figure");e.setAttribute("data-lexical-youtube-embed","true"),e.setAttribute("data-youtube-video",""),e.setAttribute("data-align",this.__payload.alignment),e.setAttribute("data-caption",this.__payload.caption??"");let 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(Sa,{nodeKey:this.__key,payload:this.__payload})}isInline(){return false}isKeyboardSelectable(){return true}};function Sa({nodeKey:i,payload:n}){let[e]=useLexicalComposerContext(),[t,o]=useState(false),[r,s]=useState(false),[a,l]=useState(n.width),[d,c]=useState(n.height),u=useRef(n.width),m=useRef(n.height),h=useRef(null),N=useRef(null),v=useRef(null);useEffect(()=>{l(n.width),c(n.height),u.current=n.width,m.current=n.height;},[n.width,n.height]),useEffect(()=>()=>{v.current!=null&&window.cancelAnimationFrame(v.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>e.registerUpdateListener(({editorState:b})=>{b.read(()=>{let S=$getSelection();if(!$isNodeSelection(S)){o(false);return}let M=S.getNodes().some(B=>B.getKey()===i);o(M);});}),[e,i]);let y=b=>{e.update(()=>{let S=$getNodeByKey(i);S instanceof W&&S.setPayload(b);});},f=b=>{b.preventDefault(),b.stopPropagation(),e.update(()=>{let S=$createNodeSelection();S.add(i),$setSelection(S);});},p=b=>S=>{if(S.preventDefault(),S.stopPropagation(),!h.current)return;let B=S.clientX,j=S.clientY,_=a,q=d;document.body.style.userSelect="none",document.body.style.cursor=b==="width"?"ew-resize":"ns-resize",s(true);let z=()=>{v.current=null,h.current&&(h.current.style.width=`${u.current}px`),N.current&&(N.current.style.height=`${m.current}px`);},F=P=>{let Y=b==="width"?be(_+(P.clientX-B),et,nt):u.current,K=b==="height"?be(q+(P.clientY-j),tt,ot):m.current;u.current=Y,m.current=K,v.current==null&&(v.current=window.requestAnimationFrame(z));},A=()=>{v.current!=null&&(window.cancelAnimationFrame(v.current),v.current=null),s(false),l(u.current),c(m.current),y({width:u.current,height:m.current}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",F),document.removeEventListener("mouseup",A);};document.addEventListener("mousemove",F),document.addEventListener("mouseup",A);},g=useMemo(()=>xa(n.alignment),[n.alignment]),E=t&&!r,T=useMemo(()=>({fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"}),[]);return jsxs("div",{style:g,children:[jsxs("div",{ref:h,className:`luthor-media-embed-shell${t?" is-selected":""}${r?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{width:a,maxWidth:"100%"},onClick:f,children:[jsx("iframe",{ref:N,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":!E,tabIndex:E?0:-1,style:{opacity:E?1:0,pointerEvents:E?"auto":"none"},onMouseDown:p("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize YouTube embed height","aria-hidden":!E,tabIndex:E?0:-1,style:{opacity:E?1:0,pointerEvents:E?"auto":"none"},onMouseDown:p("height")})]}),n.caption?jsx("figcaption",{style:T,children:n.caption}):null]})}var Jt=class extends w{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(s=>s instanceof W);r&&(this.lastSelectedYouTubeNodeKey=r.getKey());});})}getNodes(){return [W]}getPlugins(){return []}getCommands(e){return {insertYouTubeEmbed:(t,o,r,s)=>{let a=Ca(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(s??0))});a&&e.update(()=>{let l=new W({src:a,width:be(o??this.config.defaultWidth??640,et,nt),height:be(r??this.config.defaultHeight??480,tt,ot),alignment:this.config.defaultAlignment??"center",caption:"",start:s}),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 W&&r.setPayload({alignment:t});});});},resizeYouTubeEmbed:(t,o)=>{e.update(()=>{let r=$getSelection();$isNodeSelection(r)&&r.getNodes().forEach(s=>{s instanceof W&&s.setPayload({width:be(t,et,nt),height:be(o,tt,ot)});});});},setYouTubeEmbedCaption:t=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){o.getNodes().forEach(r=>{r instanceof W&&r.setPayload({caption:t});});return}if(this.lastSelectedYouTubeNodeKey){let r=$getNodeByKey(this.lastSelectedYouTubeNodeKey);r instanceof W?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(s=>s instanceof W);if(r){t(r.getPayload().caption??"");return}}if(this.lastSelectedYouTubeNodeKey){let r=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(r instanceof W){t(r.getPayload().caption??"");return}}t("");});}),updateYouTubeEmbedUrl:t=>{let o=false;return e.update(()=>{let r=$getSelection();if($isNodeSelection(r)){r.getNodes().forEach(s=>{if(s instanceof W){let a=Lr(s.getPayload().src,t);if(!a)return;s.setPayload({src:a}),o=true;}});return}if(this.lastSelectedYouTubeNodeKey){let s=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(s instanceof W){let a=Lr(s.getPayload().src,t);a&&(s.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(s=>s instanceof W);if(r){t(r.getPayload().src??"");return}}if(this.lastSelectedYouTubeNodeKey){let r=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(r instanceof W){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 W));});}),isYouTubeEmbedAlignedLeft:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){t(false);return}let r=o.getNodes().find(s=>s instanceof W);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(s=>s instanceof W);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(s=>s instanceof W);t(r?.getPayload().alignment==="right");});})}}},va=new Jt;var Na="luthor:meta";var Ta=/<!--\s*luthor:meta\s+v(\d+)\s+({[\s\S]*?})\s*-->/g;function rt(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function Nt(i){return JSON.parse(JSON.stringify(i))}function go(i){return {type:"text",version:1,text:i,detail:0,format:0,mode:"normal",style:""}}function mo(i){return {type:"paragraph",version:1,format:"",indent:0,direction:null,children:[go(i)]}}function La(i){return {type:"listitem",version:1,value:1,checked:null,indent:0,direction:null,format:"",children:[go(i)]}}function wa(i,n){return `[Unsupported ${n} preserved in ${i} metadata]`}function Ra(i,n,e){let t=n.length>0?n.join("."):"root";return `${i}:${t}:${e}`}function ka(i,n){return i==="root"||i==="quote"?mo(n):i==="list"?La(n):i==="paragraph"||i==="heading"||i==="listitem"||i==="link"||i==="autolink"||i==="code"||i==="code-highlight"?go(n):mo(n)}function Pr(i,n,e,t,o,r){let s=[];for(let[a,l]of i.entries()){if(!rt(l))continue;let d=[...e,a],c=typeof l.type=="string"?l.type:"";if(!o.has(c)){let m=wa(t,c||"node"),h={id:Ra(c||"node",d,r.length+1),type:c||"node",path:d,node:Nt(l),fallback:m};r.push(h),s.push(ka(n,m));continue}let u={...l};Array.isArray(l.children)&&(u.children=Pr(l.children,c,d,t,o,r)),s.push(u);}return s}function Pa(){return {type:"root",version:1,format:"",indent:0,direction:null,children:[mo("")]}}function Ma(i){let n=typeof i=="string"?JSON.parse(i):i;if(!rt(n)||!rt(n.root))return {root:Pa()};let e=n.root,t=Array.isArray(e.children)?e.children:[];return {root:{...e,type:"root",children:t}}}function Oa(i,n,e){if(n.length===0)return false;let t=i;for(let r of n.slice(0,-1)){if(!Array.isArray(t.children)||r<0||r>=t.children.length)return false;let s=t.children[r];if(!rt(s))return false;t=s;}let o=n[n.length-1];return typeof o!="number"||!Array.isArray(t.children)||o<0?false:o<t.children.length?(t.children[o]=Nt(e),true):o===t.children.length?(t.children.push(Nt(e)),true):false}function Tt(i,n){let e=Ma(i),t=Array.isArray(e.root.children)?e.root.children:[],o=[],r=Pr(t,"root",[],n.mode,n.supportedNodeTypes,o);return {document:{root:{...e.root,type:"root",children:r}},envelopes:o}}function Lt(i,n){if(n.length===0)return i;let t=n.map(o=>{let r=JSON.stringify(o);return `<!-- ${Na} v1 ${r} -->`}).join(`
|
|
1
|
+
import Qt,{createContext,createElement,useRef,useState,useEffect,useMemo,useCallback,useContext}from'react';import {LexicalComposer}from'@lexical/react/LexicalComposer';import {useLexicalComposerContext}from'@lexical/react/LexicalComposerContext';import {createCommand,$getSelection,$isNodeSelection,$getNodeByKey,$isRangeSelection,$createParagraphNode,$getRoot,COMMAND_PRIORITY_EDITOR,KEY_DELETE_COMMAND,KEY_BACKSPACE_COMMAND,PASTE_COMMAND,COMMAND_PRIORITY_NORMAL,DecoratorNode,$createTextNode,KEY_ENTER_COMMAND,$isTextNode,$isParagraphNode,$isRootOrShadowRoot,COMMAND_PRIORITY_LOW,$isElementNode,KEY_SPACE_COMMAND,INDENT_CONTENT_COMMAND,OUTDENT_CONTENT_COMMAND,KEY_TAB_COMMAND,$nodesOfType,INSERT_PARAGRAPH_COMMAND,ParagraphNode,FORMAT_ELEMENT_COMMAND,CAN_UNDO_COMMAND,CAN_REDO_COMMAND,CLEAR_HISTORY_COMMAND,REDO_COMMAND,UNDO_COMMAND,INSERT_LINE_BREAK_COMMAND,FORMAT_TEXT_COMMAND,$getNearestNodeFromDOMNode,$createNodeSelection,$setSelection,createEditor,TextNode,LineBreakNode,TabNode,ElementNode}from'lexical';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {$createLinkNode,TOGGLE_LINK_COMMAND,$isLinkNode,LinkNode,AutoLinkNode}from'@lexical/link';import {TRANSFORMERS,registerMarkdownShortcuts,$convertFromMarkdownString,$convertToMarkdownString}from'@lexical/markdown';import {ListNode,ListItemNode,$isListNode,INSERT_CHECK_LIST_COMMAND,INSERT_UNORDERED_LIST_COMMAND,INSERT_ORDERED_LIST_COMMAND,$isListItemNode,$getListDepth}from'@lexical/list';import {$isHeadingNode,$isQuoteNode,HeadingNode,QuoteNode,$createQuoteNode,$createHeadingNode}from'@lexical/rich-text';import {CodeNode,CodeHighlightNode,$createCodeNode,$isCodeNode,registerCodeHighlighting,PrismTokenizer,normalizeCodeLang,getCodeLanguageOptions,getCodeLanguages}from'@lexical/code';import {$generateNodesFromDOM,$generateHtmlFromNodes}from'@lexical/html';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 {$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 {ListPlugin}from'@lexical/react/LexicalListPlugin';import {CheckListPlugin}from'@lexical/react/LexicalCheckListPlugin';import {HistoryPlugin}from'@lexical/react/LexicalHistoryPlugin';import {renderToStaticMarkup}from'react-dom/server';import {RichTextPlugin}from'@lexical/react/LexicalRichTextPlugin';import {ContentEditable}from'@lexical/react/LexicalContentEditable';var Ps=Object.defineProperty;var Ms=(i,n,e)=>n in i?Ps(i,n,{enumerable:true,configurable:true,writable:true,value:e}):i[n]=e;var C=(i,n,e)=>Ms(i,typeof n!="symbol"?n+"":n,e);var gr=["--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 Os(i){return typeof i=="string"&&i.trim().length>0}function Is(i){if(!i)return;let n={};for(let e of gr){let t=i[e];Os(t)&&(n[e]=t);}return Object.keys(n).length>0?n:void 0}var $e={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 _s(i,n){return {...i,...n,text:{...i.text,...n.text},list:{...i.list,...n.list,nested:{...i.list?.nested,...n.list?.nested}},heading:{...i.heading,...n.heading},codeHighlight:{...i.codeHighlight,...n.codeHighlight},toolbar:{...i.toolbar,...n.toolbar},draggable:{...i.draggable,...n.draggable,styles:{...i.draggable?.styles,...n.draggable?.styles}},floatingToolbar:{...i.floatingToolbar,...n.floatingToolbar,styles:{...i.floatingToolbar?.styles,...n.floatingToolbar?.styles}},richText:{...i.richText,...n.richText},styles:{toolbar:{...i.styles?.toolbar,...n.styles?.toolbar},draggable:{...i.styles?.draggable,...n.styles?.draggable},floatingToolbar:{...i.styles?.floatingToolbar,...n.styles?.floatingToolbar},...n.styles}}}function As(i){return i&&typeof i=="object"}var ht=createContext(null),co=class{constructor(){C(this,"warnedMethods",new Set);}add(n){this.warn("add",n.name);}remove(n){this.warn("remove",n);}reorder(n){this.warn("reorder",n.join(", "));}warn(n,e){this.warnedMethods.has(n)||(this.warnedMethods.add(n),console.warn(`[luthor-headless] extensionsAPI.${n}("${e}") is not supported at runtime. Pass an updated \`extensions\` array to <Provider /> instead.`));}},Us=new co;function hr(){function i(){let t=useContext(ht);if(!t)throw new Error("useEditor must be used within Provider");return t}function n({children:t,config:o={},extensions:r}){let[s]=useLexicalComposerContext(),a=useMemo(()=>({formatText:(p,h)=>s?.dispatchCommand(FORMAT_TEXT_COMMAND,p)}),[s]),l=useMemo(()=>{if(!s)return {};let p={};for(let h of r)Object.assign(p,h.getCommands(s));return p},[r,s]),d=useMemo(()=>({...a,...l}),[a,l]),{plugins:c,pluginsBefore:u,pluginsAfter:m}=useMemo(()=>{let p=[],h=[];for(let f of r){let y=f.getPlugins?.()||[];(f.config?.position||"before")==="after"?h.push(...y):p.push(...y);}return {plugins:[...p,...h],pluginsBefore:p,pluginsAfter:h}},[r]);useEffect(()=>{if(!s)return;let h=[...r].sort((f,y)=>{let b=f.config?.initPriority??0;return (y.config?.initPriority??0)-b}).map(f=>f.register(s));return ()=>h.forEach(f=>f&&f())},[s,r]);let g=useMemo(()=>{if(!s)return {};let p={};for(let h of r)h.getStateQueries&&Object.assign(p,h.getStateQueries(s));return p},[r,s]),[x,L]=useState(()=>{let p={};return Object.keys(g).forEach(h=>p[h]=false),p});useEffect(()=>{let p=Object.keys(g);L(h=>{let f={};for(let b of p){let v=h[b];f[b]=v??false;}if(Object.keys(h).length!==p.length)return f;for(let b of p)if(h[b]!==f[b])return f;return h});},[g]),useEffect(()=>{if(!s)return;let p=true,h=0,f=async()=>{let v=++h,E=Object.entries(g).map(async([A,Y])=>{try{let K=await Y();return [A,K]}catch{return [A,false]}}),T=await Promise.all(E);if(!p||v!==h)return;let O=Object.fromEntries(T);L(A=>{let Y=A,K=O,J=Object.keys(Y),B=Object.keys(K);if(J.length!==B.length)return O;for(let $ of B)if(Y[$]!==K[$])return O;return A});};f();let y=s.registerUpdateListener(()=>{f();}),b=r.map(v=>{let N=v;if(typeof N.onStateChange=="function")return N.onStateChange(()=>{f();})}).filter(v=>typeof v=="function");return ()=>{p=false,y(),b.forEach(v=>v());}},[s,g,r]);let w={editor:s,config:o,extensions:r,commands:d,activeStates:x,stateQueries:g,listeners:{registerUpdate:p=>s?.registerUpdateListener(p)||(()=>{}),registerPaste:p=>s?.registerCommand(PASTE_COMMAND,p,COMMAND_PRIORITY_EDITOR)||(()=>{})},export:{toJSON:()=>s?.getEditorState().toJSON()},import:{fromJSON:p=>{if(s&&(typeof p=="string"||typeof p=="object"&&p!==null)){s.setEditorState(s.parseEditorState(p));let h=d;typeof h.rehydrateListStyles=="function"&&queueMicrotask(()=>{h.rehydrateListStyles?.();});}}},lexical:s,extensionsAPI:Us,plugins:c,hasExtension:p=>r.some(h=>h.name===p)};return jsxs(ht.Provider,{value:w,children:[u,t,m]})}function e(t){let o=useMemo(()=>t.extensions.flatMap(a=>a.getNodes?.()||[]),[t.extensions]),r=useMemo(()=>({namespace:"modern-editor",theme:t.config?.theme||$e,onError:s=>{console.error("Lexical error:",s);},nodes:o}),[t.config?.theme,o]);return jsx(LexicalComposer,{initialConfig:r,children:jsx(n,{...t})})}return {Provider:e,useEditor:i}}var Ks=hr(),Qs=Ks.Provider,Oe=()=>{let i=useContext(ht);if(!i)throw new Error("useBaseEditor must be used within Provider");return i};var Vs=(o=>(o.Toolbar="toolbar",o.Sidebar="sidebar",o.ContextMenu="contextmenu",o.Floating="floating",o))(Vs||{});var k=class{constructor(n,e=["toolbar"]){C(this,"name");C(this,"category",["toolbar"]);C(this,"config",{});C(this,"supportedFormats",[]);C(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 qs(i){return new class extends k{constructor(){super(i.name,i.category||["toolbar"]);C(this,"_plugins",[]);C(this,"_nodes",[]);C(this,"_initialize");i.config&&(this.config={...this.config,...i.config}),this._initialize=i.initialize,i.supportedFormats&&(this.supportedFormats=i.supportedFormats),i.nodes&&(this._nodes=i.nodes),i.plugins&&(this._plugins=i.plugins);}register(e){let t=this._initialize?.(e);return ()=>{typeof t=="function"&&t();}}getNodes(){return this._nodes}getPlugins(){return this._plugins}getCommands(e){return i.commands?i.commands(e):{}}getStateQueries(e){return i.stateQueries?i.stateQueries(e):{}}}}function Xs(i){i.update(()=>{$setSelection(null);});}function Js(i,n){let e=n.getAttribute("data-lexical-node-key")?.trim();if(e)return e;let t=null;return i.read(()=>{let o=$getNearestNodeFromDOMNode(n);if($isLinkNode(o)){t=o.getKey();return}let r=n.firstChild;if(!r)return;let s=$getNearestNodeFromDOMNode(r);if($isLinkNode(s)){t=s.getKey();return}let a=s?.getParent();a&&$isLinkNode(a)&&(t=a.getKey());}),t}var re=class extends k{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 He=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 s=e.getAttribute("width"),a=e.getAttribute("height"),l=s?Number(s):void 0,d=a?Number(a):void 0;try{return {node:Ue(e.src,e.alt||"",r,o,e.className||void 0,this.extractStyleObject(e),Number.isFinite(l)?l:void 0,Number.isFinite(d)?d:void 0)}}catch{return null}}catch{return null}},priority:0}),figure:()=>({conversion: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,s=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:Ue(t.src,t.alt||"",r,s,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:s,style:a,width:l,height:d,uploading:c}=n;if(!e||e.length===0)throw new Error("Cannot import ImageNode with empty src");return Ue(e,t,o,r,s,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:sg,exportDOM:ag,importJSON:lg,exportJSON:cg}=He;var Nr=createCommand("insert-image"),kr=da,go=true,fo=false,Tr=50,Lr=50,wr=2400,Rr=2400;function Xt(i,n,e){return Math.min(e,Math.max(n,Math.round(i)))}function ca(i,n,e,t){return i&&t&&n&&!e}function da({src:i,alt:n,caption:e,alignment:t="none",className:o="",style:r,nodeKey:s,width:a,height:l,resizable:d=true,scaleByRatio:c=false,uploading:u=false}){let[m]=useLexicalComposerContext(),g=useRef(null),x=useRef(null),L=useRef(null),w=useRef(0),p=useRef(0),[h,f]=useState(false),[y,b]=useState(false),[v,N]=useState(()=>m.isEditable()),[E,T]=useState(a||"auto"),[O,A]=useState(l||"auto");useEffect(()=>()=>{i&&i.startsWith("blob:")&&URL.revokeObjectURL(i);},[i]),useEffect(()=>{T(a||"auto"),A(l||"auto"),w.current=typeof a=="number"?a:0,p.current=typeof l=="number"?l:0;},[a,l]),useEffect(()=>()=>{L.current!=null&&window.cancelAnimationFrame(L.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>m.registerEditableListener(I=>{N(I);}),[m]),useEffect(()=>{if(s)return m.registerUpdateListener(({editorState:I})=>{I.read(()=>{let U=$getSelection();if($isNodeSelection(U)){let X=U.getNodes();f(X.some(se=>se.getKey()===s));}else f(false);});})},[m,s]);let Y=I=>{v&&(I.preventDefault(),I.stopPropagation(),s&&m.update(()=>{let U=$createNodeSelection();U.add(s),$setSelection(U);}));},K=I=>U=>{if(!v||!g.current||!s)return;U.preventDefault(),U.stopPropagation(),b(true),document.body.style.userSelect="none",document.body.style.cursor=I==="width"?"ew-resize":"ns-resize";let X=U.clientX,se=U.clientY,j=g.current.clientWidth||(typeof E=="number"?E:100),ee=g.current.clientHeight||(typeof O=="number"?O:100),Ce=Number.isFinite(j)&&Number.isFinite(ee)&&j>0&&ee>0?j/ee:null;w.current=j,p.current=ee;let Ae=()=>{L.current=null,x.current&&(x.current.style.width=`${w.current}px`),g.current&&(g.current.style.height=`${p.current}px`);},De=Se=>{let we=!!Ce&&(c?!Se.shiftKey:Se.shiftKey),fe=I==="width"?Xt(j+(Se.clientX-X),Tr,wr):w.current,et=I==="height"?Xt(ee+(Se.clientY-se),Lr,Rr):p.current;we&&Ce&&(I==="width"?et=Xt(fe/Ce,Lr,Rr):fe=Xt(et*Ce,Tr,wr)),w.current=fe,p.current=et,L.current==null&&(L.current=window.requestAnimationFrame(Ae));},ge=()=>{L.current!=null&&(window.cancelAnimationFrame(L.current),L.current=null),b(false),T(w.current),A(p.current),m.update(()=>{let Se=$getNodeByKey(s);Se instanceof z&&Se.setWidthAndHeight(w.current,p.current);}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",De),document.removeEventListener("mouseup",ge);};document.addEventListener("mousemove",De),document.addEventListener("mouseup",ge);},J={margin:0,display:"block",position:"relative",...r},B={maxWidth:"100%",display:"block",borderRadius:"4px",width:typeof E=="number"?"100%":"auto",height:typeof O=="number"?`${O}px`:O,margin:0},$={fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"},Q=ca(v,h,y,d);return jsxs("figure",{className:`lexical-image align-${t} ${o} ${h?"selected":""} ${y?"resizing":""} ${u?"uploading":""}`,style:J,children:[jsxs("div",{ref:x,className:`luthor-media-embed-shell${h?" is-selected":""}${y?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{position:"relative",display:"inline-block",width:E,maxWidth:"100%",cursor:v?"pointer":"default"},onClick:v?Y:void 0,children:[jsx("img",{ref:g,src:i,alt:n,style:B}),d?jsxs(Fragment,{children:[jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize image width","aria-hidden":!Q,tabIndex:Q?0:-1,style:{opacity:Q?1:0,pointerEvents:Q?"auto":"none"},onMouseDown:K("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize image height","aria-hidden":!Q,tabIndex:Q?0:-1,style:{opacity:Q?1:0,pointerEvents:Q?"auto":"none"},onMouseDown:K("height")})]}):null]}),e&&jsx("figcaption",{style:$,children:e}),jsx("div",{style:{clear:"both",height:0,fontSize:0}})]})}var z=class i extends DecoratorNode{constructor(e="",t="",o,r="none",s,a,l,d,c,u){super(u);C(this,"__src");C(this,"__alt");C(this,"__caption");C(this,"__alignment");C(this,"__className");C(this,"__style");C(this,"__width");C(this,"__height");C(this,"__uploading");this.__src=e&&e.length>0?e:"",this.__alt=t,this.__caption=o,this.__alignment=r,this.__className=s,this.__style=a,this.__width=l,this.__height=d,this.__uploading=c;}static getType(){return "image"}static clone(e){return new i(e.__src,e.__alt,e.__caption,e.__alignment,e.__className,e.__style,e.__width,e.__height,e.__uploading,e.__key)}static importDOM(){return He.importDOM()}static importJSON(e){return He.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 s=o.theme?.image||"";t.className=`${s} 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 He.exportDOM(this)}exportJSON(){return He.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(kr,{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:go,scaleByRatio:fo,uploading:this.__uploading})}catch(e){return console.error("\u274C Error rendering ImageNode:",e),jsxs("div",{style:{color:"red",border:"1px solid red",padding:"10px",backgroundColor:"#ffe6e6"},children:["Image Error: ",String(e)]})}}};function Ue(i,n,e,t="none",o,r,s,a,l){if(!i||i.length===0)throw new Error("Cannot create ImageNode with empty src");return new z(i,n,e,t,o,r,s,a,l)}var Gt=class extends k{constructor(){super("image",["toolbar"]);C(this,"recentImages",new Set);C(this,"lastSelectedImageNodeKey",null);this.config={...this.config,resizable:true,scaleByRatio:false,pasteListener:{insert:true,replace:true},debug:false,forceUpload:false},go=true,fo=false;}configure(e){e.customRenderer&&(kr=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,go=t.resizable??true,fo=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 z);c&&(this.lastSelectedImageNodeKey=c.getKey());});}),o=e.registerCommand(Nr,l=>(e.update(()=>{try{let d=l.src||(l.file?URL.createObjectURL(l.file):"");if(!d)throw new Error("No src for image");if(this.recentImages.has(d))return !0;this.recentImages.add(d),setTimeout(()=>this.recentImages.delete(d),1e3);let c=!1;l.file&&this.config.uploadHandler&&this.config.forceUpload&&(c=!0,this.config.uploadHandler(l.file).then(g=>{e.update(()=>{let x=$getNodeByKey(u.getKey());x instanceof z&&(x.setSrc(g),x.__uploading=!1);});}).catch(g=>{console.error("Upload failed:",g),e.update(()=>{let x=$getNodeByKey(u.getKey());x instanceof z&&(x.__uploading=!1);});}));let u=Ue(d,l.alt,l.caption,l.alignment||this.config.defaultAlignment||"none",l.className,l.style,void 0,void 0,c),m=$getSelection();if($isRangeSelection(m))m.insertNodes([u]);else {let g=$createParagraphNode();g.append(u),$getRoot().append(g);}}catch(d){console.error("\u274C Insertion error:",d);}}),true),COMMAND_PRIORITY_EDITOR),r=e.registerCommand(KEY_DELETE_COMMAND,()=>{let l=$getSelection();if($isNodeSelection(l)){let d=l.getNodes();if(d.some(c=>c instanceof z))return e.update(()=>{d.forEach(c=>c.remove());}),true}return false},COMMAND_PRIORITY_EDITOR),s=e.registerCommand(KEY_BACKSPACE_COMMAND,()=>{let l=$getSelection();if($isNodeSelection(l)){let d=l.getNodes();if(d.some(c=>c instanceof z))return e.update(()=>{d.forEach(c=>c.remove());}),true}return false},COMMAND_PRIORITY_EDITOR),a=()=>{};if(this.config.pasteListener?.insert||this.config.pasteListener?.replace){let l=this.config.debug?console.log:()=>{};a=e.registerCommand(PASTE_COMMAND,d=>{let c=d.clipboardData?.items;if(!c)return false;let u=false,m=Array.from(c).some(g=>g.type==="text/html");for(let g of c)if(g.type.startsWith("image/")){if(m)continue;d.preventDefault();let x=g.getAsFile();if(!x)continue;l("\u{1F4CB} Pasting image:",x.name),(this.config.uploadHandler&&this.config.forceUpload?this.config.uploadHandler(x).catch(w=>(console.error("Upload failed:",w),URL.createObjectURL(x))):Promise.resolve(URL.createObjectURL(x))).then(w=>{if(this.recentImages.has(w)){l("\u{1F6AB} Duplicate paste image src detected, skipping:",w);return}this.recentImages.add(w),setTimeout(()=>this.recentImages.delete(w),1e3);let p=false,h;this.config.uploadHandler&&this.config.forceUpload&&x&&(p=true,this.config.uploadHandler(x).then(f=>{e.update(()=>{let y=$getNodeByKey(h.getKey());y instanceof z&&(y.setSrc(f),y.__uploading=false);});}).catch(f=>{console.error("Upload failed:",f),e.update(()=>{let y=$getNodeByKey(h.getKey());y instanceof z&&(y.__uploading=false);});})),e.update(()=>{let f=$getSelection(),y=x.name||"Pasted image";if($isNodeSelection(f)&&this.config.pasteListener?.replace){let v=f.getNodes().find(N=>N instanceof z);if(v){l("\u{1F504} Replacing selected image src"),v.setSrc(w),v.__uploading=p,u=true;return}}this.config.pasteListener?.insert&&(l("\u2795 Inserting new pasted image"),h=Ue(w,y,void 0,"none",void 0,void 0,void 0,void 0,p),$isRangeSelection(f)?f.insertNodes([h]):$getRoot().append($createParagraphNode().append(h)),u=true);});});break}return u},COMMAND_PRIORITY_NORMAL);}return ()=>{t(),o(),r(),s(),a();}}getNodes(){return [z]}getCommands(e){return {insertImage:t=>{e.dispatchCommand(Nr,t);},setImageAlignment:t=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof z&&s.setAlignment(t);}});},setImageCaption:t=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof z&&s.setCaption(t);return}if(this.lastSelectedImageNodeKey){let r=$getNodeByKey(this.lastSelectedImageNodeKey);r instanceof z?r.setCaption(t):this.lastSelectedImageNodeKey=null;}});},getImageCaption:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes().find(s=>s instanceof z);if(r){t(r.__caption??"");return}}if(this.lastSelectedImageNodeKey){let r=$getNodeByKey(this.lastSelectedImageNodeKey);if(r instanceof z){t(r.__caption??"");return}}t("");});}),setImageClassName:t=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof z&&s.setClassName(t);}});},setImageStyle:t=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){let r=o.getNodes();for(let s of r)s instanceof z&&s.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 z);}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 z){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 z){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 z){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 z){t(r[0].__alignment==="none");return}}t(false);});})}}},ua=new Gt,Pr={dependencies:[z],export:i=>{if(!ma(i))return null;let n=i,e=n.__src||"",t=n.__alt||"",o=n.__caption||"",r=n.__alignment||"none";if(!e)return null;let s=`,s+=")",r!=="none"&&(s+=` <!-- align:${r} -->`),s},regExp:/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)(?:\s*<!--\s*align:(left|center|right)\s*-->)?\s*$/,replace:(i,n,e,t)=>{let[,o,r,s,a]=e;if(!r)return;let l=Ue(r,o||"",s||void 0,a||"none",void 0,void 0,void 0,void 0,false);i.replace(l);},type:"element"};function ma(i){return i instanceof z}function po(i,n,e){return i&&n&&!e}function ho(i,n,e){return i?n&&!e?"auto":"none":"auto"}function Ca(i){let n=i.trim();return /^https?:\/\//i.test(n)?n:`https://${n}`}function Or(i){try{let n=new URL(Ca(i.trim()));return n.protocol!=="http:"&&n.protocol!=="https:"||!n.hostname?null:n}catch{return null}}function ke(i,n,e){return Math.min(e,Math.max(n,Math.round(i)))}function Sa(i){return i==="center"?{margin:"1rem auto",width:"fit-content",maxWidth:"100%"}:i==="left"?{margin:"1rem auto 1rem 0",width:"fit-content",maxWidth:"100%"}:{margin:"1rem 0 1rem auto",width:"fit-content",maxWidth:"100%"}}var vt=240,Nt=140,Tt=1600,Lt=1200,ie=class i extends DecoratorNode{constructor(e,t){super(t);C(this,"__payload");this.__payload=e;}static getType(){return "iframe-embed"}static clone(e){return new i(e.__payload,e.__key)}static importJSON(e){return new i({src:e.src,width:ke(e.width,vt,Tt),height:ke(e.height,Nt,Lt),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")??"",s=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 i({src:r,width:ke(s,vt,Tt),height:ke(a,Nt,Lt),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(va,{nodeKey:this.__key,payload:this.__payload})}isInline(){return false}isKeyboardSelectable(){return true}};function va({nodeKey:i,payload:n}){let[e]=useLexicalComposerContext(),[t,o]=useState(()=>e.isEditable()),[r,s]=useState(false),[a,l]=useState(false),[d,c]=useState(n.width),[u,m]=useState(n.height),g=useRef(n.width),x=useRef(n.height),L=useRef(null),w=useRef(null),p=useRef(null);useEffect(()=>{c(n.width),m(n.height),g.current=n.width,x.current=n.height;},[n.width,n.height]),useEffect(()=>()=>{p.current!=null&&window.cancelAnimationFrame(p.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>e.registerEditableListener(E=>{o(E);}),[e]),useEffect(()=>e.registerUpdateListener(({editorState:E})=>{E.read(()=>{let T=$getSelection();if(!$isNodeSelection(T)){s(false);return}let O=T.getNodes().some(A=>A.getKey()===i);s(O);});}),[e,i]);let h=E=>{e.update(()=>{let T=$getNodeByKey(i);T instanceof ie&&T.setPayload(E);});},f=E=>{E.preventDefault(),E.stopPropagation(),e.update(()=>{let T=$createNodeSelection();T.add(i),$setSelection(T);});},y=E=>T=>{if(T.preventDefault(),T.stopPropagation(),!L.current)return;let A=T.clientX,Y=T.clientY,K=d,J=u;document.body.style.userSelect="none",document.body.style.cursor=E==="width"?"ew-resize":"ns-resize",l(true);let B=()=>{p.current=null,L.current&&(L.current.style.width=`${g.current}px`),w.current&&(w.current.style.height=`${x.current}px`);},$=I=>{let U=E==="width"?ke(K+(I.clientX-A),vt,Tt):g.current,X=E==="height"?ke(J+(I.clientY-Y),Nt,Lt):x.current;g.current=U,x.current=X,p.current==null&&(p.current=window.requestAnimationFrame(B));},Q=()=>{p.current!=null&&(window.cancelAnimationFrame(p.current),p.current=null),l(false),c(g.current),m(x.current),h({width:g.current,height:x.current}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",$),document.removeEventListener("mouseup",Q);};document.addEventListener("mousemove",$),document.addEventListener("mouseup",Q);},b=useMemo(()=>Sa(n.alignment),[n.alignment]),v=useMemo(()=>({marginTop:"0.5rem",textAlign:"center",color:"#666",fontSize:"0.9em",fontStyle:"italic"}),[]),N=po(t,r,a);return jsxs("div",{style:b,children:[jsxs("div",{ref:L,className:`luthor-media-embed-shell${r?" is-selected":""}${a?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{width:d,maxWidth:"100%"},onClick:t?f:void 0,children:[jsx("iframe",{ref:w,src:n.src,title:n.title??"Embedded content",loading:"lazy",referrerPolicy:"strict-origin-when-cross-origin",allowFullScreen:true,style:{width:"100%",height:`${u}px`,border:"0",display:"block",pointerEvents:ho(t,r,a)}}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize iframe width","aria-hidden":!N,tabIndex:N?0:-1,style:{opacity:N?1:0,pointerEvents:N?"auto":"none"},onMouseDown:y("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize iframe height","aria-hidden":!N,tabIndex:N?0:-1,style:{opacity:N?1:0,pointerEvents:N?"auto":"none"},onMouseDown:y("height")})]}),n.caption?jsx("figcaption",{style:v,children:n.caption}):null]})}var en=class extends k{constructor(n){super("iframeEmbed",["toolbar"]),this.config={defaultWidth:640,defaultHeight:360,defaultAlignment:"center",...n};}register(n){return ()=>{}}getNodes(){return [ie]}getPlugins(){return []}getCommands(n){return {insertIframeEmbed:(e,t,o,r)=>{let s=Or(e);s&&n.update(()=>{let a=new ie({src:s.toString(),width:ke(t??this.config.defaultWidth??640,vt,Tt),height:ke(o??this.config.defaultHeight??360,Nt,Lt),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 ie&&o.setPayload({alignment:e});});});},resizeIframeEmbed:(e,t)=>{n.update(()=>{let o=$getSelection();$isNodeSelection(o)&&o.getNodes().forEach(r=>{r instanceof ie&&r.setPayload({width:ke(e,vt,Tt),height:ke(t,Nt,Lt)});});});},setIframeEmbedCaption:e=>{n.update(()=>{let t=$getSelection();$isNodeSelection(t)&&t.getNodes().forEach(o=>{o instanceof ie&&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 ie);e(o?.getPayload().caption??"");});}),updateIframeEmbedUrl:e=>{let t=Or(e);if(!t)return false;let o=false;return n.update(()=>{let r=$getSelection();$isNodeSelection(r)&&r.getNodes().forEach(s=>{s instanceof ie&&(s.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 ie);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 ie));});}),isIframeEmbedAlignedLeft:()=>new Promise(e=>{n.getEditorState().read(()=>{let t=$getSelection();if(!$isNodeSelection(t)){e(false);return}let o=t.getNodes().find(r=>r instanceof ie);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 ie);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 ie);e(o?.getPayload().alignment==="right");});})}}},Na=new en;var nt=240,ot=140,rt=1600,it=1200;function be(i,n,e){return Math.min(e,Math.max(n,Math.round(i)))}function Ma(i){return i==="center"?{margin:"1rem auto",width:"fit-content",maxWidth:"100%"}:i==="left"?{margin:"1rem auto 1rem 0",width:"fit-content",maxWidth:"100%"}:{margin:"1rem 0 1rem auto",width:"fit-content",maxWidth:"100%"}}function Oa(i){let n=i.trim();return /^https?:\/\//i.test(n)?n:`https://${n}`}function bo(i){try{return new URL(Oa(i))}catch{return null}}function Hr(i){return /^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/.*)?$/i.test(i)}function Ne(i){return typeof i=="string"&&/^[A-Za-z0-9_-]{3,}$/.test(i)}function Fr(i){let n=i.hostname.toLowerCase(),e=i.pathname;if(n==="youtu.be"){let r=e.split("/").filter(Boolean)[0];return Ne(r)?{videoId:r}:null}if(e==="/playlist"){let r=i.searchParams.get("list");return Ne(r)?{playlistId:r}:null}if(e.startsWith("/shorts/")){let r=e.split("/")[2];return Ne(r)?{videoId:r}:null}if(e.startsWith("/embed/")){let r=e.split("/")[2];if(!r)return null;if(r==="videoseries"){let s=i.searchParams.get("list");return Ne(s)?{playlistId:s}:null}return Ne(r)?{videoId:r}:null}if(e==="/watch"){let r=i.searchParams.get("list"),s=i.searchParams.get("v"),a={};return Ne(s)&&(a.videoId=s),Ne(r)&&(a.playlistId=r),a.videoId||a.playlistId?a:null}let t=i.searchParams.get("v"),o=i.searchParams.get("list");return Ne(t)||Ne(o)?{videoId:Ne(t)?t:void 0,playlistId:Ne(o)?o:void 0}:null}function Ia(i,n){if(!Hr(i))return null;let e=bo(i);if(!e)return null;if(e.pathname.includes("/embed/"))return e.toString();let t=Fr(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 s=[];if(n.allowFullscreen||s.push("fs=0"),n.autoplay&&s.push("autoplay=1"),n.controls||s.push("controls=0"),n.rel!==1&&s.push(`rel=${n.rel}`),n.start>0&&s.push(`start=${Math.max(0,Math.floor(n.start))}`),s.length===0)return r;let a=r.includes("?")?"&":"?";return `${r}${a}${s.join("&")}`}function Ar(i,n){let e=bo(i);if(!e||!Hr(n))return null;let t=bo(n);if(!t)return null;let o=Fr(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 W=class i extends DecoratorNode{constructor(e,t){super(t);C(this,"__payload");this.__payload=e;}static getType(){return "youtube-embed"}static clone(e){return new i(e.__payload,e.__key)}static importJSON(e){return new i({src:e.src,width:be(e.width,nt,rt),height:be(e.height,ot,it),alignment:e.alignment,caption:e.caption??"",start:e.start})}static importDOM(){return {div:e=>e.hasAttribute("data-lexical-youtube-embed")||e.hasAttribute("data-youtube-video")?{conversion:o=>{let r=o.querySelector("iframe");if(!r)return {node:null};let s=r.getAttribute("src")??"",a=Number(r.getAttribute("width")??"640"),l=Number(r.getAttribute("height")??"480"),d=o.getAttribute("data-align")??"center",u=o.querySelector("figcaption")?.textContent??o.getAttribute("data-caption")??"",m=Number(r.getAttribute("data-start")??"0");return {node:new i({src:s,width:be(a,nt,rt),height:be(l,ot,it),alignment:d,caption:u,start:Number.isFinite(m)?m:0})}},priority:4}:null,figure:e=>e.hasAttribute("data-lexical-youtube-embed")||e.hasAttribute("data-youtube-video")?{conversion:o=>{let r=o.querySelector("iframe");if(!r)return {node:null};let s=r.getAttribute("src")??"",a=Number(r.getAttribute("width")??"640"),l=Number(r.getAttribute("height")??"480"),d=o.getAttribute("data-align")??"center",u=o.querySelector("figcaption")?.textContent??o.getAttribute("data-caption")??"",m=Number(r.getAttribute("data-start")??"0");return {node:new i({src:s,width:be(a,nt,rt),height:be(l,ot,it),alignment:d,caption:u,start:Number.isFinite(m)?m:0})}},priority:4}:null}}createDOM(){let e=document.createElement("div");return e.setAttribute("data-lexical-youtube-embed","true"),e}updateDOM(){return false}exportJSON(){return {type:"youtube-embed",version:1,src:this.__payload.src,width:this.__payload.width,height:this.__payload.height,alignment:this.__payload.alignment,caption:this.__payload.caption,start:this.__payload.start}}exportDOM(){let e=document.createElement("figure");e.setAttribute("data-lexical-youtube-embed","true"),e.setAttribute("data-youtube-video",""),e.setAttribute("data-align",this.__payload.alignment),e.setAttribute("data-caption",this.__payload.caption??"");let 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(_a,{nodeKey:this.__key,payload:this.__payload})}isInline(){return false}isKeyboardSelectable(){return true}};function _a({nodeKey:i,payload:n}){let[e]=useLexicalComposerContext(),[t,o]=useState(()=>e.isEditable()),[r,s]=useState(false),[a,l]=useState(false),[d,c]=useState(n.width),[u,m]=useState(n.height),g=useRef(n.width),x=useRef(n.height),L=useRef(null),w=useRef(null),p=useRef(null);useEffect(()=>{c(n.width),m(n.height),g.current=n.width,x.current=n.height;},[n.width,n.height]),useEffect(()=>()=>{p.current!=null&&window.cancelAnimationFrame(p.current),document.body.style.userSelect="",document.body.style.cursor="";},[]),useEffect(()=>e.registerEditableListener(E=>{o(E);}),[e]),useEffect(()=>e.registerUpdateListener(({editorState:E})=>{E.read(()=>{let T=$getSelection();if(!$isNodeSelection(T)){s(false);return}let O=T.getNodes().some(A=>A.getKey()===i);s(O);});}),[e,i]);let h=E=>{e.update(()=>{let T=$getNodeByKey(i);T instanceof W&&T.setPayload(E);});},f=E=>{E.preventDefault(),E.stopPropagation(),e.update(()=>{let T=$createNodeSelection();T.add(i),$setSelection(T);});},y=E=>T=>{if(T.preventDefault(),T.stopPropagation(),!L.current)return;let A=T.clientX,Y=T.clientY,K=d,J=u;document.body.style.userSelect="none",document.body.style.cursor=E==="width"?"ew-resize":"ns-resize",l(true);let B=()=>{p.current=null,L.current&&(L.current.style.width=`${g.current}px`),w.current&&(w.current.style.height=`${x.current}px`);},$=I=>{let U=E==="width"?be(K+(I.clientX-A),nt,rt):g.current,X=E==="height"?be(J+(I.clientY-Y),ot,it):x.current;g.current=U,x.current=X,p.current==null&&(p.current=window.requestAnimationFrame(B));},Q=()=>{p.current!=null&&(window.cancelAnimationFrame(p.current),p.current=null),l(false),c(g.current),m(x.current),h({width:g.current,height:x.current}),document.body.style.userSelect="",document.body.style.cursor="",document.removeEventListener("mousemove",$),document.removeEventListener("mouseup",Q);};document.addEventListener("mousemove",$),document.addEventListener("mouseup",Q);},b=useMemo(()=>Ma(n.alignment),[n.alignment]),v=po(t,r,a),N=useMemo(()=>({fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"}),[]);return jsxs("div",{style:b,children:[jsxs("div",{ref:L,className:`luthor-media-embed-shell${r?" is-selected":""}${a?" is-resizing":""}`,"data-luthor-selection-anchor":"true",style:{width:d,maxWidth:"100%"},onClick:t?f:void 0,children:[jsx("iframe",{ref:w,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:`${u}px`,border:"0",display:"block",pointerEvents:ho(t,r,a)}}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-width","aria-label":"Resize YouTube embed width","aria-hidden":!v,tabIndex:v?0:-1,style:{opacity:v?1:0,pointerEvents:v?"auto":"none"},onMouseDown:y("width")}),jsx("button",{type:"button",className:"luthor-media-embed-resize-handle-height","aria-label":"Resize YouTube embed height","aria-hidden":!v,tabIndex:v?0:-1,style:{opacity:v?1:0,pointerEvents:v?"auto":"none"},onMouseDown:y("height")})]}),n.caption?jsx("figcaption",{style:N,children:n.caption}):null]})}var nn=class extends k{constructor(e){super("youtubeEmbed",["toolbar"]);C(this,"lastSelectedYouTubeNodeKey",null);this.config={defaultWidth:640,defaultHeight:480,defaultAlignment:"center",allowFullscreen:true,autoplay:false,controls:true,nocookie:true,rel:1,...e};}register(e){return e.registerUpdateListener(({editorState:t})=>{t.read(()=>{let o=$getSelection();if(!$isNodeSelection(o))return;let r=o.getNodes().find(s=>s instanceof W);r&&(this.lastSelectedYouTubeNodeKey=r.getKey());});})}getNodes(){return [W]}getPlugins(){return []}getCommands(e){return {insertYouTubeEmbed:(t,o,r,s)=>{let a=Ia(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(s??0))});a&&e.update(()=>{let l=new W({src:a,width:be(o??this.config.defaultWidth??640,nt,rt),height:be(r??this.config.defaultHeight??480,ot,it),alignment:this.config.defaultAlignment??"center",caption:"",start:s}),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 W&&r.setPayload({alignment:t});});});},resizeYouTubeEmbed:(t,o)=>{e.update(()=>{let r=$getSelection();$isNodeSelection(r)&&r.getNodes().forEach(s=>{s instanceof W&&s.setPayload({width:be(t,nt,rt),height:be(o,ot,it)});});});},setYouTubeEmbedCaption:t=>{e.update(()=>{let o=$getSelection();if($isNodeSelection(o)){o.getNodes().forEach(r=>{r instanceof W&&r.setPayload({caption:t});});return}if(this.lastSelectedYouTubeNodeKey){let r=$getNodeByKey(this.lastSelectedYouTubeNodeKey);r instanceof W?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(s=>s instanceof W);if(r){t(r.getPayload().caption??"");return}}if(this.lastSelectedYouTubeNodeKey){let r=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(r instanceof W){t(r.getPayload().caption??"");return}}t("");});}),updateYouTubeEmbedUrl:t=>{let o=false;return e.update(()=>{let r=$getSelection();if($isNodeSelection(r)){r.getNodes().forEach(s=>{if(s instanceof W){let a=Ar(s.getPayload().src,t);if(!a)return;s.setPayload({src:a}),o=true;}});return}if(this.lastSelectedYouTubeNodeKey){let s=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(s instanceof W){let a=Ar(s.getPayload().src,t);a&&(s.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(s=>s instanceof W);if(r){t(r.getPayload().src??"");return}}if(this.lastSelectedYouTubeNodeKey){let r=$getNodeByKey(this.lastSelectedYouTubeNodeKey);if(r instanceof W){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 W));});}),isYouTubeEmbedAlignedLeft:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if(!$isNodeSelection(o)){t(false);return}let r=o.getNodes().find(s=>s instanceof W);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(s=>s instanceof W);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(s=>s instanceof W);t(r?.getPayload().alignment==="right");});})}}},Aa=new nn;var Da="luthor:meta";var Ha=/<!--\s*luthor:meta\s+v(\d+)\s+({[\s\S]*?})\s*-->/g;function st(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function Mt(i){return JSON.parse(JSON.stringify(i))}function Eo(i){return {type:"text",version:1,text:i,detail:0,format:0,mode:"normal",style:""}}function yo(i){return {type:"paragraph",version:1,format:"",indent:0,direction:null,children:[Eo(i)]}}function Fa(i){return {type:"listitem",version:1,value:1,checked:null,indent:0,direction:null,format:"",children:[Eo(i)]}}function Ba(i,n){return `[Unsupported ${n} preserved in ${i} metadata]`}function za(i,n,e){let t=n.length>0?n.join("."):"root";return `${i}:${t}:${e}`}function $a(i,n){return i==="root"||i==="quote"?yo(n):i==="list"?Fa(n):i==="paragraph"||i==="heading"||i==="listitem"||i==="link"||i==="autolink"||i==="code"||i==="code-highlight"?Eo(n):yo(n)}function Br(i,n,e,t,o,r){let s=[];for(let[a,l]of i.entries()){if(!st(l))continue;let d=[...e,a],c=typeof l.type=="string"?l.type:"";if(!o.has(c)){let m=Ba(t,c||"node"),g={id:za(c||"node",d,r.length+1),type:c||"node",path:d,node:Mt(l),fallback:m};r.push(g),s.push($a(n,m));continue}let u={...l};Array.isArray(l.children)&&(u.children=Br(l.children,c,d,t,o,r)),s.push(u);}return s}function ja(){return {type:"root",version:1,format:"",indent:0,direction:null,children:[yo("")]}}function Ua(i){let n=typeof i=="string"?JSON.parse(i):i;if(!st(n)||!st(n.root))return {root:ja()};let e=n.root,t=Array.isArray(e.children)?e.children:[];return {root:{...e,type:"root",children:t}}}function Ka(i,n,e){if(n.length===0)return false;let t=i;for(let r of n.slice(0,-1)){if(!Array.isArray(t.children)||r<0||r>=t.children.length)return false;let s=t.children[r];if(!st(s))return false;t=s;}let o=n[n.length-1];return typeof o!="number"||!Array.isArray(t.children)||o<0?false:o<t.children.length?(t.children[o]=Mt(e),true):o===t.children.length?(t.children.push(Mt(e)),true):false}function Ot(i,n){let e=Ua(i),t=Array.isArray(e.root.children)?e.root.children:[],o=[],r=Br(t,"root",[],n.mode,n.supportedNodeTypes,o);return {document:{root:{...e.root,type:"root",children:r}},envelopes:o}}function It(i,n){if(n.length===0)return i;let t=n.map(o=>{let r=JSON.stringify(o);return `<!-- ${Da} v1 ${r} -->`}).join(`
|
|
2
2
|
`);return i?`${i}${i.endsWith(`
|
|
3
3
|
`)?"":`
|
|
4
|
-
`}${t}`:t}function wt(i){let n=[],e=[],t=new RegExp(Ta.source,"g");for(let o of i.matchAll(t)){if(Number.parseInt(o[1]??"",10)!==1){e.push(`Ignoring metadata envelope version v${o[1]??"unknown"}.`);continue}try{let s=JSON.parse(o[2]??"");if(!rt(s)){e.push("Ignoring metadata envelope with non-object payload.");continue}let a=typeof s.type=="string"?s.type:"",l=typeof s.id=="string"?s.id:"",d=typeof s.fallback=="string"?s.fallback:"",u=(Array.isArray(s.path)?s.path:[]).filter(h=>Number.isInteger(h)&&h>=0).map(h=>Number(h)),m=rt(s.node)?s.node:null;if(!l||!a||!m){e.push("Ignoring metadata envelope with missing required fields.");continue}n.push({id:l,type:a,path:u,node:m,fallback:d});}catch{e.push("Ignoring malformed metadata envelope payload.");}}return {content:i.replace(t,"").trimEnd(),envelopes:n,warnings:e}}function Rt(i,n){if(n.length===0)return i;let e=Nt(i.root);for(let t of n){if(Oa(e,t.path,t.node))continue;Array.isArray(e.children)||(e.children=[]),e.children.push(Nt(t.node));}return {...i,root:e}}var Mr=[...TRANSFORMERS,Cr],Wa=new Set(["root","paragraph","text","linebreak","tab","heading","quote","list","listitem","link","autolink","code","code-highlight","image"]);function Or(){return createEditor({namespace:"luthor-markdown-converter",onError:i=>{throw i},nodes:[ParagraphNode,TextNode,LineBreakNode,TabNode,HeadingNode,QuoteNode,ListNode,ListItemNode,LinkNode,AutoLinkNode,CodeNode,CodeHighlightNode,$]})}function Ja(i,n){let e=typeof n=="string"?n:JSON.stringify(n??{});return i.parseEditorState(e)}function Xa(i){let{content:n,envelopes:e,warnings:t}=wt(i);for(let s of t)console.warn(`[luthor-headless] ${s}`);let o=Or();o.update(()=>{$convertFromMarkdownString(n,Mr);},{discrete:true});let r=o.getEditorState().toJSON();return Rt(r,e)}function Ga(i){let n=Tt(i,{mode:"markdown",supportedNodeTypes:Wa}),e=Or(),t=Ja(e,n.document);e.setEditorState(t,{tag:"history-merge"});let o=t.read(()=>$convertToMarkdownString(Mr));return Lt(o,n.envelopes)}var pl=new Set(["root","paragraph","text","linebreak","tab","heading","quote","list","listitem","link","autolink","code","code-highlight","image","iframe-embed","youtube-embed"]),hl=new Set(["pre","script","style","textarea"]);function Ar(){return createEditor({namespace:"luthor-html-converter",onError:i=>{throw i},nodes:[ParagraphNode,TextNode,LineBreakNode,TabNode,HeadingNode,QuoteNode,ListNode,ListItemNode,LinkNode,AutoLinkNode,CodeNode,CodeHighlightNode,$,re,W]})}function bl(i,n){let e=typeof n=="string"?n:JSON.stringify(n??{});return i.parseEditorState(e)}function Dr(){if(typeof document>"u"||typeof window>"u"||typeof DOMParser>"u")throw new Error("HTML conversion requires browser DOM APIs (document/window/DOMParser).")}function Ir(i){if(!i)return false;let n=i.getAttribute("style");return n?/\bwhite-space\s*:\s*(pre|pre-wrap|pre-line)\b/i.test(n):false}function yl(i){let n=i.parentElement;for(;n;){if(hl.has(n.tagName.toLowerCase()))return true;n=n.parentElement;}return false}function _r(i,n){let e=n==="previous"?i.previousSibling:i.nextSibling;for(;e;){if(e.nodeType!==Node.TEXT_NODE||(e.textContent??"").trim().length>0)return e;e=n==="previous"?e.previousSibling:e.nextSibling;}return null}function xl(i,n){if(!i||!n||/\s$/.test(i)||/^\s/.test(n))return false;let e=i.at(-1)??"",t=n[0]??"";return !(!e||!t||/^[,.;:!?)]$/.test(t)||/^[([{"']$/.test(e))}function El(i){let n=Array.from(i.querySelectorAll("[style]"));for(let r of n){if(!Ir(r)||r.childNodes.length!==1||r.firstChild?.nodeType!==Node.TEXT_NODE)continue;let s=r.firstChild;/[\r\n]/.test(s.data)&&(s.data=s.data.replace(/^\s*\r?\n\s*/,"").replace(/\r?\n\s*$/,""));}let e=i.createTreeWalker(i.body,NodeFilter.SHOW_TEXT),t=[],o=e.nextNode();for(;o;){let r=o,s=r.data,a=r.parentElement;if(!/^[\s\r\n\t]+$/.test(s)||!/[\r\n]/.test(s)||yl(r)||Ir(a)){o=e.nextNode();continue}let l=_r(r,"previous"),d=_r(r,"next"),c=l?.textContent??"",u=d?.textContent??"";xl(c,u)?t.push({node:r,replacement:" "}):t.push({node:r,replacement:null}),o=e.nextNode();}for(let r of t)if(r.node.parentNode){if(r.replacement===null){r.node.parentNode.removeChild(r.node);continue}r.node.data=r.replacement;}}function Cl(i){Dr();let{content:n,envelopes:e,warnings:t}=wt(i);for(let s of t)console.warn(`[luthor-headless] ${s}`);let o=Ar();o.update(()=>{let s=new DOMParser().parseFromString(n,"text/html");El(s);let a=$generateNodesFromDOM(o,s),l=$getRoot();l.clear(),l.append(...a);},{discrete:true});let r=o.getEditorState().toJSON();return Rt(r,e)}function Sl(i){Dr();let n=Tt(i,{mode:"html",supportedNodeTypes:pl}),e=Ar(),t=bl(e,n.document);e.setEditorState(t,{tag:"history-merge"});let o=t.read(()=>$generateHtmlFromNodes(e,null));return Lt(o,n.envelopes)}var Xt=class extends oe{constructor(){super("bold");}},vl=new Xt;var Gt=class extends oe{constructor(){super("italic");}},Nl=new Gt;var Tl={format:["underline"],tag:"++",type:"text-format"},Zt=class extends oe{constructor(){super("underline");}getMarkdownTransformers(){return [Tl]}},Ll=new Zt;var en=class extends oe{constructor(){super("strikethrough");}},wl=new en;var tn=class extends w{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 s=r.clipboardData;if(!s)return false;let a=s.getData("text/plain");return a&&this.config.validateUrl(a)&&this.config.autoLinkUrls?(r.preventDefault(),e.update(()=>{let l=$getSelection();if($isRangeSelection(l))if(l.isCollapsed()){let d=$createLinkNode(a);d.append($createTextNode(a)),l.insertNodes([d]);}else if(this.config.linkSelectedTextOnPaste)e.dispatchCommand(TOGGLE_LINK_COMMAND,a);else {l.insertText(a);let d=$getSelection();d&&$isRangeSelection(d)&&d.getNodes()[0]&&e.dispatchCommand(TOGGLE_LINK_COMMAND,a);}}),true):false},3),o=e.registerUpdateListener(({editorState:r})=>{r.read(()=>{let s=this.getSelectedLinkNode();if(s){this.lastSelectedLinkNodeKey=s.getKey();return}if(this.lastSelectedLinkNodeKey){let a=$getNodeByKey(this.lastSelectedLinkNodeKey);$isLinkNode(a)||(this.lastSelectedLinkNodeKey=null);}});});return ()=>{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 s=/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_.+~#?&//=]*)/g.exec(o);return s&&this.config.validateUrl(s[0])?{text:s[0],url:s[0],index:s.index,length:s[0].length}:null};e.push(jsx(AutoLinkPlugin,{matchers:[t]},"auto-link"));}return e}getCommands(e){let t=s=>s.trim(),o=s=>s.length>0&&!!this.config.validateUrl?.(s),r=(s,a,l,d)=>{s.setURL(a),typeof l<"u"&&s.setRel(l.trim()||null),typeof d<"u"&&s.setTarget(d.trim()||null);};return {insertLink:(s,a)=>{if(s){let l=t(s);if(!o(l))return;a&&e.update(()=>{let d=$getSelection();d&&d.insertText(a);}),e.dispatchCommand(TOGGLE_LINK_COMMAND,l);}else {let l=prompt("Enter URL:");if(l){let d=t(l);if(!o(d))return;e.dispatchCommand(TOGGLE_LINK_COMMAND,d);}}},updateLink:(s,a,l)=>{let d=t(s);if(!o(d))return false;let c=false;return e.update(()=>{let u=this.getSelectedLinkNode()??this.getCachedLinkNode();if(u){r(u,d,a,l),this.lastSelectedLinkNodeKey=u.getKey(),c=true;return}let m=$getSelection();if(!$isRangeSelection(m)){c=false;return}e.dispatchCommand(TOGGLE_LINK_COMMAND,{url:d,rel:typeof a>"u"?null:a.trim()||null,target:typeof l>"u"?null:l.trim()||null}),c=true;}),c},removeLink:()=>{let s=false;e.update(()=>{let a=this.getSelectedLinkNode()??this.getCachedLinkNode();if(a){let l=a.getChildren();for(let d of l)a.insertBefore(d);a.remove(),this.lastSelectedLinkNodeKey=null,s=true;return}e.dispatchCommand(TOGGLE_LINK_COMMAND,null);}),s||(this.lastSelectedLinkNodeKey=null);},getCurrentLink:()=>new Promise(s=>{e.getEditorState().read(()=>{let a=this.getSelectedLinkNode()??this.getCachedLinkNode();if(!a){s(null);return}s(this.serializeLinkNode(a));});}),getLinkByKey:s=>new Promise(a=>{e.getEditorState().read(()=>{let l=this.getLinkNodeByKey(s);if(!l){a(null);return}a(this.serializeLinkNode(l));});}),updateLinkByKey:(s,a,l,d)=>{let c=t(a);if(!o(c))return false;let u=false;return e.update(()=>{let m=this.getLinkNodeByKey(s);if(!m){u=false;return}r(m,c,l,d),this.lastSelectedLinkNodeKey=m.getKey(),u=true;}),u},removeLinkByKey:s=>{let a=false;return e.update(()=>{let l=this.getLinkNodeByKey(s);if(!l){a=false;return}this.removeLinkNode(l),this.lastSelectedLinkNodeKey=null,a=true;}),a}}}serializeLinkNode(e){return {url:e.getURL(),rel:e.getRel(),target:e.getTarget()}}removeLinkNode(e){let 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(),s=[t,o,...r];for(let a of s){if($isLinkNode(a))return a;let l=a.getParent();if(l&&$isLinkNode(l))return l}return null}getCachedLinkNode(){if(!this.lastSelectedLinkNodeKey)return null;let e=$getNodeByKey(this.lastSelectedLinkNodeKey);return $isLinkNode(e)?e:(this.lastSelectedLinkNodeKey=null,null)}getStateQueries(e){return {isLink:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if(o&&$isRangeSelection(o)){let s=o.getNodes()[0];if(s){let a=s.getParent();t($isLinkNode(a)||$isLinkNode(s));}else t(false);}else t(false);});}),isTextSelected:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();o&&$isRangeSelection(o)?t(!o.isCollapsed()):t(false);});})}}},Dl=new tn;var Ql={dependencies:[HorizontalRuleNode],export:i=>$isHorizontalRuleNode(i)?"---":null,regExp:/^(?:---|___)\s*$/,replace:(i,n,e,t)=>{let o=$createHorizontalRuleNode();i.replace(o),t||ql(o);},type:"element"},Yl=[Ql],Vl=/^(?:---|___)$/;function ql(i){let n=i.getNextSibling();if(n&&$isParagraphNode(n)){n.selectStart();return}let e=$createParagraphNode();i.insertAfter(e),e.selectStart();}var nn=class extends w{constructor(){super("horizontalRule",["toolbar"]);}register(n){let e=registerMarkdownShortcuts(n,Yl),t=n.registerCommand(KEY_ENTER_COMMAND,o=>{if(o?.shiftKey)return false;let r=false;return n.update(()=>{let s=$getSelection();if(!s||!$isRangeSelection(s)||!s.isCollapsed())return;let a=s.anchor.getNode();if(!$isTextNode(a))return;let l=a.getParent();if(!l||!$isParagraphNode(l))return;let d=l.getParent();if(!$isRootOrShadowRoot(d))return;let c=a.getTextContent().trim();if(!Vl.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(s=>$isHorizontalRuleNode(s));e(r);}else e(false);});})}}},Wl=new nn;var Qr=[{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"}],Gl={value:"default",label:"Default",fontFamily:"inherit"};function Kr(i){return i.trim().toLowerCase()}function Zl(i){return /^[a-z0-9][a-z0-9-]*$/i.test(i)}function ec(i){let n=new Set,e=[];for(let o of i){let r=o.value.trim(),s=o.label.trim(),a=o.fontFamily.trim();if(!r||!s||!a||!Zl(r))continue;let l=Kr(r);n.has(l)||(n.add(l),e.push({value:r,label:s,fontFamily:a,cssImportUrl:o.cssImportUrl?.trim()||void 0}));}return e.length===0?Qr:e.some(o=>Kr(o.value)==="default")?e:[Gl,...e]}var on=class extends w{constructor(){super("fontFamily",["toolbar"]);x(this,"loadedFontUrls",new Set);this.config={options:Qr,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=ec(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 s=this.normalizeFontValue(r);t=this.config.options.find(l=>this.normalizeFontValue(l.value)===s?true:this.normalizeFontValue(l.fontFamily)===s)?.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 s=document.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-luthor-font-url",o),document.head.appendChild(s),this.loadedFontUrls.add(t);}},tc=new on;var qr=[{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"}],oc={value:"default",label:"Default",fontSize:"inherit"};function Vr(i){return i.trim().toLowerCase()}function rc(i){return /^[a-z0-9][a-z0-9-]*$/i.test(i)}function ic(i){let n=new Set,e=[];for(let o of i){let r=String(o.value).trim(),s=String(o.label).trim(),a=String(o.fontSize).trim();if(!r||!s||!a||!rc(r))continue;let l=Vr(r);n.has(l)||(n.add(l),e.push({value:r,label:s,fontSize:a}));}return e.length===0?qr:e.some(o=>Vr(o.value)==="default")?e:[oc,...e]}var rn=class extends w{constructor(){super("fontSize",["toolbar"]),this.config={options:qr,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}configure(n){let e={...n};return n.options&&(e.options=ic(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,"")}},sc=new rn;var Jr=[{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"}],vo={value:"default",label:"Default",lineHeight:"1.5"},cc=1;function So(i){return i.trim().toLowerCase()}function dc(i){return So(i)==="default"?true:an(i)!==null}function an(i){let n=i.trim();if(!/^\d*\.?\d+$/.test(n))return null;let e=Number(n);return !Number.isFinite(e)||e<cc?null:e.toString()}function uc(i,n){let e=new Set,t=[];for(let r of i){let s=r.value.trim(),a=r.label.trim(),l=So(s);if(!s||!a||!dc(s)||e.has(l))continue;if(l==="default"){e.add(l),t.push({value:s,label:a,lineHeight:n});continue}let d=an(String(r.lineHeight));d&&(e.add(l),t.push({value:s,label:a,lineHeight:d}));}return t.length===0?Jr:t.some(r=>So(r.value)==="default")?t:[{...vo,lineHeight:n},...t]}function mc(i){return an(i)??vo.lineHeight}var sn=class extends w{constructor(){super("lineHeight",["toolbar"]),this.config={options:Jr,defaultLineHeight:vo.lineHeight,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}configure(n){let e={...n},t=mc(String(n.defaultLineHeight??this.config.defaultLineHeight));return e.defaultLineHeight=t,n.options&&(e.options=uc(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 s=this.withStyleProperty(r.getStyle(),"line-height",e);r.setStyle(s);for(let a of r.getAllTextNodes())$isTextNode(a)&&a.setStyle(this.withStyleProperty(a.getStyle(),"line-height",e));}});}getSelectedTopLevelBlocks(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)),s=t.trim();return s.length>0&&r.push(`${e}: ${s}`),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",""),s=this.normalizeValue(r);e=s.length>0&&s!=="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",""),s=this.normalizeValue(r);if(!s||s==="normal"){e="default";return}if(s===this.normalizeValue(this.config.defaultLineHeight)){e="default";return}e=this.config.options.find(l=>this.normalizeValue(l.value)===s?true:this.normalizeValue(l.lineHeight)===s)?.value??null;}),e}getSelectedBlocksLineHeight(n){let e=this.getSelectedTopLevelBlocks(n);if(e.length===0)return null;let t=null,o="";for(let r of e){let s=this.readStyleProperty(r.getStyle(),"line-height"),a=this.normalizeValue(s);if(t===null){t=a,o=s;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 an(e)??e}readStyleProperty(n,e){let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return n.match(new RegExp(`(?:^|;)\\s*${t}\\s*:\\s*([^;]+)`,"i"))?.[1]?.trim()??""}},gc=new sn;var pc=[{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"}],ln=class extends w{constructor(){super("textColor",["toolbar"]),this.config={options:pc,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}},hc=new ln;var yc=[{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"}],cn=class extends w{constructor(){super("textHighlight",["toolbar"]),this.config={options:yc,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}},xc=new cn;var dn=class extends oe{constructor(){super("subscript");}},Ec=new dn;var un=class extends oe{constructor(){super("superscript");}},Cc=new un;function mn(i,n,e){return i<n?n:i>e?e:i}function Lc({items:i,position:n,onClose:e,className:t,style:o,itemClassName:r,itemStyle:s,disabledItemClassName:a,disabledItemStyle:l}){return jsx("div",{className:t,style:{position:"fixed",left:n.x,top:n.y,zIndex:"var(--luthor-z-menu, 460)",...o},onClick:d=>d.stopPropagation(),children:i.map((d,c)=>d.separator?jsx("div",{className:"h-px bg-border my-1"},c):jsxs("div",{className:d.disabled?a:r,style:d.disabled?l:s,onClick:()=>{!d.disabled&&d.action&&(d.action(),e());},children:[d.icon&&jsx(d.icon,{className:"mr-2 h-4 w-4"}),d.label]},c))})}var gn=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,s)=>(s.priority||0)-(r.priority||0));for(let r of o){let s={editor:this.editor,target:e,selection:t,event:n};if(r.canHandle(s)){this.config.preventDefault!==false&&n.preventDefault();let a=r.getItems(s);if(a.length>0){let l=e.getBoundingClientRect();this.showMenu({items:a,position:{x:n.clientX,y:n.clientY},renderer:r.renderer||this.config.defaultRenderer,anchor:{element:e,offsetX:n.clientX-l.left,offsetY:n.clientY-l.top}});return}}}});}showMenu(n){this.currentMenu=this.resolveAnchoredMenuConfig(n),this.notifyListeners();}hideMenu(){this.currentMenu=null,this.notifyListeners();}repositionMenuFromAnchor(){if(!this.currentMenu?.anchor)return;if(!this.currentMenu.anchor.element.isConnected){this.hideMenu();return}let n=this.resolveAnchoredMenuConfig(this.currentMenu);(!this.currentMenu||n.position.x!==this.currentMenu.position.x||n.position.y!==this.currentMenu.position.y)&&(this.currentMenu=n,this.notifyListeners());}getCurrentMenu(){return this.currentMenu}getPortalContainer(){let n=this.editor.getRootElement();return n?n.closest(".luthor-editor-wrapper")??null:null}subscribe(n){return this.listeners.add(n),n(this.currentMenu),()=>{this.listeners.delete(n);}}notifyListeners(){this.listeners.forEach(n=>n(this.currentMenu));}resolveAnchoredMenuConfig(n){if(!n.anchor)return n;let{element:e,offsetX:t,offsetY:o}=n.anchor,r=e.getBoundingClientRect();return {...n,position:{x:r.left+t,y:r.top+o}}}};function wc({extension:i}){let{config:n}=Me(),[e,t]=useState(null),o=n?.theme?.contextMenu||{},r=i.config,s={container:r?.theme?.container||o.container||"luthor-context-menu",item:r?.theme?.item||o.item||"luthor-context-menu-item",itemDisabled:r?.theme?.itemDisabled||o.itemDisabled||"luthor-context-menu-item-disabled"},a={container:{...r?.styles?.container,...o.styles?.container},item:{...r?.styles?.item,...o.styles?.item},itemDisabled:{...r?.styles?.itemDisabled,...o.styles?.itemDisabled}};if(useEffect(()=>i.subscribe(t),[i]),!e)return null;let l=e.renderer||i.config.defaultRenderer,d=i.manager?.getPortalContainer()??null,c=220,u=Math.min(420,18+e.items.length*34),m=8,h=(()=>{if(!d){let E=typeof window>"u"?0:window.innerWidth,T=typeof window>"u"?0:window.innerHeight,b=Math.max(m,E-c-m),S=Math.max(m,T-u-m);return {x:mn(e.position.x,m,b),y:mn(e.position.y,m,S)}}let v=d.getBoundingClientRect(),y=e.position.x-v.left,f=e.position.y-v.top,p=Math.max(m,v.width-c-m),g=Math.max(m,v.height-u-m);return {x:mn(y,m,p),y:mn(f,m,g)}})(),N=d?{position:"absolute",...a.container}:a.container;return createPortal(jsx(l,{items:e.items,position:h,onClose:()=>i.manager?.hideMenu(),className:s.container,style:N,itemClassName:s.item,itemStyle:a.item,disabledItemClassName:s.itemDisabled,disabledItemStyle:a.itemDisabled}),d??document.body)}var fn=class extends w{constructor(e={}){super("contextMenu",["toolbar"]);x(this,"manager",null);x(this,"pendingListeners",new Set);this.config={defaultRenderer:Lc,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 gn(e,this.config),this.pendingListeners.forEach(l=>{this.manager?.subscribe(l);}),this.pendingListeners.clear();let t=l=>{this.manager?.handleContextMenu(l);},o=l=>{l.target.closest(".luthor-context-menu")||this.manager?.hideMenu();},r=l=>{l.key==="Escape"&&this.manager?.hideMenu();},s=()=>{this.manager?.repositionMenuFromAnchor();},a=e.getRootElement();return a?(a.addEventListener("contextmenu",t),document.addEventListener("mousedown",o),document.addEventListener("keydown",r),window.addEventListener("scroll",s,true),window.addEventListener("resize",s),()=>{a.removeEventListener("contextmenu",t),document.removeEventListener("mousedown",o),document.removeEventListener("keydown",r),window.removeEventListener("scroll",s,true),window.removeEventListener("resize",s),this.manager=null;}):()=>{this.manager=null;}}getCommands(e){return {registerProvider:t=>{this.manager||(this.manager=new gn(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(wc,{extension:this},"context-menu")]}subscribe(e){return this.manager?this.manager.subscribe(e):(this.pendingListeners.add(e),()=>{this.pendingListeners.delete(e);})}},Ro=new fn;function jc(i,n,e){return i<n?n:i>e?e:i}function xn(){let i=$getSelection();if($isTableSelection(i)){let n=i.getNodes().find(e=>$isTableCellNode(e));if($isTableCellNode(n))return n}if($isRangeSelection(i)){let n=i.anchor.getNode(),e=$findCellNode(n);if($isTableCellNode(e))return e}return null}function Uc({headersEnabled:i,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:i,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 Kc({extension:i}){let{editor:n}=Me(),[e,t]=useState(null),[o,r]=useState(false),[s,a]=useState(false),[l,d]=useState(null),c=useRef(null),u=useRef(null),m=y=>{n&&n.update(()=>{let f=xn();f&&(f.selectStart(),y(f));});},h=y=>{m(f=>{$getTableNodeFromLexicalNodeOrThrow(f).getChildren().filter(E=>$isTableRowNode(E)).forEach((E,T)=>{E.getChildren().filter(S=>$isTableCellNode(S)).forEach(S=>{let M=y&&T===0?TableCellHeaderStates.ROW:TableCellHeaderStates.NO_STATUS;S.setHeaderStyles(M,TableCellHeaderStates.ROW);});});});};if(useEffect(()=>{if(!n)return;let y=n.getRootElement(),f=y?.closest(".luthor-editor-wrapper")||y?.parentElement||null;t(f);let p=()=>{n.getEditorState().read(()=>{let T=$getSelection();if($isRangeSelection(T)&&!T.isCollapsed()){r(false),d(null);return}let b=xn();if(!b){r(false),d(null);return}let M=n.getElementByKey(b.getKey())?.closest("table");if(!M||!f){r(false),d(null);return}let _=$getTableNodeFromLexicalNodeOrThrow(b).getChildren().filter(se=>$isTableRowNode(se))[0]?.getChildren().filter(se=>$isTableCellNode(se))||[],q=_.length>0&&_.every(se=>se.hasHeaderState(TableCellHeaderStates.ROW));a(q);let z=f.getBoundingClientRect(),F=M.getBoundingClientRect(),A=c.current?.getBoundingClientRect(),P=A?.width??520,Y=A?.height??44,K=P/2,J=12,V=F.left-z.left+F.width/2,te=J+K,ce=Math.max(te,z.width-J-K),Te=jc(V,te,ce),Le=F.top-z.top>=Y+J;d({x:Te,y:Le?F.top-z.top-12:F.bottom-z.top+12,placeAbove:Le}),r(true);});};p();let g=n.registerUpdateListener(()=>{p();}),E=()=>{u.current===null&&(u.current=window.requestAnimationFrame(()=>{u.current=null,p();}));};return window.addEventListener("scroll",E,true),window.addEventListener("resize",E),()=>{g(),window.removeEventListener("scroll",E,true),window.removeEventListener("resize",E),u.current!==null&&(cancelAnimationFrame(u.current),u.current=null);}},[n]),!e||!o||!l||typeof document>"u")return null;let N={insertRowAbove:()=>m(()=>$insertTableRowAtSelection(false)),insertRowBelow:()=>m(()=>$insertTableRowAtSelection(true)),insertColumnLeft:()=>m(()=>$insertTableColumnAtSelection(false)),insertColumnRight:()=>m(()=>$insertTableColumnAtSelection(true)),deleteSelectedColumn:()=>m(()=>$deleteTableColumnAtSelection()),deleteSelectedRow:()=>m(()=>$deleteTableRowAtSelection()),deleteTable:()=>m(y=>{$getTableNodeFromLexicalNodeOrThrow(y).remove();})},v=i.config.tableBubbleRenderer?i.config.tableBubbleRenderer({headersEnabled:s,setHeadersEnabled:y=>{a(y),h(y);},actions:N}):jsx(Uc,{headersEnabled:s,setHeadersEnabled:y=>{a(y),h(y);},actions:N});return createPortal(jsx("div",{ref:c,className:"luthor-table-bubble-menu",style:{position:"absolute",left:l.x,top:l.y,transform:l.placeAbove?"translate(-50%, -100%)":"translate(-50%, 0)",zIndex:"var(--luthor-z-menu, 460)"},onMouseDown:y=>y.preventDefault(),children:v}),e)}var En=class extends w{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||Ro;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:s=false}=t;e.update(()=>{let a=$getSelection();if($isRangeSelection(a)){let l=$createTableNodeWithDimensions(o,r,s);a.insertNodes([l]);}});},insertRowAbove:()=>{e.update(()=>{$insertTableRowAtSelection(false);});},insertRowBelow:()=>{e.update(()=>{$insertTableRowAtSelection(true);});},insertColumnLeft:()=>{e.update(()=>{$insertTableColumnAtSelection(false);});},insertColumnRight:()=>{e.update(()=>{$insertTableColumnAtSelection(true);});},toggleRowHeader:()=>{e.update(()=>{let t=xn();if(!t)return;let o=$getTableNodeFromLexicalNodeOrThrow(t),r=$getTableRowIndexFromTableCellNode(t),s=o.getChildren()[r];if(!$isTableRowNode(s))return;let a=s.getChildren().filter(c=>$isTableCellNode(c)),d=!a.every(c=>c.hasHeaderState(TableCellHeaderStates.ROW))?TableCellHeaderStates.ROW:TableCellHeaderStates.NO_STATUS;a.forEach(c=>{c.setHeaderStyles(d,TableCellHeaderStates.ROW);});});},toggleColumnHeader:()=>{e.update(()=>{let t=xn();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(Kc,{extension:this},"table-quick-actions-plugin")]}},Qc=new En;var li=9,at={"decimal-alpha-roman":["decimal","lower-alpha","lower-roman"],"decimal-hierarchical":["decimal"],"upper-roman-upper-alpha":["upper-roman","upper-alpha","decimal","lower-alpha","decimal","lower-alpha","lower-roman","lower-alpha","lower-roman"],"upper-alpha-lower-alpha":["upper-alpha","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman"],"decimal-leading-zero-alpha":["decimal-leading-zero","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman"]},It={"disc-circle-square":["disc","circle","square"],"arrow-diamond-disc":['"\u25B8"','"\u25C6"',"disc"],"square-square-square":["square","square","square"],"arrow-circle-square":['"\u25B8"',"circle","square"]},lt="decimal-alpha-roman",ci="disc-circle-square",Rn="--luthor-checklist-variant",Oe="--luthor-unordered-pattern",bi="--luthor-unordered-pattern-token",_e="--luthor-unordered-marker-kind",Ee="--luthor-ordered-marker-content",di={"disc-arrow-square":"arrow-circle-square","square-circle-disc":"disc-circle-square","arrow-diamond-square":"arrow-diamond-disc","star-circle-square":"disc-circle-square"};function yi(i){let n=new Map;for(let e of i.split(";")){let t=e.trim();if(!t)continue;let o=t.indexOf(":");if(o<=0)continue;let r=t.slice(0,o).trim(),s=t.slice(o+1).trim();r&&n.set(r,s);}return n}function Xc(i){return Array.from(i.entries()).map(([n,e])=>`${n}: ${e}`).join("; ")}function ee(i,n){let e=i.getStyle(),t=yi(e),o=false;for(let[r,s]of Object.entries(n)){let a=t.get(r);if(s===null||s===""){t.delete(r)&&(o=true);continue}a!==s&&(t.set(r,s),o=true);}o&&i.setStyle(Xc(t));}function me(i,n){return yi(i.getStyle()).get(n)??null}function dt(i,n){let e=[...i];for(let t=0;t<e.length;t+=1){let o=e[t],r=n(o);if(r==="stop")break;r!=="skip-children"&&typeof o?.getChildren=="function"&&e.push(...o.getChildren());}}function kn(i){let n=i;for(;n;){if($isListNode(n))return n;n=n.getParent();}return null}function Gc(i){let n=i;for(;n;){if($isListItemNode(n))return n;n=n.getParent();}return null}function _t(i){let n=i;for(;;){let e=n.getParent();if(!$isListItemNode(e))return n;let t=e.getParent();if(!$isListNode(t))return n;n=t;}}function Nn(i,n){let e=$getListDepth(i),t=$getListDepth(n);return e-t}function Tn(i,n){let e=n%i.length;return i[e]??i[0]??"disc"}function ui(i,n){let e=i,t="";for(;e>0;){let o=(e-1)%26;t=String.fromCharCode((n?65:97)+o)+t,e=Math.floor((e-1)/26);}return t||(n?"A":"a")}function mi(i,n){let e=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],t=Math.max(1,Math.floor(i)),o="";for(let[r,s]of e)for(;t>=r;)o+=s,t-=r;return n?o:o.toLowerCase()}function gi(i,n,e,t){let o=e==="paren"?")":".";return `"${t?t.join("."):i==="decimal-leading-zero"?n<10?`0${n}`:`${n}`:i==="lower-alpha"?ui(n,false):i==="upper-alpha"?ui(n,true):i==="lower-roman"?mi(n,false):i==="upper-roman"?mi(n,true):`${n}`}${o}"`}function Zc(i,n){let e=0;for(let t of i.getChildren())if($isListItemNode(t)&&(Ot(t)&&(e+=1),t.getKey()===n.getKey()))return Math.max(1,e);return Math.max(1,e)}function fi(i,n){let e=[],t=i;for(;t.getKey()!==n.getKey();){let o=t.getParent();if(!$isListItemNode(o))break;let r=o.getParent();if(!$isListNode(r))break;e.push(Zc(r,o)),t=r;}return e.reverse()}function Mn(i){return i&&Object.hasOwn(It,i)?i:i&&Object.hasOwn(di,i)?di[i]??ci:ci}function ed(i){return i.startsWith('"')&&i.endsWith('"')}function Ho(i){if(ed(i)){let n=i.toLowerCase(),e=n.slice(1,-1);return n.includes("\\25c6")||e==="\u25C6"?"diamond":(n.includes("\\25b8")||n.includes("\\27a4")||e==="\u25B8"||e==="\u27A4","arrow")}switch(i){case "disc":return "disc";case "circle":return "circle";case "square":return "square";default:return "disc"}}function td(i){let n=i.trim();if(!n)return null;let e=n.match(/^(\d+)([.)])$/);if(e){let r=e[1]??"",s=e[2]??".";return {pattern:r.length>1&&r.startsWith("0")?"decimal-leading-zero-alpha":"decimal-alpha-roman",suffix:s===")"?"paren":"dot"}}let t=n.match(/^([IVXLCDMivxlcdm]+)([.)])$/);if(t)return {pattern:"upper-roman-upper-alpha",suffix:(t[2]??".")===")"?"paren":"dot"};let o=n.match(/^([A-Z]+)([.)])$/);return o?{pattern:"upper-alpha-lower-alpha",suffix:(o[2]??".")===")"?"paren":"dot"}:null}function ct(i){let n=new Map,e=i.getNodes();for(let t of e){let o=kn(t);if(!o)continue;let r=_t(o);n.set(r.getKey(),r);}if(n.size===0){let t=kn(i.anchor.getNode());if(t){let o=_t(t);n.set(o.getKey(),o);}}return [...n.values()]}function Ln(i,n){let e=Math.max(0,n-1),t=i.anchor.getNode(),o=Gc(t);if(o){let s=o.getIndent();if(typeof s=="number")return s>=e}let r=kn(t);return r?$getListDepth(r)-1>=e:false}function Fo(i){let n=[];return dt(i.getChildren(),e=>{if($isListNode(e))return "skip-children";$isTextNode(e)&&n.push(e);}),n}function Ve(i){let n=[];return dt(i.getChildren(),e=>{if($isListNode(e))return n.push(e),"skip-children"}),n}function Ot(i){let n=false,e=false;return dt(i.getChildren(),t=>{if($isListNode(t))return e=true,"skip-children";if($isTextNode(t)&&t.getTextContent().trim().length>0)return n=true,"stop"}),n?true:!e}function Io(i,n){dt(i.getChildren(),e=>{if($isListNode(e))return "skip-children";typeof e.getStyle=="function"&&typeof e.setStyle=="function"&&ee(e,{[bi]:n});});}function nd(i){let n=null;return dt(i.getChildren(),e=>{if($isListNode(e))return "skip-children";if(typeof e.getStyle=="function"){let t=me(e,bi);if(t)return n=Mn(t),"stop"}}),n}function od(i){let n=[i];for(;n.length>0;){let e=n.pop();if(e.getListType()==="check")for(let t of e.getChildren()){if(!$isListItemNode(t))continue;let o=Fo(t);for(let r of o)if(me(r,Rn)==="plain")return "plain";n.push(...Ve(t));}}return null}function rd(i){let n=[i];for(;n.length>0;){let e=n.pop();if(e.getListType()==="bullet")for(let t of e.getChildren()){if(!$isListItemNode(t))continue;let o=me(t,Oe),r=Mn(o);if(o&&Object.hasOwn(It,r))return r;let s=nd(t);if(s)return s;n.push(...Ve(t));}}return null}function _o(i){let n=rd(i);if(n)return n;let e=me(i,Oe);return Mn(e)}function Ao(i){return me(i,Rn)==="plain"?"plain":od(i)??"strikethrough"}function wn(i){let n=i.anchor.getNode(),e=null,t=null;for(;n;){if(!t&&$isListItemNode(n)&&(t=n),$isListNode(n)){e=n;break}n=n.getParent();}let o=e?_t(e):null;return {listNode:e,listItemNode:t,topListNode:o}}var Pn=class extends w{constructor(n={}){super("list",["toolbar"]),this.config=n;}getMaxListDepth(){let n=this.config.maxDepth;if(!Number.isFinite(n))return li;let e=Math.floor(n);return e>=1?e:li}register(n){let e=n.registerNodeTransform(ListNode,s=>{this.syncListNodeStyles(s);}),t=n.registerNodeTransform(ListItemNode,s=>{let a=s.getParent();$isListNode(a)&&this.syncListNodeStyles(a);}),o=n.registerCommand(KEY_SPACE_COMMAND,s=>{let a=false;return n.update(()=>{a=this.handleOrderedListShortcut(n);}),a&&s.preventDefault(),a},COMMAND_PRIORITY_EDITOR),r=n.registerCommand(INDENT_CONTENT_COMMAND,()=>{let s=$getSelection();return !$isRangeSelection(s)||!wn(s).listNode?false:Ln(s,this.getMaxListDepth())},COMMAND_PRIORITY_EDITOR);return ()=>{e(),t(),o(),r();}}getNodes(){return [ListNode,ListItemNode]}getPlugins(){return [jsx(ListPlugin,{hasStrictIndent:true},"list-plugin"),jsx(CheckListPlugin,{},"check-list-plugin")]}getCommands(n){return {toggleUnorderedList:()=>{n.update(()=>{let e=$getSelection();if(!$isRangeSelection(e))return;let t=wn(e);if(t.topListNode){if(t.topListNode.getListType()==="bullet"){t.listItemNode&&t.listItemNode.getIndent()>0?n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode);return}this.convertTopListType(t.topListNode,"bullet");return}n.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0);});},toggleOrderedList:()=>{n.update(()=>{let e=$getSelection();if(!$isRangeSelection(e))return;let t=wn(e);if(t.topListNode){if(t.topListNode.getListType()==="number"){t.listItemNode&&t.listItemNode.getIndent()>0?n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode);return}this.convertTopListType(t.topListNode,"number");return}n.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);});},toggleCheckList:()=>{n.update(()=>{let e=$getSelection();if(!$isRangeSelection(e))return;let t=wn(e);if(t.topListNode){if(t.topListNode.getListType()==="check"){t.listItemNode&&t.listItemNode.getIndent()>0?n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode);return}this.convertTopListType(t.topListNode,"check");return}n.dispatchCommand(INSERT_CHECK_LIST_COMMAND,void 0);});},indentList:()=>{n.update(()=>{let e=$getSelection();$isRangeSelection(e)&&(Ln(e,this.getMaxListDepth())||n.dispatchCommand(INDENT_CONTENT_COMMAND,void 0));});},outdentList:()=>{n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0);},insertNestedUnorderedList:()=>{n.update(()=>{let e=$getSelection();!$isRangeSelection(e)||Ln(e,this.getMaxListDepth())||(n.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),n.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0));});},insertNestedOrderedList:()=>{n.update(()=>{let e=$getSelection();!$isRangeSelection(e)||Ln(e,this.getMaxListDepth())||(n.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),n.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0));});},setOrderedListPattern:e=>{n.update(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;n.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);let o=$getSelection();if(!$isRangeSelection(o))return;let r=ct(o);for(let s of r)this.applyOrderedPattern(s,e);});},setOrderedListSuffix:e=>{n.update(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;let o=ct(t);for(let r of o)r.getListType()==="number"&&this.applyOrderedSuffix(r,e);});},setUnorderedListPattern:e=>{n.update(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;n.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0);let o=$getSelection();if(!$isRangeSelection(o))return;let r=ct(o);for(let s of r)this.applyUnorderedPattern(s,e);});},setCheckListVariant:e=>{let t=false;n.update(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let r=ct(o);if(r.length===0){t=true;return}for(let s of r)s.getListType()!=="check"&&this.convertTopListType(s,"check"),this.applyCheckListVariant(s,e);}),t&&(n.dispatchCommand(INSERT_CHECK_LIST_COMMAND,void 0),n.update(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let r=ct(o);for(let s of r)s.getListType()!=="check"&&this.convertTopListType(s,"check"),this.applyCheckListVariant(s,e);}));},rehydrateListStyles:()=>{n.update(()=>{let e=$getRoot(),t=new Map;dt(e.getChildren(),o=>{if($isListNode(o)){let r=_t(o);t.set(r.getKey(),r);}});for(let o of t.values()){if(o.getListType()==="number"){let r=me(o,"--luthor-ordered-pattern")??lt,s=Object.hasOwn(at,r)?r:lt,a=me(o,"--luthor-ordered-suffix")==="paren"?"paren":"dot";this.applyOrderedPattern(o,s),this.applyOrderedSuffix(o,a);continue}if(o.getListType()==="bullet"){let r=_o(o);this.applyUnorderedPattern(o,r);continue}if(o.getListType()==="check"){let r=Ao(o);this.applyCheckListVariant(o,r);}}});}}}applyOrderedPattern(n,e){if(n.getListType()!=="number")return;let t=at[e],o=me(n,"--luthor-ordered-suffix")??"dot";ee(n,{"--luthor-ordered-pattern":e,"--luthor-ordered-suffix":o});let r=[n];for(;r.length>0;){let s=r.pop();if(s.getListType()!=="number")continue;let a=Nn(s,n),l=Tn(t,a),d=e==="decimal-hierarchical";ee(s,{"--luthor-ordered-pattern":e,"--luthor-ordered-suffix":o,"list-style-type":"none",[Ee]:null});let c=d?fi(s,n):null,u=0;for(let m of s.getChildren()){if(!$isListItemNode(m))continue;let h=Ot(m);h&&(u+=1);let N=gi(l,Math.max(1,u),o==="paren"?"paren":"dot",d?[...c??[],Math.max(1,u)]:null);ee(m,{[Ee]:h?N:null}),r.push(...Ve(m));}}}applyOrderedSuffix(n,e){let t=[n];for(;t.length>0;){let s=t.pop();if(s.getListType()==="number"){ee(s,{"--luthor-ordered-suffix":e});for(let a of s.getChildren())$isListItemNode(a)&&t.push(...Ve(a));}}let o=me(n,"--luthor-ordered-pattern")??lt,r=Object.hasOwn(at,o)?o:lt;this.applyOrderedPattern(n,r);}applyUnorderedPattern(n,e){if(n.getListType()!=="bullet")return;let t=It[e];ee(n,{[Oe]:e});let o=[n];for(;o.length>0;){let r=o.pop();if(r.getListType()!=="bullet")continue;let s=Nn(r,n),a=Tn(t,s),l=Ho(a);ee(r,{[Oe]:e,"list-style-type":"none","--luthor-unordered-marker-content":null,[_e]:null,[Ee]:null});for(let d of r.getChildren())$isListItemNode(d)&&(ee(d,{[Oe]:e,"--luthor-unordered-marker-content":null,[_e]:Ot(d)?l:null,[Ee]:null}),Io(d,e),o.push(...Ve(d)));}}applyCheckListVariant(n,e){if(n.getListType()!=="check")return;let t=[n];for(;t.length>0;){let o=t.pop();if(o.getListType()==="check"){ee(o,{"--luthor-checklist-variant":e,"--luthor-unordered-marker-content":null,[_e]:null,[Ee]:null,"--luthor-unordered-pattern":null,"--luthor-ordered-pattern":null,"--luthor-ordered-suffix":null,"list-style-type":null});for(let r of o.getChildren()){if(!$isListItemNode(r))continue;ee(r,{"--luthor-checklist-variant":e,[Oe]:null,"--luthor-unordered-marker-content":null,[_e]:null,[Ee]:null}),Io(r,null);let s=Fo(r);for(let a of s)ee(a,{[Rn]:e==="plain"?"plain":null});t.push(...Ve(r));}}}}syncListNodeStyles(n){let e=_t(n);if(e.getListType()==="number"){let t=me(e,"--luthor-ordered-pattern")??lt;if(!Object.hasOwn(at,t))return;let o=at[t],r=Nn(n,e),s=Tn(o,r),a=t==="decimal-hierarchical",l=me(e,"--luthor-ordered-suffix")??"dot";ee(n,{"--luthor-ordered-pattern":t,"--luthor-ordered-suffix":l,"list-style-type":"none",[Ee]:null});let d=a?fi(n,e):null,c=0;for(let u of n.getChildren()){if(!$isListItemNode(u))continue;let m=Ot(u);m&&(c+=1);let h=gi(s,Math.max(1,c),l==="paren"?"paren":"dot",a?[...d??[],Math.max(1,c)]:null);ee(u,{[Ee]:m?h:null});}return}if(e.getListType()==="bullet"){let t=_o(e),o=It[t],r=Nn(n,e),s=Tn(o,r),a=Ho(s);ee(n,{[Oe]:t,"list-style-type":"none","--luthor-unordered-marker-content":null,[_e]:null,[Ee]:null});for(let l of n.getChildren())$isListItemNode(l)&&(ee(l,{[Oe]:t,"--luthor-unordered-marker-content":null,[_e]:Ot(l)?a:null,[Ee]:null}),Io(l,t));return}if(e.getListType()==="check"){let t=Ao(e);ee(n,{"--luthor-checklist-variant":t,"--luthor-unordered-marker-content":null,[_e]:null,[Ee]:null,"--luthor-unordered-pattern":null,"--luthor-ordered-pattern":null,"--luthor-ordered-suffix":null,"list-style-type":null});for(let o of n.getChildren()){if(!$isListItemNode(o))continue;ee(o,{"--luthor-checklist-variant":t,[Oe]:null,"--luthor-unordered-marker-content":null,[_e]:null,[Ee]:null});let r=Fo(o);for(let s of r)ee(s,{[Rn]:t==="plain"?"plain":null});}}}convertTopListType(n,e){let t=[n];for(;t.length>0;){let r=t.pop();r.setListType(e);for(let s of r.getChildren())$isListItemNode(s)&&t.push(...Ve(s));}if(e==="number"){let r=me(n,"--luthor-ordered-pattern"),s=r&&Object.hasOwn(at,r)?r:lt,a=me(n,"--luthor-ordered-suffix")==="paren"?"paren":"dot";this.applyOrderedPattern(n,s),this.applyOrderedSuffix(n,a);return}if(e==="bullet"){let r=_o(n);this.applyUnorderedPattern(n,r);return}let o=Ao(n);this.applyCheckListVariant(n,o);}handleOrderedListShortcut(n){let e=$getSelection();if(!$isRangeSelection(e)||!e.isCollapsed())return false;let t=e.anchor.getNode();if(kn(t))return false;let o=t;for(;o&&!$isParagraphNode(o);)o=o.getParent();if(!$isParagraphNode(o))return false;let r=o,s=td(r.getTextContent());if(!s)return false;r.clear(),n.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);let a=$getSelection();if(!$isRangeSelection(a))return true;let l=ct(a);for(let d of l)d.getListType()==="number"&&(this.applyOrderedPattern(d,s.pattern),this.applyOrderedSuffix(d,s.suffix));return true}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);});})}}},id=new Pn;var ad="plain";function At(){return ad}function xi(){return PrismTokenizer}async function Ei(i){return i?.provider?i.provider:i?.loadProvider?i.loadProvider():null}async function Ci(i){return i?i.tokenizer?i.tokenizer:i.getTokenizer?i.getTokenizer():null:null}var An=class An extends w{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??xi()),this.resolveConfiguredTokenizer().then(a=>{o||!a||r(a);}));let s=e.registerCommand(KEY_TAB_COMMAND,a=>{let l=false;return e.update(()=>{let d=$getSelection();if(!$isRangeSelection(d))return;let c=d.anchor.getNode();this.getBlockNode(c)&&(l=true,!this.hasReachedCodeTabLimit(d)&&d.insertText(" "));}),l?(a?.preventDefault(),true):false},COMMAND_PRIORITY_LOW);return ()=>{o=true,t(),s();}}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?.(At()),r});}});}async resolveConfiguredTokenizer(){if(this.config.tokenizer)return this.config.tokenizer;let e=await this.loadCodeHighlightProvider();return Ci(e)}async loadCodeHighlightProvider(){return this.config.provider?this.config.provider:this.codeHighlightProviderPromise?this.codeHighlightProviderPromise:(this.codeHighlightProviderPromise=Ei(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 s=r.getNodes();for(let a of s){let l=this.getBlockNode(a);if(!l){o=false;break}if(this.getNodeFormat(l)!==e){o=false;break}}}),o}getBlockNode(e){let 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}hasReachedCodeTabLimit(e){let t=e.anchor,o=t.getNode();if(typeof o.getTextContent!="function")return false;let r=o.getTextContent(),s=typeof t.offset=="number"?t.offset:r.length,a=Math.max(0,Math.min(r.length,s)),l=r.lastIndexOf(`
|
|
5
|
-
`,a-1)+1;return (r.slice(l,a).match(/^\t*/)?.[0].length??0)>=An.MAX_CODE_TAB_DEPTH}};x(An,"MAX_CODE_TAB_DEPTH",8);var _n=An,pd=new _n;var Td='<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>',Ld='<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>',wd=["plaintext","typescript","javascript","markdown","html","css","python","sql","java","c","cpp","rust","powershell","xml"],Hn=class extends w{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:s})=>{(r.size>0||s.size>0)&&this.ensureCodeBlockThemes(e);});return queueMicrotask(()=>{this.ensureCodeBlockThemes(e);}),()=>{t(),o(),this.languageOptions=[];}}getPlugins(){return [createElement(kd,{key:"code-intelligence-controls",extension:this})]}getCommands(e){return {setCodeLanguage:t=>{let o=ut(t),r=this.getThemeForLanguage(o);e.update(()=>{this.getSelectionCodeNodes().forEach(s=>{s.setLanguage(o??null),s.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:Pi(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=ut(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 s=ut(o);r.setLanguage(s??null),r.setTheme(this.getThemeForLanguage(s));});}getCodeBlockText(e,t){return e.getEditorState().read(()=>{let o=$getNodeByKey(t);return !o||!$isCodeNode(o)?"":o.getTextContent()})}getThemeForLanguage(e){let t=ut(e);return !t||t==="plain"?At():"hljs"}ensureCodeBlockThemes(e){let t=e.getEditorState().read(()=>$nodesOfType(CodeNode).map(o=>{let r=o.getTheme?.()??"",s=this.getThemeForLanguage(o.getLanguage());return {key:o.getKey(),nextTheme:s??At(),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 s=this.getNearestCodeNode(r);s&&o.set(s.getKey(),s);}),Array.from(o.values())}getNearestCodeNode(e){let t=e;for(;t;){if($isCodeNode(t))return t;t=t.getParent();}return null}getLanguageOptions(){let e=wd.map(r=>ut(r)).filter(r=>!!r),t=Id(this.config.languageOptions);if(!t)return zo(e);let o=_d(t.values);return t.mode==="replace"?zo(o):zo([...e,...o])}async getPrimaryCodeBlockText(e){return new Promise(t=>{e.getEditorState().read(()=>{let r=this.getSelectionCodeNodes()[0];if(!r){t(null);return}let s=r.getTextContent().trim();if(!s){t(null);return}t({key:r.getKey(),text:s});});})}},Rd=34;function kd({extension:i}){let[n]=useLexicalComposerContext(),[e,t]=useState([]),[o,r]=useState({}),s=useRef(null),a=useRef(new Map),l=useMemo(()=>i.getLanguageOptionsSnapshot(),[i]),d=useCallback(()=>{let p=ki(n);if(!p)return [];let g=p.getBoundingClientRect(),E=i.getCodeBlocksSnapshot(n),T=[];return E.forEach(b=>{let S=n.getElementByKey(b.key);if(!S||!S.isConnected)return;S.classList.add("luthor-code-block--interactive");let M=S.getBoundingClientRect(),B=Math.max(120,Math.round(M.width)),j=Math.max(0,Math.round(M.top-g.top-Rd)),_=Math.max(0,Math.round(M.left-g.left));T.push({key:b.key,language:b.language,top:j,left:_,width:B});}),T},[n,i]),c=useCallback(()=>{let p=d();t(g=>Pd(g,p)?g:p);},[d]),u=useCallback(()=>{s.current===null&&(s.current=requestAnimationFrame(()=>{s.current=null,c();}));},[c]),m=useCallback(p=>{let g=a.current.get(p);g&&(clearTimeout(g),a.current.delete(p));},[]),h=useCallback((p,g)=>{m(p),r(T=>({...T,[p]:g}));let E=setTimeout(()=>{r(T=>{if(!(p in T))return T;let b={...T};return delete b[p],b}),a.current.delete(p);},1200);a.current.set(p,E);},[m]),N=useCallback((p,g)=>{i.setCodeBlockLanguage(n,p,g),u();},[n,i,u]),v=i.isCopyAllowed(),y=useCallback(async p=>{if(!v)return;let g=i.getCodeBlockText(n,p);if(!g.trim())return;if(await Pi(g)){h(p,"copied");return}h(p,"error");},[v,n,i,h]);if(useEffect(()=>{u();let p=0,g=null,E=()=>{u(),p+=1,!(p>=20)&&(g=requestAnimationFrame(E));};g=requestAnimationFrame(E);let T=n.registerUpdateListener(()=>{u();}),b=()=>{u();},S=a.current;return window.addEventListener("scroll",b,true),window.addEventListener("resize",b,{passive:true}),()=>{T(),window.removeEventListener("scroll",b,true),window.removeEventListener("resize",b),g!==null&&cancelAnimationFrame(g),s.current!==null&&(cancelAnimationFrame(s.current),s.current=null),S.forEach(M=>clearTimeout(M)),S.clear();}},[n,u]),useEffect(()=>{let p=new Set(e.map(g=>g.key));r(g=>{let E=false,T={};return Object.entries(g).forEach(([b,S])=>{if(p.has(b)){T[b]=S;return}E=true,m(b);}),E?T:g});},[m,e]),typeof document>"u"||e.length===0)return null;let f=ki(n);return f?createPortal(createElement("div",{className:"luthor-codeblock-controls-layer","aria-hidden":false},e.map(p=>{let g=o[p.key],E=["luthor-codeblock-copy",g==="copied"?"is-copied":"",g==="error"?"is-copy-error":""].filter(Boolean).join(" "),T=g==="copied"?"Copied":g==="error"?"Copy failed":"Copy to clipboard";return createElement("div",{key:p.key,className:"luthor-codeblock-controls","data-code-node-key":p.key,style:{position:"absolute",top:`${p.top}px`,left:`${p.left}px`,width:`${p.width}px`}},createElement("span",{className:"luthor-codeblock-controls-left"},createElement("select",{className:"luthor-codeblock-language",value:p.language,"aria-label":"Code language",onChange:b=>{let S=b.target;N(p.key,S.value);}},l.map(b=>createElement("option",{key:b,value:b},b)))),createElement("span",{className:"luthor-codeblock-controls-right"},v?createElement("button",{className:E,type:"button","aria-label":"Copy code",title:T,"data-tooltip":T,onMouseDown:b=>{b.preventDefault();},onClick:()=>{y(p.key);},dangerouslySetInnerHTML:{__html:g==="copied"?Ld:Td}}):null))})),f):null}function Pd(i,n){if(i.length!==n.length)return false;for(let e=0;e<i.length;e+=1){let t=i[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 Pi(i){if(typeof navigator<"u"&&navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(i),!0}catch{}if(typeof document>"u")return false;let n=document.createElement("textarea");n.value=i,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 ki(i){let n=i.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 ut(i){if(!i)return null;let n=i.trim().toLowerCase();if(!n||n==="auto")return null;let e=normalizeCodeLang(n);return !e||e==="auto"||!Md(e)?null:e}function Md(i){let n=i.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 Od=new Hn;function Id(i){if(!i)return null;if(Array.isArray(i))return {mode:"append",values:i};let n=i;return {mode:n.mode??"append",values:Array.isArray(n.values)?n.values:[]}}function _d(i){let n=[],e=new Set;for(let t of i){let o=t.trim();if(!o)continue;let r=ut(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 zo(i){return Array.from(new Set(i)).sort((n,e)=>n.localeCompare(e))}var Fn=class extends oe{constructor(){super("code");}register(n){let e=super.register(n),t=n.getRootElement();if(!t)return e;let o=a=>{if(a.nodeType===Node.TEXT_NODE)return a;for(let l=0;l<a.childNodes.length;l+=1){let d=a.childNodes[l];if(!d)continue;let c=o(d);if(c)return c}return null},r=a=>{if(a.nodeType===Node.TEXT_NODE)return a;for(let l=a.childNodes.length-1;l>=0;l-=1){let d=a.childNodes[l];if(!d)continue;let c=r(d);if(c)return c}return null},s=a=>{if(a.button!==0)return;let l=window.getSelection();if(l&&l.rangeCount>0&&!l.getRangeAt(0).collapsed)return;let d=a.target;if(!(d instanceof Node))return;let c=d instanceof HTMLElement?d:d.parentElement;if(!c)return;let u=c.closest(".luthor-text-code, code");if(u instanceof HTMLElement||(u=document.elementFromPoint(a.clientX+4,a.clientY)?.closest(".luthor-text-code, code")??null),!(u instanceof HTMLElement)||!t.contains(u))return;let m=u.getBoundingClientRect(),h=Math.max(4,Math.min(8,m.width/2)),N=null,v=0;a.clientX<=m.left+h?(N=o(u),v=0):a.clientX>=m.right-h&&(N=r(u),v=N?.data.length??0),N&&(a.preventDefault(),n.focus(()=>{let y=window.getSelection();if(!y)return;let f=document.createRange();f.setStart(N,v),f.collapse(true),y.removeAllRanges(),y.addRange(f);}));};return t.addEventListener("click",s,true),()=>{t.removeEventListener("click",s,true),e();}}},Ad=new Fn;var zn=class extends w{constructor(){super("blockFormat",["toolbar"]);}register(n){let e=n.registerCommand(INSERT_PARAGRAPH_COMMAND,()=>{let o=$getSelection();if($isRangeSelection(o)){let r=o.anchor.getNode(),s=this.getBlockNode(r);if(s&&($isHeadingNode(s)||$isQuoteNode(s)))return false}return false},COMMAND_PRIORITY_NORMAL),t=n.registerCommand(KEY_ENTER_COMMAND,o=>{let r=false;return n.update(()=>{let s=$getSelection();if(!$isRangeSelection(s))return;let a=s.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 s of r){let a=this.getBlockNode(s);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 s of r){let a=this.getBlockNode(s);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}},Yd=new zn;var $n=class extends w{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}}},Zd=new $n;var Qn=class extends w{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(ru,{config:this.config,extension:this},"draggable-block")]}getCommands(e){return {moveBlock:(t,o,r)=>{e.update(()=>{let s=$getNodeByKey(t),a=$getNodeByKey(o);s&&a&&(s.remove(),r?a.insertAfter(s):a.insertBefore(s));});},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 s=r.getPreviousSibling();s&&(r.remove(),s.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 s=r.getNextSibling();s&&(r.remove(),s.insertAfter(r));}}});}}}getStateQueries(e){return {isDragging:async()=>this.isDraggingState}}setIsDragging(e){this.isDraggingState!==e&&(this.isDraggingState=e,this.stateChangeCallbacks.forEach(t=>t()));}onStateChange(e){return this.stateChangeCallbacks.add(e),()=>this.stateChangeCallbacks.delete(e)}},ou=new Qn;function ru({config:i,extension:n}){let[e]=useLexicalComposerContext(),{config:t,extensions:o}=Me(),s=o.find(C=>C.name==="draggableBlock")?.config,a=useMemo(()=>t?.theme?.draggable||{},[t?.theme?.draggable]),[l,d]=useState(null),[c,u]=useState(false),[m,h]=useState(null),[N,v]=useState(false),y=useRef(null),f=useRef(null),p=useRef(null),g=useRef(null),E=useRef(null),T=useRef(null),b=useRef(null),S=useRef(null),[M,B]=useState(null);useEffect(()=>{n.setIsDragging(c);},[c,n]);let j=typeof document<"u"&&typeof window<"u",_=e.getRootElement(),q=j?_?.closest?.(".luthor-editor")||_?.parentElement||document.body:null,z=s?.anchorElem||i.anchorElem||q,F=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:{...F.handle,...a.styles?.handle,...s?.styles?.handle},handleActive:{...F.handleActive,...a.styles?.handleActive,...s?.styles?.handleActive},blockDragging:{...F.blockDragging,...a.styles?.blockDragging,...s?.styles?.blockDragging},dropIndicator:{...F.dropIndicator,...a.styles?.dropIndicator,...s?.styles?.dropIndicator},addButton:{...F.addButton,...a.styles?.addButton,...s?.styles?.addButton},buttonStack:{...F.buttonStack,...a.styles?.buttonStack,...s?.styles?.buttonStack}}),[F,s?.styles,a.styles]),P=useMemo(()=>({handle:s?.theme?.handle||a.handle||"luthor-draggable-handle",handleActive:s?.theme?.handleActive||a.handleActive||"luthor-draggable-handle-active",blockDragging:s?.theme?.blockDragging||a.blockDragging||"luthor-draggable-block-dragging",dropIndicator:s?.theme?.dropIndicator||a.dropIndicator||"luthor-draggable-drop-indicator",addButton:s?.theme?.addButton||a.addButton||"luthor-draggable-add-button",buttonStack:s?.theme?.buttonStack||a.buttonStack||"luthor-draggable-button-stack"}),[s?.theme,a]),Y=useCallback(C=>{if(!C||!P.blockDragging)return;(P.blockDragging.includes(" ")?P.blockDragging.split(" ").filter(Boolean):[P.blockDragging]).forEach(k=>C.classList.remove(k)),C.style.opacity="";},[P]),K=useCallback(C=>{if(!C||!P.blockDragging)return;(P.blockDragging.includes(" ")?P.blockDragging.split(" ").filter(Boolean):[P.blockDragging]).forEach(k=>C.classList.add(k)),Object.assign(C.style,A.blockDragging);},[P,A.blockDragging]),J=useCallback(()=>{let C=e.getRootElement();if(C)try{C.focus({preventScroll:!0});}catch{C.focus();}},[e]),V=useCallback(()=>{y.current&&Y(y.current),u(false),h(null),J(),setTimeout(()=>{y.current=null,f.current=null;},100);},[Y,J]);useEffect(()=>()=>{y.current&&Y(y.current),g.current&&clearTimeout(g.current),E.current!==null&&window.cancelAnimationFrame(E.current),b.current!==null&&window.cancelAnimationFrame(b.current);},[Y]),useEffect(()=>{p.current=l;},[l]);let te=useCallback(C=>{T.current=C,E.current===null&&(E.current=window.requestAnimationFrame(()=>{E.current=null;let R=T.current;d(k=>k===R?k:R);}));},[]),ce=useCallback(C=>{S.current=C,b.current===null&&(b.current=window.requestAnimationFrame(()=>{b.current=null;let R=S.current;R!=null&&B(k=>k!=null&&Math.abs(k-R)<.5?k:R);}));},[]),Te=useCallback(C=>{let R=null;e.update(()=>{let k=$createParagraphNode(),I=$getNearestNodeFromDOMNode(C);if(I)try{I.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"){te(k);let I=k.getBoundingClientRect();ce(I.top+window.scrollY+I.height/2);}},0),J();},[e,J,te,ce]);useEffect(()=>{if(l||y.current)v(true);else {let C=setTimeout(()=>v(false),300);return ()=>clearTimeout(C)}},[l]),useEffect(()=>{let C=k=>{if(c)return;let I=e.getRootElement();if(!I)return;let O=k.target;ce(k.clientY+window.scrollY);let L=O&&O.closest&&(O.closest(".drag-handle-area")||O.closest('[draggable="true"]')||O.closest(".luthor-drag-button")||O.closest(".luthor-draggable-button-stack")),ne=window.getSelection(),U=ne&&ne.rangeCount>0&&!ne.isCollapsed,H=null,D=O;for(;D&&D!==I&&D!==document.body;){if(D.parentElement===I){H=D;break}D=D.parentElement;}g.current&&(clearTimeout(g.current),g.current=null),(H||L)&&!U&&!c?H&&te(H):g.current=setTimeout(()=>{te(null),g.current=null;},500);},R=()=>{c||(g.current&&(clearTimeout(g.current),g.current=null),g.current=setTimeout(()=>{te(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),E.current!==null&&(window.cancelAnimationFrame(E.current),E.current=null),b.current!==null&&(window.cancelAnimationFrame(b.current),b.current=null);}},[e,c,te,ce]);let Fe=useCallback((C,R)=>{C.stopPropagation(),u(true),h(null),y.current=R,K(R);let k=e.read(()=>{let O=$getNearestNodeFromDOMNode(R);return O?O.getKey():null});k&&(f.current=k,C.dataTransfer?.setData("application/x-lexical-drag",JSON.stringify({key:k}))),C.dataTransfer.effectAllowed="move";let I=R.cloneNode(true);I.style.opacity="0.6",I.style.position="absolute",I.style.top="-9999px",I.style.left="-9999px",document.body.appendChild(I),C.dataTransfer.setDragImage(I,0,0),setTimeout(()=>document.body.removeChild(I),0);},[e,K]),Le=useCallback((C,R)=>{C.preventDefault(),u(true),y.current=R,K(R);let k=e.read(()=>{let I=$getNearestNodeFromDOMNode(R);return I?I.getKey():null});k&&(f.current=k);},[e,K]),se=useCallback(C=>{if(!c||!y.current)return;C.preventDefault();let R=C.touches[0];if(!R)return;let k=e.getRootElement();if(!k)return;let I=null,O=document.elementFromPoint(R.clientX,R.clientY);if(O){let L=O;for(;L&&L!==k;){if(L.parentElement===k){I=L;break}L=L.parentElement;}}if(I&&I!==y.current){let L=I.getBoundingClientRect(),ne=R.clientY<L.top+L.height/2;h({top:ne?L.top+window.scrollY:L.bottom+window.scrollY,left:L.left+window.scrollX,width:L.width});}else h(null);},[e,c]),ge=useCallback(C=>{if(!c||!f.current)return;C.preventDefault();let R=C.changedTouches[0];if(!R)return;let k=e.getRootElement();if(!k)return;let I=null,O=document.elementFromPoint(R.clientX,R.clientY);if(O){let L=O;for(;L&&L!==k;){if(L.parentElement===k){I=L;break}L=L.parentElement;}}I&&I!==y.current&&(e.update(()=>{let L=$getNodeByKey(f.current),ne=$getNearestNodeFromDOMNode(I);if(L&&ne){let U=I.getBoundingClientRect(),H=R.clientY>=U.top+U.height/2;L.remove(),H?ne.insertAfter(L):ne.insertBefore(L);}}),setTimeout(()=>{if(f.current)try{let L=e.getElementByKey(f.current);L&&L instanceof HTMLElement&&typeof L.getBoundingClientRect=="function"&&d(L);}catch(L){console.warn("Error finding moved element:",L);}},50)),V();},[e,c,V]);useEffect(()=>{let C=e.getRootElement();if(!C)return;let R=O=>{let L=O.target;if(L.nodeType!==Node.ELEMENT_NODE&&(L=L.parentNode),!L||!(L instanceof HTMLElement)){O.preventDefault();return}if(L.closest('[draggable="true"]'))return;let U=window.getSelection();if(!U||U.isCollapsed||!(s?.enableTextSelectionDrag??i.enableTextSelectionDrag)){O.preventDefault();return}let H=U.anchorNode;H?.nodeType===Node.TEXT_NODE&&(H=H.parentNode);let D=null;for(;H&&H!==C;){if(H.parentNode===C){D=H;break}H=H.parentNode;}if(!D){O.preventDefault();return}U.collapse(U.anchorNode,U.anchorOffset);let Z=e.read(()=>$getNearestNodeFromDOMNode(D)?.getKey()??null);if(!Z){O.preventDefault();return}O.dataTransfer.clearData(),O.dataTransfer.setData("application/x-lexical-drag",JSON.stringify({key:Z})),O.dataTransfer.effectAllowed="move";let Q=D.cloneNode(true);Q.style.opacity="0.6",Q.style.position="absolute",Q.style.top="-9999px",Q.style.left="-9999px",document.body.appendChild(Q),O.dataTransfer.setDragImage(Q,0,0),setTimeout(()=>document.body.removeChild(Q),0),u(true),h(null),y.current=D,K(D),f.current=Z;},k=O=>{let L=O.target;if(L.nodeType!==Node.ELEMENT_NODE&&(L=L.parentNode),!L||!(L instanceof HTMLElement))return;let ne=L;O.preventDefault(),O.dataTransfer.dropEffect="move";let U=null,H=ne;for(;H&&H!==C;){if(H.parentElement===C){U=H;break}H=H.parentElement;}if(U&&U!==y.current){let D=U.getBoundingClientRect(),Z=O.clientY<D.top+D.height/2;h({top:Z?D.top+window.scrollY:D.bottom+window.scrollY,left:D.left+window.scrollX,width:D.width});}else h(null);},I=O=>{let L=O.target;if(L.nodeType!==Node.ELEMENT_NODE&&(L=L.parentNode),!L||!(L instanceof HTMLElement))return;let ne=L;O.preventDefault(),h(null);let U=O.dataTransfer?.getData("application/x-lexical-drag");if(!U){V();return}let{key:H}=JSON.parse(U);if(!H){V();return}let D=null,Z=ne;for(;Z&&Z!==C;){if(Z.parentElement===C){D=Z;break}Z=Z.parentElement;}D&&D!==y.current&&(e.update(()=>{let Q=$getNodeByKey(H),Re=$getNearestNodeFromDOMNode(D);if(Q&&Re){let Ze=D.getBoundingClientRect(),$t=O.clientY>=Ze.top+Ze.height/2;Q.remove(),$t?Re.insertAfter(Q):Re.insertBefore(Q);}}),setTimeout(()=>{if(f.current)try{let Q=e.getElementByKey(f.current);Q&&Q instanceof HTMLElement&&typeof Q.getBoundingClientRect=="function"&&d(Q);}catch(Q){console.warn("Error finding moved element:",Q);}J();},50)),V();};return C.addEventListener("dragstart",R),C.addEventListener("dragover",k),C.addEventListener("drop",I),C.addEventListener("dragend",V),()=>{C.removeEventListener("dragstart",R),C.removeEventListener("dragover",k),C.removeEventListener("drop",I),C.removeEventListener("dragend",V);}},[e,V,K,J,s?.enableTextSelectionDrag,i.enableTextSelectionDrag]),useEffect(()=>{if(!c)return;let C=()=>{V();},R=I=>{I.key==="Escape"&&V();},k=()=>{document.hidden&&V();};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,V]),useEffect(()=>{let C=e.getRootElement();if(!C)return;let R=null,k=0,I=0,O=U=>{if(U.touches.length!==1||!(s?.enableTextSelectionDrag??i.enableTextSelectionDrag))return;let H=U.touches[0];if(!H)return;let D=U.target;if(D.nodeType!==Node.ELEMENT_NODE&&(D=D.parentNode),!D||!(D instanceof HTMLElement))return;let Z=D;Z.closest('[draggable="true"]')||(k=H.clientX,I=H.clientY,R=setTimeout(()=>{R=null;let Q=null,Re=Z;for(;Re&&Re!==C;){if(Re.parentElement===C){Q=Re;break}Re=Re.parentElement;}if(!Q)return;let Ze=window.getSelection();Ze&&!Ze.isCollapsed&&Ze.collapseToStart(),u(true),y.current=Q,K(Q);let $t=e.read(()=>$getNearestNodeFromDOMNode(Q)?.getKey()??null);$t&&(f.current=$t);},500));},L=U=>{if(R&&U.touches.length===1){let H=U.touches[0];if(!H)return;let D=H.clientX-k,Z=H.clientY-I;Math.sqrt(D*D+Z*Z)>10&&(clearTimeout(R),R=null);}},ne=()=>{R&&(clearTimeout(R),R=null);};return C.addEventListener("touchstart",O,{passive:false}),C.addEventListener("touchmove",L,{passive:false}),C.addEventListener("touchend",ne,{passive:false}),document.addEventListener("touchmove",se,{passive:false}),document.addEventListener("touchend",ge,{passive:false}),()=>{C.removeEventListener("touchstart",O),C.removeEventListener("touchmove",L),C.removeEventListener("touchend",ne),document.removeEventListener("touchmove",se),document.removeEventListener("touchend",ge);}},[e,K,V,c,se,ge,s?.enableTextSelectionDrag,i.enableTextSelectionDrag]);let we=l||y.current;if(!j||!z||!we||typeof we.getBoundingClientRect!="function")return null;let fe=we.getBoundingClientRect();if(!fe.width||!fe.height)return null;let Ge=_?.closest?.(".luthor-editor")||null,to=Ge||_;if(!to)return null;let is=to.getBoundingClientRect(),ss=window.getComputedStyle(to),as=Number.parseFloat(ss.getPropertyValue("--luthor-drag-gutter-width"))||40,Xo=(s?.showAddButton??i.showAddButton)!==false,ls=Xo?52:24,cs=is.left+window.scrollX+Math.max(0,(as-ls)/2),ds=(s?.buttonStackPosition||i.buttonStackPosition)==="right"?fe.right+window.scrollX+(s?.offsetRight||i.offsetRight||10):Ge?cs:fe.left+window.scrollX+(s?.offsetLeft||i.offsetLeft||-40),zt=24,Go=zt/2,no=fe.top+window.scrollY,Zo=fe.bottom+window.scrollY,us=no+fe.height/2,ms=M??us,gs=no+zt/2,fs=Zo-zt/2,ps=Math.min(fs,Math.max(gs,ms)),er=no,hs=Math.max(er,Zo-(Go+zt/2)),bs=Math.min(hs,Math.max(er,ps-Go)),tr=z.getBoundingClientRect(),nr=z===document.body?0:tr.left+window.scrollX,or=z===document.body?0:tr.top+window.scrollY,ys=ds-nr,xs=bs-or;return jsxs(Fragment,{children:[createPortal(jsx("div",{className:`luthor-draggable-button-stack ${P.buttonStack} ${N?"":"fade-out"}`,style:{position:"absolute",left:0,top:0,transform:`translate3d(${ys}px, ${xs}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:[Xo&&jsx("button",{type:"button","aria-label":"Add block",title:"Add",className:`luthor-drag-button ${P.addButton}`,onMouseDown:C=>{C.preventDefault(),C.stopPropagation();},onClick:C=>{C.preventDefault(),C.stopPropagation(),!(!we||c)&&Te(we);},style:A.addButton,children:"+"}),s?.handleRenderer||i.handleRenderer?(s?.handleRenderer||i.handleRenderer)({rect:fe,isDragging:c,onDragStart:C=>Fe(C,we),className:`luthor-drag-button ${P.handle} ${c?P.handleActive:""}`.trim()}):jsx("div",{className:`luthor-drag-button ${P.handle} ${c?P.handleActive:""}`.trim(),draggable:true,onDragStart:C=>Fe(C,we),onDragEnd:V,onTouchStart:C=>Le(C,we),style:c?A.handleActive:A.handle,children:"\u22EE\u22EE"})]})}),z),m&&(s?.dropIndicatorRenderer||i.dropIndicatorRenderer?createPortal((s?.dropIndicatorRenderer||i.dropIndicatorRenderer)({...m,className:P.dropIndicator}),z):createPortal(jsx("div",{className:P.dropIndicator,style:{position:"absolute",top:m.top-4-or,left:m.left-nr,width:m.width,height:"8px",pointerEvents:"none",zIndex:9997,...A.dropIndicator}}),z))]})}function $i(i){let n=renderToStaticMarkup(i),e=document.createElement("div");e.innerHTML=n;let t=e.firstElementChild;return e.remove(),t}function pu(i){let n=i.isContainer??false,e=createCommand("insert-custom-node");function t({node:l,payload:d,nodeKey:c,children:u}){let[m]=useLexicalComposerContext(),[h,N]=useState(false);useEffect(()=>m.registerUpdateListener(({editorState:y})=>{y.read(()=>{let f=$getSelection();N($isNodeSelection(f)&&f.getNodes().some(p=>p.__key===c));});}),[m,c]);let v=y=>{m.update(()=>{let f=l.getWritable();f.__payload={...f.__payload,...y};});};return i.render?i.render({node:l,payload:d,children:u,nodeKey:c,isSelected:h,updatePayload:v}):null}class o extends ElementNode{constructor(c={},u,m){super(m);x(this,"__payload");x(this,"__nodeType");this.__payload=c,this.__nodeType=u;}static getType(){return i.nodeType}static clone(c){return new o(c.__payload,c.__nodeType,c.__key)}isSelectable(){return true}canBeEmpty(){return false}canInsertTextBefore(){return false}canInsertTextAfter(){return false}static importJSON(c){let{payload:u}=c;return new o(u,c.type)}static importDOM(){return i.importDOM?i.importDOM():{}}static exportDOM(c,{node:u}){if(i.exportDOM){let h=document.createElement("div");return i.exportDOM(c,{element:h,node:u})}let m=document.createElement("div");return m.setAttribute("data-custom-node-type",i.nodeType),{element:m}}exportJSON(){return {type:this.__nodeType,version:1,payload:this.__payload,children:this.getChildren().map(c=>c.exportJSON()),direction:null,format:"",indent:0}}createDOM(c){if(i.createDOM){let m=i.createDOM(c,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m.setAttribute("data-lexical-key",this.getKey()),m}if(i.jsx){let m=i.jsx({node:this,payload:this.__payload,nodeKey:this.getKey(),isSelected:false,updatePayload:N=>{this.setPayload(N);}}),h=$i(m);return h.setAttribute("data-custom-node-type",this.__nodeType),h.setAttribute("data-lexical-key",this.getKey()),h}let u=document.createElement("div");return u.setAttribute("data-custom-node-type",this.__nodeType),u.setAttribute("data-lexical-key",this.getKey()),u.style.border="2px solid #ccc",u.style.borderRadius="8px",u.style.padding="16px",u.style.margin="8px 0",u.style.position="relative",u}updateDOM(c,u,m){return i.updateDOM?i.updateDOM(c,u,m):false}getPayload(){return this.__payload}setPayload(c){let u=this.getWritable();u.__payload={...this.__payload,...c};}}class r extends DecoratorNode{constructor(c={},u,m){super(m);x(this,"__payload");x(this,"__nodeType");this.__payload=c,this.__nodeType=u;}static getType(){return i.nodeType}static clone(c){return new r(c.__payload,c.__nodeType,c.__key)}isSelectable(){return true}static importJSON(c){let{payload:u}=c;return new r(u,c.type)}static importDOM(){return i.importDOM?i.importDOM():{}}static exportDOM(c,{node:u}){if(i.exportDOM){let h=document.createElement("span");return i.exportDOM(c,{element:h,node:u})}let m=document.createElement("span");return m.setAttribute("data-custom-node-type",i.nodeType),{element:m}}exportJSON(){return {type:this.__nodeType,version:1,payload:this.__payload}}createDOM(c){let u=document.createElement("span");if(u.setAttribute("data-custom-node-type",this.__nodeType),i.createDOM){let m=i.createDOM(c,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m}return u}updateDOM(c,u,m){return i.updateDOM?i.updateDOM(c,u,m):false}getPayload(){return this.__payload}setPayload(c){let u=this.getWritable();u.__payload={...this.__payload,...c};}decorate(){return jsx(t,{node:this,payload:this.__payload,nodeKey:this.__key})}}function s(l=i.defaultPayload||{}){if(n){let d=new o(l,i.nodeType);if(i.initialChildren)i.initialChildren().forEach(u=>{if(u.type==="paragraph"){let m=$createParagraphNode();u.children&&u.children.forEach(h=>{h.type==="text"&&m.append($createTextNode(h.text||""));}),d.append(m);}});else {let c=$createParagraphNode();c.append($createTextNode("")),d.append(c);}return d}else return new r(l,i.nodeType)}class a extends w{constructor(){super(i.nodeType,["toolbar"]);}register(d){let c=d.registerCommand(e,m=>(d.update(()=>{let h=s(m),N=$getSelection();$isRangeSelection(N)?N.insertNodes([h]):$getRoot().append($createParagraphNode().append(h));}),true),COMMAND_PRIORITY_EDITOR),u=d.registerUpdateListener(({editorState:m})=>{n&&m.read(()=>{let h=$getSelection(),N=$isNodeSelection(h)?h.getNodes():[];d.getEditorState().read(()=>{let v=$getRoot(),y=f=>{if(f.getType()===i.nodeType){let p=N.some(E=>E.__key===f.__key),g=document.querySelector(`[data-lexical-key="${f.__key}"]`);g&&(g.setAttribute("data-selected",p.toString()),g.style.borderColor=p?"#007ACC":"#ccc",g.style.backgroundColor=p?"#f0f8ff":"transparent");}"getChildren"in f&&f.getChildren().forEach(y);};y(v);});});});return ()=>{c(),u();}}getNodes(){return n?[o]:[r]}getCommands(d){return {...{insertCustomNode:u=>d.dispatchCommand(e,u)},...i.commands?i.commands(d):{}}}getStateQueries(d){return {...{isCustomNodeActive:()=>new Promise(u=>{d.getEditorState().read(()=>{let m=$getSelection();u(!!m&&$isNodeSelection(m)&&m.getNodes().some(h=>h.getType()===i.nodeType));});})},...i.stateQueries?i.stateQueries(d):{}}}}return {extension:new a,$createCustomNode:s,jsxToDOM:$i}}function ji(i,n,e){return e<=n?n:Math.min(e,Math.max(n,i))}function Eu(i,n,e,t){let o=i.getBoundingClientRect(),r=n.getBoundingClientRect(),s=ji(e,o.left+1,o.right-1),a=ji(t,r.top+1,r.bottom-1);return {x:s,y:a}}function Cu(i,n){let e=document,t=window.getSelection();if(!t)return;let o=e.caretPositionFromPoint?.(i,n);if(o){let s=document.createRange();s.setStart(o.offsetNode,o.offset),s.collapse(true),t.removeAllRanges(),t.addRange(s);return}let r=e.caretRangeFromPoint?.(i,n);r&&(r.collapse(true),t.removeAllRanges(),t.addRange(r));}function Su(i,n,e){let r=Array.from(i.children).filter(l=>l instanceof HTMLElement).reduce((l,d)=>{let c=d.getBoundingClientRect(),u=c.top+c.height/2;if(!l)return d;let m=l.getBoundingClientRect(),h=m.top+m.height/2;return Math.abs(u-e)<Math.abs(h-e)?d:l},null)??i.firstElementChild??i,{x:s,y:a}=Eu(i,r,n,e);i.focus(),Cu(s,a);}var Ui=i=>{let{contentEditable:n,placeholder:e,className:t,classNames:o,styles:r,errorBoundary:s}=i,l=bu.useContext(gt)?.config,d=typeof l?.placeholder=="string"?l.placeholder:void 0,c=l?.classNames,u=l?.styles,m=e??d??"Start writing...",h=o?.placeholder||c?.placeholder||Be.richText?.placeholder||"luthor-placeholder",N={position:"absolute",pointerEvents:"none",zIndex:1,...u?.placeholder,...r?.placeholder};return jsx("div",{className:o?.container||c?.container||t||Be.container||"luthor-editor-container",onMouseDown:v=>{if(v.button!==0)return;let y=v.target;if(!y||y.closest("button, a, input, textarea, select, [role='button']"))return;let p=v.currentTarget.querySelector("[contenteditable='true']");!p||p.contains(y)||(v.preventDefault(),Su(p,v.clientX,v.clientY));},style:{position:"relative",cursor:"text",...u?.container,...r?.container},children:jsx(RichTextPlugin,{contentEditable:n||jsx("div",{style:{display:"block"},children:jsx(ContentEditable,{className:o?.contentEditable||c?.contentEditable||Be.richText?.contentEditable||"luthor-content-editable",style:{...u?.contentEditable,...r?.contentEditable}})}),placeholder:typeof m=="string"?jsx("div",{className:h,style:N,children:m}):m||jsx("div",{className:h,style:N,children:"Start writing..."}),ErrorBoundary:s||Tu})})},Yo=class extends w{constructor(n={}){super("richText",["floating"]),this.config={showInToolbar:false,position:"after",...n};}register(n){return ()=>{}}getPlugins(){return [jsx(Ui,{...this.config},"rich-text")]}},vu=new Yo,Nu=i=>jsx(Ui,{...i}),Tu=({children:i,onError:n})=>{try{return jsx(Fragment,{children:i})}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 Ji=8,Au=9,Vn=class extends w{constructor(n={}){super("tabIndent",["toolbar"]),this.config=n;}register(n){let e=n.registerCommand(KEY_TAB_COMMAND,t=>{let o=$getSelection();if(!$isRangeSelection(o))return false;let r=o.anchor.getNode();if(this.isInCodeBlock(r))return false;t.preventDefault();let s=this.resolveTabContext(r);return s==="paragraph"?(t.shiftKey||n.update(()=>{let a=$getSelection();if($isRangeSelection(a)){if(this.hasReachedTextTabLimit(a))return;a.insertText(" ");}}),true):s==="list"?t.shiftKey?(n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0),true):(this.isListAtMaxDepth(r)||n.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),true):s==="heading"?t.shiftKey?(n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0),true):(this.isBlockAtMaxIndent(r)||n.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),true):true},COMMAND_PRIORITY_LOW);return ()=>{e();}}isInCodeBlock(n){let e=n;for(;e;){if($isCodeNode(e))return true;e=e.getParent();}return false}isListAtMaxDepth(n){let e=this.config.maxListDepth,t=Number.isFinite(e)?Math.max(1,Math.floor(e)):Au,o=Math.max(0,t-1),r=this.findNearestListItemNode(n);if(r&&typeof r.getIndent=="function"){let a=r.getIndent();if(typeof a=="number")return a>=o}let s=this.findNearestListNode(n);return s?$getListDepth(s)-1>=o:false}isBlockAtMaxIndent(n){let e=n;for(;e;){if($isRootOrShadowRoot(e))return false;if(typeof e.getIndent=="function"){let t=e.getIndent();if(typeof t=="number")return t>=Ji}e=e.getParent();}return false}resolveTabContext(n){let e=n;for(;e;){if($isListNode(e))return "list";if($isHeadingNode(e))return "heading";if($isParagraphNode(e))return "paragraph";if($isRootOrShadowRoot(e))break;e=e.getParent();}return "other"}findNearestListNode(n){let e=n;for(;e;){if($isListNode(e))return e;e=e.getParent();}return null}findNearestListItemNode(n){let e=n;for(;e;){if($isListItemNode(e))return e;e=e.getParent();}return null}hasReachedTextTabLimit(n){let e=n.anchor,t=e.getNode();if(typeof t.getTextContent!="function")return false;let o=t.getTextContent(),r=typeof e.offset=="number"?e.offset:o.length,s=Math.max(0,Math.min(o.length,r)),a=o.lastIndexOf(`
|
|
6
|
-
`,s-1)+1;return (o.slice(a,s).match(/^\t*/)?.[0].length??0)>=Ji}},Du=new Vn;var es=[{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"]}],Gi=es,Wn={":)":"\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 zu(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Bt(i){return i.trim().toLowerCase().replace(/^:+|:+$/g,"")}function Zi(i){return i.toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}function Wo(i){let n=i.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 s=Zi([o.label,...r,...o.keywords||[]].join(" "));return {item:o,searchable:s}});return {getAll:()=>[...n],resolveShortcode:o=>e.get(Bt(o))??null,search:(o,r)=>{let s=Math.max(0,r?.limit??n.length);if(s===0)return [];let a=Zi(o);return a?t.filter(l=>l.searchable.includes(a)).slice(0,s).map(l=>l.item):n.slice(0,s)}}}function ts(i){return Array.isArray(i)?i.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0):[]}function $u(i){let n=ts(i.shortcodes);return n.length>0?n.map(e=>Bt(e)):typeof i.shortcodes=="string"?i.shortcodes.split(/[,\s]+/).map(e=>Bt(e)).filter(Boolean):[]}function qo(i){if(!i||typeof i!="object")return null;let n=i;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,s=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),...$u(r)].filter(Boolean)));c.length!==0&&e.push({emoji:d,label:s,shortcodes:c,keywords:ts(r.keywords)});}return e.length===0?null:Wo(e)}async function ju(i){return new Function("name","return import(name);")(i)}var Jn=class extends w{constructor(e={}){super("emoji",["toolbar"]);x(this,"listeners",[]);x(this,"isOpen",false);x(this,"query","");x(this,"position",null);x(this,"suggestions",[]);x(this,"activeMatch",null);x(this,"viewportRafId",null);x(this,"applyingAutoReplace",false);x(this,"catalogAdapter",Wo(Gi));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:Wn,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||Wn,...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 m=this.replaceSymbolsInText(c);return m===c?false:(l.preventDefault(),e.update(()=>{let h=$getSelection();$isRangeSelection(h)&&h.insertText(m);}),true)},COMMAND_PRIORITY_EDITOR),r=l=>{this.isOpen&&l.key==="Escape"&&(l.preventDefault(),this.closeEmojiSuggestions());},s=l=>{l.target?.closest(".luthor-emoji-menu")||this.isOpen&&this.closeEmojiSuggestions();},a=()=>{!this.isOpen||!this.activeMatch||this.viewportRafId===null&&(this.viewportRafId=window.requestAnimationFrame(()=>{this.viewportRafId=null;let l=this.getCaretPosition();if(!l){this.closeEmojiSuggestions();return}this.position=l,this.notifyListeners();}));};return document.addEventListener("keydown",r),document.addEventListener("pointerdown",s),window.addEventListener("scroll",a,true),window.addEventListener("resize",a),()=>{t(),o(),document.removeEventListener("keydown",r),document.removeEventListener("pointerdown",s),window.removeEventListener("scroll",a,true),window.removeEventListener("resize",a),this.viewportRafId!==null&&(cancelAnimationFrame(this.viewportRafId),this.viewportRafId=null),this.activeMatch=null,this.isOpen=false,this.query="",this.position=null,this.suggestions=[],this.notifyListeners();}}getCommands(e){return {insertEmoji: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:Wo(e.catalog||Gi)}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=qo(e);if(t){this.catalogAdapter=t,this.refreshSuggestionsIfOpen();return}try{let r=await ju("@emoji-mart/data"),s=qo(r.default)||qo(r.data);s&&(this.catalogAdapter=s,this.refreshSuggestionsIfOpen());}catch{}}refreshSuggestionsIfOpen(){this.isOpen&&(this.suggestions=this.getSuggestions(this.query),this.isOpen=this.suggestions.length>0,this.notifyListeners());}updateFromSelection(e){let 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 s=o.anchor.offset,a=r.getTextContent(),l=a.slice(0,s);if(this.config.autoReplaceSymbols&&!this.applyingAutoReplace){let y=this.detectSymbolReplacement(a,l,s);y&&(t={nodeKey:r.getKey(),startOffset:y.startOffset,endOffset:y.endOffset,emoji:y.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 h=l.slice(c+d.length);if(/\s/.test(h)||h.length>(this.config.maxQueryLength??32)){this.closeIfNeeded();return}let N=this.getSuggestions(h),v=this.getCaretPosition();this.query=h,this.position=v,this.suggestions=N,this.isOpen=N.length>0,this.activeMatch={nodeKey:r.getKey(),startOffset:c,endOffset:s},this.notifyListeners();}),t!==null){let o=t;this.applyingAutoReplace=true,e.update(()=>{let r=$getNodeByKey(o.nodeKey);if(!$isTextNode(r))return;let s=Math.max(0,o.endOffset-o.startOffset);r.spliceText(o.startOffset,s,o.emoji,true);let a=o.startOffset+o.emoji.length;r.select(a,a);}),this.applyingAutoReplace=false;}}isSelectionInsideCodeBlock(e){if(!$isRangeSelection(e))return false;let 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||Wn).sort((s,a)=>a[0].length-s[0].length);for(let[s,a]of r){if(!t.endsWith(s))continue;let l=o-s.length,d=l>0&&e[l-1]||"",c=o<e.length&&e[o]||"",u=l===0||/\s|[([{>"'`]/.test(d),m=o===e.length||/\s|[.,!?;:)\]}"'`]/.test(c);if(u&&m)return {startOffset:l,endOffset:o,emoji:a}}return null}replaceSymbolsInText(e){let t=Object.entries(this.config.symbolReplacements||Wn),o=e;for(let[r,s]of t){let a=zu(r),l=new RegExp(`(^|\\s)${a}(?=$|\\s|[.,!?;:])`,"g");o=o.replace(l,`$1${s}`);}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 s=Math.max(0,o.endOffset-o.startOffset);r.spliceText(o.startOffset,s,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(),s=t.getClientRects()[0]||o;return {x:s.left+(this.config.offset?.x??0),y:s.bottom+(this.config.offset?.y??8)}}getState(){return {isOpen:this.isOpen,query:this.query,position:this.position,suggestions:this.suggestions}}notifyListeners(){let e=this.getState();this.listeners.forEach(t=>t(e));}},Uu=new Jn;var Xn=class extends w{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(Xu,{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;}},Ju=new Xn;function Xu({extension:i,config:n}){let[e]=useLexicalComposerContext(),{config:t}=Me(),[o,r]=useState(false),[s,a]=useState(null),[l,d]=useState(null),c=useRef(null),u=g=>(g.querySelector('[data-luthor-selection-anchor="true"]')??g).getBoundingClientRect(),m=(g,E)=>{let T;return (...b)=>{clearTimeout(T),T=setTimeout(()=>g(()=>b),E);}},h=useCallback((g,E)=>{if(typeof window>"u"||E===document.body)return g;let T=window.pageXOffset||document.documentElement.scrollLeft||0,b=window.pageYOffset||document.documentElement.scrollTop||0,S=E.getBoundingClientRect(),M=S.left+T,B=S.top+b,j=n.toolbarDimensions?.width||300,_=n.toolbarDimensions?.height||40,q=g.x-M,z=g.y-B,F=Math.max(10,Math.min(q,Math.max(10,S.width-j-10))),A=Math.max(10,Math.min(z,Math.max(10,S.height-_-10)));return {...g,x:F,y:A,top:g.top-B,left:g.left-M,bottom:g.bottom-B,right:g.right-M,positionFromRight:false}},[n.toolbarDimensions?.height,n.toolbarDimensions?.width]),N=useCallback(g=>{let E=n.offset||{y:8},T=n.positionStrategy||"below",b=window.pageXOffset||document.documentElement.scrollLeft||0,S=window.pageYOffset||document.documentElement.scrollTop||0,M=window.innerWidth,B=window.innerHeight,j=g.bottom+S+E.y;T==="above"?j=g.top+S-E.y:T==="auto"&&(j=B-g.bottom>60?g.bottom+S+E.y:g.top+S-E.y);let _=n.getActiveStates?.(),q=!!_?.isIframeEmbedSelected||!!_?.isYouTubeEmbedSelected,z=n.toolbarDimensions?.width||(q?132:300),F=n.toolbarDimensions?.height||40,A=10,P=g.left+g.width/2,Y=P+b,K,J,V=P-A,te=M-P-A,ce=z/2,Te=P-ce,Fe=P+ce,Le=Te<A,se=Fe>M-A;return !Le&&!se?(K=Y-ce,J=false):Le||V<ce?(K=b+A,J=false):se||te<ce?(K=b+M-z-A,J=true):(K=Y-ce,J=false),j-F<S?j=g.bottom+S+E.y:j+F>S+B&&(j=g.top+S-E.y-F),{x:K,y:j,width:g.width,height:g.height,top:g.top+S,left:g.left+b,bottom:g.bottom+S,right:g.right+b,positionFromRight:J}},[n]);useEffect(()=>{i.setVisible(o);},[o,i]),useEffect(()=>{let g=()=>{e.getEditorState().read(()=>{let M=$getSelection(),B=null,j=null;if($isRangeSelection(M)&&!M.isCollapsed()){let _=window.getSelection();_&&_.rangeCount>0&&(B=_.getRangeAt(0).getBoundingClientRect(),j=M);}else if($isNodeSelection(M)){let _=M.getNodes();if(_.length>0){let q=_[0];if(q){let z=q.getKey(),F=e.getElementByKey(z);F&&(B=u(F));}}}if(B&&B.width>0&&B.height>0){let _=N(B);a(_),d(j),r(true),i.setSelectionRect(_);}else a(null),d(null),r(false),i.setSelectionRect(null);});},E=m(g,n.debounceMs||100),T=e.registerUpdateListener(()=>{E();}),b=()=>{E();},S=()=>{c.current===null&&(c.current=window.requestAnimationFrame(()=>{c.current=null,g();}));};return document.addEventListener("selectionchange",b),window.addEventListener("scroll",S,true),window.addEventListener("resize",S),()=>{T(),document.removeEventListener("selectionchange",b),window.removeEventListener("scroll",S,true),window.removeEventListener("resize",S),c.current!==null&&(cancelAnimationFrame(c.current),c.current=null);}},[e,n.debounceMs,N,i]);let v=()=>{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 y=e.getRootElement()?.closest(".luthor-editor-wrapper"),f=n.anchorElem||y||document.body,p=s&&f?h(s,f):s;return createPortal(n.render({isVisible:o,selectionRect:p,selection:l,editor:e,commands:n.getCommands?.()||{},activeStates:n.getActiveStates?.()||{},hide:v,theme:t?.theme?.floatingToolbar||n.theme||{}}),f)}var Gn=class extends w{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())}},Zu=new Gn;var om=new Set(["paragraph","heading"]),Zn=class extends w{constructor(e={}){super("slashCommand",["toolbar"]);x(this,"commands",new Map);x(this,"listeners",[]);x(this,"isOpen",false);x(this,"query","");x(this,"position",null);x(this,"activeMatch",null);x(this,"viewportRafId",null);this.config={trigger:"/",offset:{x:0,y:8},...e},this.setSlashCommands(this.config.items??[]);}register(e){let 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();},s=()=>{!this.isOpen||!this.activeMatch||this.viewportRafId===null&&(this.viewportRafId=window.requestAnimationFrame(()=>{this.viewportRafId=null;let a=this.getCaretPosition();if(!a){this.closeSlashMenu();return}this.position=a,this.notifyListeners();}));};return document.addEventListener("pointerdown",r),window.addEventListener("scroll",s,true),window.addEventListener("resize",s),()=>{t(),document.removeEventListener("keydown",o),document.removeEventListener("pointerdown",r),window.removeEventListener("scroll",s,true),window.removeEventListener("resize",s),this.viewportRafId!==null&&(cancelAnimationFrame(this.viewportRafId),this.viewportRafId=null),this.activeMatch=null,this.isOpen=false,this.query="",this.position=null,this.notifyListeners();}}getCommands(e){return {registerSlashCommand: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 s=$getNodeByKey(r.nodeKey);if(!$isTextNode(s))return;let a=Math.max(0,Math.min(r.endOffset,s.getTextContentSize()));s.select(a,a);let l=Math.max(0,r.endOffset-r.startOffset);l>0&&s.spliceText(r.startOffset,l,"",true);});}return this.closeSlashMenu(),o.action(),true}updateMatchFromSelection(e){e.getEditorState().read(()=>{let t=$getSelection();if(!$isRangeSelection(t)||!t.isCollapsed()){this.closeIfNeeded();return}let o=t.anchor.getNode();if(!$isTextNode(o)){this.closeIfNeeded();return}let r=im(o);if(!om.has(r)){this.closeIfNeeded();return}let s=t.anchor.offset,l=o.getTextContent().slice(0,s),d=this.config.trigger||"/",c=l.lastIndexOf(d);if(c<0){this.closeIfNeeded();return}let u=l.slice(0,c);if(!sm(u)){this.closeIfNeeded();return}let m=l.slice(c+d.length);if(/\s/.test(m)){this.closeIfNeeded();return}let h=this.getCaretPosition();this.isOpen=true,this.query=m,this.position=h,this.activeMatch={nodeKey:o.getKey(),startOffset:c,endOffset:s,query:m},this.notifyListeners();});}closeIfNeeded(){!this.isOpen&&!this.activeMatch||this.closeSlashMenu();}getCaretPosition(){if(typeof window>"u")return null;let e=window.getSelection();if(!e||e.rangeCount===0)return null;let t=e.getRangeAt(0).cloneRange();t.collapse(true);let o=t.getBoundingClientRect(),s=t.getClientRects()[0]||o,a=this.config.offset?.x??0,l=this.config.offset?.y??8;return {x:s.left+a,y:s.bottom+l}}getState(){return {isOpen:this.isOpen,query:this.query,position:this.position,commands:this.getAllCommands()}}notifyListeners(){let e=this.getState();this.listeners.forEach(t=>t(e));}},rm=new Zn;function im(i){try{return i.getTopLevelElementOrThrow?.()?.getType?.()??""}catch{return ""}}function sm(i){return i.trim().length===0}var eo=class extends w{constructor(){super("enterKeyBehavior",["floating"]),this.config={...this.config||{},showInToolbar:false,initPriority:100};}register(n){let e,t=r=>{if(r.key!=="Enter")return;let s=false;n.update(()=>{let a=$getSelection();if(!$isRangeSelection(a))return;let l=a.anchor.getNode();if(r.shiftKey){let v=$findCellNode(l);if($isTableCellNode(v)){let p=$getTableNodeFromLexicalNodeOrThrow(v),g=$createParagraphNode();p.insertAfter(g),g.selectStart(),s=true;return}let y=this.findQuoteNode(l);if(y){let p=$createParagraphNode();y.insertAfter(p),p.selectStart(),s=true;return}let f=this.findCodeNode(l);if(f){let p=$createParagraphNode();f.insertAfter(p),p.selectStart(),s=true;return}return}let d=this.findQuoteNode(l);if(!d||!a.isCollapsed())return;let c=this.findDirectQuoteChild(l,d)||d.getLastChild();if(!c){let v=$createParagraphNode();d.append(v),v.selectStart(),s=true;return}let u=this.isEmptyQuoteLine(c),m=c.getPreviousSibling(),h=this.isEmptyQuoteLine(m);if(u&&h){let v=c,y=m;v.remove(),y?.remove();let f=$createParagraphNode();d.insertAfter(f),f.selectStart(),s=true;return}let N=$createParagraphNode();c.insertAfter(N),N.selectStart(),s=true;}),s&&(r.preventDefault(),r.stopPropagation());},o=n.registerRootListener((r,s)=>{e?.(),e=void 0,s&&s.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}},fm=new eo;export{w as BaseExtension,_s as BaseProvider,zn as BlockFormatExtension,Xt as BoldExtension,_n as CodeExtension,Fn as CodeFormatExtension,Hn as CodeIntelligenceExtension,Gn as CommandPaletteExtension,fn as ContextMenuExtension,Qn as DraggableBlockExtension,Jn as EmojiExtension,eo as EnterKeyBehaviorExtension,Ds as ExtensionCategory,Xn as FloatingToolbarExtension,on as FontFamilyExtension,rn as FontSizeExtension,$n as HistoryExtension,nn as HorizontalRuleExtension,qt as IframeEmbedExtension,Yt as ImageExtension,Gt as ItalicExtension,es as LIGHTWEIGHT_EMOJI_CATALOG,rr as LUTHOR_EDITOR_THEME_TOKENS,sn as LineHeightExtension,tn as LinkExtension,Pn as ListExtension,Nu as RichText,Zn as SlashCommandExtension,en as StrikethroughExtension,dn as SubscriptExtension,un as SuperscriptExtension,Vn as TabIndentExtension,En as TableExtension,ln as TextColorExtension,oe as TextFormatExtension,cn as TextHighlightExtension,Zt as UnderlineExtension,Jt as YouTubeEmbedExtension,Lt as appendMetadataEnvelopes,Yd as blockFormatExtension,vl as boldExtension,Bs as clearLexicalSelection,pd as codeExtension,Ad as codeFormatExtension,Od as codeIntelligenceExtension,Zu as commandPaletteExtension,Ro as contextMenuExtension,pu as createCustomNodeExtension,ar as createEditorSystem,vs as createEditorThemeStyleVars,Hs as createExtension,Be as defaultLuthorTheme,ou as draggableBlockExtension,Uu as emojiExtension,fm as enterKeyBehaviorExtension,wt as extractMetadataEnvelopes,Ju as floatingToolbarExtension,tc as fontFamilyExtension,sc as fontSizeExtension,Zd as historyExtension,Wl as horizontalRuleExtension,Cl as htmlToJSON,ma as iframeEmbedExtension,Zs as imageExtension,Ts as isLuthorTheme,Nl as italicExtension,Sl as jsonToHTML,Ga as jsonToMarkdown,gc as lineHeightExtension,Dl as linkExtension,id as listExtension,Xa as markdownToJSON,Ns as mergeThemes,Tt as prepareDocumentForBridge,Rt as rehydrateDocumentFromEnvelopes,zs as resolveLinkNodeKeyFromAnchor,vu as richTextExtension,rm as slashCommandExtension,wl as strikethroughExtension,Ec as subscriptExtension,Cc as superscriptExtension,Du as tabIndentExtension,Qc as tableExtension,hc as textColorExtension,xc as textHighlightExtension,Ll as underlineExtension,Me as useBaseEditor,va as youTubeEmbedExtension};
|
|
4
|
+
`}${t}`:t}function _t(i){let n=[],e=[],t=new RegExp(Ha.source,"g");for(let o of i.matchAll(t)){if(Number.parseInt(o[1]??"",10)!==1){e.push(`Ignoring metadata envelope version v${o[1]??"unknown"}.`);continue}try{let s=JSON.parse(o[2]??"");if(!st(s)){e.push("Ignoring metadata envelope with non-object payload.");continue}let a=typeof s.type=="string"?s.type:"",l=typeof s.id=="string"?s.id:"",d=typeof s.fallback=="string"?s.fallback:"",u=(Array.isArray(s.path)?s.path:[]).filter(g=>Number.isInteger(g)&&g>=0).map(g=>Number(g)),m=st(s.node)?s.node:null;if(!l||!a||!m){e.push("Ignoring metadata envelope with missing required fields.");continue}n.push({id:l,type:a,path:u,node:m,fallback:d});}catch{e.push("Ignoring malformed metadata envelope payload.");}}return {content:i.replace(t,"").trimEnd(),envelopes:n,warnings:e}}function At(i,n){if(n.length===0)return i;let e=Mt(i.root);for(let t of n){if(Ka(e,t.path,t.node))continue;Array.isArray(e.children)||(e.children=[]),e.children.push(Mt(t.node));}return {...i,root:e}}var zr=[...TRANSFORMERS,Pr],al=new Set(["root","paragraph","text","linebreak","tab","heading","quote","list","listitem","link","autolink","code","code-highlight","image"]);function $r(){return createEditor({namespace:"luthor-markdown-converter",onError:i=>{throw i},nodes:[ParagraphNode,TextNode,LineBreakNode,TabNode,HeadingNode,QuoteNode,ListNode,ListItemNode,LinkNode,AutoLinkNode,CodeNode,CodeHighlightNode,z]})}function ll(i,n){let e=typeof n=="string"?n:JSON.stringify(n??{});return i.parseEditorState(e)}function cl(i){let{content:n,envelopes:e,warnings:t}=_t(i);for(let s of t)console.warn(`[luthor-headless] ${s}`);let o=$r();o.update(()=>{$convertFromMarkdownString(n,zr);},{discrete:true});let r=o.getEditorState().toJSON();return At(r,e)}function dl(i){let n=Ot(i,{mode:"markdown",supportedNodeTypes:al}),e=$r(),t=ll(e,n.document);e.setEditorState(t,{tag:"history-merge"});let o=t.read(()=>$convertToMarkdownString(zr));return It(o,n.envelopes)}var wl=new Set(["root","paragraph","text","linebreak","tab","heading","quote","list","listitem","link","autolink","code","code-highlight","image","iframe-embed","youtube-embed"]),Rl=new Set(["pre","script","style","textarea"]);function Kr(){return createEditor({namespace:"luthor-html-converter",onError:i=>{throw i},nodes:[ParagraphNode,TextNode,LineBreakNode,TabNode,HeadingNode,QuoteNode,ListNode,ListItemNode,LinkNode,AutoLinkNode,CodeNode,CodeHighlightNode,z,ie,W]})}function kl(i,n){let e=typeof n=="string"?n:JSON.stringify(n??{});return i.parseEditorState(e)}function Qr(){if(typeof document>"u"||typeof window>"u"||typeof DOMParser>"u")throw new Error("HTML conversion requires browser DOM APIs (document/window/DOMParser).")}function jr(i){if(!i)return false;let n=i.getAttribute("style");return n?/\bwhite-space\s*:\s*(pre|pre-wrap|pre-line)\b/i.test(n):false}function Pl(i){let n=i.parentElement;for(;n;){if(Rl.has(n.tagName.toLowerCase()))return true;n=n.parentElement;}return false}function Ur(i,n){let e=n==="previous"?i.previousSibling:i.nextSibling;for(;e;){if(e.nodeType!==Node.TEXT_NODE||(e.textContent??"").trim().length>0)return e;e=n==="previous"?e.previousSibling:e.nextSibling;}return null}function Ml(i,n){if(!i||!n||/\s$/.test(i)||/^\s/.test(n))return false;let e=i.at(-1)??"",t=n[0]??"";return !(!e||!t||/^[,.;:!?)]$/.test(t)||/^[([{"']$/.test(e))}function Ol(i){let n=Array.from(i.querySelectorAll("[style]"));for(let r of n){if(!jr(r)||r.childNodes.length!==1||r.firstChild?.nodeType!==Node.TEXT_NODE)continue;let s=r.firstChild;/[\r\n]/.test(s.data)&&(s.data=s.data.replace(/^\s*\r?\n\s*/,"").replace(/\r?\n\s*$/,""));}let e=i.createTreeWalker(i.body,NodeFilter.SHOW_TEXT),t=[],o=e.nextNode();for(;o;){let r=o,s=r.data,a=r.parentElement;if(!/^[\s\r\n\t]+$/.test(s)||!/[\r\n]/.test(s)||Pl(r)||jr(a)){o=e.nextNode();continue}let l=Ur(r,"previous"),d=Ur(r,"next"),c=l?.textContent??"",u=d?.textContent??"";Ml(c,u)?t.push({node:r,replacement:" "}):t.push({node:r,replacement:null}),o=e.nextNode();}for(let r of t)if(r.node.parentNode){if(r.replacement===null){r.node.parentNode.removeChild(r.node);continue}r.node.data=r.replacement;}}function Il(i){Qr();let{content:n,envelopes:e,warnings:t}=_t(i);for(let s of t)console.warn(`[luthor-headless] ${s}`);let o=Kr();o.update(()=>{let s=new DOMParser().parseFromString(n,"text/html");Ol(s);let a=$generateNodesFromDOM(o,s),l=$getRoot();l.clear(),l.append(...a);},{discrete:true});let r=o.getEditorState().toJSON();return At(r,e)}function _l(i){Qr();let n=Ot(i,{mode:"html",supportedNodeTypes:wl}),e=Kr(),t=kl(e,n.document);e.setEditorState(t,{tag:"history-merge"});let o=t.read(()=>$generateHtmlFromNodes(e,null));return It(o,n.envelopes)}var on=class extends re{constructor(){super("bold");}},Al=new on;var rn=class extends re{constructor(){super("italic");}},Dl=new rn;var Hl={format:["underline"],tag:"++",type:"text-format"},sn=class extends re{constructor(){super("underline");}getMarkdownTransformers(){return [Hl]}},Fl=new sn;var an=class extends re{constructor(){super("strikethrough");}},Bl=new an;var ln=class extends k{constructor(){super("link",["toolbar"]);C(this,"lastSelectedLinkNodeKey",null);this.config={autoLinkText:false,clickableLinks:true,openLinksInNewTab:true,linkSelectedTextOnPaste:true,validateUrl:e=>{try{return new URL(e),!0}catch{return false}}};}register(e){let t=e.registerCommand(PASTE_COMMAND,r=>{let s=r.clipboardData;if(!s)return false;let a=s.getData("text/plain");return a&&this.config.validateUrl(a)&&this.config.autoLinkUrls?(r.preventDefault(),e.update(()=>{let l=$getSelection();if($isRangeSelection(l))if(l.isCollapsed()){let d=$createLinkNode(a);d.append($createTextNode(a)),l.insertNodes([d]);}else if(this.config.linkSelectedTextOnPaste)e.dispatchCommand(TOGGLE_LINK_COMMAND,a);else {l.insertText(a);let d=$getSelection();d&&$isRangeSelection(d)&&d.getNodes()[0]&&e.dispatchCommand(TOGGLE_LINK_COMMAND,a);}}),true):false},3),o=e.registerUpdateListener(({editorState:r})=>{r.read(()=>{let s=this.getSelectedLinkNode();if(s){this.lastSelectedLinkNodeKey=s.getKey();return}if(this.lastSelectedLinkNodeKey){let a=$getNodeByKey(this.lastSelectedLinkNodeKey);$isLinkNode(a)||(this.lastSelectedLinkNodeKey=null);}});});return ()=>{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 s=/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_.+~#?&//=]*)/g.exec(o);return s&&this.config.validateUrl(s[0])?{text:s[0],url:s[0],index:s.index,length:s[0].length}:null};e.push(jsx(AutoLinkPlugin,{matchers:[t]},"auto-link"));}return e}getCommands(e){let t=s=>s.trim(),o=s=>s.length>0&&!!this.config.validateUrl?.(s),r=(s,a,l,d)=>{s.setURL(a),typeof l<"u"&&s.setRel(l.trim()||null),typeof d<"u"&&s.setTarget(d.trim()||null);};return {insertLink:(s,a)=>{if(s){let l=t(s);if(!o(l))return;a&&e.update(()=>{let d=$getSelection();d&&d.insertText(a);}),e.dispatchCommand(TOGGLE_LINK_COMMAND,l);}else {let l=prompt("Enter URL:");if(l){let d=t(l);if(!o(d))return;e.dispatchCommand(TOGGLE_LINK_COMMAND,d);}}},updateLink:(s,a,l)=>{let d=t(s);if(!o(d))return false;let c=false;return e.update(()=>{let u=this.getSelectedLinkNode()??this.getCachedLinkNode();if(u){r(u,d,a,l),this.lastSelectedLinkNodeKey=u.getKey(),c=true;return}let m=$getSelection();if(!$isRangeSelection(m)){c=false;return}e.dispatchCommand(TOGGLE_LINK_COMMAND,{url:d,rel:typeof a>"u"?null:a.trim()||null,target:typeof l>"u"?null:l.trim()||null}),c=true;}),c},removeLink:()=>{let s=false;e.update(()=>{let a=this.getSelectedLinkNode()??this.getCachedLinkNode();if(a){let l=a.getChildren();for(let d of l)a.insertBefore(d);a.remove(),this.lastSelectedLinkNodeKey=null,s=true;return}e.dispatchCommand(TOGGLE_LINK_COMMAND,null);}),s||(this.lastSelectedLinkNodeKey=null);},getCurrentLink:()=>new Promise(s=>{e.getEditorState().read(()=>{let a=this.getSelectedLinkNode()??this.getCachedLinkNode();if(!a){s(null);return}s(this.serializeLinkNode(a));});}),getLinkByKey:s=>new Promise(a=>{e.getEditorState().read(()=>{let l=this.getLinkNodeByKey(s);if(!l){a(null);return}a(this.serializeLinkNode(l));});}),updateLinkByKey:(s,a,l,d)=>{let c=t(a);if(!o(c))return false;let u=false;return e.update(()=>{let m=this.getLinkNodeByKey(s);if(!m){u=false;return}r(m,c,l,d),this.lastSelectedLinkNodeKey=m.getKey(),u=true;}),u},removeLinkByKey:s=>{let a=false;return e.update(()=>{let l=this.getLinkNodeByKey(s);if(!l){a=false;return}this.removeLinkNode(l),this.lastSelectedLinkNodeKey=null,a=true;}),a}}}serializeLinkNode(e){return {url:e.getURL(),rel:e.getRel(),target:e.getTarget()}}removeLinkNode(e){let 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(),s=[t,o,...r];for(let a of s){if($isLinkNode(a))return a;let l=a.getParent();if(l&&$isLinkNode(l))return l}return null}getCachedLinkNode(){if(!this.lastSelectedLinkNodeKey)return null;let e=$getNodeByKey(this.lastSelectedLinkNodeKey);return $isLinkNode(e)?e:(this.lastSelectedLinkNodeKey=null,null)}getStateQueries(e){return {isLink:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();if(o&&$isRangeSelection(o)){let s=o.getNodes()[0];if(s){let a=s.getParent();t($isLinkNode(a)||$isLinkNode(s));}else t(false);}else t(false);});}),isTextSelected:()=>new Promise(t=>{e.getEditorState().read(()=>{let o=$getSelection();o&&$isRangeSelection(o)?t(!o.isCollapsed()):t(false);});})}}},ql=new ln;var oc={dependencies:[HorizontalRuleNode],export:i=>$isHorizontalRuleNode(i)?"---":null,regExp:/^(?:---|___)\s*$/,replace:(i,n,e,t)=>{let o=$createHorizontalRuleNode();i.replace(o),t||sc(o);},type:"element"},rc=[oc],ic=/^(?:---|___)$/;function sc(i){let n=i.getNextSibling();if(n&&$isParagraphNode(n)){n.selectStart();return}let e=$createParagraphNode();i.insertAfter(e),e.selectStart();}var cn=class extends k{constructor(){super("horizontalRule",["toolbar"]);}register(n){let e=registerMarkdownShortcuts(n,rc),t=n.registerCommand(KEY_ENTER_COMMAND,o=>{if(o?.shiftKey)return false;let r=false;return n.update(()=>{let s=$getSelection();if(!s||!$isRangeSelection(s)||!s.isCollapsed())return;let a=s.anchor.getNode();if(!$isTextNode(a))return;let l=a.getParent();if(!l||!$isParagraphNode(l))return;let d=l.getParent();if(!$isRootOrShadowRoot(d))return;let c=a.getTextContent().trim();if(!ic.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(s=>$isHorizontalRuleNode(s));e(r);}else e(false);});})}}},ac=new cn;var ei=[{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"}],dc={value:"default",label:"Default",fontFamily:"inherit"};function Zr(i){return i.trim().toLowerCase()}function uc(i){return /^[a-z0-9][a-z0-9-]*$/i.test(i)}function mc(i){let n=new Set,e=[];for(let o of i){let r=o.value.trim(),s=o.label.trim(),a=o.fontFamily.trim();if(!r||!s||!a||!uc(r))continue;let l=Zr(r);n.has(l)||(n.add(l),e.push({value:r,label:s,fontFamily:a,cssImportUrl:o.cssImportUrl?.trim()||void 0}));}return e.length===0?ei:e.some(o=>Zr(o.value)==="default")?e:[dc,...e]}var dn=class extends k{constructor(){super("fontFamily",["toolbar"]);C(this,"loadedFontUrls",new Set);this.config={options:ei,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=mc(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 s=this.normalizeFontValue(r);t=this.config.options.find(l=>this.normalizeFontValue(l.value)===s?true:this.normalizeFontValue(l.fontFamily)===s)?.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 s=document.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-luthor-font-url",o),document.head.appendChild(s),this.loadedFontUrls.add(t);}},gc=new dn;var oi=[{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"}],pc={value:"default",label:"Default",fontSize:"inherit"};function ni(i){return i.trim().toLowerCase()}function hc(i){return /^[a-z0-9][a-z0-9-]*$/i.test(i)}function bc(i){let n=new Set,e=[];for(let o of i){let r=String(o.value).trim(),s=String(o.label).trim(),a=String(o.fontSize).trim();if(!r||!s||!a||!hc(r))continue;let l=ni(r);n.has(l)||(n.add(l),e.push({value:r,label:s,fontSize:a}));}return e.length===0?oi:e.some(o=>ni(o.value)==="default")?e:[pc,...e]}var un=class extends k{constructor(){super("fontSize",["toolbar"]),this.config={options:oi,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}configure(n){let e={...n};return n.options&&(e.options=bc(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,"")}},yc=new un;var ii=[{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"}],ko={value:"default",label:"Default",lineHeight:"1.5"},Cc=1;function Ro(i){return i.trim().toLowerCase()}function Sc(i){return Ro(i)==="default"?true:gn(i)!==null}function gn(i){let n=i.trim();if(!/^\d*\.?\d+$/.test(n))return null;let e=Number(n);return !Number.isFinite(e)||e<Cc?null:e.toString()}function vc(i,n){let e=new Set,t=[];for(let r of i){let s=r.value.trim(),a=r.label.trim(),l=Ro(s);if(!s||!a||!Sc(s)||e.has(l))continue;if(l==="default"){e.add(l),t.push({value:s,label:a,lineHeight:n});continue}let d=gn(String(r.lineHeight));d&&(e.add(l),t.push({value:s,label:a,lineHeight:d}));}return t.length===0?ii:t.some(r=>Ro(r.value)==="default")?t:[{...ko,lineHeight:n},...t]}function Nc(i){return gn(i)??ko.lineHeight}var mn=class extends k{constructor(){super("lineHeight",["toolbar"]),this.config={options:ii,defaultLineHeight:ko.lineHeight,showInToolbar:true,category:["toolbar"]};}register(){return ()=>{}}configure(n){let e={...n},t=Nc(String(n.defaultLineHeight??this.config.defaultLineHeight));return e.defaultLineHeight=t,n.options&&(e.options=vc(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 s=this.withStyleProperty(r.getStyle(),"line-height",e);r.setStyle(s);for(let a of r.getAllTextNodes())$isTextNode(a)&&a.setStyle(this.withStyleProperty(a.getStyle(),"line-height",e));}});}getSelectedTopLevelBlocks(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)),s=t.trim();return s.length>0&&r.push(`${e}: ${s}`),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",""),s=this.normalizeValue(r);e=s.length>0&&s!=="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",""),s=this.normalizeValue(r);if(!s||s==="normal"){e="default";return}if(s===this.normalizeValue(this.config.defaultLineHeight)){e="default";return}e=this.config.options.find(l=>this.normalizeValue(l.value)===s?true:this.normalizeValue(l.lineHeight)===s)?.value??null;}),e}getSelectedBlocksLineHeight(n){let e=this.getSelectedTopLevelBlocks(n);if(e.length===0)return null;let t=null,o="";for(let r of e){let s=this.readStyleProperty(r.getStyle(),"line-height"),a=this.normalizeValue(s);if(t===null){t=a,o=s;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 gn(e)??e}readStyleProperty(n,e){let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return n.match(new RegExp(`(?:^|;)\\s*${t}\\s*:\\s*([^;]+)`,"i"))?.[1]?.trim()??""}},Tc=new mn;var wc=[{value:"default",label:"Default",color:"inherit"},{value:"black",label:"Black",color:"#111827"},{value:"slate",label:"Slate",color:"#334155"},{value:"red",label:"Red",color:"#dc2626"},{value:"orange",label:"Orange",color:"#ea580c"},{value:"green",label:"Green",color:"#16a34a"},{value:"blue",label:"Blue",color:"#2563eb"},{value:"purple",label:"Purple",color:"#7c3aed"}],fn=class extends k{constructor(){super("textColor",["toolbar"]),this.config={options:wc,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}},Rc=new fn;var Pc=[{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"}],pn=class extends k{constructor(){super("textHighlight",["toolbar"]),this.config={options:Pc,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}},Mc=new pn;var hn=class extends re{constructor(){super("subscript");}},Oc=new hn;var bn=class extends re{constructor(){super("superscript");}},Ic=new bn;function yn(i,n,e){return i<n?n:i>e?e:i}function Fc({items:i,position:n,onClose:e,className:t,style:o,itemClassName:r,itemStyle:s,disabledItemClassName:a,disabledItemStyle:l}){return jsx("div",{className:t,style:{position:"fixed",left:n.x,top:n.y,zIndex:"var(--luthor-z-menu, 460)",...o},onClick:d=>d.stopPropagation(),children:i.map((d,c)=>d.separator?jsx("div",{className:"h-px bg-border my-1"},c):jsxs("div",{className:d.disabled?a:r,style:d.disabled?l:s,onClick:()=>{!d.disabled&&d.action&&(d.action(),e());},children:[d.icon&&jsx(d.icon,{className:"mr-2 h-4 w-4"}),d.label]},c))})}var En=class{constructor(n,e={}){C(this,"providers",new Map);C(this,"currentMenu",null);C(this,"listeners",new Set);C(this,"editor");C(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,s)=>(s.priority||0)-(r.priority||0));for(let r of o){let s={editor:this.editor,target:e,selection:t,event:n};if(r.canHandle(s)){this.config.preventDefault!==false&&n.preventDefault();let a=r.getItems(s);if(a.length>0){let l=e.getBoundingClientRect();this.showMenu({items:a,position:{x:n.clientX,y:n.clientY},renderer:r.renderer||this.config.defaultRenderer,anchor:{element:e,offsetX:n.clientX-l.left,offsetY:n.clientY-l.top}});return}}}});}showMenu(n){this.currentMenu=this.resolveAnchoredMenuConfig(n),this.notifyListeners();}hideMenu(){this.currentMenu=null,this.notifyListeners();}repositionMenuFromAnchor(){if(!this.currentMenu?.anchor)return;if(!this.currentMenu.anchor.element.isConnected){this.hideMenu();return}let n=this.resolveAnchoredMenuConfig(this.currentMenu);(!this.currentMenu||n.position.x!==this.currentMenu.position.x||n.position.y!==this.currentMenu.position.y)&&(this.currentMenu=n,this.notifyListeners());}getCurrentMenu(){return this.currentMenu}getPortalContainer(){let n=this.editor.getRootElement();return n?n.closest(".luthor-editor-wrapper")??null:null}subscribe(n){return this.listeners.add(n),n(this.currentMenu),()=>{this.listeners.delete(n);}}notifyListeners(){this.listeners.forEach(n=>n(this.currentMenu));}resolveAnchoredMenuConfig(n){if(!n.anchor)return n;let{element:e,offsetX:t,offsetY:o}=n.anchor,r=e.getBoundingClientRect();return {...n,position:{x:r.left+t,y:r.top+o}}}};function Bc({extension:i}){let{config:n}=Oe(),[e,t]=useState(null),o=n?.theme?.contextMenu||{},r=i.config,s={container:r?.theme?.container||o.container||"luthor-context-menu",item:r?.theme?.item||o.item||"luthor-context-menu-item",itemDisabled:r?.theme?.itemDisabled||o.itemDisabled||"luthor-context-menu-item-disabled"},a={container:{...r?.styles?.container,...o.styles?.container},item:{...r?.styles?.item,...o.styles?.item},itemDisabled:{...r?.styles?.itemDisabled,...o.styles?.itemDisabled}};if(useEffect(()=>i.subscribe(t),[i]),!e)return null;let l=e.renderer||i.config.defaultRenderer,d=i.manager?.getPortalContainer()??null,c=220,u=Math.min(420,18+e.items.length*34),m=8,g=(()=>{if(!d){let y=typeof window>"u"?0:window.innerWidth,b=typeof window>"u"?0:window.innerHeight,v=Math.max(m,y-c-m),N=Math.max(m,b-u-m);return {x:yn(e.position.x,m,v),y:yn(e.position.y,m,N)}}let L=d.getBoundingClientRect(),w=e.position.x-L.left,p=e.position.y-L.top,h=Math.max(m,L.width-c-m),f=Math.max(m,L.height-u-m);return {x:yn(w,m,h),y:yn(p,m,f)}})(),x=d?{position:"absolute",...a.container}:a.container;return createPortal(jsx(l,{items:e.items,position:g,onClose:()=>i.manager?.hideMenu(),className:s.container,style:x,itemClassName:s.item,itemStyle:a.item,disabledItemClassName:s.itemDisabled,disabledItemStyle:a.itemDisabled}),d??document.body)}var xn=class extends k{constructor(e={}){super("contextMenu",["toolbar"]);C(this,"manager",null);C(this,"pendingListeners",new Set);this.config={defaultRenderer:Fc,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 En(e,this.config),this.pendingListeners.forEach(l=>{this.manager?.subscribe(l);}),this.pendingListeners.clear();let t=l=>{this.manager?.handleContextMenu(l);},o=l=>{l.target.closest(".luthor-context-menu")||this.manager?.hideMenu();},r=l=>{l.key==="Escape"&&this.manager?.hideMenu();},s=()=>{this.manager?.repositionMenuFromAnchor();},a=e.getRootElement();return a?(a.addEventListener("contextmenu",t),document.addEventListener("mousedown",o),document.addEventListener("keydown",r),window.addEventListener("scroll",s,true),window.addEventListener("resize",s),()=>{a.removeEventListener("contextmenu",t),document.removeEventListener("mousedown",o),document.removeEventListener("keydown",r),window.removeEventListener("scroll",s,true),window.removeEventListener("resize",s),this.manager=null;}):()=>{this.manager=null;}}getCommands(e){return {registerProvider:t=>{this.manager||(this.manager=new En(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(Bc,{extension:this},"context-menu")]}subscribe(e){return this.manager?this.manager.subscribe(e):(this.pendingListeners.add(e),()=>{this.pendingListeners.delete(e);})}},_o=new xn;function Zc(i,n,e){return i<n?n:i>e?e:i}function Nn(){let i=$getSelection();if($isTableSelection(i)){let n=i.getNodes().find(e=>$isTableCellNode(e));if($isTableCellNode(n))return n}if($isRangeSelection(i)){let n=i.anchor.getNode(),e=$findCellNode(n);if($isTableCellNode(e))return e}return null}function ed({headersEnabled:i,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:i,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 td({extension:i}){let{editor:n}=Oe(),[e,t]=useState(()=>n?.isEditable()??true),[o,r]=useState(null),[s,a]=useState(false),[l,d]=useState(false),[c,u]=useState(null),m=useRef(null),g=useRef(null),x=h=>{!n||!n.isEditable()||n.update(()=>{let f=Nn();f&&(f.selectStart(),h(f));});},L=h=>{x(f=>{$getTableNodeFromLexicalNodeOrThrow(f).getChildren().filter(v=>$isTableRowNode(v)).forEach((v,N)=>{v.getChildren().filter(T=>$isTableCellNode(T)).forEach(T=>{let O=h&&N===0?TableCellHeaderStates.ROW:TableCellHeaderStates.NO_STATUS;T.setHeaderStyles(O,TableCellHeaderStates.ROW);});});});};if(useEffect(()=>{if(n)return n.registerEditableListener(h=>{t(h),h||(a(false),u(null));})},[n]),useEffect(()=>{if(!n)return;let h=n.getRootElement(),f=h?.closest(".luthor-editor-wrapper")||h?.parentElement||null;r(f);let y=()=>{n.getEditorState().read(()=>{if(!n.isEditable()){a(false),u(null);return}let N=$getSelection();if($isRangeSelection(N)&&!N.isCollapsed()){a(false),u(null);return}let E=Nn();if(!E){a(false),u(null);return}let O=n.getElementByKey(E.getKey())?.closest("table");if(!O||!f){a(false),u(null);return}let K=$getTableNodeFromLexicalNodeOrThrow(E).getChildren().filter(ge=>$isTableRowNode(ge))[0]?.getChildren().filter(ge=>$isTableCellNode(ge))||[],J=K.length>0&&K.every(ge=>ge.hasHeaderState(TableCellHeaderStates.ROW));d(J);let B=f.getBoundingClientRect(),$=O.getBoundingClientRect(),Q=m.current?.getBoundingClientRect(),I=Q?.width??520,U=Q?.height??44,X=I/2,se=12,j=$.left-B.left+$.width/2,ee=se+X,Me=Math.max(ee,B.width-se-X),Ce=Zc(j,ee,Me),De=$.top-B.top>=U+se;u({x:Ce,y:De?$.top-B.top-12:$.bottom-B.top+12,placeAbove:De}),a(true);});};y();let b=n.registerUpdateListener(()=>{y();}),v=()=>{g.current===null&&(g.current=window.requestAnimationFrame(()=>{g.current=null,y();}));};return window.addEventListener("scroll",v,true),window.addEventListener("resize",v),()=>{b(),window.removeEventListener("scroll",v,true),window.removeEventListener("resize",v),g.current!==null&&(cancelAnimationFrame(g.current),g.current=null);}},[n]),!e||!o||!s||!c||typeof document>"u")return null;let w={insertRowAbove:()=>x(()=>$insertTableRowAtSelection(false)),insertRowBelow:()=>x(()=>$insertTableRowAtSelection(true)),insertColumnLeft:()=>x(()=>$insertTableColumnAtSelection(false)),insertColumnRight:()=>x(()=>$insertTableColumnAtSelection(true)),deleteSelectedColumn:()=>x(()=>$deleteTableColumnAtSelection()),deleteSelectedRow:()=>x(()=>$deleteTableRowAtSelection()),deleteTable:()=>x(h=>{$getTableNodeFromLexicalNodeOrThrow(h).remove();})},p=i.config.tableBubbleRenderer?i.config.tableBubbleRenderer({headersEnabled:l,setHeadersEnabled:h=>{d(h),L(h);},actions:w}):jsx(ed,{headersEnabled:l,setHeadersEnabled:h=>{d(h),L(h);},actions:w});return createPortal(jsx("div",{ref:m,className:"luthor-table-bubble-menu",style:{position:"absolute",left:c.x,top:c.y,transform:c.placeAbove?"translate(-50%, -100%)":"translate(-50%, 0)",zIndex:"var(--luthor-z-menu, 460)"},onMouseDown:h=>h.preventDefault(),children:p}),o)}var Tn=class extends k{constructor(e){super("table",["toolbar"]);C(this,"defaultContextMenuItems",e=>[{label:"Insert Row Above",action:()=>e.insertRowAbove()},{label:"Insert Row Below",action:()=>e.insertRowBelow()},{label:"Insert Column Left",action:()=>e.insertColumnLeft()},{label:"Insert Column Right",action:()=>e.insertColumnRight()},{separator:true,label:"",action:()=>{}},{label:"Toggle Row Header",action:()=>e.toggleRowHeader()},{label:"Toggle Column Header",action:()=>e.toggleColumnHeader()},{label:"Merge Cells",action:()=>e.mergeSelectedCells()},{label:"Split Cell",action:()=>e.unmergeSelectedCell()},{separator:true,label:"",action:()=>{}},{label:"Delete Row",action:()=>e.deleteRow()},{label:"Delete Column",action:()=>e.deleteColumn()},{label:"Delete Table",action:()=>e.deleteTable()}]);this.config={rows:3,columns:3,includeHeaders:false,enableContextMenu:true,contextMenuItems:this.defaultContextMenuItems,...e};}getContextMenuItems(e){return typeof this.config.contextMenuItems=="function"?this.config.contextMenuItems(e):Array.isArray(this.config.contextMenuItems)?this.config.contextMenuItems:this.defaultContextMenuItems(e)}configure(e){return this.config={...this.config,...e},e.contextMenuItems&&(this.config.contextMenuItems=e.contextMenuItems),this}register(e){let t;if(this.config.enableContextMenu){let o=this.config.contextMenuExtension||_o;if(o){let r={id:"table",priority:10,canHandle:({editor:a,target:l,selection:d})=>{if(!a.isEditable())return false;let c=l.closest("td, th, [data-lexical-table-cell]");return c?$isTableSelection(d)?true:c.tagName==="TD"||c.tagName==="TH":false},getItems:({editor:a})=>{let l=this.getCommands(a);return this.getContextMenuItems(l)},renderer:this.config.contextMenuRenderer||o.config?.defaultRenderer};o.getCommands(e).registerProvider(r),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:s=false}=t;e.update(()=>{let a=$getSelection();if($isRangeSelection(a)){let l=$createTableNodeWithDimensions(o,r,s);a.insertNodes([l]);}});},insertRowAbove:()=>{e.update(()=>{$insertTableRowAtSelection(false);});},insertRowBelow:()=>{e.update(()=>{$insertTableRowAtSelection(true);});},insertColumnLeft:()=>{e.update(()=>{$insertTableColumnAtSelection(false);});},insertColumnRight:()=>{e.update(()=>{$insertTableColumnAtSelection(true);});},toggleRowHeader:()=>{e.update(()=>{let t=Nn();if(!t)return;let o=$getTableNodeFromLexicalNodeOrThrow(t),r=$getTableRowIndexFromTableCellNode(t),s=o.getChildren()[r];if(!$isTableRowNode(s))return;let a=s.getChildren().filter(c=>$isTableCellNode(c)),d=!a.every(c=>c.hasHeaderState(TableCellHeaderStates.ROW))?TableCellHeaderStates.ROW:TableCellHeaderStates.NO_STATUS;a.forEach(c=>{c.setHeaderStyles(d,TableCellHeaderStates.ROW);});});},toggleColumnHeader:()=>{e.update(()=>{let t=Nn();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(td,{extension:this},"table-quick-actions-plugin")]}},nd=new Tn;var yi=9,ct={"decimal-alpha-roman":["decimal","lower-alpha","lower-roman"],"decimal-hierarchical":["decimal"],"upper-roman-upper-alpha":["upper-roman","upper-alpha","decimal","lower-alpha","decimal","lower-alpha","lower-roman","lower-alpha","lower-roman"],"upper-alpha-lower-alpha":["upper-alpha","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman"],"decimal-leading-zero-alpha":["decimal-leading-zero","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman","decimal","lower-alpha","lower-roman"]},$t={"disc-circle-square":["disc","circle","square"],"arrow-diamond-disc":['"\u25B8"','"\u25C6"',"disc"],"square-square-square":["square","square","square"],"arrow-circle-square":['"\u25B8"',"circle","square"]},dt="decimal-alpha-roman",Ei="disc-circle-square",In="--luthor-checklist-variant",Ie="--luthor-unordered-pattern",wi="--luthor-unordered-pattern-token",Fe="--luthor-unordered-marker-kind",xe="--luthor-ordered-marker-content",xi={"disc-arrow-square":"arrow-circle-square","square-circle-disc":"disc-circle-square","arrow-diamond-square":"arrow-diamond-disc","star-circle-square":"disc-circle-square"};function Ri(i){let n=new Map;for(let e of i.split(";")){let t=e.trim();if(!t)continue;let o=t.indexOf(":");if(o<=0)continue;let r=t.slice(0,o).trim(),s=t.slice(o+1).trim();r&&n.set(r,s);}return n}function cd(i){return Array.from(i.entries()).map(([n,e])=>`${n}: ${e}`).join("; ")}function ne(i,n){let e=i.getStyle(),t=Ri(e),o=false;for(let[r,s]of Object.entries(n)){let a=t.get(r);if(s===null||s===""){t.delete(r)&&(o=true);continue}a!==s&&(t.set(r,s),o=true);}o&&i.setStyle(cd(t));}function me(i,n){return Ri(i.getStyle()).get(n)??null}function mt(i,n){let e=[...i];for(let t=0;t<e.length;t+=1){let o=e[t],r=n(o);if(r==="stop")break;r!=="skip-children"&&typeof o?.getChildren=="function"&&e.push(...o.getChildren());}}function _n(i){let n=i;for(;n;){if($isListNode(n))return n;n=n.getParent();}return null}function dd(i){let n=i;for(;n;){if($isListItemNode(n))return n;n=n.getParent();}return null}function jt(i){let n=i;for(;;){let e=n.getParent();if(!$isListItemNode(e))return n;let t=e.getParent();if(!$isListNode(t))return n;n=t;}}function kn(i,n){let e=$getListDepth(i),t=$getListDepth(n);return e-t}function Pn(i,n){let e=n%i.length;return i[e]??i[0]??"disc"}function Ci(i,n){let e=i,t="";for(;e>0;){let o=(e-1)%26;t=String.fromCharCode((n?65:97)+o)+t,e=Math.floor((e-1)/26);}return t||(n?"A":"a")}function Si(i,n){let e=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],t=Math.max(1,Math.floor(i)),o="";for(let[r,s]of e)for(;t>=r;)o+=s,t-=r;return n?o:o.toLowerCase()}function vi(i,n,e,t){let o=e==="paren"?")":".";return `"${t?t.join("."):i==="decimal-leading-zero"?n<10?`0${n}`:`${n}`:i==="lower-alpha"?Ci(n,false):i==="upper-alpha"?Ci(n,true):i==="lower-roman"?Si(n,false):i==="upper-roman"?Si(n,true):`${n}`}${o}"`}function ud(i,n){let e=0;for(let t of i.getChildren())if($isListItemNode(t)&&(zt(t)&&(e+=1),t.getKey()===n.getKey()))return Math.max(1,e);return Math.max(1,e)}function Ni(i,n){let e=[],t=i;for(;t.getKey()!==n.getKey();){let o=t.getParent();if(!$isListItemNode(o))break;let r=o.getParent();if(!$isListNode(r))break;e.push(ud(r,o)),t=r;}return e.reverse()}function Dn(i){return i&&Object.hasOwn($t,i)?i:i&&Object.hasOwn(xi,i)?xi[i]??Ei:Ei}function md(i){return i.startsWith('"')&&i.endsWith('"')}function Uo(i){if(md(i)){let n=i.toLowerCase(),e=n.slice(1,-1);return n.includes("\\25c6")||e==="\u25C6"?"diamond":(n.includes("\\25b8")||n.includes("\\27a4")||e==="\u25B8"||e==="\u27A4","arrow")}switch(i){case "disc":return "disc";case "circle":return "circle";case "square":return "square";default:return "disc"}}function gd(i){let n=i.trim();if(!n)return null;let e=n.match(/^(\d+)([.)])$/);if(e){let r=e[1]??"",s=e[2]??".";return {pattern:r.length>1&&r.startsWith("0")?"decimal-leading-zero-alpha":"decimal-alpha-roman",suffix:s===")"?"paren":"dot"}}let t=n.match(/^([IVXLCDMivxlcdm]+)([.)])$/);if(t)return {pattern:"upper-roman-upper-alpha",suffix:(t[2]??".")===")"?"paren":"dot"};let o=n.match(/^([A-Z]+)([.)])$/);return o?{pattern:"upper-alpha-lower-alpha",suffix:(o[2]??".")===")"?"paren":"dot"}:null}function ut(i){let n=new Map,e=i.getNodes();for(let t of e){let o=_n(t);if(!o)continue;let r=jt(o);n.set(r.getKey(),r);}if(n.size===0){let t=_n(i.anchor.getNode());if(t){let o=jt(t);n.set(o.getKey(),o);}}return [...n.values()]}function Mn(i,n){let e=Math.max(0,n-1),t=i.anchor.getNode(),o=dd(t);if(o){let s=o.getIndent();if(typeof s=="number")return s>=e}let r=_n(t);return r?$getListDepth(r)-1>=e:false}function Ko(i){let n=[];return mt(i.getChildren(),e=>{if($isListNode(e))return "skip-children";$isTextNode(e)&&n.push(e);}),n}function We(i){let n=[];return mt(i.getChildren(),e=>{if($isListNode(e))return n.push(e),"skip-children"}),n}function zt(i){let n=false,e=false;return mt(i.getChildren(),t=>{if($isListNode(t))return e=true,"skip-children";if($isTextNode(t)&&t.getTextContent().trim().length>0)return n=true,"stop"}),n?true:!e}function Bo(i,n){mt(i.getChildren(),e=>{if($isListNode(e))return "skip-children";typeof e.getStyle=="function"&&typeof e.setStyle=="function"&&ne(e,{[wi]:n});});}function fd(i){let n=null;return mt(i.getChildren(),e=>{if($isListNode(e))return "skip-children";if(typeof e.getStyle=="function"){let t=me(e,wi);if(t)return n=Dn(t),"stop"}}),n}function pd(i){let n=[i];for(;n.length>0;){let e=n.pop();if(e.getListType()==="check")for(let t of e.getChildren()){if(!$isListItemNode(t))continue;let o=Ko(t);for(let r of o)if(me(r,In)==="plain")return "plain";n.push(...We(t));}}return null}function hd(i){let n=[i];for(;n.length>0;){let e=n.pop();if(e.getListType()==="bullet")for(let t of e.getChildren()){if(!$isListItemNode(t))continue;let o=me(t,Ie),r=Dn(o);if(o&&Object.hasOwn($t,r))return r;let s=fd(t);if(s)return s;n.push(...We(t));}}return null}function zo(i){let n=hd(i);if(n)return n;let e=me(i,Ie);return Dn(e)}function $o(i){return me(i,In)==="plain"?"plain":pd(i)??"strikethrough"}function On(i){let n=i.anchor.getNode(),e=null,t=null;for(;n;){if(!t&&$isListItemNode(n)&&(t=n),$isListNode(n)){e=n;break}n=n.getParent();}let o=e?jt(e):null;return {listNode:e,listItemNode:t,topListNode:o}}function Qo(i){let n=i.target;if(!(n instanceof HTMLElement))return null;let e=n.closest("li");if(!(e instanceof HTMLLIElement))return null;let t=e.firstElementChild;if(t instanceof HTMLElement&&(t.tagName==="UL"||t.tagName==="OL"))return null;let o=e.parentElement;if(!o||o.__lexicalListType!=="check")return null;let r=e.getBoundingClientRect(),s=i.clientX,a=window.getComputedStyle?window.getComputedStyle(e,"::before"):{width:"0px"},l=Number.parseFloat(a.width);if(!Number.isFinite(l)||l<=0)return null;let c=("pointerType"in i?i.pointerType:"")==="touch"?32:0;return (e.dir==="rtl"?s<r.right+c&&s>r.right-l-c:s>r.left-c&&s<r.left+l+c)?e:null}var An=class extends k{constructor(n={}){super("list",["toolbar"]),this.config=n;}getMaxListDepth(){let n=this.config.maxDepth;if(!Number.isFinite(n))return yi;let e=Math.floor(n);return e>=1?e:yi}register(n){let e=n.registerNodeTransform(ListNode,d=>{this.syncListNodeStyles(d);}),t=n.registerNodeTransform(ListItemNode,d=>{let c=d.getParent();$isListNode(c)&&this.syncListNodeStyles(c);}),o=n.registerCommand(KEY_SPACE_COMMAND,d=>{let c=false;return n.update(()=>{c=this.handleOrderedListShortcut(n);}),c&&d.preventDefault(),c},COMMAND_PRIORITY_EDITOR),r=n.registerCommand(INDENT_CONTENT_COMMAND,()=>{let d=$getSelection();return !$isRangeSelection(d)||!On(d).listNode?false:Mn(d,this.getMaxListDepth())},COMMAND_PRIORITY_EDITOR),s=d=>{n.isEditable()||Qo(d)&&(d.preventDefault(),d.stopPropagation());},a=d=>{if(n.isEditable())return;let c=Qo(d);c&&(d.preventDefault(),d.stopPropagation(),n.update(()=>{let u=$getNearestNodeFromDOMNode(c);if(!$isListItemNode(u))return;let m=u.getParent();!$isListNode(m)||m.getListType()!=="check"||u.toggleChecked();}));},l=n.registerRootListener((d,c)=>{c&&(c.removeEventListener("pointerdown",s),c.removeEventListener("click",a)),d&&(d.addEventListener("pointerdown",s),d.addEventListener("click",a));});return ()=>{e(),t(),o(),r(),l();}}getNodes(){return [ListNode,ListItemNode]}getPlugins(){return [jsx(ListPlugin,{hasStrictIndent:true},"list-plugin"),jsx(CheckListPlugin,{},"check-list-plugin")]}getCommands(n){return {toggleUnorderedList:()=>{n.update(()=>{let e=$getSelection();if(!$isRangeSelection(e))return;let t=On(e);if(t.topListNode){if(t.topListNode.getListType()==="bullet"){t.listItemNode&&t.listItemNode.getIndent()>0?n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode);return}this.convertTopListType(t.topListNode,"bullet");return}n.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0);});},toggleOrderedList:()=>{n.update(()=>{let e=$getSelection();if(!$isRangeSelection(e))return;let t=On(e);if(t.topListNode){if(t.topListNode.getListType()==="number"){t.listItemNode&&t.listItemNode.getIndent()>0?n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode);return}this.convertTopListType(t.topListNode,"number");return}n.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);});},toggleCheckList:()=>{n.update(()=>{let e=$getSelection();if(!$isRangeSelection(e))return;let t=On(e);if(t.topListNode){if(t.topListNode.getListType()==="check"){t.listItemNode&&t.listItemNode.getIndent()>0?n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode);return}this.convertTopListType(t.topListNode,"check");return}n.dispatchCommand(INSERT_CHECK_LIST_COMMAND,void 0);});},indentList:()=>{n.update(()=>{let e=$getSelection();$isRangeSelection(e)&&(Mn(e,this.getMaxListDepth())||n.dispatchCommand(INDENT_CONTENT_COMMAND,void 0));});},outdentList:()=>{n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0);},insertNestedUnorderedList:()=>{n.update(()=>{let e=$getSelection();!$isRangeSelection(e)||Mn(e,this.getMaxListDepth())||(n.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),n.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0));});},insertNestedOrderedList:()=>{n.update(()=>{let e=$getSelection();!$isRangeSelection(e)||Mn(e,this.getMaxListDepth())||(n.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),n.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0));});},setOrderedListPattern:e=>{n.update(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;n.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);let o=$getSelection();if(!$isRangeSelection(o))return;let r=ut(o);for(let s of r)this.applyOrderedPattern(s,e);});},setOrderedListSuffix:e=>{n.update(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;let o=ut(t);for(let r of o)r.getListType()==="number"&&this.applyOrderedSuffix(r,e);});},setUnorderedListPattern:e=>{n.update(()=>{let t=$getSelection();if(!$isRangeSelection(t))return;n.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0);let o=$getSelection();if(!$isRangeSelection(o))return;let r=ut(o);for(let s of r)this.applyUnorderedPattern(s,e);});},setCheckListVariant:e=>{let t=false;n.update(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let r=ut(o);if(r.length===0){t=true;return}for(let s of r)s.getListType()!=="check"&&this.convertTopListType(s,"check"),this.applyCheckListVariant(s,e);}),t&&(n.dispatchCommand(INSERT_CHECK_LIST_COMMAND,void 0),n.update(()=>{let o=$getSelection();if(!$isRangeSelection(o))return;let r=ut(o);for(let s of r)s.getListType()!=="check"&&this.convertTopListType(s,"check"),this.applyCheckListVariant(s,e);}));},rehydrateListStyles:()=>{n.update(()=>{let e=$getRoot(),t=new Map;mt(e.getChildren(),o=>{if($isListNode(o)){let r=jt(o);t.set(r.getKey(),r);}});for(let o of t.values()){if(o.getListType()==="number"){let r=me(o,"--luthor-ordered-pattern")??dt,s=Object.hasOwn(ct,r)?r:dt,a=me(o,"--luthor-ordered-suffix")==="paren"?"paren":"dot";this.applyOrderedPattern(o,s),this.applyOrderedSuffix(o,a);continue}if(o.getListType()==="bullet"){let r=zo(o);this.applyUnorderedPattern(o,r);continue}if(o.getListType()==="check"){let r=$o(o);this.applyCheckListVariant(o,r);}}});}}}applyOrderedPattern(n,e){if(n.getListType()!=="number")return;let t=ct[e],o=me(n,"--luthor-ordered-suffix")??"dot";ne(n,{"--luthor-ordered-pattern":e,"--luthor-ordered-suffix":o});let r=[n];for(;r.length>0;){let s=r.pop();if(s.getListType()!=="number")continue;let a=kn(s,n),l=Pn(t,a),d=e==="decimal-hierarchical";ne(s,{"--luthor-ordered-pattern":e,"--luthor-ordered-suffix":o,"list-style-type":"none",[xe]:null});let c=d?Ni(s,n):null,u=0;for(let m of s.getChildren()){if(!$isListItemNode(m))continue;let g=zt(m);g&&(u+=1);let x=vi(l,Math.max(1,u),o==="paren"?"paren":"dot",d?[...c??[],Math.max(1,u)]:null);ne(m,{[xe]:g?x:null}),r.push(...We(m));}}}applyOrderedSuffix(n,e){let t=[n];for(;t.length>0;){let s=t.pop();if(s.getListType()==="number"){ne(s,{"--luthor-ordered-suffix":e});for(let a of s.getChildren())$isListItemNode(a)&&t.push(...We(a));}}let o=me(n,"--luthor-ordered-pattern")??dt,r=Object.hasOwn(ct,o)?o:dt;this.applyOrderedPattern(n,r);}applyUnorderedPattern(n,e){if(n.getListType()!=="bullet")return;let t=$t[e];ne(n,{[Ie]:e});let o=[n];for(;o.length>0;){let r=o.pop();if(r.getListType()!=="bullet")continue;let s=kn(r,n),a=Pn(t,s),l=Uo(a);ne(r,{[Ie]:e,"list-style-type":"none","--luthor-unordered-marker-content":null,[Fe]:null,[xe]:null});for(let d of r.getChildren())$isListItemNode(d)&&(ne(d,{[Ie]:e,"--luthor-unordered-marker-content":null,[Fe]:zt(d)?l:null,[xe]:null}),Bo(d,e),o.push(...We(d)));}}applyCheckListVariant(n,e){if(n.getListType()!=="check")return;let t=[n];for(;t.length>0;){let o=t.pop();if(o.getListType()==="check"){ne(o,{"--luthor-checklist-variant":e,"--luthor-unordered-marker-content":null,[Fe]:null,[xe]:null,"--luthor-unordered-pattern":null,"--luthor-ordered-pattern":null,"--luthor-ordered-suffix":null,"list-style-type":null});for(let r of o.getChildren()){if(!$isListItemNode(r))continue;ne(r,{"--luthor-checklist-variant":e,[Ie]:null,"--luthor-unordered-marker-content":null,[Fe]:null,[xe]:null}),Bo(r,null);let s=Ko(r);for(let a of s)ne(a,{[In]:e==="plain"?"plain":null});t.push(...We(r));}}}}syncListNodeStyles(n){let e=jt(n);if(e.getListType()==="number"){let t=me(e,"--luthor-ordered-pattern")??dt;if(!Object.hasOwn(ct,t))return;let o=ct[t],r=kn(n,e),s=Pn(o,r),a=t==="decimal-hierarchical",l=me(e,"--luthor-ordered-suffix")??"dot";ne(n,{"--luthor-ordered-pattern":t,"--luthor-ordered-suffix":l,"list-style-type":"none",[xe]:null});let d=a?Ni(n,e):null,c=0;for(let u of n.getChildren()){if(!$isListItemNode(u))continue;let m=zt(u);m&&(c+=1);let g=vi(s,Math.max(1,c),l==="paren"?"paren":"dot",a?[...d??[],Math.max(1,c)]:null);ne(u,{[xe]:m?g:null});}return}if(e.getListType()==="bullet"){let t=zo(e),o=$t[t],r=kn(n,e),s=Pn(o,r),a=Uo(s);ne(n,{[Ie]:t,"list-style-type":"none","--luthor-unordered-marker-content":null,[Fe]:null,[xe]:null});for(let l of n.getChildren())$isListItemNode(l)&&(ne(l,{[Ie]:t,"--luthor-unordered-marker-content":null,[Fe]:zt(l)?a:null,[xe]:null}),Bo(l,t));return}if(e.getListType()==="check"){let t=$o(e);ne(n,{"--luthor-checklist-variant":t,"--luthor-unordered-marker-content":null,[Fe]:null,[xe]:null,"--luthor-unordered-pattern":null,"--luthor-ordered-pattern":null,"--luthor-ordered-suffix":null,"list-style-type":null});for(let o of n.getChildren()){if(!$isListItemNode(o))continue;ne(o,{"--luthor-checklist-variant":t,[Ie]:null,"--luthor-unordered-marker-content":null,[Fe]:null,[xe]:null});let r=Ko(o);for(let s of r)ne(s,{[In]:t==="plain"?"plain":null});}}}convertTopListType(n,e){let t=[n];for(;t.length>0;){let r=t.pop();r.setListType(e);for(let s of r.getChildren())$isListItemNode(s)&&t.push(...We(s));}if(e==="number"){let r=me(n,"--luthor-ordered-pattern"),s=r&&Object.hasOwn(ct,r)?r:dt,a=me(n,"--luthor-ordered-suffix")==="paren"?"paren":"dot";this.applyOrderedPattern(n,s),this.applyOrderedSuffix(n,a);return}if(e==="bullet"){let r=zo(n);this.applyUnorderedPattern(n,r);return}let o=$o(n);this.applyCheckListVariant(n,o);}handleOrderedListShortcut(n){let e=$getSelection();if(!$isRangeSelection(e)||!e.isCollapsed())return false;let t=e.anchor.getNode();if(_n(t))return false;let o=t;for(;o&&!$isParagraphNode(o);)o=o.getParent();if(!$isParagraphNode(o))return false;let r=o,s=gd(r.getTextContent());if(!s)return false;r.clear(),n.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);let a=$getSelection();if(!$isRangeSelection(a))return true;let l=ut(a);for(let d of l)d.getListType()==="number"&&(this.applyOrderedPattern(d,s.pattern),this.applyOrderedSuffix(d,s.suffix));return true}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);});})}}},bd=new An;var Ed="plain";function Ut(){return Ed}function ki(){return PrismTokenizer}async function Pi(i){return i?.provider?i.provider:i?.loadProvider?i.loadProvider():null}async function Mi(i){return i?i.tokenizer?i.tokenizer:i.getTokenizer?i.getTokenizer():null:null}var zn=class zn extends k{constructor(){super("code",["toolbar"]);C(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??ki()),this.resolveConfiguredTokenizer().then(a=>{o||!a||r(a);}));let s=e.registerCommand(KEY_TAB_COMMAND,a=>{let l=false;return e.update(()=>{let d=$getSelection();if(!$isRangeSelection(d))return;let c=d.anchor.getNode();this.getBlockNode(c)&&(l=true,!this.hasReachedCodeTabLimit(d)&&d.insertText(" "));}),l?(a?.preventDefault(),true):false},COMMAND_PRIORITY_LOW);return ()=>{o=true,t(),s();}}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?.(Ut()),r});}});}async resolveConfiguredTokenizer(){if(this.config.tokenizer)return this.config.tokenizer;let e=await this.loadCodeHighlightProvider();return Mi(e)}async loadCodeHighlightProvider(){return this.config.provider?this.config.provider:this.codeHighlightProviderPromise?this.codeHighlightProviderPromise:(this.codeHighlightProviderPromise=Pi(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 s=r.getNodes();for(let a of s){let l=this.getBlockNode(a);if(!l){o=false;break}if(this.getNodeFormat(l)!==e){o=false;break}}}),o}getBlockNode(e){let 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}hasReachedCodeTabLimit(e){let t=e.anchor,o=t.getNode();if(typeof o.getTextContent!="function")return false;let r=o.getTextContent(),s=typeof t.offset=="number"?t.offset:r.length,a=Math.max(0,Math.min(r.length,s)),l=r.lastIndexOf(`
|
|
5
|
+
`,a-1)+1;return (r.slice(l,a).match(/^\t*/)?.[0].length??0)>=zn.MAX_CODE_TAB_DEPTH}};C(zn,"MAX_CODE_TAB_DEPTH",8);var Bn=zn,wd=new Bn;var Hd='<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>',Fd='<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>',Bd=["plaintext","typescript","javascript","markdown","html","css","python","sql","java","c","cpp","rust","powershell","xml"],jn=class extends k{constructor(){super("codeIntelligence");C(this,"languageOptions",[]);this.config={isCopyAllowed:true};}register(e){this.languageOptions=this.getLanguageOptions();let t=registerMarkdownShortcuts(e,TRANSFORMERS),o=e.registerUpdateListener(({dirtyElements:r,dirtyLeaves:s})=>{(r.size>0||s.size>0)&&this.ensureCodeBlockThemes(e);});return queueMicrotask(()=>{this.ensureCodeBlockThemes(e);}),()=>{t(),o(),this.languageOptions=[];}}getPlugins(){return [createElement($d,{key:"code-intelligence-controls",extension:this})]}getCommands(e){return {setCodeLanguage:t=>{let o=gt(t),r=this.getThemeForLanguage(o);e.update(()=>{this.getSelectionCodeNodes().forEach(s=>{s.setLanguage(o??null),s.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:Fi(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=gt(t.getLanguage());return {key:t.getKey(),language:o??"plaintext",text:t.getTextContent()}}))}setCodeBlockLanguage(e,t,o){e.isEditable()&&e.update(()=>{let r=$getNodeByKey(t);if(!r||!$isCodeNode(r))return;let s=gt(o);r.setLanguage(s??null),r.setTheme(this.getThemeForLanguage(s));});}getCodeBlockText(e,t){return e.getEditorState().read(()=>{let o=$getNodeByKey(t);return !o||!$isCodeNode(o)?"":o.getTextContent()})}getThemeForLanguage(e){let t=gt(e);return !t||t==="plain"?Ut():"hljs"}ensureCodeBlockThemes(e){let t=e.getEditorState().read(()=>$nodesOfType(CodeNode).map(o=>{let r=o.getTheme?.()??"",s=this.getThemeForLanguage(o.getLanguage());return {key:o.getKey(),nextTheme:s??Ut(),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 s=this.getNearestCodeNode(r);s&&o.set(s.getKey(),s);}),Array.from(o.values())}getNearestCodeNode(e){let t=e;for(;t;){if($isCodeNode(t))return t;t=t.getParent();}return null}getLanguageOptions(){let e=Bd.map(r=>gt(r)).filter(r=>!!r),t=Qd(this.config.languageOptions);if(!t)return Wo(e);let o=Yd(t.values);return t.mode==="replace"?Wo(o):Wo([...e,...o])}async getPrimaryCodeBlockText(e){return new Promise(t=>{e.getEditorState().read(()=>{let r=this.getSelectionCodeNodes()[0];if(!r){t(null);return}let s=r.getTextContent().trim();if(!s){t(null);return}t({key:r.getKey(),text:s});});})}},zd=34;function $d({extension:i}){let[n]=useLexicalComposerContext(),[e,t]=useState(()=>n.isEditable()),[o,r]=useState([]),[s,a]=useState({}),l=useRef(null),d=useRef(new Map),c=useMemo(()=>i.getLanguageOptionsSnapshot(),[i]),u=useCallback(()=>{let y=Hi(n);if(!y)return [];let b=y.getBoundingClientRect(),v=i.getCodeBlocksSnapshot(n),N=[];return v.forEach(E=>{let T=n.getElementByKey(E.key);if(!T||!T.isConnected)return;T.classList.add("luthor-code-block--interactive");let O=T.getBoundingClientRect(),A=Math.max(120,Math.round(O.width)),Y=Math.max(0,Math.round(O.top-b.top-zd)),K=Math.max(0,Math.round(O.left-b.left));N.push({key:E.key,language:E.language,top:Y,left:K,width:A});}),N},[n,i]),m=useCallback(()=>{let y=u();r(b=>jd(b,y)?b:y);},[u]),g=useCallback(()=>{l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null,m();}));},[m]),x=useCallback(y=>{let b=d.current.get(y);b&&(clearTimeout(b),d.current.delete(y));},[]),L=useCallback((y,b)=>{x(y),a(N=>({...N,[y]:b}));let v=setTimeout(()=>{a(N=>{if(!(y in N))return N;let E={...N};return delete E[y],E}),d.current.delete(y);},1200);d.current.set(y,v);},[x]),w=useCallback((y,b)=>{e&&(i.setCodeBlockLanguage(n,y,b),g());},[n,i,e,g]),p=i.isCopyAllowed(),h=useCallback(async y=>{if(!p)return;let b=i.getCodeBlockText(n,y);if(!b.trim())return;if(await Fi(b)){L(y,"copied");return}L(y,"error");},[p,n,i,L]);if(useEffect(()=>n.registerEditableListener(t),[n]),useEffect(()=>{g();let y=0,b=null,v=()=>{g(),y+=1,!(y>=20)&&(b=requestAnimationFrame(v));};b=requestAnimationFrame(v);let N=n.registerUpdateListener(()=>{g();}),E=()=>{g();},T=d.current;return window.addEventListener("scroll",E,true),window.addEventListener("resize",E,{passive:true}),()=>{N(),window.removeEventListener("scroll",E,true),window.removeEventListener("resize",E),b!==null&&cancelAnimationFrame(b),l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),T.forEach(O=>clearTimeout(O)),T.clear();}},[n,g]),useEffect(()=>{let y=new Set(o.map(b=>b.key));a(b=>{let v=false,N={};return Object.entries(b).forEach(([E,T])=>{if(y.has(E)){N[E]=T;return}v=true,x(E);}),v?N:b});},[x,o]),typeof document>"u"||o.length===0)return null;let f=Hi(n);return f?createPortal(createElement("div",{className:"luthor-codeblock-controls-layer","aria-hidden":false},o.map(y=>{let b=s[y.key],v=["luthor-codeblock-copy",b==="copied"?"is-copied":"",b==="error"?"is-copy-error":""].filter(Boolean).join(" "),N=b==="copied"?"Copied":b==="error"?"Copy failed":"Copy to clipboard";return createElement("div",{key:y.key,className:"luthor-codeblock-controls","data-code-node-key":y.key,style:{position:"absolute",top:`${y.top}px`,left:`${y.left}px`,width:`${y.width}px`}},createElement("span",{className:"luthor-codeblock-controls-left"},createElement("select",{className:"luthor-codeblock-language",value:y.language,"aria-label":"Code language",disabled:!e,"aria-disabled":!e,onChange:E=>{let T=E.target;w(y.key,T.value);}},c.map(E=>createElement("option",{key:E,value:E},E)))),createElement("span",{className:"luthor-codeblock-controls-right"},p?createElement("button",{className:v,type:"button","aria-label":"Copy code",title:N,"data-tooltip":N,onMouseDown:E=>{E.preventDefault();},onClick:()=>{h(y.key);},dangerouslySetInnerHTML:{__html:b==="copied"?Fd:Hd}}):null))})),f):null}function jd(i,n){if(i.length!==n.length)return false;for(let e=0;e<i.length;e+=1){let t=i[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 Fi(i){if(typeof navigator<"u"&&navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(i),!0}catch{}if(typeof document>"u")return false;let n=document.createElement("textarea");n.value=i,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 Hi(i){let n=i.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 gt(i){if(!i)return null;let n=i.trim().toLowerCase();if(!n||n==="auto")return null;let e=normalizeCodeLang(n);return !e||e==="auto"||!Ud(e)?null:e}function Ud(i){let n=i.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 Kd=new jn;function Qd(i){if(!i)return null;if(Array.isArray(i))return {mode:"append",values:i};let n=i;return {mode:n.mode??"append",values:Array.isArray(n.values)?n.values:[]}}function Yd(i){let n=[],e=new Set;for(let t of i){let o=t.trim();if(!o)continue;let r=gt(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 Wo(i){return Array.from(new Set(i)).sort((n,e)=>n.localeCompare(e))}var Un=class extends re{constructor(){super("code");}register(n){let e=super.register(n),t=n.getRootElement();if(!t)return e;let o=a=>{if(a.nodeType===Node.TEXT_NODE)return a;for(let l=0;l<a.childNodes.length;l+=1){let d=a.childNodes[l];if(!d)continue;let c=o(d);if(c)return c}return null},r=a=>{if(a.nodeType===Node.TEXT_NODE)return a;for(let l=a.childNodes.length-1;l>=0;l-=1){let d=a.childNodes[l];if(!d)continue;let c=r(d);if(c)return c}return null},s=a=>{if(a.button!==0)return;let l=window.getSelection();if(l&&l.rangeCount>0&&!l.getRangeAt(0).collapsed)return;let d=a.target;if(!(d instanceof Node))return;let c=d instanceof HTMLElement?d:d.parentElement;if(!c)return;let u=c.closest(".luthor-text-code, code");if(u instanceof HTMLElement||(u=document.elementFromPoint(a.clientX+4,a.clientY)?.closest(".luthor-text-code, code")??null),!(u instanceof HTMLElement)||!t.contains(u))return;let m=u.getBoundingClientRect(),g=Math.max(4,Math.min(8,m.width/2)),x=null,L=0;a.clientX<=m.left+g?(x=o(u),L=0):a.clientX>=m.right-g&&(x=r(u),L=x?.data.length??0),x&&(a.preventDefault(),n.focus(()=>{let w=window.getSelection();if(!w)return;let p=document.createRange();p.setStart(x,L),p.collapse(true),w.removeAllRanges(),w.addRange(p);}));};return t.addEventListener("click",s,true),()=>{t.removeEventListener("click",s,true),e();}}},Vd=new Un;var Qn=class extends k{constructor(){super("blockFormat",["toolbar"]);}register(n){let e=n.registerCommand(INSERT_PARAGRAPH_COMMAND,()=>{let o=$getSelection();if($isRangeSelection(o)){let r=o.anchor.getNode(),s=this.getBlockNode(r);if(s&&($isHeadingNode(s)||$isQuoteNode(s)))return false}return false},COMMAND_PRIORITY_NORMAL),t=n.registerCommand(KEY_ENTER_COMMAND,o=>{let r=false;return n.update(()=>{let s=$getSelection();if(!$isRangeSelection(s))return;let a=s.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 s of r){let a=this.getBlockNode(s);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 s of r){let a=this.getBlockNode(s);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}},ru=new Qn;var Yn=class extends k{constructor(){super("history",["toolbar"]);C(this,"canUndoState",false);C(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}}},uu=new Yn;var Xn=class extends k{constructor(e){super("draggableBlock",["floating"]);C(this,"isDraggingState",false);C(this,"stateChangeCallbacks",new Set);this.config={showInToolbar:false,position:"after",showMoveButtons:true,showUpButton:true,showDownButton:true,showAddButton:true,buttonStackPosition:"left",enableTextSelectionDrag:true,offsetLeft:-40,offsetRight:10,...e};}register(e){return ()=>{}}getPlugins(){return [jsx(hu,{config:this.config,extension:this},"draggable-block")]}getCommands(e){return {moveBlock:(t,o,r)=>{e.isEditable()&&e.update(()=>{let s=$getNodeByKey(t),a=$getNodeByKey(o);s&&a&&(s.remove(),r?a.insertAfter(s):a.insertBefore(s));});},moveCurrentBlockUp:()=>{e.isEditable()&&e.update(()=>{let t=$getSelection();if($isRangeSelection(t)){let o=t.anchor.getNode(),r=$isElementNode(o)?o:o.getParent();if(r&&$isElementNode(r)){let s=r.getPreviousSibling();s&&(r.remove(),s.insertBefore(r));}}});},moveCurrentBlockDown:()=>{e.isEditable()&&e.update(()=>{let t=$getSelection();if($isRangeSelection(t)){let o=t.anchor.getNode(),r=$isElementNode(o)?o:o.getParent();if(r&&$isElementNode(r)){let s=r.getNextSibling();s&&(r.remove(),s.insertAfter(r));}}});}}}getStateQueries(e){return {isDragging:async()=>this.isDraggingState}}setIsDragging(e){this.isDraggingState!==e&&(this.isDraggingState=e,this.stateChangeCallbacks.forEach(t=>t()));}onStateChange(e){return this.stateChangeCallbacks.add(e),()=>this.stateChangeCallbacks.delete(e)}},pu=new Xn;function hu({config:i,extension:n}){let[e]=useLexicalComposerContext(),{config:t,extensions:o}=Oe(),s=o.find(S=>S.name==="draggableBlock")?.config,a=useMemo(()=>t?.theme?.draggable||{},[t?.theme?.draggable]),[l,d]=useState(null),[c,u]=useState(false),[m,g]=useState(()=>e.isEditable()),[x,L]=useState(null),[w,p]=useState(false),h=useRef(null),f=useRef(null),y=useRef(null),b=useRef(null),v=useRef(null),N=useRef(null),E=useRef(null),T=useRef(null),[O,A]=useState(null);useEffect(()=>{n.setIsDragging(c);},[c,n]);let Y=typeof document<"u"&&typeof window<"u",K=e.getRootElement(),J=Y?K?.closest?.(".luthor-editor")||K?.parentElement||document.body:null,B=s?.anchorElem||i.anchorElem||J,$=useMemo(()=>({handle:{cursor:"grab",userSelect:"none"},handleActive:{cursor:"grabbing"},blockDragging:{opacity:.5},dropIndicator:{backgroundColor:"var(--luthor-accent, #3b82f6)",borderRadius:"2px"},addButton:{cursor:"pointer"},buttonStack:{}}),[]),Q=useMemo(()=>({handle:{...$.handle,...a.styles?.handle,...s?.styles?.handle},handleActive:{...$.handleActive,...a.styles?.handleActive,...s?.styles?.handleActive},blockDragging:{...$.blockDragging,...a.styles?.blockDragging,...s?.styles?.blockDragging},dropIndicator:{...$.dropIndicator,...a.styles?.dropIndicator,...s?.styles?.dropIndicator},addButton:{...$.addButton,...a.styles?.addButton,...s?.styles?.addButton},buttonStack:{...$.buttonStack,...a.styles?.buttonStack,...s?.styles?.buttonStack}}),[$,s?.styles,a.styles]),I=useMemo(()=>({handle:s?.theme?.handle||a.handle||"luthor-draggable-handle",handleActive:s?.theme?.handleActive||a.handleActive||"luthor-draggable-handle-active",blockDragging:s?.theme?.blockDragging||a.blockDragging||"luthor-draggable-block-dragging",dropIndicator:s?.theme?.dropIndicator||a.dropIndicator||"luthor-draggable-drop-indicator",addButton:s?.theme?.addButton||a.addButton||"luthor-draggable-add-button",buttonStack:s?.theme?.buttonStack||a.buttonStack||"luthor-draggable-button-stack"}),[s?.theme,a]),U=useCallback(S=>{if(!S||!I.blockDragging)return;(I.blockDragging.includes(" ")?I.blockDragging.split(" ").filter(Boolean):[I.blockDragging]).forEach(M=>S.classList.remove(M)),S.style.opacity="";},[I]),X=useCallback(S=>{if(!S||!I.blockDragging)return;(I.blockDragging.includes(" ")?I.blockDragging.split(" ").filter(Boolean):[I.blockDragging]).forEach(M=>S.classList.add(M)),Object.assign(S.style,Q.blockDragging);},[I,Q.blockDragging]);useEffect(()=>e.registerEditableListener(S=>{g(S),!S&&(u(false),L(null),d(null),p(false),h.current&&U(h.current),h.current=null,f.current=null);}),[e,U]);let se=useCallback(()=>{let S=e.getRootElement();if(S)try{S.focus({preventScroll:!0});}catch{S.focus();}},[e]),j=useCallback(()=>{h.current&&U(h.current),u(false),L(null),se(),setTimeout(()=>{h.current=null,f.current=null;},100);},[U,se]);useEffect(()=>()=>{h.current&&U(h.current),b.current&&clearTimeout(b.current),v.current!==null&&window.cancelAnimationFrame(v.current),E.current!==null&&window.cancelAnimationFrame(E.current);},[U]),useEffect(()=>{y.current=l;},[l]);let ee=useCallback(S=>{N.current=S,v.current===null&&(v.current=window.requestAnimationFrame(()=>{v.current=null;let P=N.current;d(M=>M===P?M:P);}));},[]),Me=useCallback(S=>{T.current=S,E.current===null&&(E.current=window.requestAnimationFrame(()=>{E.current=null;let P=T.current;P!=null&&A(M=>M!=null&&Math.abs(M-P)<.5?M:P);}));},[]),Ce=useCallback(S=>{let P=null;e.update(()=>{let M=$createParagraphNode(),D=$getNearestNodeFromDOMNode(S);if(D)try{D.getTopLevelElementOrThrow().insertAfter(M);}catch{$getRoot().append(M);}else $getRoot().append(M);M.selectStart(),P=M.getKey();}),P&&setTimeout(()=>{let M=e.getElementByKey(P);if(M&&M instanceof HTMLElement&&typeof M.getBoundingClientRect=="function"){ee(M);let D=M.getBoundingClientRect();Me(D.top+window.scrollY+D.height/2);}},0),se();},[e,se,ee,Me]);useEffect(()=>{if(l||h.current)p(true);else {let S=setTimeout(()=>p(false),300);return ()=>clearTimeout(S)}},[l]),useEffect(()=>{let S=M=>{if(!m){ee(null);return}if(c)return;let D=e.getRootElement();if(!D)return;let _=M.target;Me(M.clientY+window.scrollY);let R=_&&_.closest&&(_.closest(".drag-handle-area")||_.closest('[draggable="true"]')||_.closest(".luthor-drag-button")||_.closest(".luthor-draggable-button-stack")),oe=window.getSelection(),V=oe&&oe.rangeCount>0&&!oe.isCollapsed,F=null,H=_;for(;H&&H!==D&&H!==document.body;){if(H.parentElement===D){F=H;break}H=H.parentElement;}b.current&&(clearTimeout(b.current),b.current=null),(F||R)&&!V&&!c?F&&ee(F):b.current=setTimeout(()=>{ee(null),b.current=null;},500);},P=()=>{c||(b.current&&(clearTimeout(b.current),b.current=null),b.current=setTimeout(()=>{ee(null),b.current=null;},300));};return document.addEventListener("mousemove",S),document.addEventListener("mouseleave",P),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseleave",P),b.current&&(clearTimeout(b.current),b.current=null),v.current!==null&&(window.cancelAnimationFrame(v.current),v.current=null),E.current!==null&&(window.cancelAnimationFrame(E.current),E.current=null);}},[e,c,m,ee,Me]);let Ae=useCallback((S,P)=>{if(!e.isEditable()){S.preventDefault();return}S.stopPropagation(),u(true),L(null),h.current=P,X(P);let M=e.read(()=>{let _=$getNearestNodeFromDOMNode(P);return _?_.getKey():null});M&&(f.current=M,S.dataTransfer?.setData("application/x-lexical-drag",JSON.stringify({key:M}))),S.dataTransfer.effectAllowed="move";let D=P.cloneNode(true);D.style.opacity="0.6",D.style.position="absolute",D.style.top="-9999px",D.style.left="-9999px",document.body.appendChild(D),S.dataTransfer.setDragImage(D,0,0),setTimeout(()=>document.body.removeChild(D),0);},[e,X]),De=useCallback((S,P)=>{if(!e.isEditable())return;S.preventDefault(),u(true),h.current=P,X(P);let M=e.read(()=>{let D=$getNearestNodeFromDOMNode(P);return D?D.getKey():null});M&&(f.current=M);},[e,X]),ge=useCallback(S=>{if(!e.isEditable()||!c||!h.current)return;S.preventDefault();let P=S.touches[0];if(!P)return;let M=e.getRootElement();if(!M)return;let D=null,_=document.elementFromPoint(P.clientX,P.clientY);if(_){let R=_;for(;R&&R!==M;){if(R.parentElement===M){D=R;break}R=R.parentElement;}}if(D&&D!==h.current){let R=D.getBoundingClientRect(),oe=P.clientY<R.top+R.height/2;L({top:oe?R.top+window.scrollY:R.bottom+window.scrollY,left:R.left+window.scrollX,width:R.width});}else L(null);},[e,c]),Se=useCallback(S=>{if(!e.isEditable()){j();return}if(!c||!f.current)return;S.preventDefault();let P=S.changedTouches[0];if(!P)return;let M=e.getRootElement();if(!M)return;let D=null,_=document.elementFromPoint(P.clientX,P.clientY);if(_){let R=_;for(;R&&R!==M;){if(R.parentElement===M){D=R;break}R=R.parentElement;}}D&&D!==h.current&&(e.update(()=>{let R=$getNodeByKey(f.current),oe=$getNearestNodeFromDOMNode(D);if(R&&oe){let V=D.getBoundingClientRect(),F=P.clientY>=V.top+V.height/2;R.remove(),F?oe.insertAfter(R):oe.insertBefore(R);}}),setTimeout(()=>{if(f.current)try{let R=e.getElementByKey(f.current);R&&R instanceof HTMLElement&&typeof R.getBoundingClientRect=="function"&&d(R);}catch(R){console.warn("Error finding moved element:",R);}},50)),j();},[e,c,j]);useEffect(()=>{let S=e.getRootElement();if(!S)return;let P=_=>{if(!e.isEditable()){_.preventDefault();return}let R=_.target;if(R.nodeType!==Node.ELEMENT_NODE&&(R=R.parentNode),!R||!(R instanceof HTMLElement)){_.preventDefault();return}if(R.closest('[draggable="true"]'))return;let V=window.getSelection();if(!V||V.isCollapsed||!(s?.enableTextSelectionDrag??i.enableTextSelectionDrag)){_.preventDefault();return}let F=V.anchorNode;F?.nodeType===Node.TEXT_NODE&&(F=F.parentNode);let H=null;for(;F&&F!==S;){if(F.parentNode===S){H=F;break}F=F.parentNode;}if(!H){_.preventDefault();return}V.collapse(V.anchorNode,V.anchorOffset);let te=e.read(()=>$getNearestNodeFromDOMNode(H)?.getKey()??null);if(!te){_.preventDefault();return}_.dataTransfer.clearData(),_.dataTransfer.setData("application/x-lexical-drag",JSON.stringify({key:te})),_.dataTransfer.effectAllowed="move";let q=H.cloneNode(true);q.style.opacity="0.6",q.style.position="absolute",q.style.top="-9999px",q.style.left="-9999px",document.body.appendChild(q),_.dataTransfer.setDragImage(q,0,0),setTimeout(()=>document.body.removeChild(q),0),u(true),L(null),h.current=H,X(H),f.current=te;},M=_=>{if(!e.isEditable())return;let R=_.target;if(R.nodeType!==Node.ELEMENT_NODE&&(R=R.parentNode),!R||!(R instanceof HTMLElement))return;let oe=R;_.preventDefault(),_.dataTransfer.dropEffect="move";let V=null,F=oe;for(;F&&F!==S;){if(F.parentElement===S){V=F;break}F=F.parentElement;}if(V&&V!==h.current){let H=V.getBoundingClientRect(),te=_.clientY<H.top+H.height/2;L({top:te?H.top+window.scrollY:H.bottom+window.scrollY,left:H.left+window.scrollX,width:H.width});}else L(null);},D=_=>{if(!e.isEditable())return;let R=_.target;if(R.nodeType!==Node.ELEMENT_NODE&&(R=R.parentNode),!R||!(R instanceof HTMLElement))return;let oe=R;_.preventDefault(),L(null);let V=_.dataTransfer?.getData("application/x-lexical-drag");if(!V){j();return}let{key:F}=JSON.parse(V);if(!F){j();return}let H=null,te=oe;for(;te&&te!==S;){if(te.parentElement===S){H=te;break}te=te.parentElement;}H&&H!==h.current&&(e.update(()=>{let q=$getNodeByKey(F),Re=$getNearestNodeFromDOMNode(H);if(q&&Re){let tt=H.getBoundingClientRect(),Wt=_.clientY>=tt.top+tt.height/2;q.remove(),Wt?Re.insertAfter(q):Re.insertBefore(q);}}),setTimeout(()=>{if(f.current)try{let q=e.getElementByKey(f.current);q&&q instanceof HTMLElement&&typeof q.getBoundingClientRect=="function"&&d(q);}catch(q){console.warn("Error finding moved element:",q);}se();},50)),j();};return S.addEventListener("dragstart",P),S.addEventListener("dragover",M),S.addEventListener("drop",D),S.addEventListener("dragend",j),()=>{S.removeEventListener("dragstart",P),S.removeEventListener("dragover",M),S.removeEventListener("drop",D),S.removeEventListener("dragend",j);}},[e,j,X,se,s?.enableTextSelectionDrag,i.enableTextSelectionDrag]),useEffect(()=>{if(!c)return;let S=()=>{j();},P=D=>{D.key==="Escape"&&j();},M=()=>{document.hidden&&j();};return window.addEventListener("dragend",S),window.addEventListener("drop",S),window.addEventListener("blur",S),document.addEventListener("keydown",P),document.addEventListener("visibilitychange",M),()=>{window.removeEventListener("dragend",S),window.removeEventListener("drop",S),window.removeEventListener("blur",S),document.removeEventListener("keydown",P),document.removeEventListener("visibilitychange",M);}},[c,j]),useEffect(()=>{let S=e.getRootElement();if(!S)return;let P=null,M=0,D=0,_=V=>{if(!e.isEditable()||V.touches.length!==1||!(s?.enableTextSelectionDrag??i.enableTextSelectionDrag))return;let F=V.touches[0];if(!F)return;let H=V.target;if(H.nodeType!==Node.ELEMENT_NODE&&(H=H.parentNode),!H||!(H instanceof HTMLElement))return;let te=H;te.closest('[draggable="true"]')||(M=F.clientX,D=F.clientY,P=setTimeout(()=>{P=null;let q=null,Re=te;for(;Re&&Re!==S;){if(Re.parentElement===S){q=Re;break}Re=Re.parentElement;}if(!q)return;let tt=window.getSelection();tt&&!tt.isCollapsed&&tt.collapseToStart(),u(true),h.current=q,X(q);let Wt=e.read(()=>$getNearestNodeFromDOMNode(q)?.getKey()??null);Wt&&(f.current=Wt);},500));},R=V=>{if(P&&V.touches.length===1){let F=V.touches[0];if(!F)return;let H=F.clientX-M,te=F.clientY-D;Math.sqrt(H*H+te*te)>10&&(clearTimeout(P),P=null);}},oe=()=>{P&&(clearTimeout(P),P=null);};return S.addEventListener("touchstart",_,{passive:false}),S.addEventListener("touchmove",R,{passive:false}),S.addEventListener("touchend",oe,{passive:false}),document.addEventListener("touchmove",ge,{passive:false}),document.addEventListener("touchend",Se,{passive:false}),()=>{S.removeEventListener("touchstart",_),S.removeEventListener("touchmove",R),S.removeEventListener("touchend",oe),document.removeEventListener("touchmove",ge),document.removeEventListener("touchend",Se);}},[e,X,j,c,ge,Se,s?.enableTextSelectionDrag,i.enableTextSelectionDrag]);let we=l||h.current;if(!m||!Y||!B||!we||typeof we.getBoundingClientRect!="function")return null;let fe=we.getBoundingClientRect();if(!fe.width||!fe.height)return null;let et=K?.closest?.(".luthor-editor")||null,so=et||K;if(!so)return null;let ps=so.getBoundingClientRect(),hs=window.getComputedStyle(so),bs=Number.parseFloat(hs.getPropertyValue("--luthor-drag-gutter-width"))||40,sr=m&&(s?.showAddButton??i.showAddButton)!==false,ys=sr?52:24,Es=ps.left+window.scrollX+Math.max(0,(bs-ys)/2),xs=(s?.buttonStackPosition||i.buttonStackPosition)==="right"?fe.right+window.scrollX+(s?.offsetRight||i.offsetRight||10):et?Es:fe.left+window.scrollX+(s?.offsetLeft||i.offsetLeft||-40),qt=24,ar=qt/2,ao=fe.top+window.scrollY,lr=fe.bottom+window.scrollY,Cs=ao+fe.height/2,Ss=O??Cs,vs=ao+qt/2,Ns=lr-qt/2,Ts=Math.min(Ns,Math.max(vs,Ss)),cr=ao,Ls=Math.max(cr,lr-(ar+qt/2)),ws=Math.min(Ls,Math.max(cr,Ts-ar)),dr=B.getBoundingClientRect(),ur=B===document.body?0:dr.left+window.scrollX,mr=B===document.body?0:dr.top+window.scrollY,Rs=xs-ur,ks=ws-mr;return jsxs(Fragment,{children:[createPortal(jsx("div",{className:`luthor-draggable-button-stack ${I.buttonStack} ${w?"":"fade-out"}`,style:{position:"absolute",left:0,top:0,transform:`translate3d(${Rs}px, ${ks}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",...Q.buttonStack},children:jsxs("div",{style:{display:"flex",flexDirection:"row",alignItems:"center",gap:"4px"},children:[sr&&jsx("button",{type:"button","aria-label":"Add block",title:"Add",className:`luthor-drag-button ${I.addButton}`,onMouseDown:S=>{S.preventDefault(),S.stopPropagation();},onClick:S=>{S.preventDefault(),S.stopPropagation(),!(!we||c)&&Ce(we);},style:Q.addButton,children:"+"}),s?.handleRenderer||i.handleRenderer?(s?.handleRenderer||i.handleRenderer)({rect:fe,isDragging:c,onDragStart:S=>Ae(S,we),className:`luthor-drag-button ${I.handle} ${c?I.handleActive:""}`.trim()}):jsx("div",{className:`luthor-drag-button ${I.handle} ${c?I.handleActive:""}`.trim(),draggable:true,onDragStart:S=>Ae(S,we),onDragEnd:j,onTouchStart:S=>De(S,we),style:c?Q.handleActive:Q.handle,children:"\u22EE\u22EE"})]})}),B),x&&(s?.dropIndicatorRenderer||i.dropIndicatorRenderer?createPortal((s?.dropIndicatorRenderer||i.dropIndicatorRenderer)({...x,className:I.dropIndicator}),B):createPortal(jsx("div",{className:I.dropIndicator,style:{position:"absolute",top:x.top-4-mr,left:x.left-ur,width:x.width,height:"8px",pointerEvents:"none",zIndex:9997,...Q.dropIndicator}}),B))]})}function Wi(i){let n=renderToStaticMarkup(i),e=document.createElement("div");e.innerHTML=n;let t=e.firstElementChild;return e.remove(),t}function wu(i){let n=i.isContainer??false,e=createCommand("insert-custom-node");function t({node:l,payload:d,nodeKey:c,children:u}){let[m]=useLexicalComposerContext(),[g,x]=useState(false);useEffect(()=>m.registerUpdateListener(({editorState:w})=>{w.read(()=>{let p=$getSelection();x($isNodeSelection(p)&&p.getNodes().some(h=>h.__key===c));});}),[m,c]);let L=w=>{m.update(()=>{let p=l.getWritable();p.__payload={...p.__payload,...w};});};return i.render?i.render({node:l,payload:d,children:u,nodeKey:c,isSelected:g,updatePayload:L}):null}class o extends ElementNode{constructor(c={},u,m){super(m);C(this,"__payload");C(this,"__nodeType");this.__payload=c,this.__nodeType=u;}static getType(){return i.nodeType}static clone(c){return new o(c.__payload,c.__nodeType,c.__key)}isSelectable(){return true}canBeEmpty(){return false}canInsertTextBefore(){return false}canInsertTextAfter(){return false}static importJSON(c){let{payload:u}=c;return new o(u,c.type)}static importDOM(){return i.importDOM?i.importDOM():{}}static exportDOM(c,{node:u}){if(i.exportDOM){let g=document.createElement("div");return i.exportDOM(c,{element:g,node:u})}let m=document.createElement("div");return m.setAttribute("data-custom-node-type",i.nodeType),{element:m}}exportJSON(){return {type:this.__nodeType,version:1,payload:this.__payload,children:this.getChildren().map(c=>c.exportJSON()),direction:null,format:"",indent:0}}createDOM(c){if(i.createDOM){let m=i.createDOM(c,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m.setAttribute("data-lexical-key",this.getKey()),m}if(i.jsx){let m=i.jsx({node:this,payload:this.__payload,nodeKey:this.getKey(),isSelected:false,updatePayload:x=>{this.setPayload(x);}}),g=Wi(m);return g.setAttribute("data-custom-node-type",this.__nodeType),g.setAttribute("data-lexical-key",this.getKey()),g}let u=document.createElement("div");return u.setAttribute("data-custom-node-type",this.__nodeType),u.setAttribute("data-lexical-key",this.getKey()),u.style.border="2px solid #ccc",u.style.borderRadius="8px",u.style.padding="16px",u.style.margin="8px 0",u.style.position="relative",u}updateDOM(c,u,m){return i.updateDOM?i.updateDOM(c,u,m):false}getPayload(){return this.__payload}setPayload(c){let u=this.getWritable();u.__payload={...this.__payload,...c};}}class r extends DecoratorNode{constructor(c={},u,m){super(m);C(this,"__payload");C(this,"__nodeType");this.__payload=c,this.__nodeType=u;}static getType(){return i.nodeType}static clone(c){return new r(c.__payload,c.__nodeType,c.__key)}isSelectable(){return true}static importJSON(c){let{payload:u}=c;return new r(u,c.type)}static importDOM(){return i.importDOM?i.importDOM():{}}static exportDOM(c,{node:u}){if(i.exportDOM){let g=document.createElement("span");return i.exportDOM(c,{element:g,node:u})}let m=document.createElement("span");return m.setAttribute("data-custom-node-type",i.nodeType),{element:m}}exportJSON(){return {type:this.__nodeType,version:1,payload:this.__payload}}createDOM(c){let u=document.createElement("span");if(u.setAttribute("data-custom-node-type",this.__nodeType),i.createDOM){let m=i.createDOM(c,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m}return u}updateDOM(c,u,m){return i.updateDOM?i.updateDOM(c,u,m):false}getPayload(){return this.__payload}setPayload(c){let u=this.getWritable();u.__payload={...this.__payload,...c};}decorate(){return jsx(t,{node:this,payload:this.__payload,nodeKey:this.__key})}}function s(l=i.defaultPayload||{}){if(n){let d=new o(l,i.nodeType);if(i.initialChildren)i.initialChildren().forEach(u=>{if(u.type==="paragraph"){let m=$createParagraphNode();u.children&&u.children.forEach(g=>{g.type==="text"&&m.append($createTextNode(g.text||""));}),d.append(m);}});else {let c=$createParagraphNode();c.append($createTextNode("")),d.append(c);}return d}else return new r(l,i.nodeType)}class a extends k{constructor(){super(i.nodeType,["toolbar"]);}register(d){let c=d.registerCommand(e,m=>(d.update(()=>{let g=s(m),x=$getSelection();$isRangeSelection(x)?x.insertNodes([g]):$getRoot().append($createParagraphNode().append(g));}),true),COMMAND_PRIORITY_EDITOR),u=d.registerUpdateListener(({editorState:m})=>{n&&m.read(()=>{let g=$getSelection(),x=$isNodeSelection(g)?g.getNodes():[];d.getEditorState().read(()=>{let L=$getRoot(),w=p=>{if(p.getType()===i.nodeType){let h=x.some(y=>y.__key===p.__key),f=document.querySelector(`[data-lexical-key="${p.__key}"]`);f&&(f.setAttribute("data-selected",h.toString()),f.style.borderColor=h?"#007ACC":"#ccc",f.style.backgroundColor=h?"#f0f8ff":"transparent");}"getChildren"in p&&p.getChildren().forEach(w);};w(L);});});});return ()=>{c(),u();}}getNodes(){return n?[o]:[r]}getCommands(d){return {...{insertCustomNode:u=>d.dispatchCommand(e,u)},...i.commands?i.commands(d):{}}}getStateQueries(d){return {...{isCustomNodeActive:()=>new Promise(u=>{d.getEditorState().read(()=>{let m=$getSelection();u(!!m&&$isNodeSelection(m)&&m.getNodes().some(g=>g.getType()===i.nodeType));});})},...i.stateQueries?i.stateQueries(d):{}}}}return {extension:new a,$createCustomNode:s,jsxToDOM:Wi}}function Xi(i,n,e){return e<=n?n:Math.min(e,Math.max(n,i))}function Mu(i,n,e,t){let o=i.getBoundingClientRect(),r=n.getBoundingClientRect(),s=Xi(e,o.left+1,o.right-1),a=Xi(t,r.top+1,r.bottom-1);return {x:s,y:a}}function Ou(i,n){let e=document,t=window.getSelection();if(!t)return;let o=e.caretPositionFromPoint?.(i,n);if(o){let s=document.createRange();s.setStart(o.offsetNode,o.offset),s.collapse(true),t.removeAllRanges(),t.addRange(s);return}let r=e.caretRangeFromPoint?.(i,n);r&&(r.collapse(true),t.removeAllRanges(),t.addRange(r));}function Ji(i,n,e){let r=Array.from(i.children).filter(l=>l instanceof HTMLElement).reduce((l,d)=>{let c=d.getBoundingClientRect(),u=c.top+c.height/2;if(!l)return d;let m=l.getBoundingClientRect(),g=m.top+m.height/2;return Math.abs(u-e)<Math.abs(g-e)?d:l},null)??i.firstElementChild??i,{x:s,y:a}=Mu(i,r,n,e);i.focus(),Ou(s,a);}function Iu(i){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(()=>i());return}globalThis.setTimeout(i,0);}function Gi(i){return !!i.closest(["button","a","input","textarea","select","[role='button']","[role='checkbox']","iframe","video","audio","embed","object",".luthor-list-item-unchecked",".luthor-list-item-checked","[data-lexical-iframe-embed]","[data-lexical-youtube-embed]","[data-iframe-embed]","[data-youtube-video]",".luthor-media-embed-shell"].join(", "))}var Zi=i=>{let{contentEditable:n,placeholder:e,className:t,nonEditableVisualMode:o=false,onEditIntent:r,classNames:s,styles:a,errorBoundary:l}=i,d=Qt.useContext(ht),c=d?.lexical??null,[u,m]=Qt.useState(!o),g=Qt.useRef(null),x=d?.config,L=typeof x?.placeholder=="string"?x.placeholder:void 0,w=x?.classNames,p=x?.styles,h=e??L??"Start writing...",f=s?.placeholder||w?.placeholder||$e.richText?.placeholder||"luthor-placeholder",y={position:"absolute",pointerEvents:"none",zIndex:1,...p?.placeholder,...a?.placeholder};return Qt.useEffect(()=>{m(!o);},[o]),Qt.useEffect(()=>{c?.setEditable(u);},[u,c]),jsx("div",{className:s?.container||w?.container||t||$e.container||"luthor-editor-container",onMouseDown:b=>{if(b.button!==0)return;let v=b.target;if(!v||Gi(v))return;let N=b.currentTarget,E=b.clientX,T=b.clientY;if(o&&!u){if(r){g.current={clientX:E,clientY:T};return}let A=N.querySelector("[contenteditable]");if(!A)return;b.preventDefault(),c?.setEditable(true),m(true),Iu(()=>{let Y=N.querySelector("[contenteditable='true']")??A;Ji(Y,E,T);});return}let O=N.querySelector("[contenteditable='true']");!O||O.contains(v)||(b.preventDefault(),Ji(O,E,T));},onMouseUp:b=>{if(b.button!==0||!r||!o||u){g.current=null;return}let v=b.target;if(!v||Gi(v)){g.current=null;return}let N=g.current;if(g.current=null,!N)return;let E=Math.abs(b.clientX-N.clientX),T=Math.abs(b.clientY-N.clientY);if(E>4||T>4)return;let O=window.getSelection();O&&!O.isCollapsed||r({clientX:b.clientX,clientY:b.clientY});},style:{position:"relative",cursor:o?"default":"text",...p?.container,...a?.container},children:jsx(RichTextPlugin,{contentEditable:n||jsx("div",{style:{display:"block"},children:jsx(ContentEditable,{className:s?.contentEditable||w?.contentEditable||$e.richText?.contentEditable||"luthor-content-editable",style:{...o?{cursor:"default",caretColor:"transparent",userSelect:"text",WebkitUserSelect:"text"}:{},...p?.contentEditable,...a?.contentEditable}})}),placeholder:typeof h=="string"?jsx("div",{className:f,style:y,children:h}):h||jsx("div",{className:f,style:y,children:"Start writing..."}),ErrorBoundary:l||Du})})},tr=class extends k{constructor(n={}){super("richText",["floating"]),this.config={showInToolbar:false,position:"after",...n};}register(n){return ()=>{}}getPlugins(){return [jsx(Zi,{...this.config},"rich-text")]}},_u=new tr,Au=i=>jsx(Zi,{...i}),Du=({children:i,onError:n})=>{try{return jsx(Fragment,{children:i})}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 ss=8,Yu=9,Gn=class extends k{constructor(n={}){super("tabIndent",["toolbar"]),this.config=n;}register(n){let e=n.registerCommand(KEY_TAB_COMMAND,t=>{let o=$getSelection();if(!$isRangeSelection(o))return false;let r=o.anchor.getNode();if(this.isInCodeBlock(r))return false;t.preventDefault();let s=this.resolveTabContext(r);return s==="paragraph"?(t.shiftKey||n.update(()=>{let a=$getSelection();if($isRangeSelection(a)){if(this.hasReachedTextTabLimit(a))return;a.insertText(" ");}}),true):s==="list"?t.shiftKey?(n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0),true):(this.isListAtMaxDepth(r)||n.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),true):s==="heading"?t.shiftKey?(n.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0),true):(this.isBlockAtMaxIndent(r)||n.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),true):true},COMMAND_PRIORITY_LOW);return ()=>{e();}}isInCodeBlock(n){let e=n;for(;e;){if($isCodeNode(e))return true;e=e.getParent();}return false}isListAtMaxDepth(n){let e=this.config.maxListDepth,t=Number.isFinite(e)?Math.max(1,Math.floor(e)):Yu,o=Math.max(0,t-1),r=this.findNearestListItemNode(n);if(r&&typeof r.getIndent=="function"){let a=r.getIndent();if(typeof a=="number")return a>=o}let s=this.findNearestListNode(n);return s?$getListDepth(s)-1>=o:false}isBlockAtMaxIndent(n){let e=n;for(;e;){if($isRootOrShadowRoot(e))return false;if(typeof e.getIndent=="function"){let t=e.getIndent();if(typeof t=="number")return t>=ss}e=e.getParent();}return false}resolveTabContext(n){let e=n;for(;e;){if($isListNode(e))return "list";if($isHeadingNode(e))return "heading";if($isParagraphNode(e))return "paragraph";if($isRootOrShadowRoot(e))break;e=e.getParent();}return "other"}findNearestListNode(n){let e=n;for(;e;){if($isListNode(e))return e;e=e.getParent();}return null}findNearestListItemNode(n){let e=n;for(;e;){if($isListItemNode(e))return e;e=e.getParent();}return null}hasReachedTextTabLimit(n){let e=n.anchor,t=e.getNode();if(typeof t.getTextContent!="function")return false;let o=t.getTextContent(),r=typeof e.offset=="number"?e.offset:o.length,s=Math.max(0,Math.min(o.length,r)),a=o.lastIndexOf(`
|
|
6
|
+
`,s-1)+1;return (o.slice(a,s).match(/^\t*/)?.[0].length??0)>=ss}},Vu=new Gn;var ds=[{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"]}],ls=ds,eo={":)":"\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 Ju(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Vt(i){return i.trim().toLowerCase().replace(/^:+|:+$/g,"")}function cs(i){return i.toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}function rr(i){let n=i.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=>Vt(a)).filter(Boolean);for(let a of r)e.has(a)||e.set(a,o);let s=cs([o.label,...r,...o.keywords||[]].join(" "));return {item:o,searchable:s}});return {getAll:()=>[...n],resolveShortcode:o=>e.get(Vt(o))??null,search:(o,r)=>{let s=Math.max(0,r?.limit??n.length);if(s===0)return [];let a=cs(o);return a?t.filter(l=>l.searchable.includes(a)).slice(0,s).map(l=>l.item):n.slice(0,s)}}}function us(i){return Array.isArray(i)?i.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0):[]}function Gu(i){let n=us(i.shortcodes);return n.length>0?n.map(e=>Vt(e)):typeof i.shortcodes=="string"?i.shortcodes.split(/[,\s]+/).map(e=>Vt(e)).filter(Boolean):[]}function or(i){if(!i||typeof i!="object")return null;let n=i;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,s=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([Vt(t),...Gu(r)].filter(Boolean)));c.length!==0&&e.push({emoji:d,label:s,shortcodes:c,keywords:us(r.keywords)});}return e.length===0?null:rr(e)}async function Zu(i){return new Function("name","return import(name);")(i)}var to=class extends k{constructor(e={}){super("emoji",["toolbar"]);C(this,"listeners",[]);C(this,"isOpen",false);C(this,"query","");C(this,"position",null);C(this,"suggestions",[]);C(this,"activeMatch",null);C(this,"viewportRafId",null);C(this,"applyingAutoReplace",false);C(this,"catalogAdapter",rr(ls));C(this,"hasExplicitCatalogConfig",false);C(this,"hasExplicitAdapterConfig",false);C(this,"externalCatalogDetectionStarted",false);this.hasExplicitCatalogConfig=Object.prototype.hasOwnProperty.call(e,"catalog"),this.hasExplicitAdapterConfig=Object.prototype.hasOwnProperty.call(e,"catalogAdapter"),this.config={trigger:":",maxSuggestions:8,maxQueryLength:32,autoReplaceSymbols:true,symbolReplacements:eo,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||eo,...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 m=this.replaceSymbolsInText(c);return m===c?false:(l.preventDefault(),e.update(()=>{let g=$getSelection();$isRangeSelection(g)&&g.insertText(m);}),true)},COMMAND_PRIORITY_EDITOR),r=l=>{this.isOpen&&l.key==="Escape"&&(l.preventDefault(),this.closeEmojiSuggestions());},s=l=>{l.target?.closest(".luthor-emoji-menu")||this.isOpen&&this.closeEmojiSuggestions();},a=()=>{!this.isOpen||!this.activeMatch||this.viewportRafId===null&&(this.viewportRafId=window.requestAnimationFrame(()=>{this.viewportRafId=null;let l=this.getCaretPosition();if(!l){this.closeEmojiSuggestions();return}this.position=l,this.notifyListeners();}));};return document.addEventListener("keydown",r),document.addEventListener("pointerdown",s),window.addEventListener("scroll",a,true),window.addEventListener("resize",a),()=>{t(),o(),document.removeEventListener("keydown",r),document.removeEventListener("pointerdown",s),window.removeEventListener("scroll",a,true),window.removeEventListener("resize",a),this.viewportRafId!==null&&(cancelAnimationFrame(this.viewportRafId),this.viewportRafId=null),this.activeMatch=null,this.isOpen=false,this.query="",this.position=null,this.suggestions=[],this.notifyListeners();}}getCommands(e){return {insertEmoji: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:rr(e.catalog||ls)}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=or(e);if(t){this.catalogAdapter=t,this.refreshSuggestionsIfOpen();return}try{let r=await Zu("@emoji-mart/data"),s=or(r.default)||or(r.data);s&&(this.catalogAdapter=s,this.refreshSuggestionsIfOpen());}catch{}}refreshSuggestionsIfOpen(){this.isOpen&&(this.suggestions=this.getSuggestions(this.query),this.isOpen=this.suggestions.length>0,this.notifyListeners());}updateFromSelection(e){let 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 s=o.anchor.offset,a=r.getTextContent(),l=a.slice(0,s);if(this.config.autoReplaceSymbols&&!this.applyingAutoReplace){let w=this.detectSymbolReplacement(a,l,s);w&&(t={nodeKey:r.getKey(),startOffset:w.startOffset,endOffset:w.endOffset,emoji:w.emoji});}let d=this.config.trigger||":",c=l.lastIndexOf(d);if(c<0){this.closeIfNeeded();return}let u=l.slice(0,c);if(!(u.length===0||/\s/.test(u[u.length-1]||""))){this.closeIfNeeded();return}let g=l.slice(c+d.length);if(/\s/.test(g)||g.length>(this.config.maxQueryLength??32)){this.closeIfNeeded();return}let x=this.getSuggestions(g),L=this.getCaretPosition();this.query=g,this.position=L,this.suggestions=x,this.isOpen=x.length>0,this.activeMatch={nodeKey:r.getKey(),startOffset:c,endOffset:s},this.notifyListeners();}),t!==null){let o=t;this.applyingAutoReplace=true,e.update(()=>{let r=$getNodeByKey(o.nodeKey);if(!$isTextNode(r))return;let s=Math.max(0,o.endOffset-o.startOffset);r.spliceText(o.startOffset,s,o.emoji,true);let a=o.startOffset+o.emoji.length;r.select(a,a);}),this.applyingAutoReplace=false;}}isSelectionInsideCodeBlock(e){if(!$isRangeSelection(e))return false;let 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||eo).sort((s,a)=>a[0].length-s[0].length);for(let[s,a]of r){if(!t.endsWith(s))continue;let l=o-s.length,d=l>0&&e[l-1]||"",c=o<e.length&&e[o]||"",u=l===0||/\s|[([{>"'`]/.test(d),m=o===e.length||/\s|[.,!?;:)\]}"'`]/.test(c);if(u&&m)return {startOffset:l,endOffset:o,emoji:a}}return null}replaceSymbolsInText(e){let t=Object.entries(this.config.symbolReplacements||eo),o=e;for(let[r,s]of t){let a=Ju(r),l=new RegExp(`(^|\\s)${a}(?=$|\\s|[.,!?;:])`,"g");o=o.replace(l,`$1${s}`);}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 s=Math.max(0,o.endOffset-o.startOffset);r.spliceText(o.startOffset,s,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(),s=t.getClientRects()[0]||o;return {x:s.left+(this.config.offset?.x??0),y:s.bottom+(this.config.offset?.y??8)}}getState(){return {isOpen:this.isOpen,query:this.query,position:this.position,suggestions:this.suggestions}}notifyListeners(){let e=this.getState();this.listeners.forEach(t=>t(e));}},em=new to;var no=class extends k{constructor(){super("floatingToolbar",["floating"]);C(this,"isVisible",false);C(this,"selectionRect",null);this.config={render:()=>null,debounceMs:100,offset:{x:0,y:8},positionStrategy:"below",theme:{container:"luthor-floating-toolbar",button:"luthor-floating-toolbar-button",buttonActive:"luthor-floating-toolbar-button-active"}};}register(e){return ()=>{}}getPlugins(){return [jsx(lm,{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;}},am=new no;function lm({extension:i,config:n}){let[e]=useLexicalComposerContext(),{config:t}=Oe(),[o,r]=useState(false),[s,a]=useState(null),[l,d]=useState(null),c=useRef(null),u=f=>(f.querySelector('[data-luthor-selection-anchor="true"]')??f).getBoundingClientRect(),m=(f,y)=>{let b;return (...v)=>{clearTimeout(b),b=setTimeout(()=>f(()=>v),y);}},g=useCallback((f,y)=>{if(typeof window>"u"||y===document.body)return f;let b=window.pageXOffset||document.documentElement.scrollLeft||0,v=window.pageYOffset||document.documentElement.scrollTop||0,N=y.getBoundingClientRect(),E=N.left+b,T=N.top+v,O=n.toolbarDimensions?.width||300,A=n.toolbarDimensions?.height||40,Y=f.x-E,K=f.y-T,J=Math.max(10,Math.min(Y,Math.max(10,N.width-O-10))),B=Math.max(10,Math.min(K,Math.max(10,N.height-A-10)));return {...f,x:J,y:B,top:f.top-T,left:f.left-E,bottom:f.bottom-T,right:f.right-E,positionFromRight:false}},[n.toolbarDimensions?.height,n.toolbarDimensions?.width]),x=useCallback(f=>{let y=n.offset||{y:8},b=n.positionStrategy||"below",v=window.pageXOffset||document.documentElement.scrollLeft||0,N=window.pageYOffset||document.documentElement.scrollTop||0,E=window.innerWidth,T=window.innerHeight,O=f.bottom+N+y.y;b==="above"?O=f.top+N-y.y:b==="auto"&&(O=T-f.bottom>60?f.bottom+N+y.y:f.top+N-y.y);let A=n.getActiveStates?.(),Y=!!A?.isIframeEmbedSelected||!!A?.isYouTubeEmbedSelected,K=n.toolbarDimensions?.width||(Y?132:300),J=n.toolbarDimensions?.height||40,B=10,$=f.left+f.width/2,Q=$+v,I,U,X=$-B,se=E-$-B,j=K/2,ee=$-j,Me=$+j,Ce=ee<B,Ae=Me>E-B;return !Ce&&!Ae?(I=Q-j,U=false):Ce||X<j?(I=v+B,U=false):Ae||se<j?(I=v+E-K-B,U=true):(I=Q-j,U=false),O-J<N?O=f.bottom+N+y.y:O+J>N+T&&(O=f.top+N-y.y-J),{x:I,y:O,width:f.width,height:f.height,top:f.top+N,left:f.left+v,bottom:f.bottom+N,right:f.right+v,positionFromRight:U}},[n]);useEffect(()=>{i.setVisible(o);},[o,i]),useEffect(()=>{let f=()=>{e.getEditorState().read(()=>{let E=$getSelection(),T=null,O=null;if($isRangeSelection(E)&&!E.isCollapsed()){let A=window.getSelection();A&&A.rangeCount>0&&(T=A.getRangeAt(0).getBoundingClientRect(),O=E);}else if($isNodeSelection(E)){let A=E.getNodes();if(A.length>0){let Y=A[0];if(Y){let K=Y.getKey(),J=e.getElementByKey(K);J&&(T=u(J));}}}if(T&&T.width>0&&T.height>0){let A=x(T);a(A),d(O),r(true),i.setSelectionRect(A);}else a(null),d(null),r(false),i.setSelectionRect(null);});},y=m(f,n.debounceMs||100),b=e.registerUpdateListener(()=>{y();}),v=()=>{y();},N=()=>{c.current===null&&(c.current=window.requestAnimationFrame(()=>{c.current=null,f();}));};return document.addEventListener("selectionchange",v),window.addEventListener("scroll",N,true),window.addEventListener("resize",N),()=>{b(),document.removeEventListener("selectionchange",v),window.removeEventListener("scroll",N,true),window.removeEventListener("resize",N),c.current!==null&&(cancelAnimationFrame(c.current),c.current=null);}},[e,n.debounceMs,x,i]);let L=()=>{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 w=e.getRootElement()?.closest(".luthor-editor-wrapper"),p=n.anchorElem||w||document.body,h=s&&p?g(s,p):s;return createPortal(n.render({isVisible:o,selectionRect:h,selection:l,editor:e,commands:n.getCommands?.()||{},activeStates:n.getActiveStates?.()||{},hide:L,theme:t?.theme?.floatingToolbar||n.theme||{}}),p)}var oo=class extends k{constructor(){super("commandPalette",["toolbar"]);C(this,"isOpen",false);C(this,"commands",new Map);C(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())}},dm=new oo;var fm=new Set(["paragraph","heading"]),ro=class extends k{constructor(e={}){super("slashCommand",["toolbar"]);C(this,"commands",new Map);C(this,"listeners",[]);C(this,"isOpen",false);C(this,"query","");C(this,"position",null);C(this,"activeMatch",null);C(this,"viewportRafId",null);this.config={trigger:"/",offset:{x:0,y:8},...e},this.setSlashCommands(this.config.items??[]);}register(e){let 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();},s=()=>{!this.isOpen||!this.activeMatch||this.viewportRafId===null&&(this.viewportRafId=window.requestAnimationFrame(()=>{this.viewportRafId=null;let a=this.getCaretPosition();if(!a){this.closeSlashMenu();return}this.position=a,this.notifyListeners();}));};return document.addEventListener("pointerdown",r),window.addEventListener("scroll",s,true),window.addEventListener("resize",s),()=>{t(),document.removeEventListener("keydown",o),document.removeEventListener("pointerdown",r),window.removeEventListener("scroll",s,true),window.removeEventListener("resize",s),this.viewportRafId!==null&&(cancelAnimationFrame(this.viewportRafId),this.viewportRafId=null),this.activeMatch=null,this.isOpen=false,this.query="",this.position=null,this.notifyListeners();}}getCommands(e){return {registerSlashCommand: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 s=$getNodeByKey(r.nodeKey);if(!$isTextNode(s))return;let a=Math.max(0,Math.min(r.endOffset,s.getTextContentSize()));s.select(a,a);let l=Math.max(0,r.endOffset-r.startOffset);l>0&&s.spliceText(r.startOffset,l,"",true);});}return this.closeSlashMenu(),o.action(),true}updateMatchFromSelection(e){e.getEditorState().read(()=>{let t=$getSelection();if(!$isRangeSelection(t)||!t.isCollapsed()){this.closeIfNeeded();return}let o=t.anchor.getNode();if(!$isTextNode(o)){this.closeIfNeeded();return}let r=hm(o);if(!fm.has(r)){this.closeIfNeeded();return}let s=t.anchor.offset,l=o.getTextContent().slice(0,s),d=this.config.trigger||"/",c=l.lastIndexOf(d);if(c<0){this.closeIfNeeded();return}let u=l.slice(0,c);if(!bm(u)){this.closeIfNeeded();return}let m=l.slice(c+d.length);if(/\s/.test(m)){this.closeIfNeeded();return}let g=this.getCaretPosition();this.isOpen=true,this.query=m,this.position=g,this.activeMatch={nodeKey:o.getKey(),startOffset:c,endOffset:s,query:m},this.notifyListeners();});}closeIfNeeded(){!this.isOpen&&!this.activeMatch||this.closeSlashMenu();}getCaretPosition(){if(typeof window>"u")return null;let e=window.getSelection();if(!e||e.rangeCount===0)return null;let t=e.getRangeAt(0).cloneRange();t.collapse(true);let o=t.getBoundingClientRect(),s=t.getClientRects()[0]||o,a=this.config.offset?.x??0,l=this.config.offset?.y??8;return {x:s.left+a,y:s.bottom+l}}getState(){return {isOpen:this.isOpen,query:this.query,position:this.position,commands:this.getAllCommands()}}notifyListeners(){let e=this.getState();this.listeners.forEach(t=>t(e));}},pm=new ro;function hm(i){try{return i.getTopLevelElementOrThrow?.()?.getType?.()??""}catch{return ""}}function bm(i){return i.trim().length===0}var io=class extends k{constructor(){super("enterKeyBehavior",["floating"]),this.config={...this.config||{},showInToolbar:false,initPriority:100};}register(n){let e,t=r=>{if(r.key!=="Enter")return;let s=false;n.update(()=>{let a=$getSelection();if(!$isRangeSelection(a))return;let l=a.anchor.getNode();if(r.shiftKey){let L=$findCellNode(l);if($isTableCellNode(L)){let h=$getTableNodeFromLexicalNodeOrThrow(L),f=$createParagraphNode();h.insertAfter(f),f.selectStart(),s=true;return}let w=this.findQuoteNode(l);if(w){let h=$createParagraphNode();w.insertAfter(h),h.selectStart(),s=true;return}let p=this.findCodeNode(l);if(p){let h=$createParagraphNode();p.insertAfter(h),h.selectStart(),s=true;return}return}let d=this.findQuoteNode(l);if(!d||!a.isCollapsed())return;let c=this.findDirectQuoteChild(l,d)||d.getLastChild();if(!c){let L=$createParagraphNode();d.append(L),L.selectStart(),s=true;return}let u=this.isEmptyQuoteLine(c),m=c.getPreviousSibling(),g=this.isEmptyQuoteLine(m);if(u&&g){let L=c,w=m;L.remove(),w?.remove();let p=$createParagraphNode();d.insertAfter(p),p.selectStart(),s=true;return}let x=$createParagraphNode();c.insertAfter(x),x.selectStart(),s=true;}),s&&(r.preventDefault(),r.stopPropagation());},o=n.registerRootListener((r,s)=>{e?.(),e=void 0,s&&s.removeEventListener("keydown",t,true),r&&(r.addEventListener("keydown",t,true),e=()=>{r.removeEventListener("keydown",t,true);});});return ()=>{e?.(),o();}}getCommands(n){return {insertHardBreak:()=>{n.focus(),n.dispatchCommand(INSERT_LINE_BREAK_COMMAND,false);}}}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}},Lm=new io;export{k as BaseExtension,Qs as BaseProvider,Qn as BlockFormatExtension,on as BoldExtension,Bn as CodeExtension,Un as CodeFormatExtension,jn as CodeIntelligenceExtension,oo as CommandPaletteExtension,xn as ContextMenuExtension,Xn as DraggableBlockExtension,to as EmojiExtension,io as EnterKeyBehaviorExtension,Vs as ExtensionCategory,no as FloatingToolbarExtension,dn as FontFamilyExtension,un as FontSizeExtension,Yn as HistoryExtension,cn as HorizontalRuleExtension,en as IframeEmbedExtension,Gt as ImageExtension,rn as ItalicExtension,ds as LIGHTWEIGHT_EMOJI_CATALOG,gr as LUTHOR_EDITOR_THEME_TOKENS,mn as LineHeightExtension,ln as LinkExtension,An as ListExtension,Au as RichText,ro as SlashCommandExtension,an as StrikethroughExtension,hn as SubscriptExtension,bn as SuperscriptExtension,Gn as TabIndentExtension,Tn as TableExtension,fn as TextColorExtension,re as TextFormatExtension,pn as TextHighlightExtension,sn as UnderlineExtension,nn as YouTubeEmbedExtension,It as appendMetadataEnvelopes,ru as blockFormatExtension,Al as boldExtension,Xs as clearLexicalSelection,wd as codeExtension,Vd as codeFormatExtension,Kd as codeIntelligenceExtension,dm as commandPaletteExtension,_o as contextMenuExtension,wu as createCustomNodeExtension,hr as createEditorSystem,Is as createEditorThemeStyleVars,qs as createExtension,$e as defaultLuthorTheme,pu as draggableBlockExtension,em as emojiExtension,Lm as enterKeyBehaviorExtension,_t as extractMetadataEnvelopes,am as floatingToolbarExtension,gc as fontFamilyExtension,yc as fontSizeExtension,uu as historyExtension,ac as horizontalRuleExtension,Il as htmlToJSON,Na as iframeEmbedExtension,ua as imageExtension,As as isLuthorTheme,Dl as italicExtension,_l as jsonToHTML,dl as jsonToMarkdown,Tc as lineHeightExtension,ql as linkExtension,bd as listExtension,cl as markdownToJSON,_s as mergeThemes,Ot as prepareDocumentForBridge,At as rehydrateDocumentFromEnvelopes,Js as resolveLinkNodeKeyFromAnchor,_u as richTextExtension,pm as slashCommandExtension,Bl as strikethroughExtension,Oc as subscriptExtension,Ic as superscriptExtension,Vu as tabIndentExtension,nd as tableExtension,Rc as textColorExtension,Mc as textHighlightExtension,Fl as underlineExtension,Oe as useBaseEditor,Aa as youTubeEmbedExtension};
|