dopecanvas 0.1.3 → 0.1.4

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 CHANGED
@@ -245,7 +245,7 @@ The included `sample-report-charts.html` demo shows this in action: four Chart.j
245
245
 
246
246
  Edit a table cell and watch every chart, total, and KPI card update instantly:
247
247
 
248
- ![Dynamic content demo](public/dynamic.gif)
248
+ ![Dynamic content demo](https://raw.githubusercontent.com/custom3dwebapp/dopecanvas/refs/heads/main/public/dynamic.gif)
249
249
 
250
250
  ---
251
251
 
@@ -1,9 +1,11 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),r=require("react"),be=require("react-dom"),ee=({dimensions:a,margins:e,pageNumber:t,totalPages:o,children:s})=>n.jsxs("div",{className:"dopecanvas-page",style:{width:`${a.width}px`,height:`${a.height}px`,backgroundColor:"#ffffff",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.15), 0 0 1px rgba(0, 0, 0, 0.1)",position:"relative",overflow:"hidden",flexShrink:0},children:[n.jsx("div",{className:"dopecanvas-page-content",style:{paddingTop:`${e.top}px`,paddingRight:`${e.right}px`,paddingBottom:`${e.bottom}px`,paddingLeft:`${e.left}px`,height:"100%",boxSizing:"border-box",overflow:"hidden"},children:s}),n.jsxs("div",{className:"dopecanvas-page-number",style:{position:"absolute",bottom:`${Math.max(e.bottom/3,16)}px`,left:0,right:0,textAlign:"center",fontSize:"11px",color:"#999",fontFamily:"system-ui, -apple-system, sans-serif",pointerEvents:"none",userSelect:"none"},children:[t," / ",o]})]}),xe=({visible:a,onAddBelow:e,onEditHTML:t,onDelete:o})=>n.jsxs("div",{className:"dopecanvas-block-toolbar",style:{...Se,display:a?"flex":"none"},onMouseDown:s=>s.preventDefault(),children:[n.jsx(V,{onClick:e,title:"Add block below",children:n.jsx(Ce,{})}),n.jsx(V,{onClick:t,title:"Edit HTML",children:n.jsx(ye,{})}),n.jsx(V,{onClick:o,title:"Delete block",danger:!0,children:n.jsx(ke,{})})]}),Ce=()=>n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",children:[n.jsx("line",{x1:"7",y1:"3",x2:"7",y2:"11"}),n.jsx("line",{x1:"3",y1:"7",x2:"11",y2:"7"})]}),ye=()=>n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("polyline",{points:"4.5,3 1.5,7 4.5,11"}),n.jsx("polyline",{points:"9.5,3 12.5,7 9.5,11"})]}),ke=()=>n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M2.5 4h9M5 4V2.5h4V4M3.5 4l.5 8h6l.5-8"})}),V=({onClick:a,title:e,children:t,danger:o})=>{const[s,l]=r.useState(!1);return n.jsx("button",{onClick:a,title:e,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{...ve,background:s?o?"#fff0f0":"#f0f0f0":"transparent",color:s&&o?"#d32f2f":"#666"},children:t})},Se={position:"absolute",top:0,left:-40,flexDirection:"column",gap:"1px",zIndex:100,background:"#fff",borderRadius:"6px",boxShadow:"0 1px 5px rgba(0,0,0,0.12)",padding:"3px",paddingRight:"6px"},ve={width:"30px",height:"26px",border:"none",cursor:"pointer",borderRadius:"4px",fontSize:"13px",fontFamily:"system-ui, -apple-system, sans-serif",display:"flex",alignItems:"center",justifyContent:"center",padding:0,transition:"background 0.1s, color 0.1s"},Te=({html:a,onSave:e,onCancel:t})=>{const[o,s]=r.useState(a),l=i=>{if(i.key==="Enter"&&(i.metaKey||i.ctrlKey)&&(i.preventDefault(),e(o)),i.key==="Escape"&&(i.preventDefault(),t()),i.key==="Tab"){i.preventDefault();const u=i.target,g=u.selectionStart,k=u.selectionEnd,h=o.substring(0,g)+" "+o.substring(k);s(h),requestAnimationFrame(()=>{u.selectionStart=u.selectionEnd=g+2})}};return be.createPortal(n.jsx("div",{style:Me,onClick:t,children:n.jsxs("div",{style:je,onClick:i=>i.stopPropagation(),children:[n.jsxs("div",{style:Ee,children:[n.jsx("span",{style:{fontWeight:600,fontSize:"14px"},children:"Edit Block HTML"}),n.jsx("span",{style:{fontSize:"11px",color:"#888"},children:"⌘Enter to save · Escape to cancel"})]}),n.jsx("textarea",{style:Le,value:o,onChange:i=>s(i.target.value),onKeyDown:l,spellCheck:!1,autoFocus:!0}),n.jsxs("div",{style:He,children:[n.jsx("button",{style:we,onClick:t,onMouseEnter:i=>{i.target.style.borderColor="#888"},onMouseLeave:i=>{i.target.style.borderColor="#555"},children:"Cancel"}),n.jsx("button",{style:Re,onClick:()=>e(o),onMouseEnter:i=>{i.target.style.background="#0055dd"},onMouseLeave:i=>{i.target.style.background="#0066ff"},children:"Save"})]})]})}),document.body)},Me={position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e4},je={width:"min(800px, 90vw)",height:"min(600px, 80vh)",background:"#1e1e1e",borderRadius:"10px",display:"flex",flexDirection:"column",overflow:"hidden",boxShadow:"0 20px 60px rgba(0, 0, 0, 0.4)"},Ee={display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px 16px",background:"#2d2d2d",color:"#ccc",borderBottom:"1px solid #444"},Le={flex:1,background:"#1e1e1e",color:"#d4d4d4",border:"none",padding:"16px",fontFamily:"'SF Mono', 'Fira Code', 'Consolas', 'Monaco', monospace",fontSize:"13px",lineHeight:"1.6",resize:"none",outline:"none",tabSize:2},He={display:"flex",justifyContent:"flex-end",gap:"8px",padding:"12px 16px",background:"#2d2d2d",borderTop:"1px solid #444"},we={padding:"6px 16px",border:"1px solid #555",borderRadius:"6px",background:"transparent",color:"#ccc",cursor:"pointer",fontSize:"13px",transition:"border-color 0.15s"},Re={padding:"6px 16px",border:"none",borderRadius:"6px",background:"#0066ff",color:"#fff",cursor:"pointer",fontSize:"13px",fontWeight:500,transition:"background 0.15s"},U={letter:{width:816,height:1056},a4:{width:794,height:1123},legal:{width:816,height:1344}},ae={top:96,right:96,bottom:96,left:96},N={size:"letter",margins:{...ae}};function Pe(a){const e=[];return a.querySelectorAll("script").forEach(t=>{const o=document.createElement("script");Array.from(t.attributes).forEach(s=>o.setAttribute(s.name,s.value)),o.textContent=t.textContent||"",t.parentNode?.replaceChild(o,t),e.push(o)}),e}function _e(a){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0),o=t.startContainer,s=Array.from(a.querySelectorAll(".dopecanvas-block-content")),l=s.findIndex(i=>i.contains(o));if(l===-1)return null;try{const i=document.createRange();i.selectNodeContents(s[l]),i.setEnd(t.startContainer,t.startOffset);const u=i.toString().length;return{blockIndex:l,textOffset:u}}catch{return null}}function Ae(a,e){const t=a.querySelectorAll(".dopecanvas-block-content");if(e.blockIndex>=t.length)return;const o=t[e.blockIndex],s=document.createTreeWalker(o,NodeFilter.SHOW_TEXT);let l=e.textOffset;for(;s.nextNode();){const i=s.currentNode;if(l<=i.length){try{const u=document.createRange();u.setStart(i,l),u.collapse(!0);const g=window.getSelection();g?.removeAllRanges(),g?.addRange(u)}catch{}return}l-=i.length}try{const i=document.createRange();i.selectNodeContents(o),i.collapse(!1);const u=window.getSelection();u?.removeAllRanges(),u?.addRange(i)}catch{}}const De=r.memo(({html:a,isEditable:e,isTable:t})=>n.jsx("div",{className:"dopecanvas-block-content",contentEditable:e&&!t?!0:void 0,suppressContentEditableWarning:!0,dangerouslySetInnerHTML:{__html:a}})),Ie=({html:a,css:e,pageConfig:t,layoutEngine:o,editableManager:s,onContentChange:l,onPaginationChange:i})=>{const u=r.useRef(null),g=r.useRef(null),k=r.useRef(null),h=r.useRef(l);h.current=l;const[p,S]=r.useState([]),w=r.useRef(null),x=r.useRef(!1),j=r.useRef([]),[R,D]=r.useState(null),[_,z]=r.useState(null),[m,C]=r.useState(""),L=r.useRef(null),P=typeof t.size=="string"?U[t.size]:t.size,W=r.useCallback(()=>{if(!g.current)return;const d=g.current.querySelectorAll(".dopecanvas-block-content"),c=[];d.forEach(b=>{const f=b.firstElementChild;f&&c.push(f.outerHTML)});const E=c.join(`
2
- `);h.current?.(E)},[]),H=r.useCallback(d=>{if(!u.current)return;const c=u.current;if(c.style.width=`${o.getContentAreaWidth()}px`,c.style.position="absolute",c.style.left="-9999px",c.style.top="0",c.style.visibility="hidden",c.innerHTML="",e){const T=document.createElement("style");T.textContent=e,c.appendChild(T)}const E=document.createElement("div");E.innerHTML=d,c.appendChild(E);const b=o.measureBlocks(E),f=b.map(T=>T.element.cloneNode(!0).outerHTML),y=o.paginate(b),v=y.pages.map(T=>({blocks:T.blockIndices.map(I=>f[I])}));c.innerHTML="",j.current=v,S(v),i?.(y),h.current?.(d)},[e,o,i]),X=r.useCallback(()=>{if(!g.current||!u.current)return;const d=g.current,c=_e(d),E=d.querySelectorAll(".dopecanvas-block-content"),b=[];if(E.forEach(M=>{const B=M.firstElementChild;B&&b.push(B.outerHTML)}),b.length===0)return;const f=u.current,y=o.getContentAreaWidth();if(f.style.width=`${y}px`,f.style.position="absolute",f.style.left="-9999px",f.style.top="0",f.style.visibility="hidden",f.innerHTML="",e){const M=document.createElement("style");M.textContent=e,f.appendChild(M)}const v=document.createElement("div");v.innerHTML=b.join(`
3
- `),f.appendChild(v);const T=o.measureBlocks(v),I=T.map(M=>M.element.cloneNode(!0).outerHTML),q=o.paginate(T);f.innerHTML="";const $=q.pages.map(M=>({blocks:M.blockIndices.map(B=>I[B])})),Q=j.current.map(M=>M.blocks.length),Y=$.map(M=>M.blocks.length);(Q.length!==Y.length||Q.some((M,B)=>M!==Y[B]))&&(x.current=!0,w.current=c,j.current=$,S($),i?.(q))},[e,o,i]),Z=r.useRef(X);Z.current=X;const J=r.useCallback(()=>{const d=new DOMParser().parseFromString(a,"text/html");d.head.querySelectorAll('style, link[rel="stylesheet"]').forEach(c=>{d.body.insertBefore(c,d.body.firstChild)}),H(d.body.innerHTML)},[a,H]);r.useEffect(()=>{J()},[J]);const A=r.useCallback(()=>{if(!g.current)return[];const d=g.current.querySelectorAll(".dopecanvas-block-content"),c=[];return d.forEach(E=>{const b=E.firstElementChild;b&&c.push(b.outerHTML)}),c},[]),he=r.useCallback(d=>{const c=A();c.splice(d+1,0,'<p style="min-height: 1.5em; line-height: 1.6;">&nbsp;</p>'),D(null),H(c.join(`
4
- `))},[A,H]),ge=r.useCallback(d=>{const c=A();c.length<=1||(c.splice(d,1),D(null),H(c.join(`
5
- `)))},[A,H]),pe=r.useCallback(d=>{const c=A();d<c.length&&(z(d),C(c[d]))},[A]),fe=r.useCallback(d=>{if(_===null)return;const c=A();_<c.length&&(c[_]=d),z(null),C(""),D(null),H(c.join(`
6
- `))},[_,A,H]),me=r.useCallback(()=>{z(null),C("")},[]);return r.useEffect(()=>{const d=g.current;if(!d)return;k.current&&k.current.disconnect(),d.querySelectorAll(".dopecanvas-block-content").forEach(y=>{const v=y.firstElementChild;v&&v.tagName==="TABLE"&&v.querySelectorAll("td, th").forEach(I=>{I.contentEditable="true"})});const E=Pe(d);let b=null;const f=new MutationObserver(()=>{x.current||(b&&clearTimeout(b),b=setTimeout(()=>{W(),Z.current()},300))});return f.observe(d,{childList:!0,subtree:!0,characterData:!0,attributes:!1}),k.current=f,w.current?requestAnimationFrame(()=>{w.current&&g.current&&(Ae(g.current,w.current),w.current=null),x.current=!1}):x.current=!1,()=>{f.disconnect(),E.forEach(y=>y.remove()),b&&clearTimeout(b)}},[p,W]),n.jsxs("div",{className:"dopecanvas-paged-view",style:Be,children:[n.jsx("div",{ref:u,"aria-hidden":"true"}),n.jsxs("div",{ref:g,style:Fe,children:[e&&n.jsx("style",{dangerouslySetInnerHTML:{__html:e}}),p.map((d,c)=>{const E=p.slice(0,c).reduce((b,f)=>b+f.blocks.length,0);return n.jsx(ee,{dimensions:P,margins:t.margins,pageNumber:c+1,totalPages:p.length,children:d.blocks.map((b,f)=>{const y=E+f,v=b.trim().toLowerCase(),T=!v.startsWith("<script")&&!v.startsWith("<style"),I=v.startsWith("<table");return n.jsxs("div",{className:"dopecanvas-block-wrapper",style:{position:"relative"},onMouseEnter:()=>{T&&(L.current&&(clearTimeout(L.current),L.current=null),D(y))},onMouseLeave:()=>{L.current=setTimeout(()=>{D(q=>q===y?null:q)},250)},children:[n.jsx(De,{html:b,isEditable:T,isTable:I}),T&&n.jsx(xe,{visible:R===y,onAddBelow:()=>he(y),onEditHTML:()=>pe(y),onDelete:()=>ge(y)})]},`${c}-${f}`)})},c)}),p.length===0&&n.jsx(ee,{dimensions:P,margins:t.margins,pageNumber:1,totalPages:1,children:n.jsx("div",{contentEditable:"true",style:{minHeight:"1em",outline:"none"},"data-placeholder":"Start typing..."})})]}),_!==null&&n.jsx(Te,{html:m,onSave:fe,onCancel:me})]})},Be={flex:1,overflow:"auto",backgroundColor:"#e8e8e8",display:"flex",flexDirection:"column",alignItems:"center"},Fe={display:"flex",flexDirection:"column",alignItems:"center",gap:"24px",padding:"24px 0"};class K{config;constructor(e=N){this.config={...e}}getConfig(){return{...this.config}}setConfig(e){e.size!==void 0&&(this.config.size=e.size),e.margins!==void 0&&(this.config.margins={...e.margins})}getPageDimensions(){return typeof this.config.size=="string"?U[this.config.size]:this.config.size}getContentAreaHeight(){return this.getPageDimensions().height-this.config.margins.top-this.config.margins.bottom}getContentAreaWidth(){return this.getPageDimensions().width-this.config.margins.left-this.config.margins.right}measureBlocks(e){const t=Array.from(e.children),o=[];for(let s=0;s<t.length;s++){const l=t[s],i=window.getComputedStyle(l),u=i.getPropertyValue("break-before")==="page"||i.getPropertyValue("page-break-before")==="always",g=i.getPropertyValue("break-after")==="page"||i.getPropertyValue("page-break-after")==="always",k=l.getBoundingClientRect(),h=parseFloat(i.marginTop)||0,p=parseFloat(i.marginBottom)||0,S=k.height+h+p;o.push({index:s,height:S,element:l,breakBefore:u,breakAfter:g})}return o}paginate(e){if(e.length===0)return{pages:[{blockIndices:[]}],pageCount:1};const t=this.getContentAreaHeight(),o=[];let s=[],l=0;for(let i=0;i<e.length;i++){const u=e[i];u.breakBefore&&s.length>0&&(o.push({blockIndices:s}),s=[],l=0),l+u.height>t&&s.length>0&&(o.push({blockIndices:s}),s=[],l=0),s.push(u.index),l+=u.height,u.breakAfter&&(o.push({blockIndices:s}),s=[],l=0)}return s.length>0&&o.push({blockIndices:s}),o.length===0&&o.push({blockIndices:[]}),{pages:o,pageCount:o.length}}}class F{observer=null;changeCallbacks=new Set;contextCallbacks=new Set;undoStack=[];redoStack=[];container=null;debounceTimer=null;selectionHandler=null;currentContext="none";static MAX_UNDO_STACK=100;static DEBOUNCE_MS=150;attach(e){this.detach(),this.container=e,this.makeChildrenEditable(e),this.pushUndoSnapshot(),this.observer=new MutationObserver(this.handleMutations),this.observer.observe(e,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["style","class"]}),this.selectionHandler=this.handleSelectionChange.bind(this),document.addEventListener("selectionchange",this.selectionHandler)}detach(){this.observer&&(this.observer.disconnect(),this.observer=null),this.selectionHandler&&(document.removeEventListener("selectionchange",this.selectionHandler),this.selectionHandler=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.container=null}makeChildrenEditable(e){const t=Array.from(e.children);for(const o of t)o.tagName==="TABLE"?this.makeTableCellsEditable(o):o.contentEditable="true"}makeTableCellsEditable(e){e.querySelectorAll("td, th").forEach(o=>{o.contentEditable="true"})}handleMutations=e=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.pushUndoSnapshot(),this.notifyChange()},F.DEBOUNCE_MS)};handleSelectionChange(){const e=window.getSelection();if(!e||e.rangeCount===0||!this.container){this.setContext("none");return}const o=e.getRangeAt(0).startContainer;let s=o;for(;s&&s!==this.container;){if(s instanceof HTMLElement){const l=s.tagName;if(l==="TD"||l==="TH"||l==="TABLE"){this.setContext("table");return}if(l==="IMG"){this.setContext("image");return}if(s.dataset?.dopecanvasChart){this.setContext("chart");return}}s=s.parentNode}this.container.contains(o)?this.setContext("text"):this.setContext("none")}setContext(e){e!==this.currentContext&&(this.currentContext=e,this.contextCallbacks.forEach(t=>t(e)))}getContext(){return this.currentContext}pushUndoSnapshot(){if(!this.container)return;const e=this.container.innerHTML,t=this.undoStack[this.undoStack.length-1];t&&t.html===e||(this.undoStack.push({html:e,timestamp:Date.now()}),this.redoStack=[],this.undoStack.length>F.MAX_UNDO_STACK&&this.undoStack.shift())}undo(){if(!this.container||this.undoStack.length<=1)return!1;const e=this.undoStack.pop();this.redoStack.push(e);const t=this.undoStack[this.undoStack.length-1];return this.pauseObserver(()=>{this.container.innerHTML=t.html,this.makeChildrenEditable(this.container)}),this.notifyChange(),!0}redo(){if(!this.container||this.redoStack.length===0)return!1;const e=this.redoStack.pop();return this.undoStack.push(e),this.pauseObserver(()=>{this.container.innerHTML=e.html,this.makeChildrenEditable(this.container)}),this.notifyChange(),!0}pauseObserver(e){this.observer&&this.observer.disconnect(),e(),this.observer&&this.container&&this.observer.observe(this.container,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["style","class"]})}onChange(e){return this.changeCallbacks.add(e),()=>{this.changeCallbacks.delete(e)}}onContextChange(e){return this.contextCallbacks.add(e),()=>{this.contextCallbacks.delete(e)}}notifyChange(){this.changeCallbacks.forEach(e=>e())}execCommand(e,t){return document.execCommand(e,!1,t)}queryCommandState(e){return document.queryCommandState(e)}queryCommandValue(e){return document.queryCommandValue(e)}getHTML(){return this.container?this.container.innerHTML:""}getPlainText(){return this.container&&(this.container.innerText||this.container.textContent)||""}}const ze=r.forwardRef(({html:a="",css:e,pageConfig:t,onContentChange:o,onPageConfigChange:s,style:l},i)=>{const[u,g]=r.useState(t||N),[k,h]=r.useState({pages:[],pageCount:0}),p=r.useRef(a),S=r.useRef(null),w=r.useRef(o);w.current=o;const x=t||u,j=r.useMemo(()=>new K(x),[]),R=r.useMemo(()=>new F,[]);r.useEffect(()=>{j.setConfig(x)},[x,j]);const D=r.useCallback(m=>{p.current=m,w.current?.(m)},[]),_=r.useCallback(m=>{const C={...x,...m,margins:{...x.margins,...m.margins||{}}};g(C),j.setConfig(C),s?.(C)},[x,j,s]),z=r.useCallback(m=>{h(m)},[]);return r.useImperativeHandle(i,()=>({execCommand:(m,C)=>R.execCommand(m,C),queryCommandState:m=>R.queryCommandState(m),queryCommandValue:m=>R.queryCommandValue(m),getPageConfig:()=>({...x}),setPageConfig:m=>{_(m)},getPageCount:()=>k.pageCount,getHTML:()=>{if(S.current){const m=S.current.querySelectorAll(".dopecanvas-block-content");if(m.length>0){const C=[];if(m.forEach(L=>{const P=L.firstElementChild;P&&C.push(P.outerHTML)}),C.length>0){const L=C.join(`
7
- `);return p.current=L,L}}}return p.current},getPlainText:()=>{const m=S.current?(()=>{const L=S.current.querySelectorAll(".dopecanvas-block-content"),P=[];return L.forEach(W=>{const H=W.firstElementChild;H&&P.push(H.outerHTML)}),P.length>0?P.join(`
8
- `):p.current})():p.current,C=document.createElement("div");return C.innerHTML=m,C.innerText||C.textContent||""},undo:()=>R.undo(),redo:()=>R.redo()}),[R,x,k.pageCount,_]),n.jsx("div",{ref:S,className:"dopecanvas-root",style:{display:"flex",flexDirection:"column",height:"100%",width:"100%",fontFamily:"system-ui, -apple-system, BlinkMacSystemFont, sans-serif",...l},children:n.jsx(Ie,{html:a,css:e,pageConfig:x,layoutEngine:j,editableManager:R,onContentChange:D,onPaginationChange:z})})});class le{layoutEngine;editableManager;sourceHTML="";sourceCSS="";measureContainer=null;contentContainer=null;paginationResult={pages:[],pageCount:0};paginationCallbacks=new Set;changeCallbacks=new Set;constructor(e=N){this.layoutEngine=new K(e),this.editableManager=new F}getLayoutEngine(){return this.layoutEngine}getEditableManager(){return this.editableManager}getPaginationResult(){return this.paginationResult}getSourceHTML(){return this.sourceHTML}getPageConfig(){return this.layoutEngine.getConfig()}loadHTML(e,t){this.sourceHTML=e,this.sourceCSS=t||""}setMeasureContainer(e){this.measureContainer=e}setContentContainer(e){this.contentContainer&&this.editableManager.detach(),this.contentContainer=e}runPagination(){if(!this.measureContainer)return{result:{pages:[{blockIndices:[]}],pageCount:1},measurements:[]};const e=this.layoutEngine.getContentAreaWidth();this.measureContainer.style.width=`${e}px`,this.measureContainer.style.position="absolute",this.measureContainer.style.left="-9999px",this.measureContainer.style.top="0",this.measureContainer.style.visibility="hidden";let t=null;this.sourceCSS&&(t=document.createElement("style"),t.textContent=this.sourceCSS,this.measureContainer.appendChild(t));const o=document.createElement("div");o.innerHTML=this.sourceHTML,this.measureContainer.appendChild(o);const s=this.layoutEngine.measureBlocks(o);return this.paginationResult=this.layoutEngine.paginate(s),this.measureContainer.innerHTML="",this.paginationCallbacks.forEach(l=>l(this.paginationResult)),{result:this.paginationResult,measurements:s}}rePaginate(){if(!this.contentContainer)return this.paginationResult;const e=this.layoutEngine.measureBlocks(this.contentContainer);return this.paginationResult=this.layoutEngine.paginate(e),this.paginationCallbacks.forEach(t=>t(this.paginationResult)),this.paginationResult}attachEditing(e){this.contentContainer=e,this.editableManager.attach(e),this.editableManager.onChange(()=>{this.sourceHTML=e.innerHTML,this.changeCallbacks.forEach(t=>t(this.sourceHTML))})}setPageConfig(e){this.layoutEngine.setConfig(e)}onPagination(e){return this.paginationCallbacks.add(e),()=>{this.paginationCallbacks.delete(e)}}onChange(e){return this.changeCallbacks.add(e),()=>{this.changeCallbacks.delete(e)}}getHTML(){return this.contentContainer?this.contentContainer.innerHTML:this.sourceHTML}getPlainText(){return this.contentContainer&&(this.contentContainer.innerText||this.contentContainer.textContent)||""}destroy(){this.editableManager.detach(),this.paginationCallbacks.clear(),this.changeCallbacks.clear(),this.measureContainer=null,this.contentContainer=null}}class qe{_html="";_css="";_pageConfig=null;_paginationResult={pages:[],pageCount:0};_changeCallbacks=new Set;_loadCallbacks=new Set;_pageConfigCallbacks=new Set;_getHTMLFn=null;_getPlainTextFn=null;loadHTML(e,t){this._html=e,this._css=t||"",this._loadCallbacks.forEach(o=>o(e,t))}getHTML(){return this._getHTMLFn?this._getHTMLFn():this._html}getPlainText(){if(this._getPlainTextFn)return this._getPlainTextFn();const e=document.createElement("div");return e.innerHTML=this._html,e.innerText||e.textContent||""}onChange(e){return this._changeCallbacks.add(e),()=>{this._changeCallbacks.delete(e)}}onLoad(e){return this._loadCallbacks.add(e),()=>{this._loadCallbacks.delete(e)}}onPageConfigChange(e){return this._pageConfigCallbacks.add(e),()=>{this._pageConfigCallbacks.delete(e)}}getPageCount(){return this._paginationResult.pageCount}getPageConfig(){return this._pageConfig}setPageConfig(e){this._pageConfig&&(this._pageConfig={...this._pageConfig,...e,margins:{...this._pageConfig.margins,...e.margins||{}}},this._pageConfigCallbacks.forEach(t=>t(this._pageConfig)))}querySelectorAll(e){const t=document.createElement("div");return t.innerHTML=this.getHTML(),Array.from(t.querySelectorAll(e))}getElementContent(e){const t=document.createElement("div");t.innerHTML=this.getHTML();const o=t.querySelector(`#${e}`);return o?o.innerHTML:null}setElementContent(e,t){const o=document.createElement("div");o.innerHTML=this.getHTML();const s=o.querySelector(`#${e}`);s&&(s.innerHTML=t,this.loadHTML(o.innerHTML,this._css))}_connectGetHTML(e){this._getHTMLFn=e}_connectGetPlainText(e){this._getPlainTextFn=e}_notifyChange(e){this._html=e,this._changeCallbacks.forEach(t=>t(e))}_updatePagination(e){this._paginationResult=e}_updatePageConfig(e){this._pageConfig=e}}function Ne(a){const[e,t]=r.useState("none");return r.useEffect(()=>a?a.onContextChange(s=>{t(s)}):void 0,[a]),e}function ce(){const[a,e]=r.useState({bold:!1,italic:!1,underline:!1,strikethrough:!1,justifyLeft:!1,justifyCenter:!1,justifyRight:!1,justifyFull:!1}),t=r.useCallback(()=>{e({bold:document.queryCommandState("bold"),italic:document.queryCommandState("italic"),underline:document.queryCommandState("underline"),strikethrough:document.queryCommandState("strikethrough"),justifyLeft:document.queryCommandState("justifyLeft"),justifyCenter:document.queryCommandState("justifyCenter"),justifyRight:document.queryCommandState("justifyRight"),justifyFull:document.queryCommandState("justifyFull")})},[]);return r.useEffect(()=>(document.addEventListener("selectionchange",t),()=>{document.removeEventListener("selectionchange",t)}),[t]),a}const ue=({onExecCommand:a})=>{const e=ce(),t=r.useRef(null),o=r.useCallback(()=>{const h=window.getSelection();h&&h.rangeCount>0&&(t.current=h.getRangeAt(0).cloneRange())},[]),s=r.useCallback(()=>{const h=t.current;if(!h)return;const p=window.getSelection();p&&(p.removeAllRanges(),p.addRange(h))},[]),l=r.useCallback((h,p)=>S=>{S.preventDefault(),a(h,p)},[a]),i=r.useCallback(h=>{s(),a("fontSize",h.target.value)},[a,s]),u=r.useCallback(h=>{s();const p=h.target.value;p==="p"?a("formatBlock","p"):a("formatBlock",p)},[a,s]),g=r.useCallback(h=>{s(),a("foreColor",h.target.value)},[a,s]),k=r.useCallback(h=>{s(),a("hiliteColor",h.target.value)},[a,s]);return n.jsxs("div",{style:We,children:[n.jsxs("select",{onChange:u,defaultValue:"p",style:ne,title:"Block Format",onMouseDown:o,children:[n.jsx("option",{value:"p",children:"Paragraph"}),n.jsx("option",{value:"h1",children:"Heading 1"}),n.jsx("option",{value:"h2",children:"Heading 2"}),n.jsx("option",{value:"h3",children:"Heading 3"}),n.jsx("option",{value:"h4",children:"Heading 4"}),n.jsx("option",{value:"h5",children:"Heading 5"}),n.jsx("option",{value:"h6",children:"Heading 6"})]}),n.jsx("div",{style:G}),n.jsxs("select",{onChange:i,defaultValue:"3",style:ne,title:"Font Size",onMouseDown:o,children:[n.jsx("option",{value:"1",children:"8pt"}),n.jsx("option",{value:"2",children:"10pt"}),n.jsx("option",{value:"3",children:"12pt"}),n.jsx("option",{value:"4",children:"14pt"}),n.jsx("option",{value:"5",children:"18pt"}),n.jsx("option",{value:"6",children:"24pt"}),n.jsx("option",{value:"7",children:"36pt"})]}),n.jsx("div",{style:G}),n.jsx(te,{icon:"B",title:"Bold (Ctrl+B)",active:e.bold,onMouseDown:l("bold"),extraStyle:{fontWeight:"bold"}}),n.jsx(te,{icon:"I",title:"Italic (Ctrl+I)",active:e.italic,onMouseDown:l("italic"),extraStyle:{fontStyle:"italic"}}),n.jsx("div",{style:G}),n.jsxs("label",{style:oe,title:"Text Color",onMouseDown:o,children:["A",n.jsx("input",{type:"color",defaultValue:"#000000",onChange:g,style:se})]}),n.jsxs("label",{style:oe,title:"Highlight Color",onMouseDown:o,children:[n.jsx("span",{style:{backgroundColor:"#ffff00",padding:"0 2px"},children:"A"}),n.jsx("input",{type:"color",defaultValue:"#ffff00",onChange:k,style:se})]})]})},te=({icon:a,title:e,active:t,onMouseDown:o,extraStyle:s})=>n.jsx("button",{type:"button",title:e,onMouseDown:o,style:{width:"28px",height:"28px",borderWidth:"1px",borderStyle:"solid",borderColor:t?"#b0b5bd":"transparent",borderRadius:"3px",backgroundColor:t?"#d0d5dd":"transparent",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"13px",color:"#333",padding:0,fontFamily:"inherit",...s},dangerouslySetInnerHTML:{__html:a}}),We={display:"flex",alignItems:"center",gap:"2px",flexWrap:"wrap"},ne={height:"28px",borderWidth:"1px",borderStyle:"solid",borderColor:"#ccc",borderRadius:"3px",fontSize:"12px",padding:"0 4px",cursor:"pointer",backgroundColor:"#fff"},G={width:"1px",height:"20px",backgroundColor:"#ddd",margin:"0 4px"},oe={position:"relative",width:"28px",height:"28px",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"13px",fontWeight:"bold"},se={position:"absolute",bottom:0,left:0,width:"100%",height:"4px",padding:0,borderWidth:0,borderStyle:"none",cursor:"pointer"},de=({pageConfig:a,pageCount:e,onPageConfigChange:t})=>{const o=r.useCallback(i=>{const u=i.target.value;t({size:u})},[t]),s=r.useCallback(i=>u=>{const g=Math.max(0,parseInt(u.target.value)||0);t({margins:{...a.margins,[i]:g}})},[a.margins,t]),l=typeof a.size=="string"?a.size:"custom";return n.jsxs("div",{style:Oe,children:[n.jsxs("label",{style:$e,children:["Page:",n.jsxs("select",{value:l,onChange:o,style:Ve,children:[n.jsx("option",{value:"letter",children:"Letter (8.5 x 11)"}),n.jsx("option",{value:"a4",children:"A4 (210 x 297mm)"}),n.jsx("option",{value:"legal",children:"Legal (8.5 x 14)"})]})]}),n.jsx("div",{style:re}),n.jsx("span",{style:{fontSize:"12px",color:"#666"},children:"Margins (px):"}),n.jsx(O,{label:"T",value:a.margins.top,onChange:s("top")}),n.jsx(O,{label:"R",value:a.margins.right,onChange:s("right")}),n.jsx(O,{label:"B",value:a.margins.bottom,onChange:s("bottom")}),n.jsx(O,{label:"L",value:a.margins.left,onChange:s("left")}),n.jsx("div",{style:re}),n.jsxs("span",{style:{fontSize:"12px",color:"#666"},children:[e," ",e===1?"page":"pages"]})]})},O=({label:a,value:e,onChange:t})=>n.jsxs("label",{style:Ge,title:`${a} margin`,children:[a,":",n.jsx("input",{type:"number",value:e,onChange:t,style:Ue,min:0,max:300,step:12})]}),Oe={display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},$e={display:"flex",alignItems:"center",gap:"4px",fontSize:"12px",color:"#666"},Ve={height:"26px",borderWidth:"1px",borderStyle:"solid",borderColor:"#ccc",borderRadius:"3px",fontSize:"12px",padding:"0 4px",cursor:"pointer",backgroundColor:"#fff"},re={width:"1px",height:"20px",backgroundColor:"#ddd",margin:"0 4px"},Ge={display:"flex",alignItems:"center",gap:"2px",fontSize:"11px",color:"#666"},Ue={width:"44px",height:"24px",borderWidth:"1px",borderStyle:"solid",borderColor:"#ccc",borderRadius:"3px",fontSize:"11px",textAlign:"center",padding:"0 2px"},Ke=({pageConfig:a,pageCount:e,onExecCommand:t,onPageConfigChange:o})=>n.jsxs("div",{style:Xe,children:[n.jsx("div",{style:ie,children:n.jsx(ue,{onExecCommand:t})}),n.jsx("div",{style:ie,children:n.jsx(de,{pageConfig:a,pageCount:e,onPageConfigChange:o})})]}),Xe={borderBottomWidth:"1px",borderBottomStyle:"solid",borderBottomColor:"#d0d0d0",backgroundColor:"#f8f8f8",padding:"4px 8px",display:"flex",flexDirection:"column",gap:"4px",flexShrink:0,zIndex:10},ie={display:"flex",alignItems:"center",gap:"4px",minHeight:"32px"};function Ze(a={}){const{initialHTML:e="",initialCSS:t="",initialConfig:o=N}=a,s=r.useRef(new le(o)),[l,i]=r.useState({pages:[{blockIndices:[]}],pageCount:1}),[u,g]=r.useState(o),k=r.useCallback((x,j)=>{s.current.loadHTML(x,j)},[]),h=r.useCallback(x=>{s.current.setPageConfig(x),g(s.current.getPageConfig())},[]),p=r.useCallback(()=>{const{result:x}=s.current.runPagination();i(x)},[]),S=r.useCallback(()=>s.current.getHTML(),[]),w=r.useCallback(()=>s.current.getPlainText(),[]);return r.useEffect(()=>{e&&s.current.loadHTML(e,t)},[e,t]),r.useEffect(()=>s.current.onPagination(j=>{i(j)}),[]),r.useEffect(()=>()=>{s.current.destroy()},[]),{engine:s.current,paginationResult:l,pageConfig:u,loadHTML:k,setPageConfig:h,triggerPagination:p,getHTML:S,getPlainText:w}}exports.DEFAULT_MARGINS=ae;exports.DEFAULT_PAGE_CONFIG=N;exports.DocumentAPI=qe;exports.DocumentEngine=le;exports.DopeCanvas=ze;exports.EditableManager=F;exports.PAGE_SIZE_PRESETS=U;exports.PageLayoutEngine=K;exports.PageSetupToolbar=de;exports.TextToolbar=ue;exports.Toolbar=Ke;exports.useDocumentEngine=Ze;exports.useFormattingState=ce;exports.useSelectionContext=Ne;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),l=require("react"),qe=require("react-dom"),ke=({dimensions:s,margins:e,pageNumber:n,totalPages:r,children:o})=>t.jsxs("div",{className:"dopecanvas-page",style:{width:`${s.width}px`,height:`${s.height}px`,backgroundColor:"#ffffff",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.15), 0 0 1px rgba(0, 0, 0, 0.1)",position:"relative",overflow:"hidden",flexShrink:0},children:[t.jsx("div",{className:"dopecanvas-page-content",style:{paddingTop:`${e.top}px`,paddingRight:`${e.right}px`,paddingBottom:`${e.bottom}px`,paddingLeft:`${e.left}px`,height:"100%",boxSizing:"border-box",overflow:"hidden"},children:o}),t.jsxs("div",{className:"dopecanvas-page-number",style:{position:"absolute",bottom:`${Math.max(e.bottom/3,16)}px`,left:0,right:0,textAlign:"center",fontSize:"11px",color:"#999",fontFamily:"system-ui, -apple-system, sans-serif",pointerEvents:"none",userSelect:"none"},children:[n," / ",r]})]}),ze=({visible:s,onAddBelow:e,onEditHTML:n,onDelete:r})=>t.jsxs("div",{className:"dopecanvas-block-toolbar",style:{...Ve,display:s?"flex":"none"},onMouseDown:o=>o.preventDefault(),children:[t.jsx(me,{onClick:e,title:"Add block below",children:t.jsx(We,{})}),t.jsx(me,{onClick:n,title:"Edit HTML",children:t.jsx(Oe,{})}),t.jsx(me,{onClick:r,title:"Delete block",danger:!0,children:t.jsx($e,{})})]}),We=()=>t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",children:[t.jsx("line",{x1:"7",y1:"3",x2:"7",y2:"11"}),t.jsx("line",{x1:"3",y1:"7",x2:"11",y2:"7"})]}),Oe=()=>t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("polyline",{points:"4.5,3 1.5,7 4.5,11"}),t.jsx("polyline",{points:"9.5,3 12.5,7 9.5,11"})]}),$e=()=>t.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:t.jsx("path",{d:"M2.5 4h9M5 4V2.5h4V4M3.5 4l.5 8h6l.5-8"})}),me=({onClick:s,title:e,children:n,danger:r})=>{const[o,a]=l.useState(!1);return t.jsx("button",{onClick:s,title:e,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),style:{...Ue,background:o?r?"#fff0f0":"#f0f0f0":"transparent",color:o&&r?"#d32f2f":"#666"},children:n})},Ve={position:"absolute",top:0,left:-40,flexDirection:"column",gap:"1px",zIndex:100,background:"#fff",borderRadius:"6px",boxShadow:"0 1px 5px rgba(0,0,0,0.12)",padding:"3px",paddingRight:"6px"},Ue={width:"30px",height:"26px",border:"none",cursor:"pointer",borderRadius:"4px",fontSize:"13px",fontFamily:"system-ui, -apple-system, sans-serif",display:"flex",alignItems:"center",justifyContent:"center",padding:0,transition:"background 0.1s, color 0.1s"},Ge=({html:s,onSave:e,onCancel:n})=>{const[r,o]=l.useState(s),a=i=>{if(i.key==="Enter"&&(i.metaKey||i.ctrlKey)&&(i.preventDefault(),e(r)),i.key==="Escape"&&(i.preventDefault(),n()),i.key==="Tab"){i.preventDefault();const h=i.target,u=h.selectionStart,p=h.selectionEnd,m=r.substring(0,u)+" "+r.substring(p);o(m),requestAnimationFrame(()=>{h.selectionStart=h.selectionEnd=u+2})}};return qe.createPortal(t.jsx("div",{style:Ke,onClick:n,children:t.jsxs("div",{style:Xe,onClick:i=>i.stopPropagation(),children:[t.jsxs("div",{style:Ze,children:[t.jsx("span",{style:{fontWeight:600,fontSize:"14px"},children:"Edit Block HTML"}),t.jsx("span",{style:{fontSize:"11px",color:"#888"},children:"⌘Enter to save · Escape to cancel"})]}),t.jsx("textarea",{style:Je,value:r,onChange:i=>o(i.target.value),onKeyDown:a,spellCheck:!1,autoFocus:!0}),t.jsxs("div",{style:Qe,children:[t.jsx("button",{style:Ye,onClick:n,onMouseEnter:i=>{i.target.style.borderColor="#888"},onMouseLeave:i=>{i.target.style.borderColor="#555"},children:"Cancel"}),t.jsx("button",{style:et,onClick:()=>e(r),onMouseEnter:i=>{i.target.style.background="#0055dd"},onMouseLeave:i=>{i.target.style.background="#0066ff"},children:"Save"})]})]})}),document.body)},Ke={position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e4},Xe={width:"min(800px, 90vw)",height:"min(600px, 80vh)",background:"#1e1e1e",borderRadius:"10px",display:"flex",flexDirection:"column",overflow:"hidden",boxShadow:"0 20px 60px rgba(0, 0, 0, 0.4)"},Ze={display:"flex",justifyContent:"space-between",alignItems:"center",padding:"12px 16px",background:"#2d2d2d",color:"#ccc",borderBottom:"1px solid #444"},Je={flex:1,background:"#1e1e1e",color:"#d4d4d4",border:"none",padding:"16px",fontFamily:"'SF Mono', 'Fira Code', 'Consolas', 'Monaco', monospace",fontSize:"13px",lineHeight:"1.6",resize:"none",outline:"none",tabSize:2},Qe={display:"flex",justifyContent:"flex-end",gap:"8px",padding:"12px 16px",background:"#2d2d2d",borderTop:"1px solid #444"},Ye={padding:"6px 16px",border:"1px solid #555",borderRadius:"6px",background:"transparent",color:"#ccc",cursor:"pointer",fontSize:"13px",transition:"border-color 0.15s"},et={padding:"6px 16px",border:"none",borderRadius:"6px",background:"#0066ff",color:"#fff",cursor:"pointer",fontSize:"13px",fontWeight:500,transition:"background 0.15s"},xe={letter:{width:816,height:1056},a4:{width:794,height:1123},legal:{width:816,height:1344}},Ee={top:96,right:96,bottom:96,left:96},ce={size:"letter",margins:{...Ee}};let tt=0;function He(){return`split-${++tt}-${Date.now()}`}const nt=40,ot=new Set(["script","style","img","video","canvas","svg","hr","iframe","object","embed","audio","picture","figure"]),rt=new Set(["p","h1","h2","h3","h4","h5","h6","blockquote","div","li","span","td","th","pre","code"]);function le(s,e){const n=s.tagName.toLowerCase();if(ot.has(n)||e<nt)return null;const r=window.getComputedStyle(s);if(r.getPropertyValue("break-before")==="page"||r.getPropertyValue("page-break-before")==="always")return null;const o=Array.from(s.children);if(o.length>1){const a=st(s,o,e);if(a)return a}if(rt.has(n)||s.childNodes.length>0){const a=it(s,e);if(a)return a}return null}function Re(s){if(s.length===0)return s;const e=[];let n=0;for(;n<s.length;){const r=s[n],o=ve(r);if(!o){e.push(r),n++;continue}const a=[r];let i=n+1;for(;i<s.length&&ve(s[i])===o;)a.push(s[i]),i++;e.push(at(a)),n=i}return e}function st(s,e,n){const r=s.getBoundingClientRect().top;let o=-1;for(let u=0;u<e.length;u++){const p=e[u].getBoundingClientRect(),m=window.getComputedStyle(e[u]),A=parseFloat(m.marginBottom)||0;if(p.bottom+A-r>n&&u>0){o=u;break}}if(o<=0)return null;const a=s.cloneNode(!1),i=s.cloneNode(!1);for(let u=0;u<e.length;u++)u<o?a.appendChild(e[u].cloneNode(!0)):i.appendChild(e[u].cloneNode(!0));const h=He();return a.setAttribute("data-dopecanvas-split-id",h),a.setAttribute("data-dopecanvas-split-part","0"),i.setAttribute("data-dopecanvas-split-id",h),i.setAttribute("data-dopecanvas-split-part","1"),{firstHTML:a.outerHTML,secondHTML:i.outerHTML}}function it(s,e){const n=s.getBoundingClientRect().top,r=[],o=document.createTreeWalker(s,NodeFilter.SHOW_TEXT);for(;o.nextNode();)r.push(o.currentNode);if(r.length===0)return null;let a=null,i=0;for(const p of r){const m=document.createRange();m.selectNodeContents(p);const A=m.getBoundingClientRect();if(A.bottom-n<=e)continue;if(A.top-n>=e){a=p,i=0;break}let k=0,j=p.length;for(;k<j;){const y=Math.floor((k+j)/2),L=document.createRange();L.setStart(p,y),L.collapse(!0),L.getBoundingClientRect().top-n>=e?j=y:k=y+1}a=p,i=k;break}if(!a)return null;const h=a.textContent||"";let u=i;for(;u>0&&h[u-1]!==" "&&h[u-1]!==`
2
+ `;)u--;if(u>0&&(i=u),i===0&&a===r[0]||i>=h.length&&a===r[r.length-1])return null;try{const p=document.createRange();p.setStart(s,0),p.setEnd(a,i);const m=document.createRange();m.setStart(a,i),m.setEndAfter(s.lastChild);const A=p.cloneContents(),k=m.cloneContents(),j=Te(A),y=Te(k);if(j.trim().length===0||y.trim().length===0)return null;const L=s.cloneNode(!1);L.appendChild(A);const _=s.cloneNode(!1);_.appendChild(k);const X=He();return L.setAttribute("data-dopecanvas-split-id",X),L.setAttribute("data-dopecanvas-split-part","0"),_.setAttribute("data-dopecanvas-split-id",X),_.setAttribute("data-dopecanvas-split-part","1"),{firstHTML:L.outerHTML,secondHTML:_.outerHTML}}catch{return null}}function ve(s){const e=s.match(/data-dopecanvas-split-id="([^"]+)"/);return e?e[1]:null}function at(s){const e=document.createElement("div"),n=[];let r="",o="";for(const a of s){e.innerHTML=a;const i=e.firstElementChild;if(i){if(!r){r=i.tagName.toLowerCase();const h=i.cloneNode(!1);h.removeAttribute("data-dopecanvas-split-id"),h.removeAttribute("data-dopecanvas-split-part");const u=document.createElement("div");u.appendChild(h);const p=u.innerHTML,m=p.lastIndexOf("</");o=m>=0?p.substring(0,m):p}n.push(i.innerHTML)}}return r?`${o}${n.join("")}</${r}>`:s[0]}function Te(s){const e=document.createElement("div");return e.appendChild(s.cloneNode(!0)),e.textContent||""}function lt(s){const e=[];return s.querySelectorAll("script").forEach(n=>{const r=document.createElement("script");Array.from(n.attributes).forEach(o=>r.setAttribute(o.name,o.value)),r.textContent=n.textContent||"",n.parentNode?.replaceChild(r,n),e.push(r)}),e}function ct(s){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const n=e.getRangeAt(0),r=n.startContainer,o=Array.from(s.querySelectorAll(".dopecanvas-block-content")),a=o.findIndex(i=>i.contains(r));if(a===-1)return null;try{const i=document.createRange();i.selectNodeContents(o[a]),i.setEnd(n.startContainer,n.startOffset);const h=i.toString().length;return{blockIndex:a,textOffset:h}}catch{return null}}function ut(s,e){const n=s.querySelectorAll(".dopecanvas-block-content");if(e.blockIndex>=n.length)return;const r=n[e.blockIndex],o=document.createTreeWalker(r,NodeFilter.SHOW_TEXT);let a=e.textOffset;for(;o.nextNode();){const i=o.currentNode;if(a<=i.length){try{const h=document.createRange();h.setStart(i,a),h.collapse(!0);const u=window.getSelection();u?.removeAllRanges(),u?.addRange(h)}catch{}return}a-=i.length}try{const i=document.createRange();i.selectNodeContents(r),i.collapse(!1);const h=window.getSelection();h?.removeAllRanges(),h?.addRange(i)}catch{}}const dt=l.memo(({html:s,isEditable:e,isTable:n})=>t.jsx("div",{className:"dopecanvas-block-content",contentEditable:e&&!n?!0:void 0,suppressContentEditableWarning:!0,dangerouslySetInnerHTML:{__html:s}}));function ht(s){const e=s.replace(/\s+/g," ").toLowerCase();return e.includes("break-before")&&e.includes("page")||e.includes("page-break-before")&&e.includes("always")}const gt=l.forwardRef(({html:s,css:e,pageConfig:n,layoutEngine:r,editableManager:o,onContentChange:a,onPaginationChange:i,showPageBreaks:h=!1},u)=>{const p=l.useRef(null),m=l.useRef(null),A=l.useRef(null),k=l.useRef(a);k.current=a;const[j,y]=l.useState([]),L=l.useRef(null),_=l.useRef(!1),X=l.useRef([]),[ee,P]=l.useState(null),[$,V]=l.useState(null),[he,te]=l.useState(""),ne=l.useRef(null),g=typeof n.size=="string"?xe[n.size]:n.size,v=l.useCallback(()=>{if(!m.current)return;const b=m.current.querySelectorAll(".dopecanvas-block-content"),d=[];b.forEach(C=>{const M=C,E=M.children;if(E.length!==0)if(E.length===1)d.push(E[0].outerHTML);else{const S=document.createElement("div");S.innerHTML=M.innerHTML,d.push(S.outerHTML)}});const N=d.join(`
3
+ `);k.current?.(N)},[]),w=l.useCallback(b=>{if(!p.current)return;const d=p.current,N=r.getContentAreaWidth(),C=r.getContentAreaHeight();if(d.style.width=`${N}px`,d.style.position="absolute",d.style.left="-9999px",d.style.top="0",d.style.visibility="hidden",d.innerHTML="",e){const c=document.createElement("style");c.textContent=e,d.appendChild(c)}const M=document.createElement("div");M.innerHTML=b,d.appendChild(M);const S=r.measureBlocks(M).map(c=>{const R=c.element;return{html:R.cloneNode(!0).outerHTML,height:c.height,element:R,breakBefore:c.breakBefore,breakAfter:c.breakAfter}}),T=[];let x=[],H=0,U=0;for(;U<S.length;){const c=S[U];c.breakBefore&&x.length>0&&(T.push(x),x=[],H=0);const R=C-H;if(c.height<=R)x.push(c.html),H+=c.height;else if(x.length>0&&R>=60){const F=le(c.element,R);if(F){x.push(F.firstHTML),T.push(x),x=[],H=0;const W=document.createElement("div");W.innerHTML=F.secondHTML;const q=W.firstElementChild;M.appendChild(q);const oe=q.getBoundingClientRect(),re=window.getComputedStyle(q),f=parseFloat(re.marginTop)||0,O=parseFloat(re.marginBottom)||0;S.splice(U+1,0,{html:q.outerHTML,height:oe.height+f+O,element:q,breakBefore:!1,breakAfter:c.breakAfter})}else T.push(x),x=[c.html],H=c.height}else if(x.length>0)T.push(x),x=[c.html],H=c.height;else{const F=le(c.element,C);if(F){x.push(F.firstHTML),T.push(x),x=[],H=0;const W=document.createElement("div");W.innerHTML=F.secondHTML;const q=W.firstElementChild;M.appendChild(q);const oe=q.getBoundingClientRect(),re=window.getComputedStyle(q),f=parseFloat(re.marginTop)||0,O=parseFloat(re.marginBottom)||0;S.splice(U+1,0,{html:q.outerHTML,height:oe.height+f+O,element:q,breakBefore:!1,breakAfter:c.breakAfter})}else x.push(c.html),T.push(x),x=[],H=0}c.breakAfter&&x.length>0&&(T.push(x),x=[],H=0),U++}x.length>0&&T.push(x),T.length===0&&T.push([]),d.innerHTML="";const Y=T.map(c=>({blocks:c})),D={pages:T.map((c,R)=>({blockIndices:Array.from({length:T[R].length},(F,W)=>W)})),pageCount:T.length};X.current=Y,y(Y),i?.(D),k.current?.(b)},[e,r,i]),z=l.useCallback(()=>{if(!m.current||!p.current)return;const b=m.current,d=ct(b),N=b.querySelectorAll(".dopecanvas-block-content"),C=[];if(N.forEach(f=>{const O=f,G=O.children;if(G.length!==0)if(G.length===1)C.push(G[0].outerHTML);else{const Q=document.createElement("div");Q.innerHTML=O.innerHTML,C.push(Q.outerHTML)}}),C.length===0)return;const E=Re(C).join(`
4
+ `),S=p.current,T=r.getContentAreaWidth(),x=r.getContentAreaHeight();if(S.style.width=`${T}px`,S.style.position="absolute",S.style.left="-9999px",S.style.top="0",S.style.visibility="hidden",S.innerHTML="",e){const f=document.createElement("style");f.textContent=e,S.appendChild(f)}const H=document.createElement("div");H.innerHTML=E,S.appendChild(H);const Y=r.measureBlocks(H).map(f=>({html:f.element.cloneNode(!0).outerHTML,height:f.height,element:f.element,breakBefore:f.breakBefore,breakAfter:f.breakAfter})),D=[];let c=[],R=0,F=0;for(;F<Y.length;){const f=Y[F];f.breakBefore&&c.length>0&&(D.push(c),c=[],R=0);const O=x-R;if(f.height<=O)c.push(f.html),R+=f.height;else if(c.length>0&&O>=60){const G=le(f.element,O);if(G){c.push(G.firstHTML),D.push(c),c=[],R=0;const Q=document.createElement("div");Q.innerHTML=G.secondHTML;const K=Q.firstElementChild;H.appendChild(K);const ge=K.getBoundingClientRect(),ae=window.getComputedStyle(K),pe=parseFloat(ae.marginTop)||0,fe=parseFloat(ae.marginBottom)||0;Y.splice(F+1,0,{html:K.outerHTML,height:ge.height+pe+fe,element:K,breakBefore:!1,breakAfter:f.breakAfter})}else D.push(c),c=[f.html],R=f.height}else if(c.length>0)D.push(c),c=[f.html],R=f.height;else{const G=le(f.element,x);if(G){c.push(G.firstHTML),D.push(c),c=[],R=0;const Q=document.createElement("div");Q.innerHTML=G.secondHTML;const K=Q.firstElementChild;H.appendChild(K);const ge=K.getBoundingClientRect(),ae=window.getComputedStyle(K),pe=parseFloat(ae.marginTop)||0,fe=parseFloat(ae.marginBottom)||0;Y.splice(F+1,0,{html:K.outerHTML,height:ge.height+pe+fe,element:K,breakBefore:!1,breakAfter:f.breakAfter})}else c.push(f.html),D.push(c),c=[],R=0}f.breakAfter&&c.length>0&&(D.push(c),c=[],R=0),F++}c.length>0&&D.push(c),D.length===0&&D.push([]),S.innerHTML="";const W=D.map(f=>({blocks:f})),q=X.current.map(f=>f.blocks.length),oe=W.map(f=>f.blocks.length);q.length!==oe.length||q.some((f,O)=>f!==oe[O])?(_.current=!0,L.current=d,X.current=W,y(W),i?.({pages:D.map(()=>({blockIndices:[]})),pageCount:D.length})):X.current=W},[e,r,i]),Z=l.useRef(z);Z.current=z;const J=l.useCallback(()=>{const b=new DOMParser().parseFromString(s,"text/html");b.head.querySelectorAll('style, link[rel="stylesheet"]').forEach(d=>{b.body.insertBefore(d,b.body.firstChild)}),w(b.body.innerHTML)},[s,w]);l.useEffect(()=>{J()},[J]);const I=l.useCallback(()=>{if(!m.current)return[];const b=m.current.querySelectorAll(".dopecanvas-block-content"),d=[];return b.forEach(N=>{const C=N.firstElementChild;C&&d.push(C.outerHTML)}),d},[]),ue=l.useCallback(b=>{const d=I();d.splice(b+1,0,'<p style="min-height: 1.5em; line-height: 1.6;">&nbsp;</p>'),P(null),w(d.join(`
5
+ `))},[I,w]),ye=l.useCallback(b=>{const d=I();d.length<=1||(d.splice(b,1),P(null),w(d.join(`
6
+ `)))},[I,w]),Ie=l.useCallback(b=>{const d=I();b<d.length&&(V(b),te(d[b]))},[I]),Ne=l.useCallback(b=>{if($===null)return;const d=I();$<d.length&&(d[$]=b),V(null),te(""),P(null),w(d.join(`
7
+ `))},[$,I,w]),Fe=l.useCallback(()=>{V(null),te("")},[]),Se=l.useCallback(()=>{const b='<div style="break-before: page;"></div>',d=I();let N=d.length;const C=window.getSelection();if(C&&C.rangeCount>0&&m.current){const M=C.getRangeAt(0).startContainer,S=Array.from(m.current.querySelectorAll(".dopecanvas-block-content")).findIndex(T=>T.contains(M));S!==-1&&(N=S+1)}d.splice(N,0,b),P(null),w(d.join(`
8
+ `))},[I,w]);return l.useImperativeHandle(u,()=>({insertPageBreak:Se}),[Se]),l.useEffect(()=>{const b=m.current;if(!b)return;A.current&&A.current.disconnect(),b.querySelectorAll(".dopecanvas-block-content").forEach(E=>{const S=E.firstElementChild;S&&S.tagName==="TABLE"&&S.querySelectorAll("td, th").forEach(x=>{x.contentEditable="true"})});const N=lt(b);let C=null;const M=new MutationObserver(()=>{_.current||(C&&clearTimeout(C),C=setTimeout(()=>{v(),Z.current()},800))});return M.observe(b,{childList:!0,subtree:!0,characterData:!0,attributes:!1}),A.current=M,L.current?requestAnimationFrame(()=>{L.current&&m.current&&(ut(m.current,L.current),L.current=null),_.current=!1}):_.current=!1,()=>{M.disconnect(),N.forEach(E=>E.remove()),C&&clearTimeout(C)}},[j,v]),t.jsxs("div",{className:"dopecanvas-paged-view",style:pt,children:[t.jsx("div",{ref:p,"aria-hidden":"true"}),t.jsxs("div",{ref:m,style:ft,children:[e&&t.jsx("style",{dangerouslySetInnerHTML:{__html:e}}),j.map((b,d)=>{const N=j.slice(0,d).reduce((C,M)=>C+M.blocks.length,0);return t.jsx(ke,{dimensions:g,margins:n.margins,pageNumber:d+1,totalPages:j.length,children:b.blocks.map((C,M)=>{const E=N+M,S=C.trim().toLowerCase(),T=!S.startsWith("<script")&&!S.startsWith("<style"),x=S.startsWith("<table"),H=ht(C);return H&&h?t.jsxs("div",{className:"dopecanvas-block-wrapper",style:{position:"relative"},children:[t.jsx("div",{className:"dopecanvas-block-content",style:{display:"none"},dangerouslySetInnerHTML:{__html:C}}),t.jsxs("div",{style:mt,children:[t.jsx("span",{style:Me}),t.jsx("span",{style:bt,children:"Page Break"}),t.jsx("span",{style:Me}),t.jsx("button",{type:"button",title:"Remove page break",onClick:()=>ye(E),onMouseDown:U=>U.preventDefault(),style:xt,children:"✕"})]})]},`${d}-${M}`):H?t.jsx("div",{className:"dopecanvas-block-wrapper",style:{position:"relative"},children:t.jsx("div",{className:"dopecanvas-block-content",dangerouslySetInnerHTML:{__html:C}})},`${d}-${M}`):t.jsxs("div",{className:"dopecanvas-block-wrapper",style:{position:"relative"},onMouseEnter:()=>{T&&(ne.current&&(clearTimeout(ne.current),ne.current=null),P(E))},onMouseLeave:()=>{ne.current=setTimeout(()=>{P(U=>U===E?null:U)},250)},children:[t.jsx(dt,{html:C,isEditable:T,isTable:x}),T&&t.jsx(ze,{visible:ee===E,onAddBelow:()=>ue(E),onEditHTML:()=>Ie(E),onDelete:()=>ye(E)})]},`${d}-${M}`)})},d)}),j.length===0&&t.jsx(ke,{dimensions:g,margins:n.margins,pageNumber:1,totalPages:1,children:t.jsx("div",{contentEditable:"true",style:{minHeight:"1em",outline:"none"},"data-placeholder":"Start typing..."})})]}),$!==null&&t.jsx(Ge,{html:he,onSave:Ne,onCancel:Fe})]})}),pt={flex:1,overflow:"auto",backgroundColor:"#e8e8e8",display:"flex",flexDirection:"column",alignItems:"center"},ft={display:"flex",flexDirection:"column",alignItems:"center",gap:"24px",padding:"24px 0"},mt={display:"flex",alignItems:"center",gap:8,padding:"6px 0",userSelect:"none"},Me={flex:1,height:0,borderTop:"2px dashed #b0b0b0"},bt={fontSize:11,fontWeight:600,color:"#888",textTransform:"uppercase",letterSpacing:"0.05em",whiteSpace:"nowrap",fontFamily:"system-ui, -apple-system, sans-serif"},xt={width:20,height:20,border:"1px solid #ccc",borderRadius:4,backgroundColor:"#fff",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:11,color:"#999",padding:0,flexShrink:0,lineHeight:1};class Ce{config;constructor(e=ce){this.config={...e}}getConfig(){return{...this.config}}setConfig(e){e.size!==void 0&&(this.config.size=e.size),e.margins!==void 0&&(this.config.margins={...e.margins})}getPageDimensions(){return typeof this.config.size=="string"?xe[this.config.size]:this.config.size}getContentAreaHeight(){return this.getPageDimensions().height-this.config.margins.top-this.config.margins.bottom}getContentAreaWidth(){return this.getPageDimensions().width-this.config.margins.left-this.config.margins.right}measureBlocks(e){const n=Array.from(e.children),r=[];for(let o=0;o<n.length;o++){const a=n[o],i=window.getComputedStyle(a),h=i.getPropertyValue("break-before")==="page"||i.getPropertyValue("page-break-before")==="always",u=i.getPropertyValue("break-after")==="page"||i.getPropertyValue("page-break-after")==="always",p=a.getBoundingClientRect(),m=parseFloat(i.marginTop)||0,A=parseFloat(i.marginBottom)||0,k=p.height+m+A;r.push({index:o,height:k,element:a,breakBefore:h,breakAfter:u})}return r}paginate(e){if(e.length===0)return{pages:[{blockIndices:[]}],pageCount:1};const n=this.getContentAreaHeight(),r=[];let o=[],a=0;for(let i=0;i<e.length;i++){const h=e[i];h.breakBefore&&o.length>0&&(r.push({blockIndices:o}),o=[],a=0),a+h.height>n&&o.length>0&&(r.push({blockIndices:o}),o=[],a=0),o.push(h.index),a+=h.height,h.breakAfter&&(r.push({blockIndices:o}),o=[],a=0)}return o.length>0&&r.push({blockIndices:o}),r.length===0&&r.push({blockIndices:[]}),{pages:r,pageCount:r.length}}}class ie{observer=null;changeCallbacks=new Set;contextCallbacks=new Set;undoStack=[];redoStack=[];container=null;debounceTimer=null;selectionHandler=null;currentContext="none";static MAX_UNDO_STACK=100;static DEBOUNCE_MS=150;attach(e){this.detach(),this.container=e,this.makeChildrenEditable(e),this.pushUndoSnapshot(),this.observer=new MutationObserver(this.handleMutations),this.observer.observe(e,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["style","class"]}),this.selectionHandler=this.handleSelectionChange.bind(this),document.addEventListener("selectionchange",this.selectionHandler)}detach(){this.observer&&(this.observer.disconnect(),this.observer=null),this.selectionHandler&&(document.removeEventListener("selectionchange",this.selectionHandler),this.selectionHandler=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.container=null}makeChildrenEditable(e){const n=Array.from(e.children);for(const r of n)r.tagName==="TABLE"?this.makeTableCellsEditable(r):r.contentEditable="true"}makeTableCellsEditable(e){e.querySelectorAll("td, th").forEach(r=>{r.contentEditable="true"})}handleMutations=e=>{this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.pushUndoSnapshot(),this.notifyChange()},ie.DEBOUNCE_MS)};handleSelectionChange(){const e=window.getSelection();if(!e||e.rangeCount===0||!this.container){this.setContext("none");return}const r=e.getRangeAt(0).startContainer;let o=r;for(;o&&o!==this.container;){if(o instanceof HTMLElement){const a=o.tagName;if(a==="TD"||a==="TH"||a==="TABLE"){this.setContext("table");return}if(a==="IMG"){this.setContext("image");return}if(o.dataset?.dopecanvasChart){this.setContext("chart");return}}o=o.parentNode}this.container.contains(r)?this.setContext("text"):this.setContext("none")}setContext(e){e!==this.currentContext&&(this.currentContext=e,this.contextCallbacks.forEach(n=>n(e)))}getContext(){return this.currentContext}pushUndoSnapshot(){if(!this.container)return;const e=this.container.innerHTML,n=this.undoStack[this.undoStack.length-1];n&&n.html===e||(this.undoStack.push({html:e,timestamp:Date.now()}),this.redoStack=[],this.undoStack.length>ie.MAX_UNDO_STACK&&this.undoStack.shift())}undo(){if(!this.container||this.undoStack.length<=1)return!1;const e=this.undoStack.pop();this.redoStack.push(e);const n=this.undoStack[this.undoStack.length-1];return this.pauseObserver(()=>{this.container.innerHTML=n.html,this.makeChildrenEditable(this.container)}),this.notifyChange(),!0}redo(){if(!this.container||this.redoStack.length===0)return!1;const e=this.redoStack.pop();return this.undoStack.push(e),this.pauseObserver(()=>{this.container.innerHTML=e.html,this.makeChildrenEditable(this.container)}),this.notifyChange(),!0}pauseObserver(e){this.observer&&this.observer.disconnect(),e(),this.observer&&this.container&&this.observer.observe(this.container,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["style","class"]})}onChange(e){return this.changeCallbacks.add(e),()=>{this.changeCallbacks.delete(e)}}onContextChange(e){return this.contextCallbacks.add(e),()=>{this.contextCallbacks.delete(e)}}notifyChange(){this.changeCallbacks.forEach(e=>e())}execCommand(e,n){return document.execCommand(e,!1,n)}queryCommandState(e){return document.queryCommandState(e)}queryCommandValue(e){return document.queryCommandValue(e)}getHTML(){return this.container?this.container.innerHTML:""}getPlainText(){return this.container&&(this.container.innerText||this.container.textContent)||""}}const Ct=l.forwardRef(({html:s="",css:e,renderMode:n="paged",pageConfig:r,onContentChange:o,onPageConfigChange:a,style:i},h)=>{const[u,p]=l.useState(r||ce),[m,A]=l.useState({pages:[],pageCount:0}),k=l.useRef(s),j=l.useRef(null),y=l.useRef(null),L=l.useRef(null),[_,X]=l.useState(!1),ee=l.useRef(o);ee.current=o;const P=r||u,$=l.useMemo(()=>new Ce(P),[]),V=l.useMemo(()=>new ie,[]);l.useEffect(()=>{$.setConfig(P)},[P,$]);const he=l.useCallback(g=>{k.current=g,ee.current?.(g)},[]),te=l.useCallback(g=>{const v={...P,...g,margins:{...P.margins,...g.margins||{}}};p(v),$.setConfig(v),a?.(v)},[P,$,a]),ne=l.useCallback(g=>{A(g)},[]);return l.useEffect(()=>{if(n!=="flow"||!y.current)return;const g=k.current||s;y.current.innerHTML=g,k.current=g},[s,n]),l.useImperativeHandle(h,()=>({execCommand:(g,v)=>V.execCommand(g,v),queryCommandState:g=>V.queryCommandState(g),queryCommandValue:g=>V.queryCommandValue(g),getPageConfig:()=>({...P}),setPageConfig:g=>{te(g)},getPageCount:()=>m.pageCount,getHTML:()=>{if(n==="flow"&&y.current){const g=y.current.innerHTML;return k.current=g,g}if(j.current){const g=j.current.querySelectorAll(".dopecanvas-block-content");if(g.length>0){const v=[];if(g.forEach(w=>{const z=w,Z=z.children;if(Z.length!==0)if(Z.length===1)v.push(Z[0].outerHTML);else{const J=document.createElement("div");J.innerHTML=z.innerHTML,v.push(J.outerHTML)}}),v.length>0){const w=v.join(`
9
+ `);return k.current=w,w}}}return k.current},getPlainText:()=>{if(n==="flow"&&y.current)return y.current.innerText||y.current.textContent||"";const g=j.current?(()=>{const w=j.current.querySelectorAll(".dopecanvas-block-content"),z=[];return w.forEach(Z=>{const J=Z,I=J.children;if(I.length!==0)if(I.length===1)z.push(I[0].outerHTML);else{const ue=document.createElement("div");ue.innerHTML=J.innerHTML,z.push(ue.outerHTML)}}),z.length>0?z.join(`
10
+ `):k.current})():k.current,v=document.createElement("div");return v.innerHTML=g,v.innerText||v.textContent||""},undo:()=>V.undo(),redo:()=>V.redo(),insertPageBreak:()=>{if(n==="flow"&&y.current){const g=window.getSelection();if(!g||g.rangeCount===0)return;const v=g.getRangeAt(0);if(!y.current.contains(v.startContainer))return;const w=document.createElement("div");w.style.breakBefore="page",v.insertNode(w),v.setStartAfter(w),v.collapse(!0),g.removeAllRanges(),g.addRange(v);const z=y.current.innerHTML;k.current=z,ee.current?.(z);return}L.current?.insertPageBreak()},setShowPageBreaks:g=>{X(g)},getShowPageBreaks:()=>_}),[V,P,m.pageCount,te,_,n]),t.jsx("div",{ref:j,className:"dopecanvas-root",style:{display:"flex",flexDirection:"column",height:"100%",width:"100%",fontFamily:"system-ui, -apple-system, BlinkMacSystemFont, sans-serif",...i},children:n==="paged"?t.jsx(gt,{ref:L,html:s,css:e,pageConfig:P,layoutEngine:$,editableManager:V,onContentChange:he,onPaginationChange:ne,showPageBreaks:_}):t.jsxs("div",{style:yt,children:[e&&t.jsx("style",{dangerouslySetInnerHTML:{__html:e}}),t.jsx("div",{ref:y,className:"dopecanvas-flow-content",contentEditable:!0,suppressContentEditableWarning:!0,style:St,onInput:()=>{if(!y.current)return;const g=y.current.innerHTML;k.current=g,ee.current?.(g)}})]})})}),yt={flex:1,overflow:"auto",backgroundColor:"#f7f7f5",padding:"24px"},St={minHeight:"100%",outline:"none",backgroundColor:"#fff",border:"1px solid #e5e7eb",borderRadius:8,padding:"20px 24px"};class Ae{layoutEngine;editableManager;sourceHTML="";sourceCSS="";measureContainer=null;contentContainer=null;paginationResult={pages:[],pageCount:0};paginationCallbacks=new Set;changeCallbacks=new Set;constructor(e=ce){this.layoutEngine=new Ce(e),this.editableManager=new ie}getLayoutEngine(){return this.layoutEngine}getEditableManager(){return this.editableManager}getPaginationResult(){return this.paginationResult}getSourceHTML(){return this.sourceHTML}getPageConfig(){return this.layoutEngine.getConfig()}loadHTML(e,n){this.sourceHTML=e,this.sourceCSS=n||""}setMeasureContainer(e){this.measureContainer=e}setContentContainer(e){this.contentContainer&&this.editableManager.detach(),this.contentContainer=e}runPagination(){if(!this.measureContainer)return{result:{pages:[{blockIndices:[]}],pageCount:1},measurements:[]};const e=this.layoutEngine.getContentAreaWidth();this.measureContainer.style.width=`${e}px`,this.measureContainer.style.position="absolute",this.measureContainer.style.left="-9999px",this.measureContainer.style.top="0",this.measureContainer.style.visibility="hidden";let n=null;this.sourceCSS&&(n=document.createElement("style"),n.textContent=this.sourceCSS,this.measureContainer.appendChild(n));const r=document.createElement("div");r.innerHTML=this.sourceHTML,this.measureContainer.appendChild(r);const o=this.layoutEngine.measureBlocks(r);return this.paginationResult=this.layoutEngine.paginate(o),this.measureContainer.innerHTML="",this.paginationCallbacks.forEach(a=>a(this.paginationResult)),{result:this.paginationResult,measurements:o}}rePaginate(){if(!this.contentContainer)return this.paginationResult;const e=this.layoutEngine.measureBlocks(this.contentContainer);return this.paginationResult=this.layoutEngine.paginate(e),this.paginationCallbacks.forEach(n=>n(this.paginationResult)),this.paginationResult}attachEditing(e){this.contentContainer=e,this.editableManager.attach(e),this.editableManager.onChange(()=>{this.sourceHTML=e.innerHTML,this.changeCallbacks.forEach(n=>n(this.sourceHTML))})}setPageConfig(e){this.layoutEngine.setConfig(e)}onPagination(e){return this.paginationCallbacks.add(e),()=>{this.paginationCallbacks.delete(e)}}onChange(e){return this.changeCallbacks.add(e),()=>{this.changeCallbacks.delete(e)}}getHTML(){return this.contentContainer?this.contentContainer.innerHTML:this.sourceHTML}getPlainText(){return this.contentContainer&&(this.contentContainer.innerText||this.contentContainer.textContent)||""}destroy(){this.editableManager.detach(),this.paginationCallbacks.clear(),this.changeCallbacks.clear(),this.measureContainer=null,this.contentContainer=null}}class kt{_html="";_css="";_pageConfig=null;_paginationResult={pages:[],pageCount:0};_changeCallbacks=new Set;_loadCallbacks=new Set;_pageConfigCallbacks=new Set;_getHTMLFn=null;_getPlainTextFn=null;loadHTML(e,n){this._html=e,this._css=n||"",this._loadCallbacks.forEach(r=>r(e,n))}getHTML(){return this._getHTMLFn?this._getHTMLFn():this._html}getPlainText(){if(this._getPlainTextFn)return this._getPlainTextFn();const e=document.createElement("div");return e.innerHTML=this._html,e.innerText||e.textContent||""}onChange(e){return this._changeCallbacks.add(e),()=>{this._changeCallbacks.delete(e)}}onLoad(e){return this._loadCallbacks.add(e),()=>{this._loadCallbacks.delete(e)}}onPageConfigChange(e){return this._pageConfigCallbacks.add(e),()=>{this._pageConfigCallbacks.delete(e)}}getPageCount(){return this._paginationResult.pageCount}getPageConfig(){return this._pageConfig}setPageConfig(e){this._pageConfig&&(this._pageConfig={...this._pageConfig,...e,margins:{...this._pageConfig.margins,...e.margins||{}}},this._pageConfigCallbacks.forEach(n=>n(this._pageConfig)))}querySelectorAll(e){const n=document.createElement("div");return n.innerHTML=this.getHTML(),Array.from(n.querySelectorAll(e))}getElementContent(e){const n=document.createElement("div");n.innerHTML=this.getHTML();const r=n.querySelector(`#${e}`);return r?r.innerHTML:null}setElementContent(e,n){const r=document.createElement("div");r.innerHTML=this.getHTML();const o=r.querySelector(`#${e}`);o&&(o.innerHTML=n,this.loadHTML(r.innerHTML,this._css))}_connectGetHTML(e){this._getHTMLFn=e}_connectGetPlainText(e){this._getPlainTextFn=e}_notifyChange(e){this._html=e,this._changeCallbacks.forEach(n=>n(e))}_updatePagination(e){this._paginationResult=e}_updatePageConfig(e){this._pageConfig=e}}function vt(s){const[e,n]=l.useState("none");return l.useEffect(()=>s?s.onContextChange(o=>{n(o)}):void 0,[s]),e}const Tt={bold:!1,italic:!1,underline:!1,strikethrough:!1,justifyLeft:!1,justifyCenter:!1,justifyRight:!1,justifyFull:!1,orderedList:!1,unorderedList:!1,superscript:!1,subscript:!1,fontName:"",fontSize:"3",foreColor:"#000000",backColor:"",formatBlock:"p"};function Be(){const[s,e]=l.useState(Tt),n=l.useCallback(()=>{try{let r=document.queryCommandValue("formatBlock")||"";r=r.replace(/^<|>$/g,"").toLowerCase(),(!r||r==="div")&&(r="p"),e({bold:document.queryCommandState("bold"),italic:document.queryCommandState("italic"),underline:document.queryCommandState("underline"),strikethrough:document.queryCommandState("strikethrough"),justifyLeft:document.queryCommandState("justifyLeft"),justifyCenter:document.queryCommandState("justifyCenter"),justifyRight:document.queryCommandState("justifyRight"),justifyFull:document.queryCommandState("justifyFull"),orderedList:document.queryCommandState("insertOrderedList"),unorderedList:document.queryCommandState("insertUnorderedList"),superscript:document.queryCommandState("superscript"),subscript:document.queryCommandState("subscript"),fontName:document.queryCommandValue("fontName")||"",fontSize:document.queryCommandValue("fontSize")||"3",foreColor:document.queryCommandValue("foreColor")||"#000000",backColor:document.queryCommandValue("backColor")||"",formatBlock:r})}catch{}},[]);return l.useEffect(()=>(document.addEventListener("selectionchange",n),()=>{document.removeEventListener("selectionchange",n)}),[n]),s}function Pe(){const s=l.useRef(null),e=l.useCallback(()=>{const o=window.getSelection();o&&o.rangeCount>0&&(s.current=o.getRangeAt(0).cloneRange())},[]),n=l.useCallback(()=>{const o=s.current;if(!o)return;const a=window.getSelection();a&&(a.removeAllRanges(),a.addRange(o))},[]),r=l.useCallback(o=>{n(),o()},[n]);return{saveSelection:e,restoreSelection:n,restoreAndExec:r}}const De=({onExecCommand:s})=>{const e=Be(),{saveSelection:n,restoreAndExec:r}=Pe(),o=l.useCallback((u,p)=>m=>{m.preventDefault(),s(u,p)},[s]),a=l.useCallback(u=>p=>{r(()=>s(u,p.target.value))},[s,r]),i=l.useCallback(u=>p=>{r(()=>s(u,p.target.value))},[s,r]),h=l.useCallback(u=>{u.preventDefault();const p=prompt("Enter URL:");p&&s("createLink",p)},[s]);return t.jsxs("div",{style:Mt,children:[t.jsxs("select",{value:e.formatBlock,onChange:a("formatBlock"),style:be,title:"Block Format",onMouseDown:n,children:[t.jsx("option",{value:"p",children:"Paragraph"}),t.jsx("option",{value:"h1",children:"Heading 1"}),t.jsx("option",{value:"h2",children:"Heading 2"}),t.jsx("option",{value:"h3",children:"Heading 3"}),t.jsx("option",{value:"h4",children:"Heading 4"}),t.jsx("option",{value:"h5",children:"Heading 5"}),t.jsx("option",{value:"h6",children:"Heading 6"})]}),t.jsx(se,{}),t.jsxs("select",{value:e.fontName.replace(/['"]/g,""),onChange:a("fontName"),style:{...be,width:110},title:"Font Family",onMouseDown:n,children:[t.jsx("option",{value:"Arial",children:"Arial"}),t.jsx("option",{value:"Georgia",children:"Georgia"}),t.jsx("option",{value:"Times New Roman",children:"Times New Roman"}),t.jsx("option",{value:"Courier New",children:"Courier New"}),t.jsx("option",{value:"Verdana",children:"Verdana"}),t.jsx("option",{value:"Trebuchet MS",children:"Trebuchet MS"}),t.jsx("option",{value:"Comic Sans MS",children:"Comic Sans MS"}),t.jsx("option",{value:"Impact",children:"Impact"}),t.jsx("option",{value:"system-ui",children:"System UI"})]}),t.jsxs("select",{value:e.fontSize,onChange:a("fontSize"),style:{...be,width:56},title:"Font Size",onMouseDown:n,children:[t.jsx("option",{value:"1",children:"8"}),t.jsx("option",{value:"2",children:"10"}),t.jsx("option",{value:"3",children:"12"}),t.jsx("option",{value:"4",children:"14"}),t.jsx("option",{value:"5",children:"18"}),t.jsx("option",{value:"6",children:"24"}),t.jsx("option",{value:"7",children:"36"})]}),t.jsx(se,{}),t.jsx(B,{icon:"B",title:"Bold (Ctrl+B)",active:e.bold,onMouseDown:o("bold"),extraStyle:{fontWeight:700}}),t.jsx(B,{icon:"I",title:"Italic (Ctrl+I)",active:e.italic,onMouseDown:o("italic"),extraStyle:{fontStyle:"italic"}}),t.jsx(B,{icon:"U",title:"Underline (Ctrl+U)",active:e.underline,onMouseDown:o("underline"),extraStyle:{textDecoration:"underline"}}),t.jsx(B,{icon:"S",title:"Strikethrough",active:e.strikethrough,onMouseDown:o("strikethrough"),extraStyle:{textDecoration:"line-through"}}),t.jsx(B,{icon:"x²",title:"Superscript",active:e.superscript,onMouseDown:o("superscript")}),t.jsx(B,{icon:"x₂",title:"Subscript",active:e.subscript,onMouseDown:o("subscript")}),t.jsx(se,{}),t.jsx(Le,{label:"A",title:"Text Color",defaultValue:"#000000",onChange:i("foreColor"),onMouseDown:n}),t.jsx(Le,{label:"A",title:"Highlight Color",defaultValue:"#ffff00",onChange:i("hiliteColor"),onMouseDown:n,highlight:!0}),t.jsx(se,{}),t.jsx(B,{icon:"≡",title:"Align Left",active:e.justifyLeft,onMouseDown:o("justifyLeft")}),t.jsx(B,{icon:"≣",title:"Align Center",active:e.justifyCenter,onMouseDown:o("justifyCenter")}),t.jsx(B,{icon:"≢",title:"Align Right",active:e.justifyRight,onMouseDown:o("justifyRight")}),t.jsx(B,{icon:"☰",title:"Justify",active:e.justifyFull,onMouseDown:o("justifyFull")}),t.jsx(se,{}),t.jsx(B,{icon:"•",title:"Bullet List",active:e.unorderedList,onMouseDown:o("insertUnorderedList")}),t.jsx(B,{icon:"1.",title:"Numbered List",active:e.orderedList,onMouseDown:o("insertOrderedList"),extraStyle:{fontSize:"11px",fontWeight:600}}),t.jsx(B,{icon:"⇤",title:"Decrease Indent",onMouseDown:o("outdent")}),t.jsx(B,{icon:"⇥",title:"Increase Indent",onMouseDown:o("indent")}),t.jsx(se,{}),t.jsx(B,{icon:"🔗",title:"Insert Link",onMouseDown:h}),t.jsx(B,{icon:"—",title:"Horizontal Rule",onMouseDown:o("insertHorizontalRule")}),t.jsx(B,{icon:"T̸",title:"Clear Formatting",onMouseDown:o("removeFormat")})]})},B=({icon:s,title:e,active:n,onMouseDown:r,extraStyle:o})=>t.jsx("button",{type:"button",title:e,onMouseDown:r,style:{width:"28px",height:"28px",borderWidth:"1px",borderStyle:"solid",borderColor:n?"#b0b5bd":"transparent",borderRadius:"3px",backgroundColor:n?"#d0d5dd":"transparent",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"13px",color:"#333",padding:0,fontFamily:"inherit",...o},dangerouslySetInnerHTML:{__html:s}}),se=()=>t.jsx("div",{style:Lt}),Le=({label:s,title:e,defaultValue:n,onChange:r,onMouseDown:o,highlight:a})=>t.jsxs("label",{style:wt,title:e,onMouseDown:o,children:[a?t.jsx("span",{style:{backgroundColor:"#ffff00",padding:"0 2px"},children:s}):s,t.jsx("input",{type:"color",defaultValue:n,onChange:r,style:jt})]}),Mt={display:"flex",alignItems:"center",gap:"2px",flexWrap:"wrap"},be={height:"28px",borderWidth:"1px",borderStyle:"solid",borderColor:"#ccc",borderRadius:"3px",fontSize:"12px",padding:"0 4px",cursor:"pointer",backgroundColor:"#fff"},Lt={width:"1px",height:"20px",backgroundColor:"#ddd",margin:"0 4px"},wt={position:"relative",width:"28px",height:"28px",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",fontSize:"13px",fontWeight:"bold"},jt={position:"absolute",bottom:0,left:0,width:"100%",height:"4px",padding:0,borderWidth:0,borderStyle:"none",cursor:"pointer"},_e=({pageConfig:s,pageCount:e,onPageConfigChange:n})=>{const r=l.useCallback(i=>{const h=i.target.value;n({size:h})},[n]),o=l.useCallback(i=>h=>{const u=Math.max(0,parseInt(h.target.value)||0);n({margins:{...s.margins,[i]:u}})},[s.margins,n]),a=typeof s.size=="string"?s.size:"custom";return t.jsxs("div",{style:Et,children:[t.jsxs("label",{style:Ht,children:["Page:",t.jsxs("select",{value:a,onChange:r,style:Rt,children:[t.jsx("option",{value:"letter",children:"Letter (8.5 x 11)"}),t.jsx("option",{value:"a4",children:"A4 (210 x 297mm)"}),t.jsx("option",{value:"legal",children:"Legal (8.5 x 14)"})]})]}),t.jsx("div",{style:we}),t.jsx("span",{style:{fontSize:"12px",color:"#666"},children:"Margins (px):"}),t.jsx(de,{label:"T",value:s.margins.top,onChange:o("top")}),t.jsx(de,{label:"R",value:s.margins.right,onChange:o("right")}),t.jsx(de,{label:"B",value:s.margins.bottom,onChange:o("bottom")}),t.jsx(de,{label:"L",value:s.margins.left,onChange:o("left")}),t.jsx("div",{style:we}),t.jsxs("span",{style:{fontSize:"12px",color:"#666"},children:[e," ",e===1?"page":"pages"]})]})},de=({label:s,value:e,onChange:n})=>t.jsxs("label",{style:At,title:`${s} margin`,children:[s,":",t.jsx("input",{type:"number",value:e,onChange:n,style:Bt,min:0,max:300,step:12})]}),Et={display:"flex",alignItems:"center",gap:"6px",flexWrap:"wrap"},Ht={display:"flex",alignItems:"center",gap:"4px",fontSize:"12px",color:"#666"},Rt={height:"26px",borderWidth:"1px",borderStyle:"solid",borderColor:"#ccc",borderRadius:"3px",fontSize:"12px",padding:"0 4px",cursor:"pointer",backgroundColor:"#fff"},we={width:"1px",height:"20px",backgroundColor:"#ddd",margin:"0 4px"},At={display:"flex",alignItems:"center",gap:"2px",fontSize:"11px",color:"#666"},Bt={width:"44px",height:"24px",borderWidth:"1px",borderStyle:"solid",borderColor:"#ccc",borderRadius:"3px",fontSize:"11px",textAlign:"center",padding:"0 2px"},Pt=({pageConfig:s,pageCount:e,onExecCommand:n,onPageConfigChange:r})=>t.jsxs("div",{style:Dt,children:[t.jsx("div",{style:je,children:t.jsx(De,{onExecCommand:n})}),t.jsx("div",{style:je,children:t.jsx(_e,{pageConfig:s,pageCount:e,onPageConfigChange:r})})]}),Dt={borderBottomWidth:"1px",borderBottomStyle:"solid",borderBottomColor:"#d0d0d0",backgroundColor:"#f8f8f8",padding:"4px 8px",display:"flex",flexDirection:"column",gap:"4px",flexShrink:0,zIndex:10},je={display:"flex",alignItems:"center",gap:"4px",minHeight:"32px"};function _t(s={}){const{initialHTML:e="",initialCSS:n="",initialConfig:r=ce}=s,o=l.useRef(new Ae(r)),[a,i]=l.useState({pages:[{blockIndices:[]}],pageCount:1}),[h,u]=l.useState(r),p=l.useCallback((y,L)=>{o.current.loadHTML(y,L)},[]),m=l.useCallback(y=>{o.current.setPageConfig(y),u(o.current.getPageConfig())},[]),A=l.useCallback(()=>{const{result:y}=o.current.runPagination();i(y)},[]),k=l.useCallback(()=>o.current.getHTML(),[]),j=l.useCallback(()=>o.current.getPlainText(),[]);return l.useEffect(()=>{e&&o.current.loadHTML(e,n)},[e,n]),l.useEffect(()=>o.current.onPagination(L=>{i(L)}),[]),l.useEffect(()=>()=>{o.current.destroy()},[]),{engine:o.current,paginationResult:a,pageConfig:h,loadHTML:p,setPageConfig:m,triggerPagination:A,getHTML:k,getPlainText:j}}exports.DEFAULT_MARGINS=Ee;exports.DEFAULT_PAGE_CONFIG=ce;exports.DocumentAPI=kt;exports.DocumentEngine=Ae;exports.DopeCanvas=Ct;exports.EditableManager=ie;exports.PAGE_SIZE_PRESETS=xe;exports.PageLayoutEngine=Ce;exports.PageSetupToolbar=_e;exports.TextToolbar=De;exports.Toolbar=Pt;exports.recombineSplitBlocks=Re;exports.trySplitBlock=le;exports.useDocumentEngine=_t;exports.useFormattingState=Be;exports.useSelectionContext=vt;exports.useSelectionSaver=Pe;
9
11
  //# sourceMappingURL=dopecanvas.cjs.map