@lyfie/luthor 1.1.0 → 2.0.1
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 +27 -155
- package/dist/index.css +1 -0
- package/dist/index.d.ts +33 -2288
- package/dist/index.js +1 -3
- package/package.json +8 -5
package/dist/index.js
CHANGED
|
@@ -1,3 +1 @@
|
|
|
1
|
-
import {createContext,useState,useEffect,useRef,useCallback,useContext,useMemo}from'react';import {LexicalComposer}from'@lexical/react/LexicalComposer';import {useLexicalComposerContext}from'@lexical/react/LexicalComposerContext';import {createCommand,PASTE_COMMAND,$getSelection,$isRangeSelection,$createTextNode,INDENT_CONTENT_COMMAND,OUTDENT_CONTENT_COMMAND,$createParagraphNode,INSERT_PARAGRAPH_COMMAND,COMMAND_PRIORITY_NORMAL,KEY_ENTER_COMMAND,COMMAND_PRIORITY_EDITOR,ParagraphNode,$isParagraphNode,CAN_UNDO_COMMAND,COMMAND_PRIORITY_LOW,CAN_REDO_COMMAND,CLEAR_HISTORY_COMMAND,REDO_COMMAND,UNDO_COMMAND,$isElementNode,$getNodeByKey,$getRoot,KEY_DELETE_COMMAND,$isNodeSelection,KEY_BACKSPACE_COMMAND,FORMAT_TEXT_COMMAND,INSERT_LINE_BREAK_COMMAND,$getNearestNodeFromDOMNode,DecoratorNode,$createNodeSelection,$setSelection,ElementNode}from'lexical';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {$createLinkNode,TOGGLE_LINK_COMMAND,LinkNode,AutoLinkNode,$isLinkNode}from'@lexical/link';import {LinkPlugin}from'@lexical/react/LexicalLinkPlugin';import {AutoLinkPlugin}from'@lexical/react/LexicalAutoLinkPlugin';import {HorizontalRuleNode,INSERT_HORIZONTAL_RULE_COMMAND,$isHorizontalRuleNode,$createHorizontalRuleNode}from'@lexical/react/LexicalHorizontalRuleNode';import {HorizontalRulePlugin}from'@lexical/react/LexicalHorizontalRulePlugin';import {TablePlugin}from'@lexical/react/LexicalTablePlugin';import {TRANSFORMERS,$convertToMarkdownString,$convertFromMarkdownString}from'@lexical/markdown';import {TableNode,TableRowNode,TableCellNode,$isTableSelection,$isTableNode,$deleteTableColumnAtSelection,$deleteTableRowAtSelection,$insertTableColumnAtSelection,$insertTableRowAtSelection,$createTableNodeWithDimensions,$isTableCellNode,$isTableRowNode}from'@lexical/table';import {createPortal}from'react-dom';import {ListNode,ListItemNode,INSERT_ORDERED_LIST_COMMAND,INSERT_UNORDERED_LIST_COMMAND,$isListItemNode,$isListNode}from'@lexical/list';import {$setBlocksType}from'@lexical/selection';import {ListPlugin}from'@lexical/react/LexicalListPlugin';import {CodeNode,$createCodeNode,$isCodeNode}from'@lexical/code';import {$isHeadingNode,$isQuoteNode,HeadingNode,QuoteNode,$createQuoteNode,$createHeadingNode}from'@lexical/rich-text';import {HistoryPlugin}from'@lexical/react/LexicalHistoryPlugin';import {$generateNodesFromDOM,$generateHtmlFromNodes}from'@lexical/html';import {renderToStaticMarkup}from'react-dom/server';import {RichTextPlugin}from'@lexical/react/LexicalRichTextPlugin';import {ContentEditable}from'@lexical/react/LexicalContentEditable';var So=Object.defineProperty;var No=(a,t,e)=>t in a?So(a,t,{enumerable:true,configurable:true,writable:true,value:e}):a[t]=e;var y=(a,t,e)=>No(a,typeof t!="symbol"?t+"":t,e);var se={text:{bold:"luthor-text-bold",italic:"luthor-text-italic",underline:"luthor-text-underline",strikethrough:"luthor-text-strikethrough",code:"luthor-text-code"},list:{ul:"luthor-list-ul",ol:"luthor-list-ol",listitem:"luthor-list-li",nested:{list:"luthor-list-nested",listitem:"luthor-list-nested-item"}},quote:"luthor-quote",heading:{h1:"luthor-heading-h1",h2:"luthor-heading-h2",h3:"luthor-heading-h3",h4:"luthor-heading-h4",h5:"luthor-heading-h5",h6:"luthor-heading-h6"},paragraph:"luthor-paragraph",link:"luthor-link",image:"lexical-image",hr:"luthor-hr",table:"luthor-table",tableRow:"luthor-table-row",tableCell:"luthor-table-cell",tableCellHeader:"luthor-table-cell-header",code:"luthor-code-block",codeHighlight:{atrule:"luthor-code-atrule",attr:"luthor-code-attr",boolean:"luthor-code-boolean",builtin:"luthor-code-builtin",cdata:"luthor-code-cdata",char:"luthor-code-char",class:"luthor-code-class","class-name":"luthor-code-class-name",comment:"luthor-code-comment",constant:"luthor-code-constant",deleted:"luthor-code-deleted",doctype:"luthor-code-doctype",entity:"luthor-code-entity",function:"luthor-code-function",important:"luthor-code-important",inserted:"luthor-code-inserted",keyword:"luthor-code-keyword",namespace:"luthor-code-namespace",number:"luthor-code-number",operator:"luthor-code-operator",prolog:"luthor-code-prolog",property:"luthor-code-property",punctuation:"luthor-code-punctuation",regex:"luthor-code-regex",selector:"luthor-code-selector",string:"luthor-code-string",symbol:"luthor-code-symbol",tag:"luthor-code-tag",url:"luthor-code-url",variable:"luthor-code-variable"},toolbar:{button:"luthor-toolbar-button",buttonActive:"luthor-toolbar-button-active",buttonDisabled:"luthor-toolbar-button-disabled",group:"luthor-toolbar-group"},container:"luthor-editor-container",wrapper:"luthor-editor-wrapper",editor:"luthor-editor",contentEditable:"luthor-content-editable",contextMenu:{container:"luthor-context-menu",item:"luthor-context-menu-item",itemDisabled:"luthor-context-menu-item-disabled"},draggable:{handle:"luthor-draggable-handle",handleActive:"luthor-draggable-handle-active",handleHover:"luthor-draggable-handle-hover",handleDragging:"luthor-draggable-handle-dragging",blockDragging:"luthor-draggable-block-dragging opacity-50 transition-opacity duration-200",dropIndicator:"luthor-draggable-drop-indicator",upButton:"luthor-draggable-up-button",downButton:"luthor-draggable-down-button",blockIsDragging:"luthor-draggable-block-is-dragging",buttonStack:"luthor-draggable-button-stack"},floatingToolbar:{container:"luthor-floating-toolbar",button:"luthor-floating-toolbar-button",buttonActive:"luthor-floating-toolbar-button-active"},htmlEmbed:{container:"luthor-html-embed-container",preview:"luthor-html-embed-preview",editor:"luthor-html-embed-editor",textarea:"luthor-html-embed-textarea",toggle:"luthor-html-embed-toggle",content:"luthor-html-embed-content"},richText:{contentEditable:"luthor-content-editable",placeholder:"luthor-placeholder"}};function To(a,t){return {...a,...t,text:{...a.text,...t.text},list:{...a.list,...t.list,nested:{...a.list?.nested,...t.list?.nested}},heading:{...a.heading,...t.heading},codeHighlight:{...a.codeHighlight,...t.codeHighlight},toolbar:{...a.toolbar,...t.toolbar},draggable:{...a.draggable,...t.draggable,styles:{...a.draggable?.styles,...t.draggable?.styles}},floatingToolbar:{...a.floatingToolbar,...t.floatingToolbar,styles:{...a.floatingToolbar?.styles,...t.floatingToolbar?.styles}},htmlEmbed:{...a.htmlEmbed,...t.htmlEmbed,styles:{...a.htmlEmbed?.styles,...t.htmlEmbed?.styles}},richText:{...a.richText,...t.richText},styles:{toolbar:{...a.styles?.toolbar,...t.styles?.toolbar},draggable:{...a.styles?.draggable,...t.styles?.draggable},floatingToolbar:{...a.styles?.floatingToolbar,...t.styles?.floatingToolbar},htmlEmbed:{...a.styles?.htmlEmbed,...t.styles?.htmlEmbed},...t.styles}}}function vo(a){return a&&typeof a=="object"}var it=createContext(null);function Pt(){function a(){let o=useContext(it);if(!o)throw new Error("useEditor must be used within Provider");return o}function t({children:o,config:n={},extensions:r}){let[i]=useLexicalComposerContext(),s={formatText:(g,b)=>i?.dispatchCommand(FORMAT_TEXT_COMMAND,g)},l=useMemo(()=>r.reduce((g,b)=>({...g,...b.getCommands(i)}),{}),[r,i]),c={...s,...l},d=useMemo(()=>r.flatMap(g=>g.getPlugins?.()||[]),[r]),f=useMemo(()=>r.filter(g=>(g.config?.position||"before")==="before").flatMap(g=>g.getPlugins?.()||[]),[r]),m=useMemo(()=>r.filter(g=>(g.config?.position||"before")==="after").flatMap(g=>g.getPlugins?.()||[]),[r]);useEffect(()=>{if(!i)return;let b=[...r].sort((C,E)=>{let x=C.config?.initPriority??0;return (E.config?.initPriority??0)-x}).map(C=>C.register(i));return ()=>b.forEach(C=>C&&C())},[i,r]);let h=useMemo(()=>r.reduce((g,b)=>({...g,...b.getStateQueries?b.getStateQueries(i):{}}),{}),[r,i]),[N,L]=useState(()=>{let g={};return Object.keys(h).forEach(b=>g[b]=false),g});useEffect(()=>{if(!i)return;let g=async()=>{let E=Object.entries(h).map(([A,O])=>O().then(B=>[A,B])),x=await Promise.all(E),I=Object.fromEntries(x);L(I);};g();let b=i.registerUpdateListener(()=>{g();}),C=r.map(E=>"onStateChange"in E&&typeof E.onStateChange=="function"?E.onStateChange(g):()=>{}).filter(Boolean);return ()=>{b(),C.forEach(E=>E());}},[i,h,r]);let T={editor:i,config:n,extensions:r,commands:c,activeStates:N,stateQueries:h,listeners:{registerUpdate:g=>i?.registerUpdateListener(g)||(()=>{}),registerPaste:g=>i?.registerCommand(PASTE_COMMAND,g,4)||(()=>{})},export:{toHTML:async()=>"",toMarkdown:async()=>"",toJSON:()=>i?.getEditorState().toJSON()},import:{fromHTML:async()=>{},fromMarkdown:async()=>{},fromJSON:g=>i?.setEditorState(i.parseEditorState(g))},lexical:i,extensionsAPI:{add:g=>{},remove:g=>{},reorder:g=>{}},plugins:d,hasExtension:g=>r.some(b=>b.name===g)};return jsxs(it.Provider,{value:T,children:[f,o,m]})}function e(o){let n=useMemo(()=>o.extensions.flatMap(s=>s.getNodes?.()||[]),[o.extensions]),r=useMemo(()=>({namespace:"modern-editor",theme:o.config?.theme||se,onError:i=>{console.error("Lexical error:",i);},nodes:n}),[o.config?.theme,n]);return jsx(LexicalComposer,{initialConfig:r,children:jsx(t,{...o})})}return {Provider:e,useEditor:a}}var ko=Pt(),Do=ko.Provider,Z=()=>{let a=useContext(it);if(!a)throw new Error("useBaseEditor must be used within Provider");return a};var Q=(n=>(n.Toolbar="toolbar",n.Sidebar="sidebar",n.ContextMenu="contextmenu",n.Floating="floating",n))(Q||{});var M=class{constructor(t,e=["toolbar"]){y(this,"name");y(this,"category",["toolbar"]);y(this,"config",{});y(this,"supportedFormats",[]);y(this,"nodeOverrides",{});this.name=t,this.category=e;}configure(t){return this.config={...this.config,...t},this}getNodes(){return []}overrideUI(t){return this}overrideNodeRender(t){return this.nodeOverrides={...this.nodeOverrides,...t},this}getPlugins(){return []}getCommands(t){return {}}getStateQueries(t){return {}}getToolbarItems(t){return []}};function Io(a){return new class extends M{constructor(){super(a.name,a.category||["toolbar"]);y(this,"_plugins",[]);y(this,"_nodes",[]);y(this,"_initialize");a.config&&(this.config={...this.config,...a.config}),this._initialize=a.initialize,a.supportedFormats&&(this.supportedFormats=a.supportedFormats),a.nodes&&(this._nodes=a.nodes),a.plugins&&(this._plugins=a.plugins);}register(e){let o=this._initialize?.(e);return ()=>{typeof o=="function"&&o();}}getNodes(){return this._nodes}getPlugins(){return this._plugins}getCommands(e){return a.commands?a.commands(e):{}}getStateQueries(e){return a.stateQueries?a.stateQueries(e):{}}}}var V=class extends M{constructor(t){super(t,["toolbar"]),this.supportedFormats=[t];}register(t){let e=t.registerCommand(INSERT_PARAGRAPH_COMMAND,()=>(t.getEditorState().read(()=>{let n=$getSelection();$isRangeSelection(n)&&n.hasFormat(this.name)&&t.dispatchCommand(FORMAT_TEXT_COMMAND,this.name);}),false),1),o=t.registerCommand(INSERT_LINE_BREAK_COMMAND,()=>false,1);return ()=>{e(),o();}}getCommands(t){return {[`toggle${this.name.charAt(0).toUpperCase()+this.name.slice(1)}`]:()=>t.dispatchCommand(FORMAT_TEXT_COMMAND,this.name)}}getStateQueries(t){return {[this.name]:()=>new Promise(e=>{t.getEditorState().read(()=>{let o=$getSelection();$isRangeSelection(o)?e(o.hasFormat(this.name)):e(false);});})}}};var Ne=class extends V{constructor(){super("bold");}},Ao=new Ne;var Te=class extends V{constructor(){super("italic");}},Fo=new Te;var at={format:["underline"],tag:"++",type:"text-format"},ve=class extends V{constructor(){super("underline");}getMarkdownTransformers(){return [at]}},$o=new ve;var Re=class extends V{constructor(){super("strikethrough");}},Qo=new Re;var Le=class extends M{constructor(){super("link",["toolbar"]),this.config={autoLinkText:false,linkSelectedTextOnPaste:true,validateUrl:t=>{try{return new URL(t),!0}catch{return false}}};}register(t){let e=t.registerCommand(PASTE_COMMAND,o=>{let n=o.clipboardData;if(!n)return false;let r=n.getData("text/plain");return r&&this.config.validateUrl(r)&&this.config.autoLinkUrls?(o.preventDefault(),t.update(()=>{let i=$getSelection();if($isRangeSelection(i))if(i.isCollapsed()){let s=$createLinkNode(r);s.append($createTextNode(r)),i.insertNodes([s]);}else if(this.config.linkSelectedTextOnPaste)t.dispatchCommand(TOGGLE_LINK_COMMAND,r);else {i.insertText(r);let s=$getSelection();s&&$isRangeSelection(s)&&s.getNodes()[0]&&t.dispatchCommand(TOGGLE_LINK_COMMAND,r);}}),true):false},3);return ()=>{e();}}getNodes(){let t=[LinkNode];return this.config.autoLinkText&&t.push(AutoLinkNode),t}getPlugins(){let t=[];if(t.push(jsx(LinkPlugin,{validateUrl:this.config.validateUrl},"link-plugin")),this.config.autoLinkText){let e=o=>{let r=/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g.exec(o);return r&&this.config.validateUrl(r[0])?{text:r[0],url:r[0],index:r.index,length:r[0].length}:null};t.push(jsx(AutoLinkPlugin,{matchers:[e]},"auto-link"));}return t}getCommands(t){return {insertLink:(e,o)=>{if(e)o&&t.update(()=>{let n=$getSelection();n&&n.insertText(o);}),t.dispatchCommand(TOGGLE_LINK_COMMAND,e);else {let n=prompt("Enter URL:");n&&t.dispatchCommand(TOGGLE_LINK_COMMAND,n);}},removeLink:()=>{t.dispatchCommand(TOGGLE_LINK_COMMAND,null);}}}getStateQueries(t){return {isLink:()=>new Promise(e=>{t.getEditorState().read(()=>{let o=$getSelection();if(o&&$isRangeSelection(o)){let r=o.getNodes()[0];if(r){let i=r.getParent();e($isLinkNode(i)||$isLinkNode(r));}else e(false);}else e(false);});}),isTextSelected:()=>new Promise(e=>{t.getEditorState().read(()=>{let o=$getSelection();o&&$isRangeSelection(o)?e(!o.isCollapsed()):e(false);});})}}},jo=new Le;var Bt={dependencies:[HorizontalRuleNode],export:a=>$isHorizontalRuleNode(a)?"---":null,regExp:/^(?:---|\*\*\*|___)\s*$/,replace:(a,t,e)=>{let o=$createHorizontalRuleNode();a.replace(o);},type:"element"},Pe=class extends M{constructor(){super("horizontalRule",["toolbar"]);}register(t){return ()=>{}}getNodes(){return [HorizontalRuleNode]}getPlugins(){return [jsx(HorizontalRulePlugin,{},"horizontal-rule")]}getCommands(t){return {insertHorizontalRule:()=>{t.dispatchCommand(INSERT_HORIZONTAL_RULE_COMMAND,void 0);}}}getStateQueries(t){return {isHorizontalRuleSelected:()=>new Promise(e=>{t.getEditorState().read(()=>{let o=$getSelection();if(o&&$isRangeSelection(o)){let r=o.getNodes().some(i=>$isHorizontalRuleNode(i));e(r);}else e(false);});})}}},tn=new Pe;var st=class{constructor(t,e=[]){y(this,"editor");y(this,"extraTransformers",[]);this.editor=t,this.extraTransformers=[...e];}registerTransformer(t){this.extraTransformers.includes(t)||this.extraTransformers.push(t);}getAllTransformers(){return [...this.extraTransformers,...TRANSFORMERS]}export(){return this.editor.getEditorState().read(()=>$convertToMarkdownString(this.getAllTransformers()))}import(t,e,o){this.editor.update(()=>{let n=$getRoot();n.clear();let r=t??"";if(!r.trim()){n.append($createParagraphNode());return}$convertFromMarkdownString(r,this.getAllTransformers()),o||$getRoot().selectEnd();},{discrete:true,onUpdate:e});}},we=class extends M{constructor(){super("markdown",["toolbar"]);y(this,"manager",null);y(this,"pendingTransformers",[]);y(this,"importTimer",null);y(this,"registerTransformer",e=>{this.manager?this.manager.registerTransformer(e):this.pendingTransformers.push(e);});this.config={importDebounce:120,transformers:[]};}configure(e){this.config={...this.config,...e};let o=e.transformers||e.customTransformers||[];return this.manager&&o.length?o.forEach(n=>this.manager?.registerTransformer(n)):o.length&&this.pendingTransformers.push(...o),this}register(e){let o=this.config.transformers||this.config.customTransformers||[];return this.manager=new st(e,[...o,...this.pendingTransformers]),this.pendingTransformers=[],()=>{this.manager=null;}}getCommands(e){return {exportToMarkdown:()=>{if(!this.manager)return "";try{return this.manager.export()}catch(o){return console.error("[MarkdownExtension] export failed",o),""}},importFromMarkdown:(o,n)=>new Promise(r=>{if(!this.manager){r();return}let{immediate:i,preventFocus:s}=n||{},l=i?0:this.config.importDebounce||0;this.importTimer&&clearTimeout(this.importTimer);let c=()=>{this.manager?.import(o,()=>{r();},s);};l>0?this.importTimer=setTimeout(c,l):c();}),registerMarkdownTransformer:o=>{this.registerTransformer(o);}}}getStateQueries(e){return {}}},xe=new we;function un({items:a,position:t,onClose:e,className:o,style:n,itemClassName:r,itemStyle:i,disabledItemClassName:s,disabledItemStyle:l}){return jsx("div",{className:o,style:{position:"fixed",left:t.x,top:t.y,zIndex:1e3,...n},onClick:c=>c.stopPropagation(),children:a.map((c,d)=>c.separator?jsx("div",{className:"h-px bg-border my-1"},d):jsxs("div",{className:c.disabled?s:r,style:c.disabled?l:i,onClick:()=>{!c.disabled&&c.action&&(c.action(),e());},children:[c.icon&&jsx(c.icon,{className:"mr-2 h-4 w-4"}),c.label]},d))})}var _e=class{constructor(t,e={}){y(this,"providers",new Map);y(this,"currentMenu",null);y(this,"listeners",new Set);y(this,"editor");y(this,"config");this.editor=t,this.config=e;}registerProvider(t){this.providers.set(t.id,t);}unregisterProvider(t){this.providers.delete(t);}handleContextMenu(t){let e=t.target;this.editor.getEditorState().read(()=>{let o=$getSelection(),n=Array.from(this.providers.values()).sort((r,i)=>(i.priority||0)-(r.priority||0));for(let r of n){let i={editor:this.editor,target:e,selection:o,event:t};if(r.canHandle(i)){this.config.preventDefault!==false&&t.preventDefault();let s=r.getItems(i);if(s.length>0){this.showMenu({items:s,position:{x:t.clientX,y:t.clientY},renderer:r.renderer||this.config.defaultRenderer});return}}}});}showMenu(t){this.currentMenu=t,this.notifyListeners();}hideMenu(){this.currentMenu=null,this.notifyListeners();}getCurrentMenu(){return this.currentMenu}subscribe(t){return this.listeners.add(t),t(this.currentMenu),()=>{this.listeners.delete(t);}}notifyListeners(){this.listeners.forEach(t=>t(this.currentMenu));}};function gn({extension:a}){let{config:t}=Z(),[e,o]=useState(null),n=t?.theme?.contextMenu||{},r=a.config,i={container:r?.theme?.container||n.container||"luthor-context-menu",item:r?.theme?.item||n.item||"luthor-context-menu-item",itemDisabled:r?.theme?.itemDisabled||n.itemDisabled||"luthor-context-menu-item-disabled"},s={container:{...r?.styles?.container,...n.styles?.container},item:{...r?.styles?.item,...n.styles?.item},itemDisabled:{...r?.styles?.itemDisabled,...n.styles?.itemDisabled}};if(useEffect(()=>a.subscribe(o),[a]),!e)return null;let l=e.renderer||a.config.defaultRenderer;return createPortal(jsx(l,{items:e.items,position:e.position,onClose:()=>a.manager?.hideMenu(),className:i.container,style:s.container,itemClassName:i.item,itemStyle:s.item,disabledItemClassName:i.itemDisabled,disabledItemStyle:s.itemDisabled}),document.body)}var ke=class extends M{constructor(e={}){super("contextMenu",["toolbar"]);y(this,"manager",null);y(this,"pendingListeners",new Set);this.config={defaultRenderer:un,position:"before",initPriority:100,...e};}configure(e){return this.config={...this.config,...e},this.manager&&Object.assign(this.manager,{config:this.config}),this}register(e){this.manager=new _e(e,this.config),this.pendingListeners.forEach(s=>{this.manager?.subscribe(s);}),this.pendingListeners.clear();let o=s=>{this.manager?.handleContextMenu(s);},n=s=>{s.target.closest(".luthor-context-menu")||this.manager?.hideMenu();},r=s=>{s.key==="Escape"&&this.manager?.hideMenu();},i=e.getRootElement();return i?(i.addEventListener("contextmenu",o),document.addEventListener("mousedown",n),document.addEventListener("keydown",r),()=>{i.removeEventListener("contextmenu",o),document.removeEventListener("mousedown",n),document.removeEventListener("keydown",r),this.manager=null;}):()=>{this.manager=null;}}getCommands(e){return {registerProvider:o=>{this.manager||(this.manager=new _e(e,this.config)),this.manager.registerProvider(o);},unregisterProvider:o=>{this.manager?.unregisterProvider(o);},showContextMenu:o=>{this.manager?.showMenu(o);},hideContextMenu:()=>{this.manager?.hideMenu();}}}getStateQueries(e){return {isContextMenuOpen:()=>Promise.resolve(this.manager?.getCurrentMenu()!==null)}}getPlugins(){return [jsx(gn,{extension:this},"context-menu")]}subscribe(e){return this.manager?this.manager.subscribe(e):(this.pendingListeners.add(e),()=>{this.pendingListeners.delete(e);})}},lt=new ke;var Ie=class extends M{constructor(e){super("table",["toolbar"]);y(this,"defaultContextMenuItems",e=>[{label:"Insert Row Above",action:()=>e.insertRowAbove()},{label:"Insert Row Below",action:()=>e.insertRowBelow()},{label:"Insert Column Left",action:()=>e.insertColumnLeft()},{label:"Insert Column Right",action:()=>e.insertColumnRight()},{label:"Delete Row",action:()=>e.deleteRow()},{label:"Delete Column",action:()=>e.deleteColumn()},{label:"Delete Table",action:()=>e.deleteTable()}]);this.config={rows:3,columns:3,includeHeaders:false,enableContextMenu:true,contextMenuItems:this.defaultContextMenuItems,...e};}getContextMenuItems(e){return typeof this.config.contextMenuItems=="function"?this.config.contextMenuItems(e):Array.isArray(this.config.contextMenuItems)?this.config.contextMenuItems:this.defaultContextMenuItems(e)}configure(e){return this.config={...this.config,...e},e.contextMenuItems&&(this.config.contextMenuItems=e.contextMenuItems),this}register(e){let o=this.config.markdownExtension||xe;try{o.registerTransformer?.(ct);}catch(n){console.warn("[TableExtension] failed to register table markdown transformer",n);}if(this.config.enableContextMenu){let n=this.config.contextMenuExtension||lt;if(n){let r={id:"table",priority:10,canHandle:({target:s,selection:l})=>{let c=s.closest("td, th, [data-lexical-table-cell]");return c?$isTableSelection(l)?true:c.tagName==="TD"||c.tagName==="TH":false},getItems:({editor:s})=>{let l=this.getCommands(s);return this.getContextMenuItems(l)},renderer:this.config.contextMenuRenderer||n.config?.defaultRenderer};return n.getCommands(e).registerProvider(r),()=>{let s=n.getCommands(e);s&&s.unregisterProvider("table");}}}return ()=>{}}getNodes(){return [TableNode,TableRowNode,TableCellNode]}getCommands(e){return {insertTable:o=>{let{rows:n=3,columns:r=3,includeHeaders:i=false}=o;e.update(()=>{let s=$getSelection();if($isRangeSelection(s)){let l=$createTableNodeWithDimensions(n,r,i);s.insertNodes([l]);}});},insertRowAbove:()=>{e.update(()=>{$insertTableRowAtSelection(false);});},insertRowBelow:()=>{e.update(()=>{$insertTableRowAtSelection(true);});},insertColumnLeft:()=>{e.update(()=>{$insertTableColumnAtSelection(false);});},insertColumnRight:()=>{e.update(()=>{$insertTableColumnAtSelection(true);});},deleteRow:()=>{e.update(()=>{$deleteTableRowAtSelection();});},deleteColumn:()=>{e.update(()=>{$deleteTableColumnAtSelection();});},deleteTable:()=>{e.update(()=>{let o=$getSelection();$isTableSelection(o)&&o.getNodes().forEach(n=>{$isTableNode(n)&&n.remove();});});},showTableContextMenu:o=>{}}}getStateQueries(e){return {isTableSelected:async()=>e.getEditorState().read(()=>{let o=$getSelection();return $isTableSelection(o)}),isInTableCell:async()=>e.getEditorState().read(()=>{let o=$getSelection();if(!o||typeof o!="object"||!("anchor"in o)||!("focus"in o))return false;try{let n=o.anchor.getNode(),r=o.focus.getNode();return $isTableCellNode(n)||$isTableCellNode(r)}catch{return false}})}}getPlugins(){return [jsx(TablePlugin,{},"table-plugin")]}},Cn=new Ie,ct={dependencies:[TableNode,TableRowNode,TableCellNode],export:a=>{if(!$isTableNode(a))return null;let t=a.getChildren();if(t.length===0)return null;let e=[];if(t.forEach(i=>{if(!$isTableRowNode(i))return;let s=i.getChildren(),l=[];s.forEach(c=>{if(!$isTableCellNode(c))return;let d=c.getTextContent().trim();l.push(d);}),l.length>0&&e.push(l);}),e.length===0)return null;let o=[];e[0]&&o.push("| "+e[0].join(" | ")+" |");let n=e[0]?.length||1,r="| "+Array(n).fill("---").join(" | ")+" |";o.push(r);for(let i=1;i<e.length;i++){let l=[...e[i]||[]];for(;l.length<n;)l.push("");o.push("| "+l.join(" | ")+" |");}return o.join(`
|
|
2
|
-
`)},regExpStart:/^\|.*\|$/,regExpEnd:{optional:true,regExp:/^$/},replace:(a,t,e,o,n,r)=>{let s=[e[0],...n||[]].filter(m=>{let h=m.trim();return h&&h.includes("|")&&h.split("|").length>1});if(s.length<2)return;let l=[];if(s.forEach(m=>{let h=m.split("|").slice(1,-1).map(N=>N.trim());h.length>0&&l.push(h);}),l.length===0||!l[0])return;let c=l.filter(m=>!m.every(h=>/^:?-+:?$/.test(h)));if(c.length===0)return;let d=$createTableNodeWithDimensions(c.length,Math.max(...c.map(m=>m.length)),false),f=d.getChildren();c.forEach((m,h)=>{let N=f[h];if($isTableRowNode(N)){let L=N.getChildren();m.forEach((T,g)=>{if(g<L.length){let b=L[g];if($isTableCellNode(b)){b.clear();let C=$createParagraphNode();T&&C.append($createTextNode(T)),b.append(C);}}});}}),a.append(d);},type:"multiline-element"};var Fe=class extends M{constructor(){super("list",["toolbar"]);}register(t){return ()=>{}}getNodes(){return [ListNode,ListItemNode]}getPlugins(){return [jsx(ListPlugin,{},"list-plugin")]}getCommands(t){return {toggleUnorderedList:()=>{t.update(()=>{let e=$getSelection();if($isRangeSelection(e)){let n=e.anchor.getNode().getParent(),r=null,i=null;for(;n;){if($isListItemNode(n)&&(i=n),$isListNode(n)){r=n;break}n=n.getParent();}r?r.getListType()==="bullet"?i&&i.getIndent()>0?t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode):t.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0):t.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0);}});},toggleOrderedList:()=>{t.update(()=>{let e=$getSelection();if($isRangeSelection(e)){let n=e.anchor.getNode().getParent(),r=null,i=null;for(;n;){if($isListItemNode(n)&&(i=n),$isListNode(n)){r=n;break}n=n.getParent();}r?r.getListType()==="number"?i&&i.getIndent()>0?t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0):$setBlocksType(e,$createParagraphNode):t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0):t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);}});},indentList:()=>{t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0);},outdentList:()=>{t.dispatchCommand(OUTDENT_CONTENT_COMMAND,void 0);},insertNestedUnorderedList:()=>{t.update(()=>{t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),t.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND,void 0);});},insertNestedOrderedList:()=>{t.update(()=>{t.dispatchCommand(INDENT_CONTENT_COMMAND,void 0),t.dispatchCommand(INSERT_ORDERED_LIST_COMMAND,void 0);});}}}getStateQueries(t){return {unorderedList:()=>new Promise(e=>{t.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o)){e(false);return}let n=o.anchor.getNode();for(;n;){if($isListNode(n)){e(n.getListType()==="bullet");return}n=n.getParent();}e(false);});}),orderedList:()=>new Promise(e=>{t.getEditorState().read(()=>{let o=$getSelection();if(!$isRangeSelection(o)){e(false);return}let n=o.anchor.getNode();for(;n;){if($isListNode(n)){e(n.getListType()==="number");return}n=n.getParent();}e(false);});})}}},Rn=new Fe;var $e=class extends M{constructor(){super("code",["toolbar"]);}register(t){return ()=>{}}getNodes(){return [CodeNode]}getCommands(t){return {toggleCodeBlock:()=>this.toggleCodeBlock(t)}}toggleCodeBlock(t){t.update(()=>{let e=$getSelection();if($isRangeSelection(e)){if(this.getCurrentFormatSync()==="code"){$setBlocksType(e,()=>$createParagraphNode());return}$setBlocksType(e,()=>$createCodeNode());}});}getStateQueries(t){return {isInCodeBlock:()=>Promise.resolve(this.isFormat("code",t))}}isFormat(t,e){let o=true;return e.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n)){o=false;return}let r=n.getNodes();for(let i of r){let s=this.getBlockNode(i);if(!s){o=false;break}if(this.getNodeFormat(s)!==t){o=false;break}}}),o}getBlockNode(t){let e=t;for(;e;){if($isCodeNode(e))return e;e=e.getParent();}return null}getNodeFormat(t){return $isCodeNode(t)?"code":null}getCurrentFormatSync(){let t=$getSelection();if(!$isRangeSelection(t))return null;let e=t.anchor.getNode(),o=this.getBlockNode(e);return o?this.getNodeFormat(o):null}},_n=new $e;var Qe=class extends V{constructor(){super("code");}},kn=new Qe;var Ke=class extends M{constructor(){super("blockFormat",["toolbar"]);}register(t){let e=t.registerCommand(INSERT_PARAGRAPH_COMMAND,()=>{let n=$getSelection();if($isRangeSelection(n)){let r=n.anchor.getNode(),i=this.getBlockNode(r);if(i&&($isHeadingNode(i)||$isQuoteNode(i)))return false}return false},COMMAND_PRIORITY_NORMAL),o=t.registerCommand(KEY_ENTER_COMMAND,n=>{if(n&&n.shiftKey)return false;let r=$getSelection();if($isRangeSelection(r)){let i=r.anchor.getNode(),s=this.getBlockNode(i);if(s&&($isHeadingNode(s)||$isQuoteNode(s)))return this.toggleBlockFormat(t,"p"),true}return false},COMMAND_PRIORITY_EDITOR);return ()=>{e(),o();}}getNodes(){return [ParagraphNode,HeadingNode,QuoteNode]}getCommands(t){return {toggleBlockFormat:e=>this.toggleBlockFormat(t,e),toggleParagraph:()=>this.toggleBlockFormat(t,"p"),toggleHeading:e=>this.toggleBlockFormat(t,e),toggleQuote:()=>this.toggleBlockFormat(t,"quote"),getCurrentBlockType:()=>this.getCurrentFormat(t)||"p"}}toggleBlockFormat(t,e){t.update(()=>{let o=$getSelection();if($isRangeSelection(o)){if(this.getCurrentFormatSync()===e){$setBlocksType(o,()=>$createParagraphNode());return}$setBlocksType(o,()=>e==="p"?$createParagraphNode():e==="quote"?$createQuoteNode():$createHeadingNode(e));}});}getStateQueries(t){return {isParagraph:()=>Promise.resolve(this.isFormat("p",t)),isH1:()=>Promise.resolve(this.isFormat("h1",t)),isH2:()=>Promise.resolve(this.isFormat("h2",t)),isH3:()=>Promise.resolve(this.isFormat("h3",t)),isH4:()=>Promise.resolve(this.isFormat("h4",t)),isH5:()=>Promise.resolve(this.isFormat("h5",t)),isH6:()=>Promise.resolve(this.isFormat("h6",t)),isQuote:()=>Promise.resolve(this.isFormat("quote",t))}}getBlockNode(t){let e=t;for(;e;){if($isParagraphNode(e)||$isHeadingNode(e)||$isQuoteNode(e))return e;e=e.getParent();}return null}isFormat(t,e){let o=true;return e.getEditorState().read(()=>{let n=$getSelection();if(!$isRangeSelection(n)){o=false;return}let r=n.getNodes();for(let i of r){let s=this.getBlockNode(i);if(!s){o=false;break}if(this.getNodeFormat(s)!==t){o=false;break}}}),o}getNodeFormat(t){return $isParagraphNode(t)?"p":$isHeadingNode(t)?t.getTag():$isQuoteNode(t)?"quote":null}getCurrentFormat(t){let e=null;return t.getEditorState().read(()=>{let o=$getSelection();if($isRangeSelection(o)){let n=o.anchor.getNode(),r=this.getBlockNode(n);r&&(e=this.getNodeFormat(r));}}),e}getCurrentFormatSync(){let t=$getSelection();if(!$isRangeSelection(t))return null;let e=t.anchor.getNode(),o=this.getBlockNode(e);return o?this.getNodeFormat(o):null}},Un=new Ke;var We=class extends M{constructor(){super("history",["toolbar"]);y(this,"canUndoState",false);y(this,"canRedoState",false);}register(e){let o=e.registerCommand(CAN_UNDO_COMMAND,r=>(this.canUndoState=r,false),COMMAND_PRIORITY_LOW),n=e.registerCommand(CAN_REDO_COMMAND,r=>(this.canRedoState=r,false),COMMAND_PRIORITY_LOW);return ()=>{o(),n();}}getPlugins(){return [jsx(HistoryPlugin,{},"history-plugin")]}getCommands(e){return {undo:()=>{e.focus(),e.dispatchCommand(UNDO_COMMAND,void 0);},redo:()=>{e.focus(),e.dispatchCommand(REDO_COMMAND,void 0);},clearHistory:()=>e.dispatchCommand(CLEAR_HISTORY_COMMAND,void 0)}}getStateQueries(e){return {canUndo:async()=>this.canUndoState,canRedo:async()=>this.canRedoState}}},jn=new We;var ye=class extends M{constructor(e){super("draggableBlock",["floating"]);y(this,"isDraggingState",false);y(this,"stateChangeCallbacks",new Set);this.config={showInToolbar:false,position:"after",showMoveButtons:true,showUpButton:true,showDownButton:true,buttonStackPosition:"left",enableTextSelectionDrag:true,offsetLeft:-40,offsetRight:10,...e};}register(e){return ()=>{}}getPlugins(){return [jsx(Gn,{config:this.config,extension:this},"draggable-block")]}getCommands(e){return {moveBlock:(o,n,r)=>{e.update(()=>{let i=$getNodeByKey(o),s=$getNodeByKey(n);i&&s&&(i.remove(),r?s.insertAfter(i):s.insertBefore(i));});},moveCurrentBlockUp:()=>{e.update(()=>{let o=$getSelection();if($isRangeSelection(o)){let n=o.anchor.getNode(),r=$isElementNode(n)?n:n.getParent();if(r&&$isElementNode(r)){let i=r.getPreviousSibling();i&&(r.remove(),i.insertBefore(r));}}});},moveCurrentBlockDown:()=>{e.update(()=>{let o=$getSelection();if($isRangeSelection(o)){let n=o.anchor.getNode(),r=$isElementNode(n)?n:n.getParent();if(r&&$isElementNode(r)){let i=r.getNextSibling();i&&(r.remove(),i.insertAfter(r));}}});}}}getStateQueries(e){return {isDragging:async()=>this.isDraggingState}}setIsDragging(e){this.isDraggingState!==e&&(this.isDraggingState=e,this.stateChangeCallbacks.forEach(o=>o()));}onStateChange(e){return this.stateChangeCallbacks.add(e),()=>this.stateChangeCallbacks.delete(e)}},ao=new ye;function Gn({config:a,extension:t}){let[e]=useLexicalComposerContext(),{config:o,extensions:n}=Z(),i=n.find(u=>u.name==="draggableBlock")?.config,s=o?.theme?.draggable||{},[l,c]=useState(null),[d,f]=useState(false),[m,h]=useState(null),[N,L]=useState(false),T=useRef(null),g=useRef(null);if(useEffect(()=>{t.setIsDragging(d);},[d,t]),typeof document>"u")return null;let b=i?.anchorElem||a.anchorElem||document.body,C={handle:{cursor:"grab",userSelect:"none"},handleActive:{cursor:"grabbing"},blockDragging:{opacity:.5},dropIndicator:{backgroundColor:"#3b82f6",borderRadius:"2px"},upButton:{cursor:"pointer"},downButton:{cursor:"pointer"},buttonStack:{}},E={handle:{...C.handle,...s.styles?.handle,...i?.styles?.handle},handleActive:{...C.handleActive,...s.styles?.handleActive,...i?.styles?.handleActive},blockDragging:{...C.blockDragging,...s.styles?.blockDragging,...i?.styles?.blockDragging},dropIndicator:{...C.dropIndicator,...s.styles?.dropIndicator,...i?.styles?.dropIndicator},upButton:{...C.upButton,...s.styles?.upButton,...i?.styles?.upButton},downButton:{...C.downButton,...s.styles?.downButton,...i?.styles?.downButton},buttonStack:{...C.buttonStack,...s.styles?.buttonStack,...i?.styles?.buttonStack}},x={handle:i?.theme?.handle||s.handle||"luthor-draggable-handle",handleActive:i?.theme?.handleActive||s.handleActive||"luthor-draggable-handle-active",blockDragging:i?.theme?.blockDragging||s.blockDragging||"luthor-draggable-block-dragging",dropIndicator:i?.theme?.dropIndicator||s.dropIndicator||"luthor-draggable-drop-indicator",upButton:i?.theme?.upButton||s.upButton||"luthor-draggable-up-button",downButton:i?.theme?.downButton||s.downButton||"luthor-draggable-down-button",buttonStack:i?.theme?.buttonStack||s.buttonStack||"luthor-draggable-button-stack"},I=useCallback(u=>{if(!u||!x.blockDragging)return;(x.blockDragging.includes(" ")?x.blockDragging.split(" ").filter(Boolean):[x.blockDragging]).forEach(w=>u.classList.remove(w)),u.style.opacity="";},[x]),A=useCallback(u=>{if(!u||!x.blockDragging)return;(x.blockDragging.includes(" ")?x.blockDragging.split(" ").filter(Boolean):[x.blockDragging]).forEach(w=>u.classList.add(w)),Object.assign(u.style,E.blockDragging);},[x,E.blockDragging]),O=useCallback(()=>{T.current&&I(T.current),f(false),h(null);let u=e.getRootElement();u&&u.focus(),setTimeout(()=>{T.current=null,g.current=null;},100);},[I,e]);useEffect(()=>()=>{T.current&&I(T.current);},[I]),useEffect(()=>{if(l||T.current)L(true);else {let u=setTimeout(()=>L(false),300);return ()=>clearTimeout(u)}},[l,T.current]),useEffect(()=>{let u,S=P=>{if(d)return;let R=e.getRootElement();if(!R)return;let p=P.target,H=p&&p.closest&&(p.closest(".drag-handle-area")||p.closest('[draggable="true"]')),D=window.getSelection(),_=D&&D.rangeCount>0&&!D.isCollapsed,v=null,k=p;for(;k&&k!==R&&k!==document.body;){if(k.parentElement===R){v=k;break}k=k.parentElement;}u&&clearTimeout(u),(v||H)&&!_&&!d?v&&v!==l&&c(v):u=setTimeout(()=>{c(null);},500);},w=()=>{d||(u&&clearTimeout(u),u=setTimeout(()=>{c(null);},300));};return document.addEventListener("mousemove",S),document.addEventListener("mouseleave",w),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseleave",w),u&&clearTimeout(u);}},[e,d,l]);let B=useCallback((u,S)=>{u.stopPropagation(),f(true),T.current=S,A(S);let w=e.read(()=>{let p=$getNearestNodeFromDOMNode(S);return p?p.getKey():null});w&&(g.current=w,u.dataTransfer?.setData("application/x-lexical-drag",JSON.stringify({key:w}))),u.dataTransfer.effectAllowed="move";let P=S.cloneNode(true);P.style.opacity="0.6",P.style.position="absolute",P.style.top="-9999px",P.style.left="-9999px",document.body.appendChild(P),u.dataTransfer.setDragImage(P,0,0),setTimeout(()=>document.body.removeChild(P),0);let R=e.getRootElement();R&&R.focus();},[e,A]),re=useCallback((u,S)=>{u.preventDefault(),f(true),T.current=S,A(S);let w=e.read(()=>{let P=$getNearestNodeFromDOMNode(S);return P?P.getKey():null});w&&(g.current=w);},[e,A]),J=useCallback(u=>{if(!d||!T.current)return;u.preventDefault();let S=u.touches[0];if(!S)return;let w=e.getRootElement();if(!w)return;let P=null,R=document.elementFromPoint(S.clientX,S.clientY);if(R){let p=R;for(;p&&p!==w;){if(p.parentElement===w){P=p;break}p=p.parentElement;}}if(P&&P!==T.current){let p=P.getBoundingClientRect(),H=S.clientY<p.top+p.height/2;h({top:H?p.top+window.scrollY:p.bottom+window.scrollY,left:p.left+window.scrollX,width:p.width});}else h(null);},[e,d]),X=useCallback(u=>{if(!d||!g.current)return;u.preventDefault();let S=u.changedTouches[0];if(!S)return;let w=e.getRootElement();if(!w)return;let P=null,R=document.elementFromPoint(S.clientX,S.clientY);if(R){let p=R;for(;p&&p!==w;){if(p.parentElement===w){P=p;break}p=p.parentElement;}}P&&P!==T.current&&(e.update(()=>{let p=$getNodeByKey(g.current),H=$getNearestNodeFromDOMNode(P);if(p&&H){let D=P.getBoundingClientRect(),_=S.clientY>=D.top+D.height/2;p.remove(),_?H.insertAfter(p):H.insertBefore(p);}}),setTimeout(()=>{if(g.current)try{let p=e.getElementByKey(g.current);p&&p instanceof HTMLElement&&typeof p.getBoundingClientRect=="function"&&c(p);}catch(p){console.warn("Error finding moved element:",p);}},50)),O();},[e,d,O]),U=useCallback(()=>{l&&e.update(()=>{let u=$getNearestNodeFromDOMNode(l);if(u){let S=u.getPreviousSibling();S&&(u.remove(),S.insertBefore(u));}});},[e,l]),z=useCallback(()=>{l&&e.update(()=>{let u=$getNearestNodeFromDOMNode(l);if(u){let S=u.getNextSibling();S&&(u.remove(),S.insertAfter(u));}});},[e,l]);useEffect(()=>{let u=e.getRootElement();if(!u)return;let S=R=>{let p=R.target;if(p.nodeType!==Node.ELEMENT_NODE&&(p=p.parentNode),!p||!(p instanceof HTMLElement)){R.preventDefault();return}if(p.closest('[draggable="true"]'))return;let D=window.getSelection();if(!D||D.isCollapsed||!(i?.enableTextSelectionDrag??a.enableTextSelectionDrag)){R.preventDefault();return}let _=D.anchorNode;_?.nodeType===Node.TEXT_NODE&&(_=_.parentNode);let v=null;for(;_&&_!==u;){if(_.parentNode===u){v=_;break}_=_.parentNode;}if(!v){R.preventDefault();return}D.collapse(D.anchorNode,D.anchorOffset);let k=e.read(()=>$getNearestNodeFromDOMNode(v)?.getKey()??null);if(!k){R.preventDefault();return}R.dataTransfer.clearData(),R.dataTransfer.setData("application/x-lexical-drag",JSON.stringify({key:k})),R.dataTransfer.effectAllowed="move";let $=v.cloneNode(true);$.style.opacity="0.6",$.style.position="absolute",$.style.top="-9999px",$.style.left="-9999px",document.body.appendChild($),R.dataTransfer.setDragImage($,0,0),setTimeout(()=>document.body.removeChild($),0),f(true),T.current=v,A(v),g.current=k;},w=R=>{let p=R.target;if(p.nodeType!==Node.ELEMENT_NODE&&(p=p.parentNode),!p||!(p instanceof HTMLElement))return;let H=p;R.preventDefault(),R.dataTransfer.dropEffect="move";let D=null,_=H;for(;_&&_!==u;){if(_.parentElement===u){D=_;break}_=_.parentElement;}if(D&&D!==T.current){let v=D.getBoundingClientRect(),k=R.clientY<v.top+v.height/2;h({top:k?v.top+window.scrollY:v.bottom+window.scrollY,left:v.left+window.scrollX,width:v.width});}else h(null);},P=R=>{let p=R.target;if(p.nodeType!==Node.ELEMENT_NODE&&(p=p.parentNode),!p||!(p instanceof HTMLElement))return;let H=p;R.preventDefault(),h(null);let D=R.dataTransfer?.getData("application/x-lexical-drag");if(!D){O();return}let{key:_}=JSON.parse(D);if(!_){O();return}let v=null,k=H;for(;k&&k!==u;){if(k.parentElement===u){v=k;break}k=k.parentElement;}v&&v!==T.current&&(e.update(()=>{let $=$getNodeByKey(_),W=$getNearestNodeFromDOMNode(v);if($&&W){let ce=v.getBoundingClientRect(),Se=R.clientY>=ce.top+ce.height/2;$.remove(),Se?W.insertAfter($):W.insertBefore($);}}),setTimeout(()=>{if(g.current)try{let W=e.getElementByKey(g.current);W&&W instanceof HTMLElement&&typeof W.getBoundingClientRect=="function"&&c(W);}catch(W){console.warn("Error finding moved element:",W);}let $=e.getRootElement();$&&$.focus();},50)),O();};return u.addEventListener("dragstart",S),u.addEventListener("dragover",w),u.addEventListener("drop",P),u.addEventListener("dragend",O),()=>{u.removeEventListener("dragstart",S),u.removeEventListener("dragover",w),u.removeEventListener("drop",P),u.removeEventListener("dragend",O);}},[e,O,A,i?.enableTextSelectionDrag,a.enableTextSelectionDrag]),useEffect(()=>{let u=e.getRootElement();if(!u)return;let S=null,w=0,P=0,R=D=>{if(D.touches.length!==1||!(i?.enableTextSelectionDrag??a.enableTextSelectionDrag))return;let _=D.touches[0];if(!_)return;let v=D.target;if(v.nodeType!==Node.ELEMENT_NODE&&(v=v.parentNode),!v||!(v instanceof HTMLElement))return;let k=v;k.closest('[draggable="true"]')||(w=_.clientX,P=_.clientY,S=setTimeout(()=>{S=null;let $=null,W=k;for(;W&&W!==u;){if(W.parentElement===u){$=W;break}W=W.parentElement;}if(!$)return;let ce=window.getSelection();ce&&!ce.isCollapsed&&ce.collapseToStart(),f(true),T.current=$,A($);let Se=e.read(()=>$getNearestNodeFromDOMNode($)?.getKey()??null);Se&&(g.current=Se);},500));},p=D=>{if(S&&D.touches.length===1){let _=D.touches[0];if(!_)return;let v=_.clientX-w,k=_.clientY-P;Math.sqrt(v*v+k*k)>10&&(clearTimeout(S),S=null);}},H=D=>{S&&(clearTimeout(S),S=null);};return u.addEventListener("touchstart",R,{passive:false}),u.addEventListener("touchmove",p,{passive:false}),u.addEventListener("touchend",H,{passive:false}),document.addEventListener("touchmove",J,{passive:false}),document.addEventListener("touchend",X,{passive:false}),()=>{u.removeEventListener("touchstart",R),u.removeEventListener("touchmove",p),u.removeEventListener("touchend",H),document.removeEventListener("touchmove",J),document.removeEventListener("touchend",X);}},[e,A,O,d,J,X,i?.enableTextSelectionDrag,a.enableTextSelectionDrag]);let K=l||T.current;if(!K||typeof K.getBoundingClientRect!="function")return null;let Y=K.getBoundingClientRect();return !Y.width||!Y.height?null:jsxs(Fragment,{children:[createPortal(jsx("div",{className:`${x.buttonStack} ${N?"":"fade-out"}`,style:{position:"absolute",left:(i?.buttonStackPosition||a.buttonStackPosition)==="right"?Y.right+window.scrollX+(i?.offsetRight||a.offsetRight||10):Y.left+window.scrollX+(i?.offsetLeft||a.offsetLeft||-40),top:Y.top+window.scrollY,zIndex:40,display:"flex",flexDirection:"row",gap:"6px",alignItems:"center",pointerEvents:"auto",willChange:"transform, opacity",backfaceVisibility:"hidden",perspective:"1000px",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",...E.buttonStack},children:jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"4px",alignItems:"center"},children:[(i?.showMoveButtons??a.showMoveButtons)!==false&&(i?.showUpButton??a.showUpButton)!==false&&(i?.buttonsRenderer||a.buttonsRenderer?(i?.buttonsRenderer||a.buttonsRenderer)({rect:Y,onMoveUp:U,onMoveDown:z,showUp:true,showDown:false,upClassName:`luthor-drag-button ${x.upButton}`,downClassName:`luthor-drag-button ${x.downButton}`}):jsx("button",{className:`luthor-drag-button ${x.upButton}`,onClick:U,style:E.upButton,children:"\u2191"})),i?.handleRenderer||a.handleRenderer?(i?.handleRenderer||a.handleRenderer)({rect:Y,isDragging:d,onDragStart:u=>B(u,K),className:`luthor-drag-button ${x.handle} ${d?x.handleActive:""}`.trim()}):jsx("div",{className:`luthor-drag-button ${x.handle} ${d?x.handleActive:""}`.trim(),draggable:true,onDragStart:u=>B(u,K),onTouchStart:u=>re(u,K),style:d?E.handleActive:E.handle,children:"\u22EE\u22EE"}),(i?.showMoveButtons??a.showMoveButtons)!==false&&(i?.showDownButton??a.showDownButton)!==false&&(i?.buttonsRenderer||a.buttonsRenderer?(i?.buttonsRenderer||a.buttonsRenderer)({rect:Y,onMoveUp:U,onMoveDown:z,showUp:false,showDown:true,upClassName:`luthor-drag-button ${x.upButton}`,downClassName:`luthor-drag-button ${x.downButton}`}):jsx("button",{className:`luthor-drag-button ${x.downButton}`,onClick:z,style:E.downButton,children:"\u2193"}))]})}),b),m&&(i?.dropIndicatorRenderer||a.dropIndicatorRenderer?createPortal((i?.dropIndicatorRenderer||a.dropIndicatorRenderer)({...m,className:x.dropIndicator}),b):createPortal(jsx("div",{className:x.dropIndicator,style:{position:"absolute",top:m.top-4,left:m.left,width:m.width,height:"8px",pointerEvents:"none",zIndex:9997,...E.dropIndicator}}),b))]})}var je=class extends M{constructor(){super("html",["toolbar"]);}register(t){return ()=>{}}getCommands(t){return {exportToHTML:()=>t.getEditorState().read(()=>$generateHtmlFromNodes(t)),importFromHTML:(e,o)=>new Promise(n=>{t.update(()=>{try{let r=$getRoot();if(r.clear(),e.trim()){let s=new DOMParser().parseFromString(e,"text/html"),l=$generateNodesFromDOM(t,s);l&&l.length>0?l.forEach(c=>{c&&r.append(c);}):r.append($createParagraphNode());}else r.append($createParagraphNode());o?.preventFocus||$getRoot().selectEnd();}catch(r){console.error("Error importing HTML:",r);let i=$getRoot();i.clear(),i.append($createParagraphNode());}},{discrete:true,onUpdate:n});})}}getStateQueries(t){return {canExportHTML:async()=>true}}},or=new je;var oe=class a extends DecoratorNode{constructor(e,o){super(o);y(this,"__payload");this.__payload=e;}static getType(){return "html-embed"}static clone(e){return new a(e.__payload,e.__key)}createDOM(){let e=document.createElement("div");return e.setAttribute("data-lexical-html-embed","true"),e.className="html-embed-container",e}updateDOM(){return false}static importJSON(e){let o={html:e.html||'<div style="padding: 20px; border-radius: 8px; text-align: center;"><h3>Custom HTML Block</h3><p>Edit this HTML to create your custom embed!</p></div>',preview:e.preview??true};return new a(o)}exportJSON(){return {type:"html-embed",html:this.__payload.html,preview:this.__payload.preview,version:1}}static importDOM(){return {div:e=>e.hasAttribute("data-lexical-html-embed")?{conversion:o=>{let r={html:o.getAttribute("data-html-content")||"",preview:true};return {node:new a(r)}},priority:4}:null,p:e=>e.querySelector('div[data-lexical-html-embed="true"]')?{conversion:n=>{let r=n.querySelector('div[data-lexical-html-embed="true"]');if(r){let s={html:r.getAttribute("data-html-content")||"",preview:true};return {node:new a(s)}}return {node:null}},priority:4}:null}}exportDOM(){let e=document.createElement("div");return e.setAttribute("data-lexical-html-embed","true"),e.setAttribute("data-html-content",this.__payload.html),{element:e}}getPayload(){return this.getLatest().__payload}setPayload(e){let o=this.getWritable();o.__payload={...o.__payload,...e};}decorate(e){return jsx(sr,{nodeKey:this.__key,payload:this.__payload,editor:e})}isInline(){return false}isKeyboardSelectable(){return true}},sr=({nodeKey:a,payload:t,editor:e})=>{let{config:o,extensions:n}=Z(),i=n.find(E=>E.name==="htmlEmbed")?.config,s=o?.theme?.htmlEmbed||{},l=useRef(null),c=E=>{e.update(()=>{let x=$getNodeByKey(a);x&&x.setPayload(E);});},d=()=>{if(!t.preview&&l.current){let E=l.current.value;E!==t.html&&c({html:E});}c({preview:!t.preview});},f=()=>{if(l.current){let E=l.current.value;E!==t.html&&c({html:E});}c({preview:true});},m={container:{...i?.styles?.container,...s.styles?.container},preview:{...i?.styles?.preview,...s.styles?.preview},editor:{...i?.styles?.editor,...s.styles?.editor},textarea:{...i?.styles?.textarea,...s.styles?.textarea},toggle:{...i?.styles?.toggle,...s.styles?.toggle},content:{...i?.styles?.content,...s.styles?.content}},h={container:i?.theme?.container||s.container||"",preview:i?.theme?.preview||s.preview||"",editor:i?.theme?.editor||s.editor||"",textarea:i?.theme?.textarea||s.textarea||"",toggle:i?.theme?.toggle||s.toggle||"",content:i?.theme?.content||s.content||""},N=({children:E,className:x,style:I})=>jsx("div",{className:x,style:I,children:E}),L=({html:E,onToggleEdit:x,className:I,style:A,toggleClassName:O,toggleStyle:B})=>jsxs("div",{className:I,style:A,children:[jsx("div",{className:h.content,style:m.content,dangerouslySetInnerHTML:{__html:E}}),i?.toggleRenderer?i.toggleRenderer({isPreview:true,onClick:x,className:O,style:B}):jsx("button",{className:O,style:B,onClick:x,title:"Edit HTML",type:"button",children:"\u270F\uFE0F Edit"})]}),T=({html:E,onTogglePreview:x,onSave:I,className:A,style:O,textareaClassName:B,textareaStyle:re,toggleClassName:J,toggleStyle:X})=>jsxs("div",{className:A,style:O,children:[jsx("textarea",{ref:l,className:B,style:re,defaultValue:E,placeholder:"Enter HTML here..."}),i?.toggleRenderer?i.toggleRenderer({isPreview:false,onClick:I,className:J,style:X}):jsx("button",{className:J,style:X,onClick:I,title:"Preview HTML",type:"button",children:"\u{1F441}\uFE0F Preview"})]}),g=i?.containerRenderer||N,b=i?.previewRenderer||L,C=i?.editorRenderer||T;return jsx(g,{className:h.container,style:m.container,children:t.preview?jsx(b,{html:t.html,onToggleEdit:d,className:h.preview,style:m.preview,toggleClassName:h.toggle,toggleStyle:m.toggle}):jsx(C,{html:t.html,onTogglePreview:d,onSave:f,className:h.editor,style:m.editor,textareaClassName:h.textarea,textareaStyle:m.textarea,toggleClassName:h.toggle,toggleStyle:m.toggle})})},Ge=class extends M{constructor(t){super("htmlEmbed",["toolbar"]),this.config={defaultHtml:'<div style="padding: 20px; border-radius: 8px; text-align: center;"><h3>Custom HTML Block</h3><p>Edit this HTML to create your custom embed!</p></div>',defaultPreview:false,...t};}register(t){let e=this.config.markdownExtension||xe;try{e.registerTransformer?.(Et);}catch(o){console.warn("[HTMLEmbedExtension] failed to register html embed markdown transformer",o);}return ()=>{}}getNodes(){return [oe]}getPlugins(){return []}getCommands(t){return {insertHTMLEmbed:e=>{t.update(()=>{let o={html:e||this.config.defaultHtml,preview:this.config.defaultPreview},n=new oe(o),r=$getSelection();$isRangeSelection(r)?r.insertNodes([n]):$getRoot().append(n);});},toggleHTMLPreview:()=>{t.update(()=>{let e=$getSelection();$isRangeSelection(e)&&e.getNodes().forEach(n=>{if(n instanceof oe){let r=n.getPayload();n.setPayload({preview:!r.preview});}});});}}}getStateQueries(t){return {isHTMLEmbedSelected:()=>new Promise(e=>{t.getEditorState().read(()=>{let o=$getSelection();if($isRangeSelection(o)){let n=o.getNodes().some(r=>r instanceof oe);e(n);}else e(false);});}),isHTMLPreviewMode:()=>new Promise(e=>{t.getEditorState().read(()=>{let o=$getSelection();if($isRangeSelection(o)){let n=o.getNodes().find(r=>r instanceof oe);e(n?n.getPayload().preview:false);}else e(false);});})}}},Et={dependencies:[oe],export:a=>{if(a&&typeof a.getType=="function"&&a.getType()==="html-embed")try{return "```html-embed\n"+a.getPayload().html+"\n```"}catch(t){return console.error("\u274C Error exporting HTML embed:",t),null}return null},regExpStart:/^```html-embed\s*$/,regExpEnd:{optional:true,regExp:/^```$/},replace:(a,t,e,o,n,r)=>{let i=n.join(`
|
|
3
|
-
`);try{let s={html:i,preview:!0},l=new oe(s);a.append(l);}catch(s){console.error("\u274C Error creating HTML embed node:",s);}},type:"multiline-element"},lr=new Ge;var ae=class{static importDOM(){return {img:()=>({conversion:t=>{try{if(!t||!(t instanceof HTMLImageElement)||!t.src)return null;let e=t,o="none",n=e.style;n.textAlign?o=n.textAlign:n.float&&(o=n.float==="left"?"left":n.float==="right"?"right":"none"),e.classList.contains("align-left")?o="left":e.classList.contains("align-center")?o="center":e.classList.contains("align-right")&&(o="right");let r,i=e.closest("figure");if(i){let s=i.querySelector("figcaption");s&&(r=s.textContent||void 0);}try{return {node:de(e.src,e.alt||"",r,o,e.className||void 0,this.extractStyleObject(e))}}catch{return null}}catch{return null}},priority:0}),figure:()=>({conversion:t=>{try{if(!t||!(t instanceof HTMLElement)||t.tagName!=="FIGURE")return null;let e=t,o=e.querySelector("img");if(!o||!o.src)return null;let r=e.querySelector("figcaption")?.textContent||void 0;try{return {node:de(o.src,o.alt||"",r,"center",e.className||void 0,this.extractStyleObject(e))}}catch{return null}}catch{return null}},priority:1})}}static exportDOM(t){let{element:e,after:o}=this.createImageElement(t);return {element:e,after:o}}static exportJSON(t){return {type:"image",version:1,src:t.__src,alt:t.__alt,caption:t.__caption,alignment:t.__alignment,className:t.__className,style:t.__style?this.styleObjectToRecord(t.__style):void 0,width:t.__width,height:t.__height,uploading:t.__uploading}}static importJSON(t){let{src:e,alt:o,caption:n,alignment:r,className:i,style:s,width:l,height:c,uploading:d}=t;if(!e||e.length===0)throw new Error("Cannot import ImageNode with empty src");return de(e,o,n,r,i,s?this.recordToStyleObject(s):void 0,l,c,d)}static createImageElement(t){let e=document.createElement("figure"),o=document.createElement("img");switch(o.src=t.__src,o.alt=t.__alt,t.__width&&(o.width=t.__width),t.__height&&(o.height=t.__height),t.__className&&(o.className=t.__className),t.__style&&Object.assign(o.style,t.__style),e.className=`lexical-image align-${t.__alignment}`,t.__alignment){case "left":e.style.textAlign="left";break;case "center":e.style.textAlign="center";break;case "right":e.style.textAlign="right";break;default:e.style.textAlign="left";}if(e.style.margin="1rem 0",e.style.display="block",e.appendChild(o),t.__caption){let n=document.createElement("figcaption");n.textContent=t.__caption,n.style.fontSize="0.9em",n.style.color="#666",n.style.fontStyle="italic",n.style.marginTop="0.5rem",n.style.textAlign="center",e.appendChild(n);}return {element:e,after:n=>n}}static extractStyleObject(t){if(!t||!(t instanceof HTMLElement)||!t.style||!t.style.length)return;let e={};try{for(let o=0;o<t.style.length;o++){let n=t.style.item(o);n&&(e[n]=t.style.getPropertyValue(n));}return Object.keys(e).length>0?e:void 0}catch{return}}static styleObjectToRecord(t){let e={};for(let[o,n]of Object.entries(t))e[o]=String(n);return e}static recordToStyleObject(t){return {...t}}},{importDOM:Rl,exportDOM:Ml,importJSON:Ll,exportJSON:Pl}=ae;var go=createCommand("insert-image"),po=br;function br({src:a,alt:t,caption:e,alignment:o="none",className:n="",style:r,nodeKey:i,width:s,height:l,resizable:c=true,uploading:d=false}){let [f]=useLexicalComposerContext(),m=useRef(null);useRef(null);let [N,L]=useState(false),[T,g]=useState(false),[b,C]=useState(1),[E,x]=useState(s||"auto"),[I,A]=useState(l||"auto");useEffect(()=>{let U=m.current;U&&(U.onload=()=>{C(U.naturalWidth/U.naturalHeight);});},[a]),useEffect(()=>()=>{a&&a.startsWith("blob:")&&URL.revokeObjectURL(a);},[a]),useEffect(()=>{x(s||"auto"),A(l||"auto");},[s,l]),useEffect(()=>{if(i)return f.registerUpdateListener(({editorState:U})=>{U.read(()=>{let z=$getSelection();if($isNodeSelection(z)){let K=z.getNodes();L(K.some(Y=>Y.getKey()===i));}else L(false);});})},[f,i]);let O=U=>{U.preventDefault(),U.stopPropagation(),i&&f.update(()=>{let z=$createNodeSelection();z.add(i),$setSelection(z);});},B=U=>z=>{if(!m.current||!z.target)return;z.preventDefault(),g(true);let K="touches"in z?z.touches?.[0]?.clientX||0:z.clientX,Y="touches"in z?z.touches?.[0]?.clientY||0:z.clientY,u=m.current.clientWidth||100,S=m.current.clientHeight||100,w=u,P=S,R=H=>{let D="touches"in H?H.touches?.[0]?.clientX||0:H.clientX,_="touches"in H?H.touches?.[0]?.clientY||0:H.clientY,v=u,k=S;U.includes("e")&&(v+=D-K),U.includes("w")&&(v+=K-D),U.includes("s")&&(k+=_-Y),U.includes("n")&&(k+=Y-_),H.shiftKey&&(k=v/b),v=Math.max(50,v),k=Math.max(50,k),w=v,P=k,x(v),A(k);},p=()=>{g(false),f.update(()=>{let H=$getNodeByKey(i);H instanceof F&&typeof w=="number"&&typeof P=="number"&&H.setWidthAndHeight(w,P);}),document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",p),document.removeEventListener("touchmove",R),document.removeEventListener("touchend",p);};document.addEventListener("mousemove",R),document.addEventListener("mouseup",p),document.addEventListener("touchmove",R,{passive:false}),document.addEventListener("touchend",p);},re={margin:0,display:"block",position:"relative"},J={maxWidth:"100%",display:"block",borderRadius:"4px",width:typeof E=="number"?"100%":E,height:typeof I=="number"?"100%":I,margin:0},X={fontSize:"0.9em",color:"#666",fontStyle:"italic",marginTop:"0.5rem",textAlign:"center"};return jsxs("figure",{className:`lexical-image align-${o} ${n} ${N?"selected":""} ${T?"resizing":""} ${d?"uploading":""}`,style:re,children:[jsxs("div",{style:{position:"relative",display:"inline-block",width:E,height:I,cursor:"pointer"},onClick:O,children:[jsx("img",{ref:m,src:a,alt:t,style:J}),N&&c&&jsxs(Fragment,{children:[jsx("div",{className:"resizer ne",onMouseDown:B("ne"),onTouchStart:B("ne"),style:{position:"absolute",top:"-5px",right:"-5px",width:"10px",height:"10px",background:"#007acc",cursor:"ne-resize",borderRadius:"50%"}}),jsx("div",{className:"resizer nw",onMouseDown:B("nw"),onTouchStart:B("nw"),style:{position:"absolute",top:"-5px",left:"-5px",width:"10px",height:"10px",background:"#007acc",cursor:"nw-resize",borderRadius:"50%"}}),jsx("div",{className:"resizer se",onMouseDown:B("se"),onTouchStart:B("se"),style:{position:"absolute",bottom:"-5px",right:"-5px",width:"10px",height:"10px",background:"#007acc",cursor:"se-resize",borderRadius:"50%"}}),jsx("div",{className:"resizer sw",onMouseDown:B("sw"),onTouchStart:B("sw"),style:{position:"absolute",bottom:"-5px",left:"-5px",width:"10px",height:"10px",background:"#007acc",cursor:"sw-resize",borderRadius:"50%"}})]})]}),e&&jsx("figcaption",{style:X,children:e}),jsx("div",{style:{clear:"both",height:0,fontSize:0}})]})}var F=class a extends DecoratorNode{constructor(e="",o="",n,r="none",i,s,l,c,d,f){super(f);y(this,"__src");y(this,"__alt");y(this,"__caption");y(this,"__alignment");y(this,"__className");y(this,"__style");y(this,"__width");y(this,"__height");y(this,"__uploading");this.__src=e&&e.length>0?e:"",this.__alt=o,this.__caption=n,this.__alignment=r,this.__className=i,this.__style=s,this.__width=l,this.__height=c,this.__uploading=d;}static getType(){return "image"}static clone(e){return new a(e.__src,e.__alt,e.__caption,e.__alignment,e.__className,e.__style,e.__width,e.__height,e.__uploading,e.__key)}static importDOM(){return ae.importDOM()}static importJSON(e){return ae.importJSON(e)}createDOM(e){let o=document.createElement("div"),n=e.theme?.image||"",r=this.__alignment;return o.className=`${n} lexical-image-container align-${r}`.trim(),o.style.display=r==="center"?"block":"inline-block",o.style.float=r==="left"?"left":r==="right"?"right":"none",o.style.margin=r==="center"?"1rem auto":r==="left"?"0 1rem 1rem 0":r==="right"?"0 0 1rem 1rem":"1rem 0",o.style.textAlign=r==="center"?"center":"inherit",o.style.position="relative",o}updateDOM(e,o,n){let r=this.__alignment;if(r!==e.__alignment){let i=n.theme?.image||"";o.className=`${i} lexical-image-container align-${r}`.trim();}return o.style.display=r==="center"?"block":"inline-block",o.style.float=r==="left"?"left":r==="right"?"right":"none",o.style.margin=r==="center"?"1rem auto":r==="left"?"0 1rem 1rem 0":r==="right"?"0 0 1rem 1rem":"1rem 0",o.style.textAlign=r==="center"?"center":"inherit",o.style.position="relative",false}exportDOM(){return ae.exportDOM(this)}exportJSON(){return ae.exportJSON(this)}setSrc(e){if(!e||e.length===0){console.warn("Attempted to set empty src on ImageNode");return}let o=this.getWritable();o.__src=e;}setAlt(e){let o=this.getWritable();o.__alt=e;}setCaption(e){let o=this.getWritable();o.__caption=e;}setAlignment(e){let o=this.getWritable();o.__alignment=e;}setClassName(e){let o=this.getWritable();o.__className=e;}setStyle(e){let o=this.getWritable();o.__style=e;}getWidth(){return this.__width}getHeight(){return this.__height}setWidthAndHeight(e,o){let n=this.getWritable();n.__width=e,n.__height=o;}isInline(){return false}isBlockElement(){return true}canBeEmpty(){return false}decorate(){if(!this.__src||this.__src.length===0)return console.error("\u274C No src provided to ImageNode"),jsx("div",{style:{color:"red",border:"1px solid red",padding:"10px",backgroundColor:"#ffe6e6"},children:"Image Error: No source URL provided"});try{return jsx(po,{src:this.__src,alt:this.__alt,caption:this.__caption,alignment:this.__alignment,className:this.__className,style:this.__style,nodeKey:this.getKey(),width:this.__width,height:this.__height,resizable:!0,uploading:this.__uploading})}catch(e){return console.error("\u274C Error rendering ImageNode:",e),jsxs("div",{style:{color:"red",border:"1px solid red",padding:"10px",backgroundColor:"#ffe6e6"},children:["Image Error: ",String(e)]})}}};function de(a,t,e,o="none",n,r,i,s,l){if(!a||a.length===0)throw new Error("Cannot create ImageNode with empty src");return new F(a,t,e,o,n,r,i,s,l)}var tt=class extends M{constructor(){super("image",["toolbar"]);y(this,"recentImages",new Set);this.config={...this.config,resizable:true,pasteListener:{insert:true,replace:true},debug:false,forceUpload:false};}configure(e){return e.customRenderer&&(po=e.customRenderer),e.uploadHandler&&(this.config.uploadHandler=e.uploadHandler),e.defaultAlignment&&(this.config.defaultAlignment=e.defaultAlignment),e.classNames&&(this.config.classNames=e.classNames),e.styles&&(this.config.styles=e.styles),this.config.pasteListener={insert:e.pasteListener?.insert??this.config.pasteListener?.insert??true,replace:e.pasteListener?.replace??this.config.pasteListener?.replace??true},this.config.debug=e.debug??this.config.debug??false,this.config={...this.config,...e,resizable:e.resizable??true},this}register(e){let o=e.registerCommand(go,s=>(e.update(()=>{try{let l=s.src||(s.file?URL.createObjectURL(s.file):"");if(!l)throw new Error("No src for image");if(this.recentImages.has(l))return !0;this.recentImages.add(l),setTimeout(()=>this.recentImages.delete(l),1e3);let c=!1;s.file&&this.config.uploadHandler&&this.config.forceUpload&&(c=!0,this.config.uploadHandler(s.file).then(m=>{e.update(()=>{let h=$getNodeByKey(d.getKey());h instanceof F&&(h.setSrc(m),h.__uploading=!1);});}).catch(m=>{console.error("Upload failed:",m),e.update(()=>{let h=$getNodeByKey(d.getKey());h instanceof F&&(h.__uploading=!1);});}));let d=de(l,s.alt,s.caption,s.alignment||this.config.defaultAlignment||"none",s.className,s.style,void 0,void 0,c),f=$getSelection();if($isRangeSelection(f))f.insertNodes([d]);else {let m=$createParagraphNode();m.append(d),$getRoot().append(m);}}catch(l){console.error("\u274C Insertion error:",l);}}),true),COMMAND_PRIORITY_EDITOR),n=e.registerCommand(KEY_DELETE_COMMAND,()=>{let s=$getSelection();if($isNodeSelection(s)){let l=s.getNodes();if(l.some(c=>c instanceof F))return e.update(()=>{l.forEach(c=>c.remove());}),true}return false},COMMAND_PRIORITY_EDITOR),r=e.registerCommand(KEY_BACKSPACE_COMMAND,()=>{let s=$getSelection();if($isNodeSelection(s)){let l=s.getNodes();if(l.some(c=>c instanceof F))return e.update(()=>{l.forEach(c=>c.remove());}),true}return false},COMMAND_PRIORITY_EDITOR),i=()=>{};if(this.config.pasteListener?.insert||this.config.pasteListener?.replace){let s=this.config.debug?console.log:()=>{};i=e.registerCommand(PASTE_COMMAND,l=>{let c=l.clipboardData?.items;if(!c)return false;let d=false,f=Array.from(c).some(m=>m.type==="text/html");for(let m of c)if(m.type.startsWith("image/")){if(f)continue;l.preventDefault();let h=m.getAsFile();if(!h)continue;s("\u{1F4CB} Pasting image:",h.name),(this.config.uploadHandler&&this.config.forceUpload?this.config.uploadHandler(h).catch(L=>(console.error("Upload failed:",L),URL.createObjectURL(h))):Promise.resolve(URL.createObjectURL(h))).then(L=>{if(this.recentImages.has(L)){s("\u{1F6AB} Duplicate paste image src detected, skipping:",L);return}this.recentImages.add(L),setTimeout(()=>this.recentImages.delete(L),1e3);let T=false,g;this.config.uploadHandler&&this.config.forceUpload&&h&&(T=true,this.config.uploadHandler(h).then(b=>{e.update(()=>{let C=$getNodeByKey(g.getKey());C instanceof F&&(C.setSrc(b),C.__uploading=false);});}).catch(b=>{console.error("Upload failed:",b),e.update(()=>{let C=$getNodeByKey(g.getKey());C instanceof F&&(C.__uploading=false);});})),e.update(()=>{let b=$getSelection(),C=h.name||"Pasted image";if($isNodeSelection(b)&&this.config.pasteListener?.replace){let x=b.getNodes().find(I=>I instanceof F);if(x){s("\u{1F504} Replacing selected image src"),x.setSrc(L),x.__uploading=T,d=true;return}}this.config.pasteListener?.insert&&(s("\u2795 Inserting new pasted image"),g=de(L,C,void 0,"none",void 0,void 0,void 0,void 0,T),$isRangeSelection(b)?b.insertNodes([g]):$getRoot().append($createParagraphNode().append(g)),d=true);});});break}return d},COMMAND_PRIORITY_NORMAL);}return ()=>{o(),n(),r(),i();}}getNodes(){return [F]}getCommands(e){return {insertImage:o=>{e.dispatchCommand(go,o);},setImageAlignment:o=>{e.update(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();for(let i of r)i instanceof F&&i.setAlignment(o);}});},setImageCaption:o=>{e.update(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();for(let i of r)i instanceof F&&i.setCaption(o);}});},setImageClassName:o=>{e.update(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();for(let i of r)i instanceof F&&i.setClassName(o);}});},setImageStyle:o=>{e.update(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();for(let i of r)i instanceof F&&i.setStyle(o);}});}}}getStateQueries(e){return {imageSelected:()=>new Promise(o=>{e.getEditorState().read(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();o(r.length===1&&r[0]instanceof F);}else o(false);});}),isImageAlignedLeft:()=>new Promise(o=>{e.getEditorState().read(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();if(r.length===1&&r[0]instanceof F){o(r[0].__alignment==="left");return}}o(false);});}),isImageAlignedCenter:()=>new Promise(o=>{e.getEditorState().read(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();if(r.length===1&&r[0]instanceof F){o(r[0].__alignment==="center");return}}o(false);});}),isImageAlignedRight:()=>new Promise(o=>{e.getEditorState().read(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();if(r.length===1&&r[0]instanceof F){o(r[0].__alignment==="right");return}}o(false);});}),isImageAlignedNone:()=>new Promise(o=>{e.getEditorState().read(()=>{let n=$getSelection();if($isNodeSelection(n)){let r=n.getNodes();if(r.length===1&&r[0]instanceof F){o(r[0].__alignment==="none");return}}o(false);});})}}},yr=new tt,fo={dependencies:[F],export:a=>{if(!Er(a))return null;let t=a,e=t.__src||"",o=t.__alt||"",n=t.__caption||"",r=t.__alignment||"none";if(!e)return null;let i=`,i+=")",r!=="none"&&(i+=` <!-- align:${r} -->`),i},regExp:/^!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)(?:\s*<!--\s*align:(left|center|right)\s*-->)?\s*$/,replace:(a,t,e,o)=>{let[,n,r,i,s]=e;if(!r)return;let l=de(r,n||"",i||void 0,s||"none",void 0,void 0,void 0,void 0,false);a.replace(l);},type:"element"};function Er(a){return a instanceof F}function bo(a){let t=renderToStaticMarkup(a),e=document.createElement("div");e.innerHTML=t;let o=e.firstElementChild;return e.remove(),o}function _r(a){let t=a.isContainer??false,e=createCommand("insert-custom-node");function o({node:l,payload:c,nodeKey:d,children:f}){let[m]=useLexicalComposerContext(),[h,N]=useState(false);useEffect(()=>m.registerUpdateListener(({editorState:T})=>{T.read(()=>{let g=$getSelection();N($isNodeSelection(g)&&g.getNodes().some(b=>b.__key===d));});}),[m,d]);let L=T=>{m.update(()=>{let g=l.getWritable();g.__payload={...g.__payload,...T};});};return a.render?a.render({node:l,payload:c,children:f,nodeKey:d,isSelected:h,updatePayload:L}):null}class n extends ElementNode{constructor(d={},f,m){super(m);y(this,"__payload");y(this,"__nodeType");this.__payload=d,this.__nodeType=f;}static getType(){return a.nodeType}static clone(d){return new n(d.__payload,d.__nodeType,d.__key)}isSelectable(){return true}canBeEmpty(){return false}canInsertTextBefore(){return false}canInsertTextAfter(){return false}static importJSON(d){let{payload:f,children:m}=d;return new n(f,d.type)}static importDOM(){return a.importDOM?a.importDOM():{}}static exportDOM(d,{node:f}){if(a.exportDOM){let h=document.createElement("div");return a.exportDOM(d,{element:h,node:f})}let m=document.createElement("div");return m.setAttribute("data-custom-node-type",a.nodeType),{element:m}}exportJSON(){return {type:this.__nodeType,version:1,payload:this.__payload,children:this.getChildren().map(d=>d.exportJSON()),direction:null,format:"",indent:0}}createDOM(d){if(a.createDOM){let m=a.createDOM(d,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m.setAttribute("data-lexical-key",this.getKey()),m}if(a.jsx){let m=a.jsx({node:this,payload:this.__payload,nodeKey:this.getKey(),isSelected:false,updatePayload:N=>{this.setPayload(N);}}),h=bo(m);return h.setAttribute("data-custom-node-type",this.__nodeType),h.setAttribute("data-lexical-key",this.getKey()),h}let f=document.createElement("div");return f.setAttribute("data-custom-node-type",this.__nodeType),f.setAttribute("data-lexical-key",this.getKey()),f.style.border="2px solid #ccc",f.style.borderRadius="8px",f.style.padding="16px",f.style.margin="8px 0",f.style.position="relative",f}updateDOM(d,f,m){return a.updateDOM?a.updateDOM(d,f,m):false}getPayload(){return this.__payload}setPayload(d){let f=this.getWritable();f.__payload={...this.__payload,...d};}}class r extends DecoratorNode{constructor(d={},f,m){super(m);y(this,"__payload");y(this,"__nodeType");this.__payload=d,this.__nodeType=f;}static getType(){return a.nodeType}static clone(d){return new r(d.__payload,d.__nodeType,d.__key)}isSelectable(){return true}static importJSON(d){let{payload:f}=d;return new r(f,d.type)}static importDOM(){return a.importDOM?a.importDOM():{}}static exportDOM(d,{node:f}){if(a.exportDOM){let h=document.createElement("span");return a.exportDOM(d,{element:h,node:f})}let m=document.createElement("span");return m.setAttribute("data-custom-node-type",a.nodeType),{element:m}}exportJSON(){return {type:this.__nodeType,version:1,payload:this.__payload}}createDOM(d){let f=document.createElement("span");if(f.setAttribute("data-custom-node-type",this.__nodeType),a.createDOM){let m=a.createDOM(d,this);return m.setAttribute("data-custom-node-type",this.__nodeType),m}return f}updateDOM(d,f,m){return a.updateDOM?a.updateDOM(d,f,m):false}getPayload(){return this.__payload}setPayload(d){let f=this.getWritable();f.__payload={...this.__payload,...d};}decorate(){return jsx(o,{node:this,payload:this.__payload,nodeKey:this.__key,children:void 0})}}function i(l=a.defaultPayload||{}){if(t){let c=new n(l,a.nodeType);if(a.initialChildren)a.initialChildren().forEach(f=>{if(f.type==="paragraph"){let m=$createParagraphNode();f.children&&f.children.forEach(h=>{h.type==="text"&&m.append($createTextNode(h.text||""));}),c.append(m);}});else {let d=$createParagraphNode();d.append($createTextNode("")),c.append(d);}return c}else return new r(l,a.nodeType)}class s extends M{constructor(){super(a.nodeType,["toolbar"]);}register(c){let d=c.registerCommand(e,m=>(c.update(()=>{let h=i(m),N=$getSelection();$isRangeSelection(N)?N.insertNodes([h]):$getRoot().append($createParagraphNode().append(h));}),true),COMMAND_PRIORITY_EDITOR),f=c.registerUpdateListener(({editorState:m,prevEditorState:h})=>{t&&m.read(()=>{let N=$getSelection(),L=$isNodeSelection(N)?N.getNodes():[];c.getEditorState().read(()=>{let T=$getRoot(),g=b=>{if(b.getType()===a.nodeType){let C=L.some(x=>x.__key===b.__key),E=document.querySelector(`[data-lexical-key="${b.__key}"]`);E&&(E.setAttribute("data-selected",C.toString()),E.style.borderColor=C?"#007ACC":"#ccc",E.style.backgroundColor=C?"#f0f8ff":"transparent");}"getChildren"in b&&b.getChildren().forEach(g);};g(T);});});});return ()=>{d(),f();}}getNodes(){return t?[n]:[r]}getCommands(c){return {...{insertCustomNode:f=>c.dispatchCommand(e,f)},...a.commands?a.commands(c):{}}}getStateQueries(c){return {...{isCustomNodeActive:()=>new Promise(f=>{c.getEditorState().read(()=>{let m=$getSelection();f(!!m&&$isNodeSelection(m)&&m.getNodes().some(h=>h.getType()===a.nodeType));});})},...a.stateQueries?a.stateQueries(c):{}}}}return {extension:new s,$createCustomNode:i,jsxToDOM:bo}}var yo=a=>{let{contentEditable:t,placeholder:e,className:o,classNames:n,styles:r,errorBoundary:i}=a,s=n?.placeholder||se.richText?.placeholder||"luthor-placeholder",l={position:"absolute",top:0,left:0,pointerEvents:"none",color:"#999",zIndex:1,...r?.placeholder};return jsx("div",{className:n?.container||o||se.container||"luthor-editor-container",style:{position:"relative",...r?.container},children:jsx(RichTextPlugin,{contentEditable:t||jsx(ContentEditable,{className:n?.contentEditable||se.richText?.contentEditable||"luthor-content-editable",style:r?.contentEditable}),placeholder:typeof e=="string"?jsx("div",{className:s,style:l,children:e}):e||jsx("div",{className:s,style:l,children:"Start writing..."}),ErrorBoundary:i||Hr})})},Tt=class extends M{constructor(t={}){super("richText",["floating"]),this.config={showInToolbar:false,position:"after",...t};}register(t){return ()=>{}}getPlugins(){return [jsx(yo,{...this.config},"rich-text")]}},Eo=new Tt,Ir=a=>jsx(yo,{...a}),Hr=({children:a,onError:t})=>{try{return jsx(Fragment,{children:a})}catch(e){return console.error("RichTextPlugin Error:",e),t(e),jsxs("div",{className:"editor-error-boundary",children:[jsx("h3",{children:"Editor Error"}),jsx("p",{children:"Something went wrong with the editor. Please refresh the page."})]})}};var nt=class extends M{constructor(){super("floatingToolbar",["floating"]);y(this,"isVisible",false);y(this,"selectionRect",null);this.config={render:()=>null,debounceMs:100,offset:{x:0,y:8},positionStrategy:"below",theme:{container:"luthor-floating-toolbar",button:"luthor-floating-toolbar-button",buttonActive:"luthor-floating-toolbar-button-active"}};}register(e){return ()=>{}}getPlugins(){return [jsx(Wr,{extension:this,config:this.config},"floating-toolbar")]}getCommands(e){return {}}getStateQueries(e){return {isFloatingVisible:async()=>this.isVisible}}updateContext(e,o){this.config&&(this.config.commands=e,this.config.activeStates=o);}getSelectionRect(){return this.selectionRect}getIsVisible(){return this.isVisible}setVisible(e){this.isVisible=e;}setSelectionRect(e){this.selectionRect=e;}},Kr=new nt;function Wr({extension:a,config:t}){let[e]=useLexicalComposerContext(),{config:o}=Z(),[n,r]=useState(false),[i,s]=useState(null),[l,c]=useState(null),d=(N,L)=>{let T;return (...g)=>{clearTimeout(T),T=setTimeout(()=>N(()=>g),L);}},f=N=>{let L=t.offset||{y:8},T=t.positionStrategy||"below",g=window.pageXOffset||document.documentElement.scrollLeft||0,b=window.pageYOffset||document.documentElement.scrollTop||0,C=window.innerWidth,E=window.innerHeight,x=N.bottom+b+L.y;if(T==="above")x=N.top+b-L.y;else if(T==="auto"){let P=E-N.bottom;N.top;x=P>60?N.bottom+b+L.y:N.top+b-L.y;}let I=t.toolbarDimensions?.width||300,A=t.toolbarDimensions?.height||40,O=10,B=N.left+N.width/2,re=B+g,J,X=false,U=B-O,z=C-B-O,K=I/2,Y=B-K,u=B+K,S=Y<O,w=u>C-O;return !S&&!w?(J=re-K,X=false):S||U<K?(J=g+O,X=false):w||z<K?(J=g+C-I-O,X=true):(J=re-K,X=false),x-A<b?x=N.bottom+b+L.y:x+A>b+E&&(x=N.top+b-L.y-A),{x:J,y:x,width:N.width,height:N.height,top:N.top+b,left:N.left+g,bottom:N.bottom+b,right:N.right+g,positionFromRight:X}};useEffect(()=>{a.setVisible(n);},[n,a]),useEffect(()=>{let L=d(()=>{e.getEditorState().read(()=>{let b=$getSelection(),C=null,E=null;if($isRangeSelection(b)&&!b.isCollapsed()){let x=window.getSelection();x&&x.rangeCount>0&&(C=x.getRangeAt(0).getBoundingClientRect(),E=b);}else if($isNodeSelection(b)){let x=b.getNodes();if(x.length>0){let I=x[0];if(I){let A=I.getKey(),O=e.getElementByKey(A);O&&(C=O.getBoundingClientRect());}}}if(C&&C.width>0&&C.height>0){let x=f(C);s(x),c(E),r(true),a.setSelectionRect(x);}else s(null),c(null),r(false),a.setSelectionRect(null);});},t.debounceMs||100),T=e.registerUpdateListener(()=>{L();}),g=()=>{L();};return document.addEventListener("selectionchange",g),()=>{T(),document.removeEventListener("selectionchange",g);}},[e,t.debounceMs]);let m=()=>{r(false),s(null),c(null);};if(!t.render)return console.warn("FloatingToolbarExtension: No render function provided in config."),null;if(typeof document>"u")return null;let h=t.anchorElem||document.body;return createPortal(t.render({isVisible:n,selectionRect:i,selection:l,editor:e,commands:t.getCommands?.()||{},activeStates:t.getActiveStates?.()||{},hide:m,theme:o?.theme?.floatingToolbar||t.theme||{}}),h)}var rt=class extends M{constructor(){super("commandPalette",["toolbar"]);y(this,"isOpen",false);y(this,"commands",new Map);y(this,"listeners",[]);}register(e){let o=n=>{(n.metaKey||n.ctrlKey)&&n.shiftKey&&n.key==="P"&&(n.preventDefault(),this.toggleCommandPalette()),n.key==="Escape"&&this.isOpen&&this.hideCommandPalette();};return document.addEventListener("keydown",o),this.registerTableCommands(e),()=>{document.removeEventListener("keydown",o);}}getCommands(e){return {showCommandPalette:()=>this.showCommandPalette(),hideCommandPalette:()=>this.hideCommandPalette(),registerCommand:o=>this.registerCommand(o),unregisterCommand:o=>this.unregisterCommand(o)}}getStateQueries(e){return {isCommandPaletteOpen:()=>Promise.resolve(this.isOpen)}}showCommandPalette(){this.isOpen=true,this.notifyListeners();}hideCommandPalette(){this.isOpen=false,this.notifyListeners();}toggleCommandPalette(){this.isOpen=!this.isOpen,this.notifyListeners();}registerCommand(e){this.commands.set(e.id,e),this.notifyListeners();}unregisterCommand(e){this.commands.delete(e),this.notifyListeners();}registerTableCommands(e){[{id:"table.insertRowAbove",label:"Insert Row Above",category:"Table",action:()=>{console.log("Insert row above");},keywords:["table","row","insert","above"]},{id:"table.insertRowBelow",label:"Insert Row Below",category:"Table",action:()=>{console.log("Insert row below");},keywords:["table","row","insert","below"]},{id:"table.insertColumnLeft",label:"Insert Column Left",category:"Table",action:()=>{console.log("Insert column left");},keywords:["table","column","insert","left"]},{id:"table.insertColumnRight",label:"Insert Column Right",category:"Table",action:()=>{console.log("Insert column right");},keywords:["table","column","insert","right"]},{id:"table.deleteRow",label:"Delete Row",category:"Table",action:()=>{console.log("Delete row");},keywords:["table","row","delete","remove"]},{id:"table.deleteColumn",label:"Delete Column",category:"Table",action:()=>{console.log("Delete column");},keywords:["table","column","delete","remove"]}].forEach(n=>this.registerCommand(n));}notifyListeners(){let e=Array.from(this.commands.values());this.listeners.forEach(o=>o(this.isOpen,e));}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter(o=>o!==e);}}getAllCommands(){return Array.from(this.commands.values())}},Jr=new rt;var Xr=[Et,Bt,at,ct,fo];export{Xr as ALL_MARKDOWN_TRANSFORMERS,M as BaseExtension,Do as BaseProvider,Ke as BlockFormatExtension,Ne as BoldExtension,$e as CodeExtension,Qe as CodeFormatExtension,rt as CommandPaletteExtension,ke as ContextMenuExtension,ye as DraggableBlockExtension,Q as ExtensionCategory,nt as FloatingToolbarExtension,Ge as HTMLEmbedExtension,je as HTMLExtension,We as HistoryExtension,Pe as HorizontalRuleExtension,tt as ImageExtension,Te as ItalicExtension,Le as LinkExtension,Fe as ListExtension,we as MarkdownExtension,Ir as RichText,Re as StrikethroughExtension,Ie as TableExtension,V as TextFormatExtension,ve as UnderlineExtension,Un as blockFormatExtension,Ao as boldExtension,_n as codeExtension,kn as codeFormatExtension,Jr as commandPaletteExtension,lt as contextMenuExtension,_r as createCustomNodeExtension,Pt as createEditorSystem,Io as createExtension,se as defaultLuthorTheme,ao as draggableBlockExtension,Kr as floatingToolbarExtension,jn as historyExtension,tn as horizontalRuleExtension,lr as htmlEmbedExtension,or as htmlExtension,yr as imageExtension,vo as isLuthorTheme,Fo as italicExtension,jo as linkExtension,Rn as listExtension,xe as markdownExtension,To as mergeThemes,Eo as richTextExtension,Qo as strikethroughExtension,Cn as tableExtension,$o as underlineExtension,Z as useBaseEditor};
|
|
1
|
+
import {MarkdownExtension,ALL_MARKDOWN_TRANSFORMERS,ImageExtension,TableExtension,HTMLEmbedExtension,FloatingToolbarExtension,ContextMenuExtension,CommandPaletteExtension,DraggableBlockExtension,LinkExtension,createEditorSystem,boldExtension,italicExtension,underlineExtension,strikethroughExtension,horizontalRuleExtension,listExtension,historyExtension,blockFormatExtension,htmlExtension,codeExtension,codeFormatExtension,RichText}from'@lyfie/luthor-headless';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import Rt,{forwardRef,useState,useRef,useEffect,useMemo}from'react';var te={id:"blog",label:"Blog",description:"Long form publishing with media and quotes.",toolbar:["heading","bold","italic","link","image","blockquote","bulletedList","numberedList"],config:{placeholder:"Tell your story..."},css:"blog/styles.css"};var oe={id:"chat",label:"Chat",description:"Compact composer with mentions and quick formatting.",toolbar:["bold","italic","link","emoji","mention"],config:{placeholder:"Write a message..."},css:"chat/styles.css"};var re={id:"classic",label:"Classic",description:"Full featured WYSIWYG default.",toolbar:["undo","redo","bold","italic","underline","link","image","table","bulletedList","numberedList"],config:{placeholder:"Start writing..."},css:"classic/styles.css"};var ne={id:"cms",label:"CMS",description:"Structured content with validation and schema rules.",toolbar:["heading","bold","italic","link","image"],config:{placeholder:"Compose structured content..."},css:"cms/styles.css"};var ie={id:"code",label:"Code",description:"Developer focused editing with code as a first class block.",toolbar:["code","codeBlock","copy","link"],config:{placeholder:"Paste or write code..."},css:"code/styles.css"};var ae={id:"default",label:"Default",description:"Balanced general purpose editor preset.",toolbar:["heading","bold","italic","link","image","table"],config:{placeholder:"Start writing..."},css:"default/styles.css"};var le={id:"docs",label:"Docs",description:"Documentation focused with code and callouts.",toolbar:["heading","bold","italic","code","codeBlock","link"],config:{placeholder:"Write documentation..."},css:"docs/styles.css"};var se={id:"email",label:"Email",description:"Email safe markup with stricter rules.",toolbar:["bold","italic","link","button","table"],config:{placeholder:"Write an email..."},css:"email/styles.css"};function u({size:e=16,className:n,children:i}){return jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:n,"aria-hidden":"true",children:i})}function O(e){return jsxs(u,{...e,children:[jsx("path",{d:"M7 5h6a3 3 0 0 1 0 6H7z"}),jsx("path",{d:"M7 11h7a3 3 0 0 1 0 6H7z"})]})}function $(e){return jsxs(u,{...e,children:[jsx("path",{d:"M11 5h6"}),jsx("path",{d:"M7 19h6"}),jsx("path",{d:"M14 5l-4 14"})]})}function q(e){return jsxs(u,{...e,children:[jsx("path",{d:"M6 4v6a6 6 0 0 0 12 0V4"}),jsx("path",{d:"M4 20h16"})]})}function j(e){return jsxs(u,{...e,children:[jsx("path",{d:"M4 12h16"}),jsx("path",{d:"M7 5h7a3 3 0 0 1 0 6H7"}),jsx("path",{d:"M7 19h10"})]})}function Q(e){return jsxs(u,{...e,children:[jsx("path",{d:"M8 7l-4 5 4 5"}),jsx("path",{d:"M16 7l4 5-4 5"})]})}function Ee(e){return jsxs(u,{...e,children:[jsx("path",{d:"M4 6h16"}),jsx("path",{d:"M4 18h16"}),jsx("path",{d:"M9 9l-3 3 3 3"}),jsx("path",{d:"M15 9l3 3-3 3"})]})}function R(e){return jsxs(u,{...e,children:[jsx("path",{d:"M10 13a5 5 0 0 1 0-7l2-2a5 5 0 1 1 7 7l-2 2"}),jsx("path",{d:"M14 11a5 5 0 0 1 0 7l-2 2a5 5 0 1 1-7-7l2-2"})]})}function W(e){return jsxs(u,{...e,children:[jsx("path",{d:"M8 8l8 8"}),jsx("path",{d:"M10 13a5 5 0 0 1 0-7l2-2a5 5 0 0 1 7 7l-1 1"}),jsx("path",{d:"M14 11a5 5 0 0 1 0 7l-2 2a5 5 0 0 1-7-7l1-1"})]})}function V(e){return jsxs(u,{...e,children:[jsx("path",{d:"M8 6h12"}),jsx("path",{d:"M8 12h12"}),jsx("path",{d:"M8 18h12"}),jsx("circle",{cx:"4",cy:"6",r:"1"}),jsx("circle",{cx:"4",cy:"12",r:"1"}),jsx("circle",{cx:"4",cy:"18",r:"1"})]})}function Y(e){return jsxs(u,{...e,children:[jsx("path",{d:"M9 6h11"}),jsx("path",{d:"M9 12h11"}),jsx("path",{d:"M9 18h11"}),jsx("path",{d:"M4 6h1"}),jsx("path",{d:"M4 12h1"}),jsx("path",{d:"M4 18h1"})]})}function Ce(e){return jsxs(u,{...e,children:[jsx("path",{d:"M3 7v6h6"}),jsx("path",{d:"M21 17a9 9 0 0 0-9-9H3"})]})}function Me(e){return jsxs(u,{...e,children:[jsx("path",{d:"M21 7v6h-6"}),jsx("path",{d:"M3 17a9 9 0 0 1 9-9h9"})]})}function Pe(e){return jsxs(u,{...e,children:[jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),jsx("circle",{cx:"8",cy:"10",r:"2"}),jsx("path",{d:"M21 16l-5-5-4 4-2-2-5 5"})]})}function _(e){return jsxs(u,{...e,children:[jsx("path",{d:"M4 6h16"}),jsx("path",{d:"M4 12h10"}),jsx("path",{d:"M4 18h12"})]})}function N(e){return jsxs(u,{...e,children:[jsx("path",{d:"M4 6h16"}),jsx("path",{d:"M7 12h10"}),jsx("path",{d:"M6 18h12"})]})}function G(e){return jsxs(u,{...e,children:[jsx("path",{d:"M4 6h16"}),jsx("path",{d:"M10 12h10"}),jsx("path",{d:"M8 18h12"})]})}function Le(e){return jsxs(u,{...e,children:[jsx("path",{d:"M12 16V6"}),jsx("path",{d:"M8 10l4-4 4 4"}),jsx("path",{d:"M4 18h16"})]})}function Be(e){return jsx(u,{...e,children:jsx("path",{d:"M5 12h14"})})}function ze(e){return jsxs(u,{...e,children:[jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),jsx("path",{d:"M3 10h18"}),jsx("path",{d:"M9 4v16"}),jsx("path",{d:"M15 4v16"})]})}function Te(e){return jsxs(u,{...e,children:[jsx("path",{d:"M14 2H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7z"}),jsx("path",{d:"M14 2v5h5"}),jsx("path",{d:"M9 13l-2 2 2 2"}),jsx("path",{d:"M15 13l2 2-2 2"})]})}function Re(e){return jsxs(u,{...e,children:[jsx("path",{d:"M2 12s4-6 10-6 10 6 10 6-4 6-10 6-10-6-10-6"}),jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Ne(e){return jsxs(u,{...e,children:[jsx("path",{d:"M3 17l4 4"}),jsx("path",{d:"M14 3l7 7"}),jsx("path",{d:"M7 21l10-10"})]})}function Z(e){return jsxs(u,{...e,children:[jsx("path",{d:"M7 7h10v10H7z"}),jsx("path",{d:"M7 7v-2a2 2 0 1 1 4 0v2"}),jsx("path",{d:"M13 7v-2a2 2 0 1 1 4 0v2"}),jsx("path",{d:"M7 17v2a2 2 0 1 0 4 0v-2"}),jsx("path",{d:"M13 17v2a2 2 0 1 0 4 0v-2"})]})}function He(e){return jsxs(u,{...e,children:[jsx("path",{d:"M4 6h16"}),jsx("path",{d:"M12 6v12"})]})}function Ke(e){return jsxs(u,{...e,children:[jsx("path",{d:"M6 8h4v8H6z"}),jsx("path",{d:"M14 8h4v8h-4z"})]})}function Fe(e){return jsxs(u,{...e,children:[jsx("path",{d:"M4 6h16"}),jsx("path",{d:"M4 12h10"}),jsx("path",{d:"M4 18h16"}),jsx("path",{d:"M14 9l4 3-4 3"})]})}function Se(e){return jsxs(u,{...e,children:[jsx("path",{d:"M4 6h16"}),jsx("path",{d:"M4 12h10"}),jsx("path",{d:"M4 18h16"}),jsx("path",{d:"M18 9l-4 3 4 3"})]})}function Ae(e){return jsxs(u,{...e,children:[jsx("circle",{cx:"12",cy:"12",r:"4"}),jsx("path",{d:"M12 2v3"}),jsx("path",{d:"M12 19v3"}),jsx("path",{d:"M4.9 4.9l2.1 2.1"}),jsx("path",{d:"M17 17l2.1 2.1"}),jsx("path",{d:"M2 12h3"}),jsx("path",{d:"M19 12h3"}),jsx("path",{d:"M4.9 19.1L7 17"}),jsx("path",{d:"M17 7l2.1-2.1"})]})}function Ue(e){return jsx(u,{...e,children:jsx("path",{d:"M21 12.8A8 8 0 1 1 11.2 3a6 6 0 0 0 9.8 9.8z"})})}function De(e){return jsxs(u,{...e,children:[jsx("circle",{cx:"11",cy:"11",r:"7"}),jsx("path",{d:"M20 20l-3-3"})]})}function Oe(e){return jsx(u,{...e,children:jsx("path",{d:"M6 9l6 6 6-6"})})}function $e(e){return jsxs(u,{...e,children:[jsx("path",{d:"M6 6l12 12"}),jsx("path",{d:"M18 6l-12 12"})]})}function c({children:e,onClick:n,title:i,active:l,disabled:r,className:a,type:s="button"}){return jsx("button",{type:s,className:`luthor-toolbar-button${l?" active":""}${a?` ${a}`:""}`,onClick:n,title:i,disabled:r,children:e})}function ue({children:e,onClick:n,variant:i="primary",type:l="button",className:r}){return jsx("button",{type:l,onClick:n,className:`${i==="primary"?"luthor-button-primary":"luthor-button-secondary"}${r?` ${r}`:""}`,children:e})}function qe({value:e,onValueChange:n,options:i,placeholder:l="Select..."}){let[r,a]=useState(false),s=useRef(null);useEffect(()=>{function v(y){s.current&&!s.current.contains(y.target)&&a(false);}return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]);let d=i.find(v=>v.value===e);return jsxs("div",{className:"luthor-select",ref:s,children:[jsxs("button",{className:`luthor-select-trigger ${r?"open":""}`,onClick:()=>a(!r),type:"button",children:[jsx("span",{children:d?.label||l}),jsx(Oe,{size:14})]}),r&&jsx("div",{className:"luthor-select-dropdown",children:i.map(v=>jsx("button",{className:`luthor-select-option ${e===v.value?"selected":""}`,onClick:()=>{n(v.value),a(false);},type:"button",children:v.label},v.value))})]})}function pe({trigger:e,children:n,isOpen:i,onOpenChange:l}){let r=useRef(null);return useEffect(()=>{function a(s){r.current&&!r.current.contains(s.target)&&l(false);}return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[l]),jsxs("div",{className:"luthor-dropdown",ref:r,children:[jsx("div",{onClick:()=>l(!i),children:e}),i&&jsx("div",{className:"luthor-dropdown-content",children:n})]})}function je({isOpen:e,onClose:n,title:i,children:l}){let r=useRef(null);return useEffect(()=>{function a(d){r.current&&!r.current.contains(d.target)&&n();}function s(d){d.key==="Escape"&&n();}return e&&(document.addEventListener("mousedown",a),document.addEventListener("keydown",s),document.body.style.overflow="hidden"),()=>{document.removeEventListener("mousedown",a),document.removeEventListener("keydown",s),document.body.style.overflow="unset";}},[e,n]),e?jsx("div",{className:"luthor-dialog-overlay",children:jsxs("div",{className:"luthor-dialog",ref:r,children:[jsxs("div",{className:"luthor-dialog-header",children:[jsx("h3",{className:"luthor-dialog-title",children:i}),jsx("button",{className:"luthor-dialog-close",onClick:n,type:"button",children:jsx($e,{size:16})})]}),jsx("div",{className:"luthor-dialog-content",children:l})]})}):null}function We(e){let{isVisible:n,selectionRect:i,commands:l,activeStates:r}=e;if(!n||!i)return null;let a={position:"absolute",top:i.y,left:i.positionFromRight?"auto":i.x,right:i.positionFromRight?10:"auto",zIndex:9999,pointerEvents:"auto"};return r?.imageSelected?jsxs("div",{className:"luthor-floating-toolbar",style:a,children:[jsx(c,{onClick:()=>l.setImageAlignment("left"),active:r.isImageAlignedLeft,title:"Align Left",children:jsx(_,{size:14})}),jsx(c,{onClick:()=>l.setImageAlignment("center"),active:r.isImageAlignedCenter,title:"Align Center",children:jsx(N,{size:14})}),jsx(c,{onClick:()=>l.setImageAlignment("right"),active:r.isImageAlignedRight,title:"Align Right",children:jsx(G,{size:14})}),jsx("div",{className:"luthor-floating-toolbar-separator"}),jsx(c,{onClick:()=>l.setImageCaption(prompt("Enter caption:")||""),title:"Edit Caption",children:jsx(Ke,{size:14})})]}):jsxs("div",{className:"luthor-floating-toolbar",style:a,children:[jsx(c,{onClick:()=>l.toggleBold(),active:r.bold,title:"Bold",children:jsx(O,{size:14})}),jsx(c,{onClick:()=>l.toggleItalic(),active:r.italic,title:"Italic",children:jsx($,{size:14})}),jsx(c,{onClick:()=>l.toggleUnderline(),active:r.underline,title:"Underline",children:jsx(q,{size:14})}),jsx(c,{onClick:()=>l.toggleStrikethrough(),active:r.strikethrough,title:"Strikethrough",children:jsx(j,{size:14})}),jsx("div",{className:"luthor-floating-toolbar-separator"}),jsx(c,{onClick:()=>l.formatText("code"),active:r.code,title:"Inline Code",children:jsx(Q,{size:14})}),jsx(c,{onClick:()=>r.isLink?l.removeLink():l.insertLink(),active:r.isLink,title:r.isLink?"Remove Link":"Insert Link",children:r.isLink?jsx(W,{size:14}):jsx(R,{size:14})}),jsx("div",{className:"luthor-floating-toolbar-separator"}),jsx(c,{onClick:()=>l.toggleUnorderedList(),active:r.unorderedList,title:"Bullet List",children:jsx(V,{size:14})}),jsx(c,{onClick:()=>l.toggleOrderedList(),active:r.orderedList,title:"Numbered List",children:jsx(Y,{size:14})})]})}var K=new MarkdownExtension;K.config={...K.config,customTransformers:ALL_MARKDOWN_TRANSFORMERS};var F=new ImageExtension;F.config={...F.config,uploadHandler:async e=>URL.createObjectURL(e),defaultAlignment:"center",resizable:true,pasteListener:{insert:true,replace:true},debug:false};var he=new TableExtension;he.config={...he.config,enableContextMenu:true,markdownExtension:K};var me=new HTMLEmbedExtension;me.config={...me.config,markdownExtension:K};var J={commands:{},activeStates:{}};function Ve(e,n){J.commands=e,J.activeStates=n;}var ge=new FloatingToolbarExtension;ge.config={...ge.config,render:e=>jsx(We,{...e}),getCommands:()=>J.commands,getActiveStates:()=>J.activeStates};var be=new ContextMenuExtension;be.config={...be.config,preventDefault:true};var Ct=new CommandPaletteExtension,fe=new DraggableBlockExtension;fe.config={...fe.config,showMoveButtons:true,showUpButton:true,showDownButton:true,buttonStackPosition:"left"};var xe=new LinkExtension;xe.config={...xe.config,linkSelectedTextOnPaste:true,autoLinkText:true,autoLinkUrls:true};var z=[boldExtension,italicExtension,underlineExtension,strikethroughExtension,xe,horizontalRuleExtension,he,listExtension,historyExtension,F,blockFormatExtension,htmlExtension,K,codeExtension,codeFormatExtension,me,ge,be,Ct,fe];function Ye(){return [{id:"format.bold",label:"Toggle Bold",description:"Make text bold or remove bold formatting",category:"Format",action:e=>e.toggleBold(),shortcuts:[{key:"b",ctrlKey:true}],keywords:["bold","strong","format"]},{id:"format.italic",label:"Toggle Italic",description:"Make text italic or remove italic formatting",category:"Format",action:e=>e.toggleItalic(),shortcuts:[{key:"i",ctrlKey:true}],keywords:["italic","emphasis","format"]},{id:"format.underline",label:"Toggle Underline",description:"Add or remove underline formatting",category:"Format",action:e=>e.toggleUnderline(),shortcuts:[{key:"u",ctrlKey:true}],keywords:["underline","format"]},{id:"format.strikethrough",label:"Toggle Strikethrough",description:"Add or remove strikethrough formatting",category:"Format",action:e=>e.toggleStrikethrough(),keywords:["strikethrough","format"]},{id:"format.code",label:"Toggle Inline Code",description:"Format text as inline code",category:"Format",action:e=>e.formatText("code"),shortcuts:[{key:"`",ctrlKey:true}],keywords:["code","inline","format"]},{id:"block.heading1",label:"Heading 1",description:"Convert to large heading",category:"Block",action:e=>e.toggleHeading("h1"),shortcuts:[{key:"1",ctrlKey:true,altKey:true}],keywords:["heading","h1"]},{id:"block.heading2",label:"Heading 2",description:"Convert to medium heading",category:"Block",action:e=>e.toggleHeading("h2"),shortcuts:[{key:"2",ctrlKey:true,altKey:true}],keywords:["heading","h2"]},{id:"block.heading3",label:"Heading 3",description:"Convert to small heading",category:"Block",action:e=>e.toggleHeading("h3"),shortcuts:[{key:"3",ctrlKey:true,altKey:true}],keywords:["heading","h3"]},{id:"block.paragraph",label:"Paragraph",description:"Convert to paragraph",category:"Block",action:e=>e.toggleParagraph(),shortcuts:[{key:"0",ctrlKey:true,altKey:true}],keywords:["paragraph","text"]},{id:"block.quote",label:"Quote",description:"Convert to blockquote",category:"Block",action:e=>e.toggleQuote(),keywords:["quote","blockquote"]},{id:"block.codeblock",label:"Code Block",description:"Convert to code block",category:"Block",action:e=>e.toggleCodeBlock(),shortcuts:[{key:"`",ctrlKey:true,shiftKey:true}],keywords:["code","block"]},{id:"list.bullet",label:"Bullet List",description:"Create or toggle bullet list",category:"List",action:e=>e.toggleUnorderedList(),shortcuts:[{key:"l",ctrlKey:true,shiftKey:true}],keywords:["list","bullet"]},{id:"list.numbered",label:"Numbered List",description:"Create or toggle numbered list",category:"List",action:e=>e.toggleOrderedList(),shortcuts:[{key:"l",ctrlKey:true,altKey:true}],keywords:["list","numbered"]},{id:"link.insert",label:"Insert Link",description:"Insert or edit a link",category:"Insert",action:e=>e.insertLink(),shortcuts:[{key:"k",ctrlKey:true}],keywords:["link","url"]},{id:"link.remove",label:"Remove Link",description:"Remove link formatting",category:"Format",action:e=>e.removeLink(),shortcuts:[{key:"k",ctrlKey:true,shiftKey:true}],keywords:["unlink","remove","link"]},{id:"insert.horizontal-rule",label:"Insert Horizontal Rule",description:"Insert a horizontal line separator",category:"Insert",action:e=>e.insertHorizontalRule(),keywords:["horizontal","rule"]},{id:"insert.image",label:"Insert Image",description:"Insert an image from URL",category:"Insert",action:e=>{let n=prompt("Enter image URL:");if(n){let i=prompt("Enter alt text:")||"";e.insertImage({src:n,alt:i});}},keywords:["image","photo"]},{id:"insert.table",label:"Insert Table",description:"Insert a 3x3 table",category:"Insert",action:e=>e.insertTable({rows:3,columns:3,includeHeaders:true}),keywords:["table","grid"]},{id:"insert.html-embed",label:"Insert HTML Embed",description:"Insert a custom HTML block",category:"Insert",action:e=>e.insertHTMLEmbed(),keywords:["html","embed"]},{id:"edit.undo",label:"Undo",description:"Undo the last action",category:"Edit",action:e=>e.undo(),shortcuts:[{key:"z",ctrlKey:true}],keywords:["undo","revert"]},{id:"edit.redo",label:"Redo",description:"Redo the last undone action",category:"Edit",action:e=>e.redo(),shortcuts:[{key:"y",ctrlKey:true},{key:"z",ctrlKey:true,shiftKey:true}],keywords:["redo","repeat"]},{id:"palette.show",label:"Show Command Palette",description:"Open the command palette",category:"View",action:e=>e.showCommandPalette(),shortcuts:[{key:"p",ctrlKey:true,shiftKey:true}],keywords:["command","palette"]}]}function _e(e){return Ye().map(n=>({id:n.id,label:n.label,description:n.description,category:n.category,action:()=>n.action(e),keywords:n.keywords,shortcut:n.shortcuts?.[0]?Pt(n.shortcuts[0]):void 0}))}function Pt(e){let n=[];return e.ctrlKey&&n.push("Ctrl"),e.metaKey&&n.push("Cmd"),e.altKey&&n.push("Alt"),e.shiftKey&&n.push("Shift"),n.push(e.key.toUpperCase()),n.join("+")}function Ge(e,n=document.body){let i=Ye(),l=r=>{for(let a of i)if(a.shortcuts){for(let s of a.shortcuts)if(r.key.toLowerCase()===s.key.toLowerCase()&&!!r.ctrlKey==!!s.ctrlKey&&!!r.metaKey==!!s.metaKey&&!!r.shiftKey==!!s.shiftKey&&!!r.altKey==!!s.altKey){s.preventDefault!==false&&r.preventDefault(),(!a.condition||a.condition(e))&&a.action(e);return}}};return n.addEventListener("keydown",l),()=>n.removeEventListener("keydown",l)}function zt(e,n){let i=useRef(null),l=F.config;return {handlers:useMemo(()=>({insertFromUrl:()=>{let a=prompt("Enter image URL:");if(!a)return;let s=prompt("Enter alt text:")||"",d=prompt("Enter caption (optional):")||void 0;e.insertImage({src:a,alt:s,caption:d});},insertFromFile:()=>i.current?.click(),handleUpload:async a=>{let s=a.target.files?.[0];if(!s)return;let d;if(l.uploadHandler)try{d=await l.uploadHandler(s);}catch{alert("Failed to upload image");return}else d=URL.createObjectURL(s);e.insertImage({src:d,alt:s.name,file:s}),a.target.value="";},setAlignment:a=>{e.setImageAlignment(a);},setCaption:()=>{let a=prompt("Enter caption:")||"";e.setImageCaption(a);}}),[e,l]),fileInputRef:i}}function Je({commands:e,hasExtension:n,activeStates:i,isDark:l,toggleTheme:r,onCommandPaletteOpen:a,editor:s}){let{handlers:d,fileInputRef:v}=zt(e),[y,w]=useState(false),[h,f]=useState(false),[k,L]=useState(false),[P,B]=useState({rows:3,columns:3,includeHeaders:false}),D=[{value:"p",label:"Paragraph"},{value:"h1",label:"Heading 1"},{value:"h2",label:"Heading 2"},{value:"h3",label:"Heading 3"},{value:"h4",label:"Heading 4"},{value:"h5",label:"Heading 5"},{value:"h6",label:"Heading 6"},{value:"quote",label:"Quote"}],we=i.isH1?"h1":i.isH2?"h2":i.isH3?"h3":i.isH4?"h4":i.isH5?"h5":i.isH6?"h6":i.isQuote?"quote":"p",b=m=>{m==="p"?e.toggleParagraph():m.startsWith("h")?e.toggleHeading(m):m==="quote"&&e.toggleQuote();};return jsxs(Fragment,{children:[jsxs("div",{className:"luthor-toolbar",children:[jsxs("div",{className:"luthor-toolbar-section",children:[jsx(c,{onClick:()=>e.toggleBold(),active:i.bold,title:"Bold (Ctrl+B)",children:jsx(O,{size:16})}),jsx(c,{onClick:()=>e.toggleItalic(),active:i.italic,title:"Italic (Ctrl+I)",children:jsx($,{size:16})}),jsx(c,{onClick:()=>e.toggleUnderline(),active:i.underline,title:"Underline (Ctrl+U)",children:jsx(q,{size:16})}),jsx(c,{onClick:()=>e.toggleStrikethrough(),active:i.strikethrough,title:"Strikethrough",children:jsx(j,{size:16})}),jsx(c,{onClick:()=>e.formatText("code"),active:i.code,title:"Inline Code",children:jsx(Q,{size:16})}),jsx(c,{onClick:()=>i.isLink?e.removeLink():e.insertLink(),active:i.isLink,title:i.isLink?"Remove Link":"Insert Link",children:i.isLink?jsx(W,{size:16}):jsx(R,{size:16})})]}),n("blockFormat")&&jsxs("div",{className:"luthor-toolbar-section",children:[jsx(qe,{value:we,onValueChange:b,options:D,placeholder:"Format"}),n("code")&&jsx(c,{onClick:()=>e.toggleCodeBlock(),active:i.isInCodeBlock,title:"Code Block",children:jsx(Ee,{size:16})})]}),n("list")&&jsxs("div",{className:"luthor-toolbar-section",children:[jsx(c,{onClick:()=>e.toggleUnorderedList(),active:i.unorderedList,title:"Bullet List",children:jsx(V,{size:16})}),jsx(c,{onClick:()=>e.toggleOrderedList(),active:i.orderedList,title:"Numbered List",children:jsx(Y,{size:16})}),(i.unorderedList||i.orderedList)&&jsxs(Fragment,{children:[jsx(c,{onClick:()=>e.indentList(),title:"Indent List",children:jsx(Fe,{size:14})}),jsx(c,{onClick:()=>e.outdentList(),title:"Outdent List",children:jsx(Se,{size:14})})]})]}),n("horizontalRule")&&jsx("div",{className:"luthor-toolbar-section",children:jsx(c,{onClick:()=>e.insertHorizontalRule(),title:"Insert Horizontal Rule",children:jsx(Be,{size:16})})}),n("table")&&jsx("div",{className:"luthor-toolbar-section",children:jsx(c,{onClick:()=>L(true),title:"Insert Table",children:jsx(ze,{size:16})})}),n("image")&&jsxs("div",{className:"luthor-toolbar-section",children:[jsxs(pe,{trigger:jsx("button",{className:`luthor-toolbar-button ${i.imageSelected?"active":""}`,title:"Insert Image",children:jsx(Pe,{size:16})}),isOpen:y,onOpenChange:w,children:[jsxs("button",{className:"luthor-dropdown-item",onClick:()=>{d.insertFromUrl(),w(false);},children:[jsx(R,{size:16}),jsx("span",{children:"From URL"})]}),jsxs("button",{className:"luthor-dropdown-item",onClick:()=>{d.insertFromFile(),w(false);},children:[jsx(Le,{size:16}),jsx("span",{children:"Upload File"})]})]}),i.imageSelected&&jsxs(pe,{trigger:jsx("button",{className:"luthor-toolbar-button",title:"Align Image",children:jsx(N,{size:16})}),isOpen:h,onOpenChange:f,children:[jsxs("button",{className:"luthor-dropdown-item",onClick:()=>{d.setAlignment("left"),f(false);},children:[jsx(_,{size:16}),jsx("span",{children:"Align Left"})]}),jsxs("button",{className:"luthor-dropdown-item",onClick:()=>{d.setAlignment("center"),f(false);},children:[jsx(N,{size:16}),jsx("span",{children:"Align Center"})]}),jsxs("button",{className:"luthor-dropdown-item",onClick:()=>{d.setAlignment("right"),f(false);},children:[jsx(G,{size:16}),jsx("span",{children:"Align Right"})]}),jsxs("button",{className:"luthor-dropdown-item",onClick:()=>{d.setCaption(),f(false);},children:[jsx(He,{size:16}),jsx("span",{children:"Set Caption"})]})]}),jsx("input",{ref:v,type:"file",accept:"image/*",onChange:d.handleUpload,className:"luthor-file-input"})]}),n("htmlEmbed")&&jsxs("div",{className:"luthor-toolbar-section",children:[jsx(c,{onClick:()=>e.insertHTMLEmbed(),active:i.isHTMLEmbedSelected,title:"Insert HTML Embed",children:jsx(Te,{size:16})}),i.isHTMLEmbedSelected&&jsx(c,{onClick:()=>e.toggleHTMLPreview(),title:"Toggle Preview/Edit",children:i.isHTMLPreviewMode?jsx(Re,{size:16}):jsx(Ne,{size:16})})]}),n("history")&&jsxs("div",{className:"luthor-toolbar-section",children:[jsx(c,{onClick:()=>e.undo(),disabled:!i.canUndo,title:"Undo (Ctrl+Z)",children:jsx(Ce,{size:16})}),jsx(c,{onClick:()=>e.redo(),disabled:!i.canRedo,title:"Redo (Ctrl+Y)",children:jsx(Me,{size:16})})]}),jsx("div",{className:"luthor-toolbar-section",children:jsx(c,{onClick:a,title:"Command Palette (Ctrl+Shift+P)",children:jsx(Z,{size:16})})}),jsx("div",{className:"luthor-toolbar-section",children:jsx(c,{onClick:r,title:l?"Light Mode":"Dark Mode",children:l?jsx(Ae,{size:16}):jsx(Ue,{size:16})})})]}),jsx(je,{isOpen:k,onClose:()=>L(false),title:"Insert Table",children:jsxs("div",{className:"luthor-table-dialog",children:[jsxs("div",{className:"luthor-form-group",children:[jsx("label",{htmlFor:"table-rows",children:"Rows:"}),jsx("input",{id:"table-rows",type:"number",min:"1",max:"20",value:P.rows,onChange:m=>B(I=>({...I,rows:parseInt(m.target.value)||1})),className:"luthor-input"})]}),jsxs("div",{className:"luthor-form-group",children:[jsx("label",{htmlFor:"table-columns",children:"Columns:"}),jsx("input",{id:"table-columns",type:"number",min:"1",max:"20",value:P.columns,onChange:m=>B(I=>({...I,columns:parseInt(m.target.value)||1})),className:"luthor-input"})]}),jsx("div",{className:"luthor-form-group",children:jsxs("label",{className:"luthor-checkbox-label",children:[jsx("input",{type:"checkbox",checked:P.includeHeaders||false,onChange:m=>B(I=>({...I,includeHeaders:m.target.checked})),className:"luthor-checkbox"}),"Include headers"]})}),jsxs("div",{className:"luthor-dialog-actions",children:[jsx(ue,{variant:"secondary",onClick:()=>L(false),children:"Cancel"}),jsx(ue,{variant:"primary",onClick:()=>{e.insertTable(P),L(false);},children:"Insert Table"})]})]})})]})}function et({isOpen:e,onClose:n,commands:i}){let[l,r]=useState(""),[a,s]=useState(0),d=useRef(null),v=i.filter(h=>`${h.label} ${h.description||""} ${h.keywords?.join(" ")||""}`.toLowerCase().includes(l.toLowerCase())),y=v.reduce((h,f)=>{let k=f.category||"Other";return h[k]||(h[k]=[]),h[k].push(f),h},{}),w=v;return useEffect(()=>{s(0);},[l]),useEffect(()=>{e&&d.current&&(d.current.focus(),r(""),s(0));},[e]),useEffect(()=>{let h=f=>{if(e)switch(f.key){case "Escape":f.preventDefault(),n();break;case "ArrowDown":f.preventDefault(),s(k=>Math.min(k+1,w.length-1));break;case "ArrowUp":f.preventDefault(),s(k=>Math.max(k-1,0));break;case "Enter":f.preventDefault(),w[a]&&(w[a].action(),n());break}};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[e,a,w,n]),e?jsx("div",{className:"luthor-command-palette-overlay",onClick:n,children:jsxs("div",{className:"luthor-command-palette",onClick:h=>h.stopPropagation(),children:[jsxs("div",{className:"luthor-command-palette-header",children:[jsx(De,{size:16,className:"luthor-command-palette-icon"}),jsx("input",{ref:d,type:"text",placeholder:"Type a command or search...",value:l,onChange:h=>r(h.target.value),className:"luthor-command-palette-input"}),jsx("kbd",{className:"luthor-command-palette-kbd",children:"ESC"})]}),jsx("div",{className:"luthor-command-palette-list",children:Object.keys(y).length===0?jsx("div",{className:"luthor-command-palette-empty",children:"No commands found"}):Object.entries(y).map(([h,f])=>jsxs("div",{className:"luthor-command-palette-group",children:[jsx("div",{className:"luthor-command-palette-group-title",children:h}),f.map(k=>{let L=w.indexOf(k);return jsxs("div",{className:`luthor-command-palette-item ${L===a?"selected":""}`,onClick:()=>{k.action(),n();},onMouseEnter:()=>s(L),children:[jsxs("div",{className:"luthor-command-palette-item-content",children:[jsx("div",{className:"luthor-command-palette-item-title",children:k.label}),k.description&&jsx("div",{className:"luthor-command-palette-item-description",children:k.description})]}),k.shortcut&&jsx("kbd",{className:"luthor-command-palette-item-shortcut",children:k.shortcut})]},k.id)})]},h))}),jsx("div",{className:"luthor-command-palette-footer",children:jsxs("span",{className:"luthor-command-palette-hint",children:[jsx(Z,{size:14}),jsx("span",{children:"Use arrow keys, Enter, ESC"})]})})]})}):null}var{Provider:St,useEditor:At}=createEditorSystem();function Ut({mode:e,onModeChange:n}){return jsxs("div",{className:"luthor-mode-tabs",children:[jsx("button",{className:`luthor-mode-tab ${e==="visual"?"active":""}`,onClick:()=>n("visual"),children:"Visual"}),jsx("button",{className:`luthor-mode-tab ${e==="html"?"active":""}`,onClick:()=>n("html"),children:"HTML"}),jsx("button",{className:`luthor-mode-tab ${e==="markdown"?"active":""}`,onClick:()=>n("markdown"),children:"Markdown"})]})}function ot({value:e,onChange:n,placeholder:i}){return jsx("textarea",{className:"luthor-source-view",value:e,onChange:l=>n(l.target.value),placeholder:i,spellCheck:false})}function Dt({className:e,isDark:n,toggleTheme:i,onReady:l}){let{commands:r,hasExtension:a,activeStates:s,lexical:d,extensions:v}=At(),[y,w]=useState("visual"),[h,f]=useState({html:"",markdown:""}),[k,L]=useState({isOpen:false,commands:[]}),P=useRef(r),B=useRef(false);useEffect(()=>{P.current=r;},[r]),useEffect(()=>{Ve(r,s);},[r,s]);let D=useMemo(()=>({injectMarkdown:b=>{setTimeout(()=>{d&&d.update(()=>{P.current.importFromMarkdown(b,{immediate:true,preventFocus:true});});},100);},injectHTML:b=>{setTimeout(()=>{d&&d.update(()=>{P.current.importFromHTML(b,{preventFocus:true});});},100);},getMarkdown:()=>P.current.exportToMarkdown(),getHTML:()=>P.current.exportToHTML()}),[d]);return useEffect(()=>{if(!d||!r)return;let b=_e(r);b.forEach(I=>r.registerCommand(I));let m=Ge(r,document.body);return B.current||(B.current=true,l?.(D)),()=>{m(),b.forEach(I=>r.unregisterCommand(I.id));}},[d,r,D,l]),useEffect(()=>{let b=v.find(m=>m.name==="commandPalette");if(!(!b||!b.subscribe))return b.subscribe((m,I)=>{L({isOpen:m,commands:I});})},[v]),jsxs(Fragment,{children:[jsxs("div",{className:"luthor-editor-header",children:[jsx(Ut,{mode:y,onModeChange:async b=>{if(y==="markdown"&&b!=="markdown"&&a("markdown")&&(await r.importFromMarkdown(h.markdown,{immediate:true}),await new Promise(m=>setTimeout(m,50))),y==="html"&&b!=="html"&&a("html")&&(await r.importFromHTML(h.html),await new Promise(m=>setTimeout(m,50))),b==="markdown"&&y!=="markdown"&&a("markdown")){await new Promise(I=>setTimeout(I,50));let m=r.exportToMarkdown();f(I=>({...I,markdown:m}));}if(b==="html"&&y!=="html"&&a("html")){await new Promise(I=>setTimeout(I,50));let m=r.exportToHTML();f(I=>({...I,html:m}));}w(b),b==="visual"&&setTimeout(()=>d?.focus(),100);}}),y==="visual"&&jsx(Je,{commands:r,hasExtension:a,activeStates:s,isDark:n,toggleTheme:i,onCommandPaletteOpen:()=>r.showCommandPalette(),editor:d})]}),jsxs("div",{className:"luthor-editor","data-mode":y,children:[y==="visual"&&jsx(RichText,{placeholder:"Write anything...",classNames:{container:"luthor-richtext-container",contentEditable:"luthor-content-editable",placeholder:"luthor-placeholder"}}),y!=="visual"&&jsxs("div",{className:"luthor-source-panel",children:[y==="html"&&jsx(ot,{value:h.html,onChange:b=>f(m=>({...m,html:b})),placeholder:"Enter HTML content..."}),y==="markdown"&&jsx(ot,{value:h.markdown,onChange:b=>f(m=>({...m,markdown:b})),placeholder:"Enter Markdown content..."})]})]}),jsx(et,{isOpen:k.isOpen,onClose:()=>r.hideCommandPalette(),commands:k.commands})]})}var U=forwardRef(({className:e,onReady:n,initialTheme:i="light"},l)=>{let[r,a]=useState(i),s=r==="dark",d=()=>a(s?"light":"dark"),[v,y]=useState(null);Rt.useImperativeHandle(l,()=>v,[v]);let w=h=>{y(h),n?.(h);};return jsx("div",{className:`luthor-editor-wrapper ${e||""}`,"data-editor-theme":r,children:jsx(St,{extensions:z,children:jsx(Dt,{className:e,isDark:s,toggleTheme:d,onReady:w})})})});U.displayName="ExtensiveEditor";var ke={id:"extensive",label:"Extensive",description:"All features enabled for power users.",extensions:[...z],components:{Editor:U},toolbar:["undo","redo","heading","bold","italic","underline","strikethrough","link","image","table","blockquote","code","codeBlock","bulletedList","numberedList"],config:{placeholder:"Write anything..."},css:"extensive/styles.css"};var ye={id:"markdown",label:"Markdown",description:"Markdown first editing with predictable output.",toolbar:["bold","italic","link","code","codeBlock"],config:{placeholder:"Write in markdown..."},css:"markdown/styles.css"};var Ie={id:"minimal",label:"Minimal",description:"Lightweight editor for short text and embeds.",toolbar:["bold","italic","link"],config:{placeholder:"Write something..."},css:"minimal/styles.css"};var wr={minimal:Ie,classic:re,docs:le,blog:te,cms:ne,chat:oe,email:se,markdown:ye,code:ie,default:ae,extensive:ke};export{U as ExtensiveEditor,te as blogPreset,oe as chatPreset,re as classicPreset,ne as cmsPreset,ie as codePreset,ae as defaultPreset,le as docsPreset,se as emailPreset,z as extensiveExtensions,ke as extensivePreset,ye as markdownPreset,Ie as minimalPreset,wr as presetRegistry};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lyfie/luthor",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "Luthor
|
|
3
|
+
"version": "2.0.1",
|
|
4
|
+
"description": "Luthor presets and plug-and-play configuration for the headless editor",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"private": false,
|
|
7
7
|
"main": "./dist/index.js",
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"react",
|
|
22
22
|
"typescript",
|
|
23
23
|
"wysiwyg",
|
|
24
|
-
"
|
|
24
|
+
"presets"
|
|
25
25
|
],
|
|
26
26
|
"author": "Luthor Team",
|
|
27
27
|
"license": "MIT",
|
|
@@ -33,6 +33,9 @@
|
|
|
33
33
|
"url": "https://github.com/lyfie-app/luthor/issues"
|
|
34
34
|
},
|
|
35
35
|
"homepage": "https://github.com/lyfie-app/luthor#readme",
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@lyfie/luthor-headless": "2.0.0"
|
|
38
|
+
},
|
|
36
39
|
"devDependencies": {
|
|
37
40
|
"@types/node": "^20.19.9",
|
|
38
41
|
"@types/react": "^19.1.1",
|
|
@@ -40,8 +43,8 @@
|
|
|
40
43
|
"eslint": "^9.32.0",
|
|
41
44
|
"tsup": "^8.0.0",
|
|
42
45
|
"typescript": "^5.7.3",
|
|
43
|
-
"@repo/
|
|
44
|
-
"@repo/
|
|
46
|
+
"@repo/typescript-config": "0.0.0",
|
|
47
|
+
"@repo/eslint-config": "0.0.0"
|
|
45
48
|
},
|
|
46
49
|
"peerDependencies": {
|
|
47
50
|
"@lexical/code": ">=0.34.0",
|