UNPKG

dz-rich-text-editor

Version:

A comprehensive React rich text editor component with image upload, resize functionality, and standalone CSS. Ready for NPM publishing.

59 lines 53 kB
(function(i,be){typeof exports=="object"&&typeof module<"u"?module.exports=be(require("react")):typeof define=="function"&&define.amd?define(["react"],be):(i=typeof globalThis<"u"?globalThis:i||self,i.DZRichTextEditor=be(i.React))})(this,function(i){"use strict";var be={exports:{}},Ye={};/**
 * @license React
 * react-jsx-runtime.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var Pt;function Ot(){if(Pt)return Ye;Pt=1;var M=i,j=Symbol.for("react.element"),$=Symbol.for("react.fragment"),_=Object.prototype.hasOwnProperty,D=M.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,ee={key:!0,ref:!0,__self:!0,__source:!0};function W(N,x,B){var L,P={},V=null,g=null;B!==void 0&&(V=""+B),x.key!==void 0&&(V=""+x.key),x.ref!==void 0&&(g=x.ref);for(L in x)_.call(x,L)&&!ee.hasOwnProperty(L)&&(P[L]=x[L]);if(N&&N.defaultProps)for(L in x=N.defaultProps,x)P[L]===void 0&&(P[L]=x[L]);return{$$typeof:j,type:N,key:V,ref:g,props:P,_owner:D.current}}return Ye.Fragment=$,Ye.jsx=W,Ye.jsxs=W,Ye}var Ve={};/**
 * @license React
 * react-jsx-runtime.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var zt;function Mt(){return zt||(zt=1,process.env.NODE_ENV!=="production"&&function(){var M=i,j=Symbol.for("react.element"),$=Symbol.for("react.portal"),_=Symbol.for("react.fragment"),D=Symbol.for("react.strict_mode"),ee=Symbol.for("react.profiler"),W=Symbol.for("react.provider"),N=Symbol.for("react.context"),x=Symbol.for("react.forward_ref"),B=Symbol.for("react.suspense"),L=Symbol.for("react.suspense_list"),P=Symbol.for("react.memo"),V=Symbol.for("react.lazy"),g=Symbol.for("react.offscreen"),Re=Symbol.iterator,Xe="@@iterator";function xt(t){if(t===null||typeof t!="object")return null;var s=Re&&t[Re]||t[Xe];return typeof s=="function"?s:null}var ce=M.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function E(t){{for(var s=arguments.length,o=new Array(s>1?s-1:0),u=1;u<s;u++)o[u-1]=arguments[u];Je("error",t,o)}}function Je(t,s,o){{var u=ce.ReactDebugCurrentFrame,b=u.getStackAddendum();b!==""&&(s+="%s",o=o.concat([b]));var v=o.map(function(p){return String(p)});v.unshift("Warning: "+s),Function.prototype.apply.call(console[t],console,v)}}var Ne=!1,Ke=!1,Ge=!1,Le=!1,dt=!1,te;te=Symbol.for("react.module.reference");function wt(t){return!!(typeof t=="string"||typeof t=="function"||t===_||t===ee||dt||t===D||t===B||t===L||Le||t===g||Ne||Ke||Ge||typeof t=="object"&&t!==null&&(t.$$typeof===V||t.$$typeof===P||t.$$typeof===W||t.$$typeof===N||t.$$typeof===x||t.$$typeof===te||t.getModuleId!==void 0))}function Ae(t,s,o){var u=t.displayName;if(u)return u;var b=s.displayName||s.name||"";return b!==""?o+"("+b+")":o}function De(t){return t.displayName||"Context"}function I(t){if(t==null)return null;if(typeof t.tag=="number"&&E("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case _:return"Fragment";case $:return"Portal";case ee:return"Profiler";case D:return"StrictMode";case B:return"Suspense";case L:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case N:var s=t;return De(s)+".Consumer";case W:var o=t;return De(o._context)+".Provider";case x:return Ae(t,t.render,"ForwardRef");case P:var u=t.displayName||null;return u!==null?u:I(t.type)||"Memo";case V:{var b=t,v=b._payload,p=b._init;try{return I(p(v))}catch{return null}}}return null}var re=Object.assign,ae=0,_e,Ze,ut,Pe,ve,ft,ye;function mt(){}mt.__reactDisabledLog=!0;function Qe(){{if(ae===0){_e=console.log,Ze=console.info,ut=console.warn,Pe=console.error,ve=console.group,ft=console.groupCollapsed,ye=console.groupEnd;var t={configurable:!0,enumerable:!0,value:mt,writable:!0};Object.defineProperties(console,{info:t,log:t,warn:t,error:t,group:t,groupCollapsed:t,groupEnd:t})}ae++}}function qe(){{if(ae--,ae===0){var t={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:re({},t,{value:_e}),info:re({},t,{value:Ze}),warn:re({},t,{value:ut}),error:re({},t,{value:Pe}),group:re({},t,{value:ve}),groupCollapsed:re({},t,{value:ft}),groupEnd:re({},t,{value:ye})})}ae<0&&E("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var H=ce.ReactCurrentDispatcher,$e;function ze(t,s,o){{if($e===void 0)try{throw Error()}catch(b){var u=b.stack.trim().match(/\n( *(at )?)/);$e=u&&u[1]||""}return`
`+$e+t}}var Be=!1,K;{var Ie=typeof WeakMap=="function"?WeakMap:Map;K=new Ie}function St(t,s){if(!t||Be)return"";{var o=K.get(t);if(o!==void 0)return o}var u;Be=!0;var b=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var v;v=H.current,H.current=null,Qe();try{if(s){var p=function(){throw Error()};if(Object.defineProperty(p.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(p,[])}catch(k){u=k}Reflect.construct(t,[],p)}else{try{p.call()}catch(k){u=k}t.call(p.prototype)}}else{try{throw Error()}catch(k){u=k}t()}}catch(k){if(k&&u&&typeof k.stack=="string"){for(var m=k.stack.split(`
`),R=u.stack.split(`
`),w=m.length-1,C=R.length-1;w>=1&&C>=0&&m[w]!==R[C];)C--;for(;w>=1&&C>=0;w--,C--)if(m[w]!==R[C]){if(w!==1||C!==1)do if(w--,C--,C<0||m[w]!==R[C]){var A=`
`+m[w].replace(" at new "," at ");return t.displayName&&A.includes("<anonymous>")&&(A=A.replace("<anonymous>",t.displayName)),typeof t=="function"&&K.set(t,A),A}while(w>=1&&C>=0);break}}}finally{Be=!1,H.current=v,qe(),Error.prepareStackTrace=b}var G=t?t.displayName||t.name:"",X=G?ze(G):"";return typeof t=="function"&&K.set(t,X),X}function He(t,s,o){return St(t,!1)}function z(t){var s=t.prototype;return!!(s&&s.isReactComponent)}function ne(t,s,o){if(t==null)return"";if(typeof t=="function")return St(t,z(t));if(typeof t=="string")return ze(t);switch(t){case B:return ze("Suspense");case L:return ze("SuspenseList")}if(typeof t=="object")switch(t.$$typeof){case x:return He(t.render);case P:return ne(t.type,s,o);case V:{var u=t,b=u._payload,v=u._init;try{return ne(v(b),s,o)}catch{}}}return""}var F=Object.prototype.hasOwnProperty,Oe={},xe=ce.ReactDebugCurrentFrame;function le(t){if(t){var s=t._owner,o=ne(t.type,t._source,s?s.type:null);xe.setExtraStackFrame(o)}else xe.setExtraStackFrame(null)}function se(t,s,o,u,b){{var v=Function.call.bind(F);for(var p in t)if(v(t,p)){var m=void 0;try{if(typeof t[p]!="function"){var R=Error((u||"React class")+": "+o+" type `"+p+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof t[p]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw R.name="Invariant Violation",R}m=t[p](s,p,u,o,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(w){m=w}m&&!(m instanceof Error)&&(le(b),E("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",u||"React class",o,p,typeof m),le(null)),m instanceof Error&&!(m.message in Oe)&&(Oe[m.message]=!0,le(b),E("Failed %s type: %s",o,m.message),le(null))}}}var Me=Array.isArray;function et(t){return Me(t)}function de(t){{var s=typeof Symbol=="function"&&Symbol.toStringTag,o=s&&t[Symbol.toStringTag]||t.constructor.name||"Object";return o}}function pt(t){try{return oe(t),!1}catch{return!0}}function oe(t){return""+t}function tt(t){if(pt(t))return E("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",de(t)),oe(t)}var ue=ce.ReactCurrentOwner,Bt={key:!0,ref:!0,__self:!0,__source:!0},rt,Ct,We;We={};function kt(t){if(F.call(t,"ref")){var s=Object.getOwnPropertyDescriptor(t,"ref").get;if(s&&s.isReactWarning)return!1}return t.ref!==void 0}function Fe(t){if(F.call(t,"key")){var s=Object.getOwnPropertyDescriptor(t,"key").get;if(s&&s.isReactWarning)return!1}return t.key!==void 0}function at(t,s){if(typeof t.ref=="string"&&ue.current&&s&&ue.current.stateNode!==s){var o=I(ue.current.type);We[o]||(E('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',I(ue.current.type),t.ref),We[o]=!0)}}function jt(t,s){{var o=function(){rt||(rt=!0,E("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",s))};o.isReactWarning=!0,Object.defineProperty(t,"key",{get:o,configurable:!0})}}function U(t,s){{var o=function(){Ct||(Ct=!0,E("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",s))};o.isReactWarning=!0,Object.defineProperty(t,"ref",{get:o,configurable:!0})}}var Et=function(t,s,o,u,b,v,p){var m={$$typeof:j,type:t,key:s,ref:o,props:p,_owner:v};return m._store={},Object.defineProperty(m._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(m,"_self",{configurable:!1,enumerable:!1,writable:!1,value:u}),Object.defineProperty(m,"_source",{configurable:!1,enumerable:!1,writable:!1,value:b}),Object.freeze&&(Object.freeze(m.props),Object.freeze(m)),m};function fe(t,s,o,u,b){{var v,p={},m=null,R=null;o!==void 0&&(tt(o),m=""+o),Fe(s)&&(tt(s.key),m=""+s.key),kt(s)&&(R=s.ref,at(s,b));for(v in s)F.call(s,v)&&!Bt.hasOwnProperty(v)&&(p[v]=s[v]);if(t&&t.defaultProps){var w=t.defaultProps;for(v in w)p[v]===void 0&&(p[v]=w[v])}if(m||R){var C=typeof t=="function"?t.displayName||t.name||"Unknown":t;m&&jt(p,C),R&&U(p,C)}return Et(t,m,R,b,u,ue.current,p)}}var nt=ce.ReactCurrentOwner,lt=ce.ReactDebugCurrentFrame;function me(t){if(t){var s=t._owner,o=ne(t.type,t._source,s?s.type:null);lt.setExtraStackFrame(o)}else lt.setExtraStackFrame(null)}var S;S=!1;function we(t){return typeof t=="object"&&t!==null&&t.$$typeof===j}function pe(){{if(nt.current){var t=I(nt.current.type);if(t)return`

Check the render method of \``+t+"`."}return""}}function st(t){{if(t!==void 0){var s=t.fileName.replace(/^.*[\\\/]/,""),o=t.lineNumber;return`

Check your code at `+s+":"+o+"."}return""}}var Se={};function Ue(t){{var s=pe();if(!s){var o=typeof t=="string"?t:t.displayName||t.name;o&&(s=`

Check the top-level render call using <`+o+">.")}return s}}function Ce(t,s){{if(!t._store||t._store.validated||t.key!=null)return;t._store.validated=!0;var o=Ue(s);if(Se[o])return;Se[o]=!0;var u="";t&&t._owner&&t._owner!==nt.current&&(u=" It was passed a child from "+I(t._owner.type)+"."),me(t),E('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',o,u),me(null)}}function he(t,s){{if(typeof t!="object")return;if(et(t))for(var o=0;o<t.length;o++){var u=t[o];we(u)&&Ce(u,s)}else if(we(t))t._store&&(t._store.validated=!0);else if(t){var b=xt(t);if(typeof b=="function"&&b!==t.entries)for(var v=b.call(t),p;!(p=v.next()).done;)we(p.value)&&Ce(p.value,s)}}}function ot(t){{var s=t.type;if(s==null||typeof s=="string")return;var o;if(typeof s=="function")o=s.propTypes;else if(typeof s=="object"&&(s.$$typeof===x||s.$$typeof===P))o=s.propTypes;else return;if(o){var u=I(s);se(o,t.props,"prop",u,t)}else if(s.PropTypes!==void 0&&!S){S=!0;var b=I(s);E("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",b||"Unknown")}typeof s.getDefaultProps=="function"&&!s.getDefaultProps.isReactClassApproved&&E("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function y(t){{for(var s=Object.keys(t.props),o=0;o<s.length;o++){var u=s[o];if(u!=="children"&&u!=="key"){me(t),E("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",u),me(null);break}}t.ref!==null&&(me(t),E("Invalid attribute `ref` supplied to `React.Fragment`."),me(null))}}var O={};function ht(t,s,o,u,b,v){{var p=wt(t);if(!p){var m="";(t===void 0||typeof t=="object"&&t!==null&&Object.keys(t).length===0)&&(m+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var R=st(b);R?m+=R:m+=pe();var w;t===null?w="null":et(t)?w="array":t!==void 0&&t.$$typeof===j?(w="<"+(I(t.type)||"Unknown")+" />",m=" Did you accidentally export a JSX literal instead of a component?"):w=typeof t,E("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",w,m)}var C=fe(t,s,o,b,v);if(C==null)return C;if(p){var A=s.children;if(A!==void 0)if(u)if(et(A)){for(var G=0;G<A.length;G++)he(A[G],t);Object.freeze&&Object.freeze(A)}else E("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else he(A,t)}if(F.call(s,"key")){var X=I(t),k=Object.keys(s).filter(function(At){return At!=="key"}),it=k.length>0?"{key: someKey, "+k.join(": ..., ")+": ...}":"{key: someKey}";if(!O[X+it]){var J=k.length>0?"{"+k.join(": ..., ")+": ...}":"{}";E(`A props object containing a "key" prop is being spread into JSX:
  let props = %s;
  <%s {...props} />
React keys must be passed directly to JSX without using spread:
  let props = %s;
  <%s key={someKey} {...props} />`,it,X,J,X),O[X+it]=!0}}return t===_?y(C):ot(C),C}}function Tt(t,s,o){return ht(t,s,o,!0)}function Rt(t,s,o){return ht(t,s,o,!1)}var Nt=Rt,Lt=Tt;Ve.Fragment=_,Ve.jsx=Nt,Ve.jsxs=Lt}()),Ve}process.env.NODE_ENV==="production"?be.exports=Ot():be.exports=Mt();var a=be.exports;const yt=async(M,j={})=>{var $;if(!M)throw new Error("No file provided for upload.");try{const{uploadApiUrl:_="~/upload",clientId:D="00",clientSecret:ee="00"}=j;if(!_)throw new Error("Upload API URL is required in configuration");const W=new FormData;W.append("image",M),D&&W.append("client_id",D),ee&&W.append("client_secret",ee);const N=await fetch(_,{method:"POST",body:W,headers:{accept:"application/json"}});if(!N.ok)throw new Error(`Upload failed: ${N.status} ${N.statusText}`);const B=($=(await N.json()).data)==null?void 0:$.authenticatedUrl;if(!B)throw new Error("No authenticatedUrl received from server");return B}catch(_){throw console.error("Upload failed:",_),_}};return({value:M="",onChange:j,toolbarOptions:$=["bold","italic","underline","strikethrough","highlight","fontColor","headings","fontFamily","lineSpacing","alignLeft","alignCenter","alignRight","alignJustify","unorderedList","orderedList","todoList","increaseIndent","decreaseIndent","link","insertImage","blockquote","codeBlock","pageBreak","caseChange","insertTable"],placeholder:_="Start typing...",readOnly:D=!1,height:ee="h-64",width:W="w-full",toolbarPosition:N="top",stickyToolbar:x=!1,stickyOffset:B=0,debounceTime:L=300,customClasses:P={},uploadConfig:V={}})=>{const g=i.useRef(null),Re=i.useRef(null),Xe=i.useRef(null),[xt,ce]=i.useState({}),[E,Je]=i.useState(!1),[Ne,Ke]=i.useState(""),[Ge,Le]=i.useState(""),[dt,te]=i.useState(null),[wt,Ae]=i.useState(!1),[De,I]=i.useState("#000000"),[re,ae]=i.useState(!1),[_e,Ze]=i.useState("#ffff00"),[ut,Pe]=i.useState(!1),[ve,ft]=i.useState(3),[ye,mt]=i.useState(3),[Qe,qe]=i.useState({}),[H,$e]=i.useState(!1),[ze,Be]=i.useState(0),[K,Ie]=i.useState(!1),[St,He]=i.useState(null),[z,ne]=i.useState(null),[F,Oe]=i.useState(null),[xe,le]=i.useState({x:0,y:0}),[se,Me]=i.useState(null),[et,de]=i.useState(!1),pt=i.useRef(null),oe=i.useRef(!1),[tt,ue]=i.useState(null),[Bt,rt]=i.useState(!1),[Ct,We]=i.useState(null),[kt,Fe]=i.useState(!1),[at,jt]=i.useState(null),[U,Et]=i.useState(null),[fe,nt]=i.useState([]),[lt,me]=i.useState({x:0,y:0}),[S,we]=i.useState({tableBackground:"#ffffff",tableBorderColor:"#cccccc",tableBorderWidth:"1",tableBorderStyle:"solid",tableAlignment:"left",cellPadding:"8",cellSpacing:"0",cellBackground:"#ffffff",cellTextAlign:"left",cellVerticalAlign:"middle",cellBorderColor:"#cccccc",cellBorderWidth:"1",cellBorderStyle:"solid"}),pe=i.useRef(null),st=i.useCallback(e=>{pe.current&&clearTimeout(pe.current),pe.current=setTimeout(()=>{j==null||j(e)},L)},[j,L]),Se={wrapper:`editor-wrapper ${W}`,toolbar:"editor-toolbar",contentArea:`editor-content ${ee}`,button:"toolbar-btn"},Ue={wrapper:`${Se.wrapper} ${P.wrapper||""}`,toolbar:`${Se.toolbar} ${P.toolbar||""} ${x?"editor-toolbar-sticky":""}`,contentArea:`${Se.contentArea} ${P.contentArea||""}`,button:`${Se.button} ${P.button||""}`};i.useEffect(()=>{if(!x||!Re.current||!Xe.current)return;const e=Re.current,n=Xe.current;Be(e.offsetHeight);const r=()=>{const f=n.getBoundingClientRect().top<=B;f!==H&&$e(f)},l=()=>{Be(e.offsetHeight)};return window.addEventListener("scroll",r),window.addEventListener("resize",l),r(),()=>{window.removeEventListener("scroll",r),window.removeEventListener("resize",l)}},[x,B,H]);const Ce=()=>{const e=window.getSelection();e.rangeCount>0&&te(e.getRangeAt(0).cloneRange())},he=()=>{if(dt){const e=window.getSelection();e.removeAllRanges(),e.addRange(dt)}},ot=()=>{const e={};$.forEach(n=>{switch(n){case"bold":e.bold=document.queryCommandState("bold");break;case"italic":e.italic=document.queryCommandState("italic");break;case"underline":e.underline=document.queryCommandState("underline");break;case"strikethrough":e.strikethrough=document.queryCommandState("strikeThrough");break;case"unorderedList":e.unorderedList=document.queryCommandState("insertUnorderedList");break;case"orderedList":e.orderedList=document.queryCommandState("insertOrderedList");break}}),ce(e)},y=(e,n=null)=>{var r;D||((r=g.current)==null||r.focus(),document.execCommand(e,!1,n),ot(),J())},O=(e,n=null)=>{if(!D)switch(e){case"bold":y("bold");break;case"italic":y("italic");break;case"underline":y("underline");break;case"strikethrough":y("strikeThrough");break;case"highlight":n?y("hiliteColor",n):(ae(!0),Ce());break;case"fontColor":n?y("foreColor",n):(Ae(!0),Ce());break;case"alignLeft":y("justifyLeft");break;case"alignCenter":y("justifyCenter");break;case"alignRight":y("justifyRight");break;case"alignJustify":y("justifyFull");break;case"unorderedList":y("insertUnorderedList");break;case"orderedList":y("insertOrderedList");break;case"todoList":Rt();break;case"increaseIndent":y("indent");break;case"decreaseIndent":y("outdent");break;case"blockquote":y("formatBlock","<blockquote>");break;case"codeBlock":y("formatBlock","<pre>");break;case"pageBreak":Nt();break;case"caseChange":Lt();break;case"insertTable":Pe(!0),Ce();break;case"lineSpacing":break;case"link":ht();break;case"insertImage":nr();break}},ht=()=>{const e=window.getSelection();e.toString()?(Le(e.toString()),Ce(),Je(!0)):alert("Please select text to create a link")},Tt=()=>{Ne&&Ge&&(he(),y("createLink",Ne)),Je(!1),Ke(""),Le(""),te(null)},Rt=()=>{y("insertHTML",`
      <ul style="list-style: none; padding-left: 0;">
        <li style="margin: 8px 0;">
          <input type="checkbox" style="margin-right: 8px;" /> Todo item 1
        </li>
        <li style="margin: 8px 0;">
          <input type="checkbox" style="margin-right: 8px;" /> Todo item 2
        </li>
      </ul>
    `)},Nt=()=>{y("insertHTML",'<div style="page-break-after: always; border-bottom: 2px dashed #ccc; margin: 20px 0; padding-bottom: 20px;"><br></div>')},Lt=()=>{const e=window.getSelection();if(e.toString()){const n=e.toString();let r;n===n.toUpperCase()?r=n.toLowerCase():n===n.toLowerCase()?r=n.replace(/\w\S*/g,l=>l.charAt(0).toUpperCase()+l.substr(1).toLowerCase()):r=n.toUpperCase(),y("insertText",r)}},t=e=>{e==="p"?y("formatBlock","<p>"):y("formatBlock",`<${e}>`)},s=e=>{y("fontName",e)},o=e=>{const n=window.getSelection(),r=n.rangeCount>0?n.getRangeAt(0):null;if(r&&!r.collapsed){const l=document.createElement("span");l.style.lineHeight=e.lineHeight,l.style.marginBottom=e.paragraphSpacing,l.style.display="block";try{r.surroundContents(l)}catch{const f=r.extractContents();l.appendChild(f),r.insertNode(l)}}else{const l=g.current;l&&(l.style.lineHeight=e.lineHeight,l.querySelectorAll("p, div, h1, h2, h3, h4, h5, h6").forEach(f=>{f.style.marginBottom=e.paragraphSpacing}))}J()},u=e=>{he(),y("foreColor",e),Ae(!1),I(e),te(null)},b=()=>{he(),document.execCommand("removeFormat",!1,"foreColor"),Ae(!1),te(null)},v=e=>{he(),y("hiliteColor",e),ae(!1),Ze(e),te(null)},p=()=>{let n=`<table id="${`table_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}" class="resizable-table" style="border-collapse: collapse; width: 100%; margin: 10px 0; position: relative;"><tbody>`;for(let r=0;r<ve;r++){n+="<tr>";for(let l=0;l<ye;l++)n+='<td style="border: 1px solid #ccc; padding: 8px; min-width: 100px; min-height: 30px; position: relative;">&nbsp;</td>';n+="</tr>"}n+="</tbody></table>",he(),y("insertHTML",n),Pe(!1),te(null),setTimeout(()=>{m()},100)},m=()=>{if(!g.current)return;g.current.querySelectorAll("table").forEach(r=>{r.classList.contains("resizable-table")||(r.classList.add("resizable-table"),r.style.position||(r.style.position="relative"))}),g.current.querySelectorAll("table.resizable-table").forEach(r=>{r.querySelectorAll(".resize-handle").forEach(c=>c.remove());const l=document.createElement("div");l.className="resize-handle table-resize-handle",l.title="Drag to resize table",l.addEventListener("mousedown",c=>R(c,r)),r.appendChild(l);const d=r.querySelector("tr");if(d){const c=d.querySelectorAll("td, th");c.forEach((T,Y)=>{if(Y<c.length-1){const h=document.createElement("div");h.className="resize-handle column-resize-handle",h.title="Drag to resize column",h.addEventListener("mousedown",Z=>w(Z,r,Y)),T.appendChild(h)}})}const f=r.querySelectorAll("tr");f.forEach((c,T)=>{if(T<f.length-1){const Y=c.querySelector("td, th");if(Y){const h=document.createElement("div");h.className="resize-handle row-resize-handle",h.title="Drag to resize row",h.addEventListener("mousedown",Z=>C(Z,r,T)),Y.appendChild(h)}}})})},R=(e,n)=>{e.preventDefault(),e.stopPropagation();const r=n.getBoundingClientRect();Ie(!0),He("table"),ne(n),le({x:e.clientX,y:e.clientY}),Me({width:r.width,height:r.height}),n.classList.add("resizing"),document.body.classList.add("resizing"),document.addEventListener("mousemove",A),document.addEventListener("mouseup",k),document.body.style.cursor="nw-resize"},w=(e,n,r)=>{e.preventDefault(),e.stopPropagation();const l=Array.from(n.querySelectorAll("tr")).map(d=>d.querySelectorAll("td, th")[r]).filter(Boolean);Ie(!0),He("column"),ne(n),Oe({columnIndex:r,cells:l}),le({x:e.clientX,y:e.clientY}),Me({width:l[0]?l[0].getBoundingClientRect().width:100}),n.classList.add("resizing"),document.body.classList.add("resizing"),document.addEventListener("mousemove",G),document.addEventListener("mouseup",k),document.body.style.cursor="col-resize"},C=(e,n,r)=>{e.preventDefault(),e.stopPropagation();const l=n.querySelectorAll("tr")[r];l&&(Ie(!0),He("row"),ne(n),Oe({rowIndex:r,row:l}),le({x:e.clientX,y:e.clientY}),Me({height:l.getBoundingClientRect().height}),n.classList.add("resizing"),document.body.classList.add("resizing"),document.addEventListener("mousemove",X),document.addEventListener("mouseup",k),document.body.style.cursor="row-resize")},A=e=>{if(!K||!z||!se)return;const n=e.clientX-xe.x,r=e.clientY-xe.y,l=Math.max(200,se.width+n),d=Math.max(100,se.height+r);z.style.width=`${l}px`,z.style.height=`${d}px`,z.style.transform="scale(1.02)",z.style.transition="none"},G=e=>{if(!K||!F||!se)return;const n=e.clientX-xe.x,r=Math.max(50,se.width+n);F.cells.forEach(l=>{l&&(l.style.width=`${r}px`,l.style.minWidth=`${r}px`,l.style.maxWidth=`${r}px`)})},X=e=>{if(!K||!F||!se)return;const n=e.clientY-xe.y,r=Math.max(30,se.height+n);F.row&&(F.row.style.height=`${r}px`,F.row.querySelectorAll("td, th").forEach(d=>{d.style.height=`${r}px`,d.style.minHeight=`${r}px`}))},k=()=>{z&&(z.classList.remove("resizing"),z.classList.add("resize-complete"),z.style.transform="",z.style.transition="",setTimeout(()=>{z&&z.classList.remove("resize-complete")},600)),document.body.classList.remove("resizing"),Ie(!1),He(null),ne(null),Oe(null),le({x:0,y:0}),Me(null),document.removeEventListener("mousemove",A),document.removeEventListener("mousemove",G),document.removeEventListener("mousemove",X),document.removeEventListener("mouseup",k),document.body.style.cursor="default",J()};i.useEffect(()=>()=>{document.removeEventListener("mousemove",A),document.removeEventListener("mousemove",G),document.removeEventListener("mousemove",X),document.removeEventListener("mouseup",k)},[]),i.useEffect(()=>{g.current&&setTimeout(()=>{m()},100)},[M]);const it=e=>{const n=document.createElement("div");return n.innerHTML=e,n.querySelectorAll(".image-resize-wrapper").forEach(f=>{const c=f.querySelector("img");c&&(c.removeAttribute("data-resize-enabled"),c.removeAttribute("data-original-cursor"),c.style.cursor==="pointer"&&c.style.removeProperty("cursor"),f.parentNode.insertBefore(c,f)),f.remove()}),n.querySelectorAll("img").forEach(f=>{f.removeAttribute("data-resize-enabled"),f.removeAttribute("data-original-cursor"),f.style.cursor==="pointer"&&f.style.removeProperty("cursor")}),n.querySelectorAll(".resize-handle").forEach(f=>f.remove()),n.innerHTML},J=()=>{if(g.current){const e=g.current.innerHTML;if(oe.current){st(e);return}if(e.includes("image-resize-wrapper")||e.includes("resize-handle")){const r=it(e);st(r)}else st(e)}},At=()=>{oe.current=!0,J(),ot(),setTimeout(()=>{m()},50),setTimeout(()=>{oe.current=!1},100)},Wt=e=>{if(D){e.preventDefault();return}if(e.key==="Tab"){e.preventDefault(),e.shiftKey?O("decreaseIndent"):O("increaseIndent");return}if(e.ctrlKey||e.metaKey)switch(e.key){case"b":e.preventDefault(),O("bold");break;case"i":e.preventDefault(),O("italic");break;case"u":e.preventDefault(),O("underline");break;case"l":e.preventDefault(),O("alignLeft");break;case"e":e.preventDefault(),O("alignCenter");break;case"r":e.preventDefault(),O("alignRight");break;case"j":e.preventDefault(),O("alignJustify");break;case"1":e.preventDefault(),o(gt[0]);break;case"2":e.preventDefault(),o(gt[3]);break;case"5":e.preventDefault(),o(gt[2]);break}};i.useEffect(()=>{if(g.current&&M!==g.current.innerHTML){const e=oe.current;oe.current=!1,g.current.innerHTML=M,oe.current=e}},[M]),i.useEffect(()=>{const e=()=>{document.activeElement===g.current&&ot()};return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[]),i.useEffect(()=>()=>{pe.current&&clearTimeout(pe.current)},[]),i.useEffect(()=>{const e=n=>{if(!Object.values(Qe).some(f=>f))return;const l=document.querySelectorAll(".dropdown-container");let d=!0;l.forEach(f=>{f.contains(n.target)&&(d=!1)}),d&&qe({})};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[Qe]),i.useEffect(()=>{const e=r=>{K||tr(r)},n=r=>{const l=document.querySelector(".table-style-menu"),d=l&&l.contains(r.target),f=r.target.closest("table.resizable-table");!d&&!f&&Fe(!1)};return g.current&&g.current.addEventListener("click",e),document.addEventListener("click",n),()=>{g.current&&g.current.removeEventListener("click",e),document.removeEventListener("click",n)}},[K]);const Ft={bold:{label:"B",title:"Bold (Ctrl+B)",className:"font-bold"},italic:{label:"I",title:"Italic (Ctrl+I)",className:"italic"},underline:{label:"U",title:"Underline (Ctrl+U)",className:"underline"},strikethrough:{label:"S",title:"Strikethrough",className:"line-through"},highlight:{label:"🖍️",title:"Highlight Text",className:""},fontColor:{label:"🎨",title:"Font Color",className:""},headings:{label:"H",title:"Headings",className:"font-bold",isDropdown:!0},fontFamily:{label:"Font",title:"Font Family",className:"",isDropdown:!0},lineSpacing:{label:"⫽",title:"Line & Paragraph Spacing (Ctrl+1/2/5)",className:"",isDropdown:!0},alignLeft:{label:"⬅️",title:"Align Left",className:""},alignCenter:{label:"⬆️",title:"Align Center",className:""},alignRight:{label:"➡️",title:"Align Right",className:""},alignJustify:{label:"↔️",title:"Justify",className:""},unorderedList:{label:"•",title:"Bullet List",className:"",isDropdown:!0},orderedList:{label:"1.",title:"Numbered List",className:""},todoList:{label:"☑️",title:"Todo List",className:""},increaseIndent:{label:"→",title:"Increase Indent",className:""},decreaseIndent:{label:"←",title:"Decrease Indent",className:""},link:{label:"🔗",title:"Insert Link",className:""},insertImage:{label:"🖼️",title:"Insert Image",className:""},blockquote:{label:"❝",title:"Quote",className:""},codeBlock:{label:"<>",title:"Code Block",className:"font-mono"},pageBreak:{label:"📄",title:"Page Break",className:""},caseChange:{label:"Aa",title:"Change Case",className:""},insertTable:{label:"⊞",title:"Insert Table",className:""}},Ut=[{value:"p",label:"Normal"},{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"}],Yt=[{value:"Arial",label:"Arial"},{value:"Georgia",label:"Georgia"},{value:"Times New Roman",label:"Times New Roman"},{value:"Courier New",label:"Courier New"},{value:"Verdana",label:"Verdana"},{value:"Helvetica",label:"Helvetica"}],gt=[{value:"1.0",label:"Single (1.0)",lineHeight:"1.0",paragraphSpacing:"0"},{value:"1.15",label:"1.15",lineHeight:"1.15",paragraphSpacing:"0.2em"},{value:"1.5",label:"1.5",lineHeight:"1.5",paragraphSpacing:"0.5em"},{value:"2.0",label:"Double (2.0)",lineHeight:"2.0",paragraphSpacing:"1em"},{value:"2.5",label:"2.5",lineHeight:"2.5",paragraphSpacing:"1.2em"},{value:"3.0",label:"Triple (3.0)",lineHeight:"3.0",paragraphSpacing:"1.5em"}],Vt=["#000000","#333333","#666666","#999999","#cccccc","#ffffff","#ff0000","#ff9900","#ffff00","#00ff00","#0099ff","#6600ff","#ff00ff","#ff3366","#33ff99","#3366ff","#9933ff","#ff6633"],Xt=["#ffff00","#ffcc00","#ff9900","#ff6600","#ff3300","#ff0066","#ff00cc","#cc00ff","#6600ff","#0066ff","#00ccff","#00ffcc","#00ff66","#66ff00","#ccff00","#ffff66","#ffcccc","#ccffcc"],Jt=[{value:"disc",label:"● Disc"},{value:"circle",label:"○ Circle"},{value:"square",label:"■ Square"}],Kt=e=>{const n=Ft[e];if(!n)return null;if(n.isDropdown)return Zt(e,n);const r=xt[e],l=`${Ue.button} ${n.className} ${r?"toolbar-btn-active":""}`;return a.jsx("button",{type:"button",className:l,title:n.title,onClick:()=>O(e),disabled:D,children:n.label},e)},[Gt,bt]=i.useState({headings:"Normal",fontFamily:"Arial",lineSpacing:"Single (1.0)",unorderedList:"● Disc"}),Zt=(e,n)=>{const r=Qe[e]||!1,l=()=>{qe(c=>({...c,[e]:!r}))},d=()=>{qe(c=>({...c,[e]:!1}))},f=()=>Gt[e]||n.label;return a.jsxs("div",{className:"dropdown-container wide-dropdown",children:[a.jsxs("button",{type:"button",className:`dropdown-trigger ${r?"active":""}`,title:n.title,onClick:l,disabled:D,style:{minWidth:"120px",justifyContent:"space-between"},children:[a.jsx("span",{children:f()}),a.jsx("span",{className:"dropdown-arrow",children:"▼"})]}),r&&a.jsxs("div",{className:"dropdown-menu",style:{minWidth:"120px"},children:[e==="headings"&&Ut.map(c=>a.jsx("button",{type:"button",className:"dropdown-item",onClick:()=>{t(c.value),bt(T=>({...T,headings:c.label})),d()},style:{fontFamily:(c.value==="h1","inherit"),fontSize:c.value==="h1"?"1.1rem":c.value==="h2"?"1.05rem":c.value==="h3"?"1rem":"0.875rem",fontWeight:c.value.startsWith("h")?"600":"400"},children:c.label},c.value)),e==="fontFamily"&&Yt.map(c=>a.jsx("button",{type:"button",className:"dropdown-item font-preview",style:{"--font-family":c.value,fontFamily:c.value},onClick:()=>{s(c.value),bt(T=>({...T,fontFamily:c.label})),d()},children:c.label},c.value)),e==="lineSpacing"&&gt.map(c=>a.jsx("button",{type:"button",className:"dropdown-item",onClick:()=>{o(c),bt(T=>({...T,lineSpacing:c.label})),d()},children:a.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[a.jsx("span",{children:c.label}),a.jsx("span",{style:{fontSize:"0.75rem",opacity:.6},children:c.lineHeight})]})},c.value)),e==="unorderedList"&&Jt.map(c=>a.jsx("button",{type:"button",className:"dropdown-item",onClick:()=>{mr(c.value),bt(T=>({...T,unorderedList:c.label})),d()},children:c.label},c.value))]})]},e)},It=()=>a.jsx("div",{ref:Re,className:Ue.toolbar,style:{position:x&&H?"fixed":"relative",top:x&&H?`${B}px`:"auto",left:x&&H?"0":"auto",right:x&&H?"0":"auto",zIndex:x&&H?"1000":"auto",width:x&&H?"100%":"auto",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)"},children:$.map(e=>Kt(e))}),Qt=()=>E?a.jsx("div",{className:"modal-backdrop",children:a.jsxs("div",{className:"compact-modal",children:[a.jsx("h3",{children:"🔗 Insert Link"}),a.jsxs("div",{className:"compact-form",children:[a.jsx("input",{type:"text",value:Ge,onChange:e=>Le(e.target.value),className:"compact-input",placeholder:"Link text",autoFocus:!0}),a.jsx("input",{type:"url",value:Ne,onChange:e=>Ke(e.target.value),className:"compact-input",placeholder:"https://example.com"})]}),a.jsxs("div",{className:"compact-actions",children:[a.jsx("button",{type:"button",onClick:()=>{Je(!1),Ke(""),Le("")},className:"btn-compact-secondary",children:"Cancel"}),a.jsx("button",{type:"button",onClick:Tt,className:"btn-compact-primary",disabled:!Ne||!Ge,children:"Insert"})]})]})}):null,qt=()=>wt?a.jsx("div",{className:"modal-backdrop",children:a.jsxs("div",{className:"compact-modal color-modal",children:[a.jsx("h3",{children:"🎨 Text Color"}),a.jsxs("div",{className:"compact-color-section",children:[a.jsx("div",{className:"compact-color-grid",children:Vt.slice(0,12).map(e=>a.jsx("button",{type:"button",className:`compact-color-btn ${De===e?"selected":""}`,style:{backgroundColor:e},onClick:()=>u(e),title:e},e))}),a.jsxs("div",{className:"compact-custom-color",children:[a.jsx("input",{type:"color",value:De,onChange:e=>I(e.target.value),className:"compact-color-input"}),a.jsx("button",{type:"button",onClick:()=>u(De),className:"btn-compact-accent",children:"Apply"})]})]}),a.jsxs("div",{className:"compact-actions",children:[a.jsx("button",{type:"button",onClick:b,className:"btn-compact-danger",children:"Remove Text Color"}),a.jsx("button",{type:"button",onClick:()=>Ae(!1),className:"btn-compact-secondary",children:"Cancel"})]})]})}):null,$t=()=>re?a.jsx("div",{className:"modal-backdrop",children:a.jsxs("div",{className:"compact-modal color-modal",children:[a.jsx("h3",{children:"🖍️ Highlight"}),a.jsxs("div",{className:"compact-color-section",children:[a.jsx("div",{className:"compact-color-grid",children:Xt.slice(0,12).map(e=>a.jsx("button",{type:"button",className:`compact-color-btn ${_e===e?"selected":""}`,style:{backgroundColor:e},onClick:()=>v(e),title:e},e))}),a.jsxs("div",{className:"compact-custom-color",children:[a.jsx("input",{type:"color",value:_e,onChange:e=>Ze(e.target.value),className:"compact-color-input"}),a.jsx("button",{type:"button",onClick:()=>v(_e),className:"btn-compact-accent",children:"Apply"})]})]}),a.jsxs("div",{className:"compact-actions",children:[a.jsx("button",{type:"button",onClick:()=>v("transparent"),className:"btn-compact-danger",children:"Remove Highlight"}),a.jsx("button",{type:"button",onClick:()=>ae(!1),className:"btn-compact-secondary",children:"Cancel"})]})]})}):null,er=()=>ut?a.jsx("div",{className:"modal-backdrop",children:a.jsxs("div",{className:"compact-modal table-modal",children:[a.jsx("h3",{children:"⊞ Insert Table"}),a.jsxs("div",{className:"compact-table-controls",children:[a.jsxs("div",{className:"table-dimension-control",children:[a.jsx("label",{children:"Rows"}),a.jsx("input",{type:"number",min:"1",max:"10",value:ve,onChange:e=>ft(parseInt(e.target.value)||1),className:"compact-number-input"})]}),a.jsxs("div",{className:"table-dimension-control",children:[a.jsx("label",{children:"Columns"}),a.jsx("input",{type:"number",min:"1",max:"10",value:ye,onChange:e=>mt(parseInt(e.target.value)||1),className:"compact-number-input"})]})]}),a.jsxs("div",{className:"table-preview",children:[ve," × ",ye," table"]}),a.jsxs("div",{className:"compact-actions",children:[a.jsx("button",{type:"button",onClick:()=>Pe(!1),className:"btn-compact-secondary",children:"Cancel"}),a.jsx("button",{type:"button",onClick:p,className:"btn-compact-primary",disabled:ve<1||ye<1,children:"Insert"})]})]})}):null,tr=e=>{const n=e.target,r=n.closest("table"),l=n.closest("td, th");if(r&&r.classList.contains("resizable-table")){let d="table",f=r,c=[];if(l){d="cell",f=l,c=[l];const ct=window.getSelection();if(ct.rangeCount>0){const Te=ct.getRangeAt(0),Q=[];if(Te.startContainer!==Te.endContainer){const ie=Te.commonAncestorContainer;ie.nodeType===Node.ELEMENT_NODE&&(ie.querySelectorAll("td, th").forEach(q=>{Te.intersectsNode(q)&&Q.push(q)}),Q.length>1&&(c=Q))}}}jt(f),Et(d),nt(c);const T=rr(f,d);we(T);const Y=f.getBoundingClientRect(),h={x:Y.right+10,y:Y.top},Z={width:window.innerWidth,height:window.innerHeight};h.x+320>Z.width&&(h.x=Y.left-330),h.y+400>Z.height&&(h.y=Math.max(10,Z.height-410)),me(h),Fe(!0)}else Fe(!1)},rr=(e,n)=>{const r={...S};if(n==="table"){const l=window.getComputedStyle(e);r.tableBackground=vt(l.backgroundColor)||"#ffffff",r.tableBorderColor=vt(l.borderColor)||"#cccccc",r.tableBorderWidth=l.borderWidth.replace("px","")||"1",r.tableBorderStyle=l.borderStyle||"solid",r.tableAlignment=l.marginLeft==="auto"&&l.marginRight==="auto"?"center":l.marginRight==="auto"?"left":"right"}else if(n==="cell"){const l=window.getComputedStyle(e);r.cellBackground=vt(l.backgroundColor)||"#ffffff",r.cellTextAlign=l.textAlign||"left",r.cellVerticalAlign=l.verticalAlign||"middle",r.cellBorderColor=vt(l.borderColor)||"#cccccc",r.cellBorderWidth=l.borderWidth.replace("px","")||"1",r.cellBorderStyle=l.borderStyle||"solid",r.cellPadding=l.padding.replace("px","")||"8"}return r},vt=e=>{if(!e||e==="rgba(0, 0, 0, 0)"||e==="transparent")return"#ffffff";const n=e.match(/\d+/g);if(!n)return"#ffffff";const r=parseInt(n[0]),l=parseInt(n[1]),d=parseInt(n[2]);return"#"+((1<<24)+(r<<16)+(l<<8)+d).toString(16).slice(1)},ke=(e,n)=>{if(!at||U!=="table")return;const r=at;switch(e){case"tableBackground":r.style.backgroundColor=n;break;case"tableBorderColor":r.style.borderColor=n;break;case"tableBorderWidth":r.style.borderWidth=`${n}px`;break;case"tableBorderStyle":r.style.borderStyle=n;break;case"tableAlignment":n==="center"?(r.style.marginLeft="auto",r.style.marginRight="auto"):n==="right"?(r.style.marginLeft="auto",r.style.marginRight="0"):(r.style.marginLeft="0",r.style.marginRight="auto");break;case"cellPadding":r.querySelectorAll("td, th").forEach(d=>{d.style.padding=`${n}px`});break;case"cellSpacing":r.style.borderSpacing=`${n}px`;break}we(l=>({...l,[e]:n})),J()},je=(e,n)=>{fe.length!==0&&(fe.forEach(r=>{switch(e){case"cellBackground":r.style.backgroundColor=n;break;case"cellTextAlign":r.style.textAlign=n;break;case"cellVerticalAlign":r.style.verticalAlign=n;break;case"cellBorderColor":r.style.borderColor=n;break;case"cellBorderWidth":r.style.borderWidth=`${n}px`;break;case"cellBorderStyle":r.style.borderStyle=n;break;case"cellPadding":r.style.padding=`${n}px`;break}}),we(r=>({...r,[e]:n})),J())},ar=()=>{if(!kt||!at)return null;const e=U==="table",n=U==="cell"||U==="row"||U==="column";return a.jsx("div",{className:"table-style-menu",style:{position:"fixed",left:`${lt.x}px`,top:`${lt.y}px`,zIndex:1e3},children:a.jsxs("div",{className:"table-style-panel",children:[a.jsxs("div",{className:"table-style-header",children:[a.jsx("h3",{children:e?"📊 Table Styles":U==="row"?"📏 Row Styles":U==="column"?"📋 Column Styles":"🔲 Cell Styles"}),a.jsx("button",{className:"table-style-close",onClick:()=>Fe(!1),title:"Close",children:"✕"})]}),a.jsxs("div",{className:"table-style-content",children:[e&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"style-section",children:[a.jsx("h4",{children:"🎨 Table Appearance"}),a.jsxs("div",{className:"style-row",children:[a.jsx("label",{children:"Background:"}),a.jsx("input",{type:"color",value:S.tableBackground,onChange:r=>ke("tableBackground",r.target.value),className:"color-input"})]}),a.jsxs("div",{className:"style-row",children:[a.jsx("label",{children:"Alignment:"}),a.jsxs("select",{value:S.tableAlignment,onChange:r=>ke("tableAlignment",r.target.value),className:"style-select",children:[a.jsx("option",{value:"left",children:"Left"}),a.jsx("option",{value:"center",children:"Center"}),a.jsx("option",{value:"right",children:"Right"})]})]})]}),a.jsxs("div",{className:"style-section",children:[a.jsx("h4",{children:"🔲 Border & Spacing"}),a.jsxs("div",{className:"style-row",children:[a.jsx("label",{children:"Border Color:"}),a.jsx("input",{type:"color",value:S.tableBorderColor,onChange:r=>ke("tableBorderColor",r.target.value),className:"color-input"})]}),a.jsxs("div",{className:"style-row",children:[a.jsx("label",{children:"Border Width:"}),a.jsxs("select",{value:S.tableBorderWidth,onChange:r=>ke("tableBorderWidth",r.target.value),className:"style-select",children:[a.jsx("option",{value:"0",children:"None"}),a.jsx("option",{value:"1",children:"Thin (1px)"}),a.jsx("option",{value:"2",children:"Medium (2px)"}),a.jsx("option",{value:"3",children:"Thick (3px)"}),a.jsx("option",{value:"4",children:"Extra Thick (4px)"})]})]}),a.jsxs("div",{className:"style-row",children:[a.jsx("label",{children:"Border Style:"}),a.jsxs("select",{value:S.tableBorderStyle,onChange:r=>ke("tableBorderStyle",r.target.value),className:"style-select",children:[a.jsx("option",{value:"solid",children:"Solid"}),a.jsx("option",{value:"dashed",children:"Dashed"}),a.jsx("option",{value:"dotted",children:"Dotted"}),a.jsx("option",{value:"double",children:"Double"})]})]}),a.jsxs("div",{className:"style-row",children:[a.jsx("label",{children:"Cell Padding:"}),a.jsx("input",{type:"range",min:"0",max:"20",value:S.cellPadding,onChange:r=>ke("cellPadding",r.target.value),className:"style-range"}),a.jsxs("span",{className:"range-value",children:[S.cellPadding,"px"]})]}),a.jsxs("div",{className:"style-row",children:[a.jsx("label",{children:"Cell Spacing:"}),a.jsx("input",{type:"range",min:"0",max:"10",value:S.cellSpacing,onChange:r=>ke("cellSpacing",r.target.value),className:"style-range"}),a.jsxs("span",{className:"range-value",children:[S.cellSpacing,"px"]})]})]})]}),n&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"style-section",children:[a.jsx("h4",{children:"🎨 Cell Appearance"}),a.jsxs("div",{className:"style-row",children:[a.jsx("label",{children:"Background:"}),a.jsx("input",{type:"color",value:S.cellBackground,onChange:r=>je("cellBackground",r.target.value),className:"color-input"})]})]}),a.jsxs("div",{className:"style-section",children:[a.jsx("h4",{children:"📝 Text Alignment"}),a.jsxs("div",{className:"style-row",children:[a.jsx("label",{children:"Horizontal:"}),a.jsx("div",{className:"alignment-buttons",children:["left","center","right","justify"].map(r=>a.jsx("button",{className:`alignment-btn ${S.cellTextAlign===r?"active":""}`,onClick:()=>je("cellTextAlign",r),title:`Align ${r}`,children:r==="left"?"⬅️":r==="center"?"⬆️":r==="right"?"➡️":"↔️"},r))})]}),a.jsxs("div",{className:"style-row",children:[a.jsx("label",{children:"Vertical:"}),a.jsx("div",{className:"alignment-buttons",children:[{value:"top",icon:"⬆️",label:"Top"},{value:"middle",icon:"◾",label:"Middle"},{value:"bottom",icon:"⬇️",label:"Bottom"}].map(r=>a.jsx("button",{className:`alignment-btn ${S.cellVerticalAlign===r.value?"active":""}`,onClick:()=>je("cellVerticalAlign",r.value),title:r.label,children:r.icon},r.value))})]})]}),a.jsxs("div",{className:"style-section",children:[a.jsx("h4",{children:"🔲 Cell Border"}),a.jsxs("div",{className:"style-row",children:[a.jsx("label",{children:"Border Color:"}),a.jsx("input",{type:"color",value:S.cellBorderColor,onChange:r=>je("cellBorderColor",r.target.value),className:"color-input"})]}),a.jsxs("div",{className:"style-row",children:[a.jsx("label",{children:"Border Width:"}),a.jsxs("select",{value:S.cellBorderWidth,onChange:r=>je("cellBorderWidth",r.target.value),className:"style-select",children:[a.jsx("option",{value:"0",children:"None"}),a.jsx("option",{value:"1",children:"Thin (1px)"}),a.jsx("option",{value:"2",children:"Medium (2px)"}),a.jsx("option",{value:"3",children:"Thick (3px)"})]})]}),a.jsxs("div",{className:"style-row",children:[a.jsx("label",{children:"Border Style:"}),a.jsxs("select",{value:S.cellBorderStyle,onChange:r=>je("cellBorderStyle",r.target.value),className:"style-select",children:[a.jsx("option",{value:"solid",children:"Solid"}),a.jsx("option",{value:"dashed",children:"Dashed"}),a.jsx("option",{value:"dotted",children:"Dotted"}),a.jsx("option",{value:"double",children:"Double"})]})]}),a.jsxs("div",{className:"style-row",children:[a.jsx("label",{children:"Padding:"}),a.jsx("input",{type:"range",min:"0",max:"20",value:S.cellPadding,onChange:r=>je("cellPadding",r.target.value),className:"style-range"}),a.jsxs("span",{className:"range-value",children:[S.cellPadding,"px"]})]})]})]}),a.jsx("div",{className:"style-section",children:a.jsx("div",{className:"selection-info",children:a.jsx("small",{children:U==="table"?"Entire table selected":U==="row"?`Row selected (${fe.length} cells)`:U==="column"?`Column selected (${fe.length} cells)`:`${fe.length} cell${fe.length>1?"s":""} selected`})})})]})]})})},nr=()=>{var e;D||(e=pt.current)==null||e.click()},lr=async e=>{var r;const n=e.target.files;if(n&&n.length>0){const l=n[0];if(!l.type.startsWith("image/")){alert("Please select an image file.");return}const d=10*1024*1024;if(l.size>d){alert("Image file is too large. Please select an image smaller than 10MB.");return}try{de(!0);const f=await yt(l,V);(r=g.current)==null||r.focus(),document.execCommand("insertHTML",!1,`<img src="${f}" alt="${l.name}" style="max-width: 100%; height: auto; margin: 5px 0;" />`),setTimeout(()=>{Ee()},100),J()}catch(f){console.error("Image upload failed:",f),alert("Failed to upload image. Please try again.")}finally{de(!1),e.target.value=""}}},sr=async e=>{const r=(e.clipboardData||window.clipboardData).items;let l=null;for(let d=0;d<r.length;d++)if(r[d].type.indexOf("image")!==-1){l=r[d].getAsFile();break}if(l){e.preventDefault(),de(!0);try{const d=await yt(l,V);document.execCommand("insertHTML",!1,`<img src="${d}" alt="${l.name}" />`),setTimeout(()=>{Ee()},100)}catch(d){console.error("Image upload failed:",d)}finally{de(!1)}}},or=e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.style.backgroundColor="#f0f8ff",e.currentTarget.style.border="2px dashed #007acc"},ir=e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.style.backgroundColor="",e.currentTarget.style.border=""},cr=async e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.style.backgroundColor="",e.currentTarget.style.border="";const r=Array.from(e.dataTransfer.files).filter(l=>l.type.startsWith("image/"));if(r.length>0){de(!0);try{for(const l of r){const d=await yt(l,V);document.execCommand("insertHTML",!1,`<img src="${d}" alt="${l.name}" style="max-width: 100%; height: auto; margin: 5px 0;" />`)}setTimeout(()=>{Ee()},100)}catch(l){console.error("Image upload failed:",l)}finally{de(!1)}}},Ee=i.useCallback(()=>{if(!g.current)return;g.current.querySelectorAll("img").forEach(n=>{var r;if(!n.dataset.resizeEnabled){if((r=n.parentElement)!=null&&r.classList.contains("image-resize-wrapper")){const l=n.parentElement;l.parentNode.insertBefore(n,l),l.remove()}n.dataset.resizeEnabled="true",n.dataset.originalCursor||(n.dataset.originalCursor=n.style.cursor||""),n.style.cursor="pointer",n.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),dr(n)})}})},[]),dr=i.useCallback(e=>{Dt();const n=e.style.cursor;e.dataset.originalCursor=n;const r=document.createElement("div");r.className="image-resize-wrapper",r.style.cssText=`
      position: relative;
      display: inline-block;
      border: 2px solid #007acc;
      box-sizing: border-box;
      margin: 5px;
      z-index: 1000000;
      isolation: isolate;
    `,e.parentNode.insertBefore(r,e),r.appendChild(e),["nw","ne","sw","se","n","s","e","w"].forEach(d=>{const f=document.createElement("div");f.className=`resize-handle resize-${d}`,f.style.cssText=`
        position: absolute;
        width: 8px;
        height: 8px;
        background: #007acc;
        border: 1px solid white;
        cursor: ${Ht(d)};
        z-index: 1000000;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
      `,ur(f,d),f.addEventListener("mousedown",c=>fr(c,e,d)),r.appendChild(f)}),ue(e)},[]),Ht=e=>({nw:"nw-resize",ne:"ne-resize",sw:"sw-resize",se:"se-resize",n:"n-resize",s:"s-resize",e:"e-resize",w:"w-resize"})[e],ur=(e,n)=>{switch(n){case"nw":e.style.top="-4px",e.style.left="-4px";break;case"ne":e.style.top="-4px",e.style.right="-4px";break;case"sw":e.style.bottom="-4px",e.style.left="-4px";break;case"se":e.style.bottom="-4px",e.style.right="-4px";break;case"n":e.style.top="-4px",e.style.left="50%",e.style.transform="translateX(-50%)";break;case"s":e.style.bottom="-4px",e.style.left="50%",e.style.transform="translateX(-50%)";break;case"e":e.style.right="-4px",e.style.top="50%",e.style.transform="translateY(-50%)";break;case"w":e.style.left="-4px",e.style.top="50%",e.style.transform="translateY(-50%)";break}},fr=i.useCallback((e,n,r)=>{e.preventDefault(),e.stopPropagation();const l=n.getBoundingClientRect(),d=e.clientX,f=e.clientY,c=l.width,T=l.height,Y=c/T;rt(!0),We({img:n,position:r,startX:d,startY:f,startWidth:c,startHeight:T,aspectRatio:Y});const h={img:n,position:r,startX:d,startY:f,startWidth:c,startHeight:T,aspectRatio:Y},Z=Te=>{const Q=Te.clientX-h.startX,ie=Te.clientY-h.startY;let ge=h.startWidth,q=h.startHeight;switch(h.position){case"se":ge=Math.max(50,h.startWidth+Q),q=Math.max(30,h.startHeight+ie);break;case"sw":ge=Math.max(50,h.startWidth-Q),q=Math.max(30,h.startHeight+ie);break;case"ne":ge=Math.max(50,h.startWidth+Q),q=Math.max(30,h.startHeight-ie);break;case"nw":ge=Math.max(50,h.startWidth-Q),q=Math.max(30,h.startHeight-ie);break;case"e":ge=Math.max(50,h.startWidth+Q);break;case"w":ge=Math.max(50,h.startWidth-Q);break;case"s":q=Math.max(30,h.startHeight+ie);break;case"n":q=Math.max(30,h.startHeight-ie);break}h.img.style.width=`${ge}px`,h.img.style.height=`${q}px`},ct=()=>{rt(!1),We(null),document.removeEventListener("mousemove",Z),document.removeEventListener("mouseup",ct),document.body.style.cursor="default",document.body.style.userSelect="auto",j&&g.current&&j(g.current.innerHTML)};document.addEventListener("mousemove",Z),document.addEventListener("mouseup",ct),document.body.style.cursor=Ht(r),document.body.style.userSelect="none"},[j]),Dt=i.useCallback(()=>{if(!g.current)return;g.current.querySelectorAll(".image-resize-wrapper").forEach(n=>{const r=n.querySelector("img");r&&(r.dataset.originalCursor!==void 0&&(r.dataset.originalCursor?r.style.cursor=r.dataset.originalCursor:r.style.removeProperty("cursor"),delete r.dataset.originalCursor),delete r.dataset.resizeEnabled,n.parentNode.insertBefore(r,n)),n.remove()}),ue(null),setTimeout(()=>{if(g.current&&j){const n=g.current.innerHTML;j(n)}},0)},[j]),_t=i.useCallback(e=>{tt&&!e.target.closest(".image-resize-wrapper")&&!e.target.closest("img")&&Dt()},[tt,Dt]);i.useEffect(()=>{if(g.current){const e=setTimeout(()=>{Ee()},200);return()=>clearTimeout(e)}},[M,Ee]),i.useEffect(()=>{if(g.current){const e=setTimeout(()=>{Ee()},500);return()=>clearTimeout(e)}},[Ee]),i.useEffect(()=>(document.addEventListener("click",_t),()=>document.removeEventListener("click",_t)),[_t]),i.useEffect(()=>()=>{document.body.style.cursor="default",document.body.style.userSelect="auto"},[]);const mr=e=>{y("insertUnorderedList"),setTimeout(()=>{const n=window.getSelection();if(n.rangeCount>0){const l=n.getRangeAt(0).startContainer.parentElement.closest("ul");l&&(l.style.listStyleType=e)}J()},50)};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{ref:Xe,className:Ue.wrapper,children:[N==="top"&&It(),a.jsx("div",{ref:g,contentEditable:!D,className:Ue.contentArea,onInput:At,onKeyDown:Wt,onPaste:sr,onDragOver:or,onDragLeave:ir,onDrop:cr,onBlur:J,"data-placeholder":_,style:{minHeight:"100px",paddingTop:x&&H&&N==="top"?`${ze}px`:void 0},suppressContentEditableWarning:!0}),N==="bottom"&&It()]}),a.jsx("input",{ref:pt,type:"file",accept:"image/*",style:{display:"none"},onChange:lr}),et&&a.jsx("div",{className:"upload-indicator",children:a.jsx("p",{children:"Uploading image..."})}),Qt(),qt(),$t(),er(),ar()]})}});