@productcloudos/editor 1.0.5 → 1.0.7

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.
Files changed (51) hide show
  1. package/dist/pc-editor.esm.js +2403 -279
  2. package/dist/pc-editor.esm.js.map +1 -1
  3. package/dist/pc-editor.js +2406 -278
  4. package/dist/pc-editor.js.map +1 -1
  5. package/dist/pc-editor.min.js +1 -1
  6. package/dist/pc-editor.min.js.map +1 -1
  7. package/dist/types/lib/core/PCEditor.d.ts +89 -1
  8. package/dist/types/lib/core/PCEditor.d.ts.map +1 -1
  9. package/dist/types/lib/fonts/FontManager.d.ts +71 -0
  10. package/dist/types/lib/fonts/FontManager.d.ts.map +1 -0
  11. package/dist/types/lib/fonts/index.d.ts +3 -0
  12. package/dist/types/lib/fonts/index.d.ts.map +1 -0
  13. package/dist/types/lib/index.d.ts +6 -4
  14. package/dist/types/lib/index.d.ts.map +1 -1
  15. package/dist/types/lib/objects/table/TableObject.d.ts +72 -1
  16. package/dist/types/lib/objects/table/TableObject.d.ts.map +1 -1
  17. package/dist/types/lib/objects/table/types.d.ts +20 -0
  18. package/dist/types/lib/objects/table/types.d.ts.map +1 -1
  19. package/dist/types/lib/panes/ConditionalSectionPane.d.ts +62 -0
  20. package/dist/types/lib/panes/ConditionalSectionPane.d.ts.map +1 -0
  21. package/dist/types/lib/panes/FormattingPane.d.ts +1 -0
  22. package/dist/types/lib/panes/FormattingPane.d.ts.map +1 -1
  23. package/dist/types/lib/panes/ImagePane.d.ts.map +1 -1
  24. package/dist/types/lib/panes/RepeatingSectionPane.d.ts.map +1 -1
  25. package/dist/types/lib/panes/TablePane.d.ts +4 -2
  26. package/dist/types/lib/panes/TablePane.d.ts.map +1 -1
  27. package/dist/types/lib/panes/TableRowLoopPane.d.ts.map +1 -1
  28. package/dist/types/lib/panes/TextBoxPane.d.ts.map +1 -1
  29. package/dist/types/lib/panes/index.d.ts +2 -0
  30. package/dist/types/lib/panes/index.d.ts.map +1 -1
  31. package/dist/types/lib/rendering/CanvasManager.d.ts +2 -0
  32. package/dist/types/lib/rendering/CanvasManager.d.ts.map +1 -1
  33. package/dist/types/lib/rendering/FlowingTextRenderer.d.ts +17 -1
  34. package/dist/types/lib/rendering/FlowingTextRenderer.d.ts.map +1 -1
  35. package/dist/types/lib/rendering/PDFGenerator.d.ts +13 -0
  36. package/dist/types/lib/rendering/PDFGenerator.d.ts.map +1 -1
  37. package/dist/types/lib/text/ConditionalSectionManager.d.ts +101 -0
  38. package/dist/types/lib/text/ConditionalSectionManager.d.ts.map +1 -0
  39. package/dist/types/lib/text/FlowingTextContent.d.ts +44 -6
  40. package/dist/types/lib/text/FlowingTextContent.d.ts.map +1 -1
  41. package/dist/types/lib/text/ParagraphFormatting.d.ts +1 -1
  42. package/dist/types/lib/text/ParagraphFormatting.d.ts.map +1 -1
  43. package/dist/types/lib/text/PredicateEvaluator.d.ts +23 -0
  44. package/dist/types/lib/text/PredicateEvaluator.d.ts.map +1 -0
  45. package/dist/types/lib/text/index.d.ts +3 -1
  46. package/dist/types/lib/text/index.d.ts.map +1 -1
  47. package/dist/types/lib/text/types.d.ts +21 -0
  48. package/dist/types/lib/text/types.d.ts.map +1 -1
  49. package/dist/types/lib/types/index.d.ts +13 -0
  50. package/dist/types/lib/types/index.d.ts.map +1 -1
  51. package/package.json +2 -1
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("pdf-lib"),require("pdfjs-dist")):"function"==typeof define&&define.amd?define(["exports","pdf-lib","pdfjs-dist"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).PCEditor={},t.PDFLib,t.pdfjsLib)}(this,function(t,e,i){"use strict";function n(t){var e=Object.create(null);return t&&Object.keys(t).forEach(function(i){if("default"!==i){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}),e.default=t,Object.freeze(e)}var s=n(i);class o{constructor(){this.events=new Map}on(t,e){this.events.has(t)||this.events.set(t,new Set),this.events.get(t).add(e)}off(t,e){const i=this.events.get(t);i&&(i.delete(e),0===i.size&&this.events.delete(t))}emit(t,...e){const i=this.events.get(t);i&&i.forEach(i=>{try{i(...e)}catch(e){console.error(`Error in event handler for ${t}:`,e)}})}once(t,e){const i=(...n)=>{this.off(t,i),e(...n)};this.on(t,i)}removeAllListeners(t){t?this.events.delete(t):this.events.clear()}listenerCount(t){const e=this.events.get(t);return e?e.size:0}}class r extends o{constructor(t,e){super(),this._id=t.id,this._settings=e}get id(){return this._id}get settings(){return{...this._settings}}getPageDimensions(){const t={A4:{width:210,height:297},Letter:{width:215.9,height:279.4},Legal:{width:215.9,height:355.6},A3:{width:297,height:420}};let e;return e="Custom"===this._settings.pageSize&&this._settings.customPageSize?{width:this._settings.customPageSize.width,height:this._settings.customPageSize.height}:"Custom"!==this._settings.pageSize&&t[this._settings.pageSize]||t.A4,"landscape"===this._settings.pageOrientation&&(e={width:e.height,height:e.width}),this.convertToPixels(e)}convertToPixels(t){const e={px:1,mm:96/25.4,in:96,pt:96/72}[this._settings.units]||1;return{width:t.width*e,height:t.height*e}}getContentBounds(){const t=this.getPageDimensions(),e=this._settings.margins,i=this.convertToPixels({width:1,height:1}).width,n=e.top*i,s=e.bottom*i,o=e.left*i,r=e.right*i;return{position:{x:o,y:n},size:{width:t.width-o-r,height:t.height-n-s}}}getHeaderBounds(){const t=this.getPageDimensions(),e=this._settings.margins,i=this.convertToPixels({width:1,height:1}).width,n=e.top*i,s=e.left*i,o=e.right*i;return{position:{x:s,y:0},size:{width:t.width-s-o,height:n}}}getFooterBounds(){const t=this.getPageDimensions(),e=this._settings.margins,i=this.convertToPixels({width:1,height:1}).width,n=e.bottom*i,s=e.left*i,o=e.right*i;return{position:{x:s,y:t.height-n},size:{width:t.width-s-o,height:n}}}updateSettings(t){this._settings=t,this.emit("settings-changed",{settings:t}),this.emit("change")}toData(){return{id:this._id}}}const a={listType:"bullet",bulletStyle:"disc",nestingLevel:0},l={fontFamily:"Arial",fontSize:14,fontWeight:"normal",fontStyle:"normal",color:"#000000"},h={alignment:"left"},d="",c="\f";class g extends o{constructor(t){super(),this.content="",this.cursorPosition=0,this.fieldCheckCallback=null,this.selectionAnchor=null,t&&(this.content=t)}setFieldCheckCallback(t){this.fieldCheckCallback=t}isReplacementChar(t){return this.content.charAt(t)===d}isFieldAt(t){return!!this.fieldCheckCallback&&(this.isReplacementChar(t)&&this.fieldCheckCallback(t))}getText(){return this.content}setText(t){const e=this.content;this.content=t,this.cursorPosition=Math.min(this.cursorPosition,t.length),this.emit("text-changed",{text:t,previousContent:e,cursorPosition:this.cursorPosition})}insertText(t,e){const i=e??this.cursorPosition,n=this.content;return this.content=this.content.slice(0,i)+t+this.content.slice(i),this.cursorPosition=i+t.length,this.emit("text-inserted",{text:t,position:i,newCursorPosition:this.cursorPosition,previousContent:n}),this.cursorPosition}deleteText(t,e){const i=t+e,n=this.content,s=this.content.slice(t,i);return this.content=this.content.slice(0,t)+this.content.slice(i),this.cursorPosition=Math.min(this.cursorPosition,t),this.emit("text-deleted",{start:t,length:e,deletedText:s,newCursorPosition:this.cursorPosition,previousContent:n}),s}backspace(){if(0===this.cursorPosition)return!1;const t=this.cursorPosition-1;return this.isFieldAt(t),this.deleteText(t,1),!0}deleteForward(){return!(this.cursorPosition>=this.content.length)&&(this.isFieldAt(this.cursorPosition),this.deleteText(this.cursorPosition,1),!0)}getCursorPosition(){return this.cursorPosition}setCursorPosition(t){const e=this.cursorPosition,i=Math.max(0,Math.min(t,this.content.length));this.cursorPosition=i,this.cursorPosition!==e&&(this.emit("cursor-moved",{position:this.cursorPosition,previousPosition:e}),null!==this.selectionAnchor&&this.emitSelectionChange())}moveCursor(t){if(0!==t)if(t<0)for(let e=0;e<Math.abs(t);e++)this.moveCursorLeft();else for(let e=0;e<t;e++)this.moveCursorRight()}moveCursorLeft(){if(0===this.cursorPosition)return;const t=this.cursorPosition-1;this.setCursorPosition(t)}moveCursorRight(){if(this.cursorPosition>=this.content.length)return;const t=this.cursorPosition+1;this.isFieldAt(this.cursorPosition),this.setCursorPosition(t)}get length(){return this.content.length}get isEmpty(){return 0===this.content.length}charAt(t){return this.content.charAt(t)}substring(t,e){return this.content.substring(t,e)}indexOf(t,e){return this.content.indexOf(t,e)}clear(){this.setText("")}setSelectionAnchor(t){this.selectionAnchor=t??this.cursorPosition}getSelection(){if(null===this.selectionAnchor)return null;const t=Math.min(this.selectionAnchor,this.cursorPosition),e=Math.max(this.selectionAnchor,this.cursorPosition);return t===e?null:{start:t,end:e}}hasSelection(){return null!==this.getSelection()}hasSelectionAnchor(){return null!==this.selectionAnchor}clearSelection(){null!==this.selectionAnchor&&(this.selectionAnchor=null,this.emit("selection-changed",{selection:null}))}getSelectedText(){const t=this.getSelection();return t?this.content.substring(t.start,t.end):""}deleteSelection(){const t=this.getSelection();return!!t&&(this.deleteText(t.start,t.end-t.start),this.selectionAnchor=null,!0)}selectLeft(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorLeft(),this.emitSelectionChange()}selectRight(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorRight(),this.emitSelectionChange()}emitSelectionChange(){this.emit("selection-changed",{selection:this.getSelection()})}isWordChar(t){return/[\w\u00C0-\u024F]/.test(t)}getWordBoundaries(t){if(0===this.content.length)return{start:0,end:0};const e=Math.max(0,Math.min(t,this.content.length));if(e>=this.content.length){let t=e;for(;t>0&&this.isWordChar(this.content.charAt(t-1));)t--;return{start:t,end:this.content.length}}const i=this.content.charAt(e);if(!this.isWordChar(i)){if(e>0&&this.isWordChar(this.content.charAt(e-1))){let t=e-1;for(;t>0&&this.isWordChar(this.content.charAt(t-1));)t--;return{start:t,end:e}}return{start:e,end:e}}let n=e;for(;n>0&&this.isWordChar(this.content.charAt(n-1));)n--;let s=e;for(;s<this.content.length&&this.isWordChar(this.content.charAt(s));)s++;return{start:n,end:s}}getParagraphBoundaries(t){if(0===this.content.length)return{start:0,end:0};const e=Math.max(0,Math.min(t,this.content.length));let i=e;for(;i>0&&"\n"!==this.content.charAt(i-1);)i--;let n=e;for(;n<this.content.length&&"\n"!==this.content.charAt(n);)n++;return{start:i,end:n}}selectWord(){const{start:t,end:e}=this.getWordBoundaries(this.cursorPosition);t!==e&&(this.selectionAnchor=t,this.cursorPosition=e,this.emitSelectionChange())}selectParagraph(){const{start:t,end:e}=this.getParagraphBoundaries(this.cursorPosition);this.selectionAnchor=t,this.cursorPosition=e,this.emitSelectionChange()}selectAll(){0!==this.content.length&&(this.selectionAnchor=0,this.cursorPosition=this.content.length,this.emitSelectionChange())}moveCursorToLineStart(){let t=this.cursorPosition;for(;t>0&&"\n"!==this.content.charAt(t-1);)t--;this.setCursorPosition(t)}moveCursorToLineEnd(){let t=this.cursorPosition;for(;t<this.content.length&&"\n"!==this.content.charAt(t);)t++;this.setCursorPosition(t)}moveCursorToDocumentStart(){this.setCursorPosition(0)}moveCursorToDocumentEnd(){this.setCursorPosition(this.content.length)}selectToLineStart(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorToLineStart(),this.emitSelectionChange()}selectToLineEnd(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorToLineEnd(),this.emitSelectionChange()}selectToDocumentStart(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorToDocumentStart(),this.emitSelectionChange()}selectToDocumentEnd(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorToDocumentEnd(),this.emitSelectionChange()}moveCursorWordLeft(){if(0===this.cursorPosition)return;let t=this.cursorPosition-1;for(;t>0&&!this.isWordChar(this.content.charAt(t));)t--;for(;t>0&&this.isWordChar(this.content.charAt(t-1));)t--;this.setCursorPosition(t)}moveCursorWordRight(){if(this.cursorPosition>=this.content.length)return;let t=this.cursorPosition;for(;t<this.content.length&&this.isWordChar(this.content.charAt(t));)t++;for(;t<this.content.length&&!this.isWordChar(this.content.charAt(t));)t++;this.setCursorPosition(t)}selectWordLeft(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorWordLeft(),this.emitSelectionChange()}selectWordRight(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorWordRight(),this.emitSelectionChange()}}class u extends o{constructor(t){super(),this.formatting=new Map,this._pendingFormatting=null,this._defaultFormatting={...l,...t}}get defaultFormatting(){return{...this._defaultFormatting}}setDefaultFormatting(t){this._defaultFormatting={...this._defaultFormatting,...t},this.emit("default-formatting-changed",{formatting:this._defaultFormatting})}getFormattingAt(t){const e=this.formatting.get(t);return e?{...this._defaultFormatting,...e}:{...this._defaultFormatting}}applyFormatting(t,e,i,n=!1){for(let n=t;n<e;n++){const t=this.formatting.get(n)||{...this._defaultFormatting};this.formatting.set(n,{...t,...i})}n||this.emit("formatting-changed",{start:t,end:e,formatting:i})}setFormattingAt(t,e,i=!1){this.formatting.set(t,{...e}),i||this.emit("formatting-changed",{start:t,end:t+1,formatting:e})}clearFormatting(t,e){for(let i=t;i<e;i++)this.formatting.delete(i);this.emit("formatting-cleared",{start:t,end:e})}shiftFormatting(t,e){if(0===e)return;const i=new Map;for(const[n,s]of this.formatting.entries())if(n>=t){this.formatting.delete(n);const t=n+e;t>=0&&i.set(t,s)}for(const[t,e]of i.entries())this.formatting.set(t,e)}handleDeletion(t,e){for(let i=t;i<t+e;i++)this.formatting.delete(i);this.shiftFormatting(t+e,-e)}getAllFormatting(){return new Map(this.formatting)}getCompressedRuns(t){const e=[],i=this._defaultFormatting;let n=null;for(let s=0;s<t;s++){const t=this.getFormattingAt(s);if(null===n||t.fontFamily!==n.fontFamily||t.fontSize!==n.fontSize||t.fontWeight!==n.fontWeight||t.fontStyle!==n.fontStyle||t.color!==n.color||t.backgroundColor!==n.backgroundColor){(!(t.fontFamily===i.fontFamily&&t.fontSize===i.fontSize&&t.fontWeight===i.fontWeight&&t.fontStyle===i.fontStyle&&t.color===i.color&&t.backgroundColor===i.backgroundColor)||e.length>0)&&e.push({index:s,formatting:{...t}}),n=t}}return e}setAllFormatting(t){this.formatting=new Map(t),this.emit("formatting-restored")}clear(){this.formatting.clear(),this._pendingFormatting=null,this.emit("formatting-cleared",{start:0,end:1/0})}setPendingFormatting(t){this._pendingFormatting={...this._pendingFormatting,...t},this.emit("pending-formatting-changed",{formatting:this._pendingFormatting})}getPendingFormatting(){return this._pendingFormatting?{...this._pendingFormatting}:null}hasPendingFormatting(){return null!==this._pendingFormatting}clearPendingFormatting(){null!==this._pendingFormatting&&(this._pendingFormatting=null,this.emit("pending-formatting-cleared"))}applyPendingFormatting(t,e){this._pendingFormatting&&e>0&&this.applyFormatting(t,t+e,this._pendingFormatting)}}const f=["disc","circle","square"],p=["decimal","lower-alpha","lower-roman"];class m extends o{constructor(t){super(),this.formatting=new Map,this._defaultFormatting={...h,...t}}get defaultFormatting(){return{...this._defaultFormatting}}setDefaultFormatting(t){this._defaultFormatting={...this._defaultFormatting,...t},this.emit("default-formatting-changed",{formatting:this._defaultFormatting})}getParagraphStart(t,e){if(t<=0)return 0;for(let i=Math.min(t-1,e.length-1);i>=0;i--)if("\n"===e[i])return i+1;return 0}getFormattingAt(t,e){const i=this.getParagraphStart(t,e);return this.getFormattingForParagraph(i)}getFormattingForParagraph(t){const e=this.formatting.get(t);return e?{...e}:{...this._defaultFormatting}}setAlignment(t,e){const i=this.formatting.get(t)||{...this._defaultFormatting};this.formatting.set(t,{...i,alignment:e}),this.emit("paragraph-formatting-changed",{paragraphStart:t,alignment:e})}setListFormatting(t,e){const i=this.formatting.get(t)||{...this._defaultFormatting};if(void 0===e){const{listFormatting:e,...n}=i;this.formatting.set(t,n)}else this.formatting.set(t,{...i,listFormatting:e});this.emit("paragraph-formatting-changed",{paragraphStart:t,listFormatting:e})}clearListFormatting(t){this.setListFormatting(t,void 0)}toggleList(t,e){const i=this.formatting.get(t),n=i?.listFormatting;if(n?.listType===e)this.clearListFormatting(t);else{const i=n?.nestingLevel??0,s="bullet"===e?{listType:"bullet",bulletStyle:this.getBulletStyleForLevel(i),nestingLevel:i}:{listType:"number",numberStyle:this.getNumberStyleForLevel(i),nestingLevel:i};this.setListFormatting(t,s)}}indentParagraph(t){const e=this.formatting.get(t),i=e?.listFormatting;if(!i)return void this.setListFormatting(t,{...a});if(i.nestingLevel>=8)return;const n=i.nestingLevel+1,s="bullet"===i.listType?{...i,nestingLevel:n,bulletStyle:this.getBulletStyleForLevel(n)}:{...i,nestingLevel:n,numberStyle:this.getNumberStyleForLevel(n)};this.setListFormatting(t,s)}outdentParagraph(t){const e=this.formatting.get(t),i=e?.listFormatting;if(!i)return;if(0===i.nestingLevel)return void this.clearListFormatting(t);const n=i.nestingLevel-1,s="bullet"===i.listType?{...i,nestingLevel:n,bulletStyle:this.getBulletStyleForLevel(n)}:{...i,nestingLevel:n,numberStyle:this.getNumberStyleForLevel(n)};this.setListFormatting(t,s)}getBulletStyleForLevel(t){return f[t%f.length]}getNumberStyleForLevel(t){return p[t%p.length]}getListNumber(t,e){const i=this.getFormattingForParagraph(t).listFormatting;if(!i||"number"!==i.listType)return;const n=i.nestingLevel,s=[0];for(let t=0;t<e.length;t++)"\n"===e[t]&&s.push(t+1);const o=s.indexOf(t);if(-1===o)return i.startNumber??1;let r=0,a=1;for(let t=o;t>=0;t--){const e=s[t],i=this.getFormattingForParagraph(e).listFormatting;if(!(i&&i.nestingLevel>n)){if(!i||"number"!==i.listType||i.nestingLevel!==n)break;if(r++,void 0!==i.startNumber){a=i.startNumber;break}}}return a+r-1}applyToRange(t,e,i,n){const s=this.getParagraphBoundariesInRange(t,e,i);for(const t of s){const e=this.formatting.get(t)||{...this._defaultFormatting};this.formatting.set(t,{...e,...n})}this.emit("paragraph-formatting-changed",{start:t,end:e,formatting:n})}getParagraphBoundariesInRange(t,e,i){const n=[],s=this.getParagraphStart(t,i);n.push(s);for(let s=t;s<e&&s<i.length;s++)"\n"===i[s]&&s+1<=e&&n.push(s+1);return[...new Set(n)]}shiftParagraphs(t,e,i){if(0===e)return;const n=new Map;for(const[i,s]of this.formatting.entries())if(i>t){this.formatting.delete(i);const t=i+e;t>=0&&n.set(t,s)}for(const[t,e]of n.entries())this.formatting.set(t,e);const s=i.slice(t,t+e);if(s.includes("\n")){const e=this.getParagraphStart(t,i),n=this.formatting.get(e);if(n)for(let e=0;e<s.length;e++)if("\n"===s[e]){const i=t+e+1;this.formatting.has(i)||this.formatting.set(i,{...n})}}}handleDeletion(t,e){const i=t+e;for(const e of this.formatting.keys())e>t&&e<i&&this.formatting.delete(e);const n=new Map;for(const[t,s]of this.formatting.entries())if(t>=i){this.formatting.delete(t);const i=t-e;i>=0&&n.set(i,s)}for(const[t,e]of n.entries())this.formatting.set(t,e)}clear(){this.formatting.clear(),this.emit("paragraph-formatting-cleared")}toJSON(){return Array.from(this.formatting.entries()).map(([t,e])=>({paragraphStart:t,formatting:e}))}fromJSON(t){this.formatting.clear();for(const e of t)this.formatting.set(e.paragraphStart,e.formatting);this.emit("paragraph-formatting-loaded")}getAllFormatting(){return new Map(this.formatting)}}class b extends o{constructor(){super(),this.fields=new Map,this.nextId=1}insert(t,e,i){const n={id:"field-"+this.nextId++,textIndex:e,fieldName:t,fieldType:i?.fieldType,displayFormat:i?.displayFormat,defaultValue:i?.defaultValue,formatting:i?.formatting};return this.fields.set(e,n),this.emit("field-added",{field:n}),n}remove(t){const e=this.fields.get(t);return e&&(this.fields.delete(t),this.emit("field-removed",{field:e})),e}getFieldAt(t){return this.fields.get(t)}hasFieldAt(t){return this.fields.has(t)}getFieldsInRange(t,e){const i=[];for(const[n,s]of this.fields)n>=t&&n<e&&i.push({textIndex:n,field:s});return i.sort((t,e)=>t.textIndex-e.textIndex)}insertAt(t,e){e.textIndex=t,this.fields.set(t,e),this.emit("field-added",{field:e})}getFields(){return new Map(this.fields)}getFieldsArray(){return Array.from(this.fields.values()).sort((t,e)=>t.textIndex-e.textIndex)}findById(t){for(const e of this.fields.values())if(e.id===t)return e}findByFieldName(t){for(const e of this.fields.values())if(e.fieldName===t)return e}findAllByFieldName(t){return Array.from(this.fields.values()).filter(e=>e.fieldName===t)}isPageNumberField(t){return"pageNumber"===t.fieldType}isPageCountField(t){return"pageCount"===t.fieldType}isSpecialField(t){return"pageNumber"===t.fieldType||"pageCount"===t.fieldType}getPageNumberFields(){return Array.from(this.fields.values()).filter(t=>"pageNumber"===t.fieldType)}getPageCountFields(){return Array.from(this.fields.values()).filter(t=>"pageCount"===t.fieldType)}getDataFields(){return Array.from(this.fields.values()).filter(t=>!t.fieldType||"data"===t.fieldType)}shiftFields(t,e){const i=[];for(const[e,n]of this.fields)e>=t&&i.push({oldIndex:e,field:n});for(const{oldIndex:t,field:n}of i)this.fields.delete(t),n.textIndex=t+e,this.fields.set(n.textIndex,n);i.length>0&&this.emit("fields-shifted",{fromIndex:t,delta:e})}handleDeletion(t,e){const i=t+e,n=[],s=[];for(const[e,o]of this.fields)e>=t&&e<i?n.push(o):e>=i&&s.push({oldIndex:e,field:o});for(const t of n)this.fields.delete(t.textIndex),this.emit("field-removed",{field:t});for(const{oldIndex:t,field:i}of s)this.fields.delete(t),i.textIndex=t-e,this.fields.set(i.textIndex,i);return(n.length>0||s.length>0)&&this.emit("fields-changed"),n}updateFieldConfig(t,e){const i=this.fields.get(t);return!!i&&(void 0!==e.fieldName&&(i.fieldName=e.fieldName),void 0!==e.displayFormat&&(i.displayFormat=e.displayFormat),void 0!==e.defaultValue&&(i.defaultValue=e.defaultValue),void 0!==e.formatConfig&&(i.formatConfig=e.formatConfig?{...e.formatConfig}:void 0),this.emit("field-updated",{field:i}),!0)}setFieldFormatting(t,e){const i=this.fields.get(t);return!!i&&(i.formatting={...e},this.emit("field-formatting-changed",{field:i}),!0)}getFieldFormatting(t){const e=this.fields.get(t);return e?.formatting||l}getDisplayText(t,e,i){return"pageNumber"===t.fieldType?void 0!==e?t.displayFormat?t.displayFormat.replace(/%d/g,String(e)):String(e):"{{page}}":"pageCount"===t.fieldType?void 0!==i?t.displayFormat?t.displayFormat.replace(/%d/g,String(i)):String(i):"{{pages}}":`{{field: ${t.fieldName}}}`}getDisplayTextAt(t){const e=this.fields.get(t);if(e)return this.getDisplayText(e)}get count(){return this.fields.size}get isEmpty(){return 0===this.fields.size}clear(){const t=this.fields.size>0;this.fields.clear(),t&&this.emit("fields-cleared")}toJSON(){return this.getFieldsArray()}fromJSON(t){this.clear();for(const e of t){const t={id:e.id,textIndex:e.textIndex,fieldName:e.fieldName,fieldType:e.fieldType,displayFormat:e.displayFormat,defaultValue:e.defaultValue,formatting:e.formatting?{...e.formatting}:void 0,formatConfig:e.formatConfig?{...e.formatConfig}:void 0};this.fields.set(t.textIndex,t);const i=parseInt(e.id.replace("field-",""),10);!isNaN(i)&&i>=this.nextId&&(this.nextId=i+1)}this.emit("fields-loaded",{count:this.fields.size})}}class x extends o{constructor(){super(),this.objects=new Map}getObjects(){return new Map(this.objects)}getObjectsArray(){return Array.from(this.objects.entries()).sort((t,e)=>t[0]-e[0]).map(([t,e])=>({object:e,textIndex:t}))}getObjectAt(t){return this.objects.get(t)}getObjectsInRange(t,e){const i=[];for(const[n,s]of this.objects.entries())n>=t&&n<e&&i.push({object:s,textIndex:n});return i.sort((t,e)=>t.textIndex-e.textIndex)}hasObjectAt(t){return this.objects.has(t)}insert(t,e){t.textIndex=e,this.objects.set(e,t),t.on("position-changed",()=>{this.emit("object-updated",{object:t,textIndex:t.textIndex})}),t.on("offset-changed",()=>{this.emit("object-updated",{object:t,textIndex:t.textIndex})}),t.on("size-changed",()=>{this.emit("object-updated",{object:t,textIndex:t.textIndex})}),this.emit("object-added",{object:t,textIndex:e})}remove(t){const e=this.objects.get(t);if(e)return this.objects.delete(t),this.emit("object-removed",{object:e,textIndex:t}),e}shiftObjects(t,e){if(0===e)return;const i=[];for(const[e,n]of this.objects.entries())e>=t&&i.push({oldIndex:e,object:n});for(const{oldIndex:t}of i)this.objects.delete(t);for(const{oldIndex:t,object:n}of i){const i=t+e;i>=0&&(n.textIndex=i,this.objects.set(i,n))}i.length>0&&this.emit("objects-shifted",{fromIndex:t,delta:e})}handleDeletion(t,e){const i=t+e,n=[],s=[];for(const[e,o]of this.objects)e>=t&&e<i?n.push(o):e>=i&&s.push({oldIndex:e,object:o});for(const t of n)this.objects.delete(t.textIndex),this.emit("object-removed",{object:t,textIndex:t.textIndex});for(const{oldIndex:t}of s)this.objects.delete(t);for(const{oldIndex:t,object:i}of s){const n=t-e;i.textIndex=n,this.objects.set(n,i)}return(n.length>0||s.length>0)&&this.emit("objects-changed"),n}get count(){return this.objects.size}get isEmpty(){return 0===this.objects.size}clear(){const t=this.objects.size>0;this.objects.clear(),t&&this.emit("objects-cleared")}getObjectIds(){return Array.from(this.objects.values()).map(t=>t.id)}findById(t){for(const[e,i]of this.objects.entries())if(i.id===t)return{object:i,textIndex:e}}findByType(t){const e=[];for(const[i,n]of this.objects.entries())n.objectType===t&&e.push({object:n,textIndex:i});return e.sort((t,e)=>t.textIndex-e.textIndex)}updatePosition(t,e){const i=this.objects.get(t);return!!i&&(i.position=e,this.emit("object-updated",{object:i,textIndex:t}),!0)}deselectAll(){for(const t of this.objects.values())t.selected&&(t.selected=!1)}getSelectedObject(){for(const[t,e]of this.objects.entries())if(e.selected)return{object:e,textIndex:t}}}class y extends o{constructor(){super(),this.sections=new Map,this.nextId=1}create(t,e,i){const n="section-"+this.nextId++,s={id:n,fieldPath:i,startIndex:t,endIndex:e};return this.sections.set(n,s),this.emit("section-added",{section:s}),s}remove(t){const e=this.sections.get(t);return e&&(this.sections.delete(t),this.emit("section-removed",{section:e})),e}getSection(t){return this.sections.get(t)}getSections(){return Array.from(this.sections.values())}getSectionsSorted(){return this.getSections().sort((t,e)=>t.startIndex-e.startIndex)}getSectionsDescending(){return this.getSections().sort((t,e)=>e.startIndex-t.startIndex)}getSectionContaining(t){for(const e of this.sections.values())if(t>=e.startIndex&&t<e.endIndex)return e}getSectionAtBoundary(t){for(const e of this.sections.values())if(e.startIndex===t||e.endIndex===t)return e}updateFieldPath(t,e){const i=this.sections.get(t);return!!i&&(i.fieldPath=e,this.emit("section-updated",{section:i}),!0)}updateVisualState(t,e){const i=this.sections.get(t);return!!i&&(i.visualState=e,!0)}shiftSections(t,e){let i=!1;for(const n of this.sections.values())t<=n.startIndex?(n.startIndex+=e,n.endIndex+=e,i=!0):t<n.endIndex&&(n.endIndex+=e,i=!0);i&&this.emit("sections-shifted",{fromIndex:t,delta:e})}handleDeletion(t,e){const i=t+e,n=[],s=[];for(const o of this.sections.values())if(o.startIndex>=t&&o.endIndex<=i)n.push(o);else{if(o.startIndex<i&&o.endIndex>t){if(t<=o.startIndex){n.push(o);continue}if(t<o.endIndex){if(i>=o.endIndex){const e=t;if(e<=o.startIndex){n.push(o);continue}s.push({id:o.id,newStart:o.startIndex,newEnd:e})}else{const t=o.endIndex-e;s.push({id:o.id,newStart:o.startIndex,newEnd:t})}continue}}o.startIndex>=i&&s.push({id:o.id,newStart:o.startIndex-e,newEnd:o.endIndex-e})}for(const t of n)this.sections.delete(t.id),this.emit("section-removed",{section:t});for(const t of s){const e=this.sections.get(t.id);e&&(e.startIndex=t.newStart,e.endIndex=t.newEnd)}return(n.length>0||s.length>0)&&this.emit("sections-changed"),n}validateBoundaries(t,e,i){if(0!==t&&"\n"!==i[t-1])return!1;if(0!==e&&e<i.length&&"\n"!==i[e-1])return!1;if(e<=t)return!1;for(const i of this.sections.values())if(t>=i.startIndex&&t<i.endIndex||e>i.startIndex&&e<=i.endIndex||t<=i.startIndex&&e>=i.endIndex)return!1;return!0}get count(){return this.sections.size}get isEmpty(){return 0===this.sections.size}clear(){const t=this.sections.size>0;this.sections.clear(),t&&this.emit("sections-cleared")}toJSON(){return this.getSectionsSorted().map(t=>({id:t.id,fieldPath:t.fieldPath,startIndex:t.startIndex,endIndex:t.endIndex}))}fromJSON(t){this.clear();for(const e of t){const t={id:e.id,fieldPath:e.fieldPath,startIndex:e.startIndex,endIndex:e.endIndex};this.sections.set(t.id,t);const i=parseInt(e.id.replace("section-",""),10);!isNaN(i)&&i>=this.nextId&&(this.nextId=i+1)}this.emit("sections-loaded",{count:this.sections.size})}}class w extends o{constructor(){super(...arguments),this.hyperlinks=new Map,this.nextId=1}insert(t,e,i,n){const s=this.generateId(),o={id:s,url:t,startIndex:e,endIndex:i,title:n?.title,formatting:n?.formatting};return this.hyperlinks.set(s,o),this.emit("hyperlink-added",{hyperlink:o}),o}remove(t){this.hyperlinks.has(t)&&(this.hyperlinks.delete(t),this.emit("hyperlink-removed",{id:t}))}update(t,e){const i=this.hyperlinks.get(t);i&&(void 0!==e.url&&(i.url=e.url),void 0!==e.title&&(i.title=e.title),void 0!==e.startIndex&&(i.startIndex=e.startIndex),void 0!==e.endIndex&&(i.endIndex=e.endIndex),void 0!==e.formatting&&(i.formatting=e.formatting),this.emit("hyperlink-updated",{id:t,updates:e}))}getHyperlinkById(t){return this.hyperlinks.get(t)}getHyperlinkAt(t){for(const e of this.hyperlinks.values())if(t>=e.startIndex&&t<e.endIndex)return e}getHyperlinksInRange(t,e){const i=[];for(const n of this.hyperlinks.values())n.startIndex<e&&n.endIndex>t&&i.push(n);return i}getAll(){return Array.from(this.hyperlinks.values())}shiftHyperlinks(t,e){for(const i of this.hyperlinks.values())t<=i.startIndex?(i.startIndex+=e,i.endIndex+=e):t<i.endIndex&&(i.endIndex+=e)}handleDeletion(t,e){const i=t+e,n=[];for(const s of this.hyperlinks.values()){const o=s.startIndex,r=s.endIndex;t>=r||(i<=o?(s.startIndex-=e,s.endIndex-=e):t<=o&&i>=r?n.push(s.id):t>o&&i<r?s.endIndex-=e:t<=o&&i>o&&i<r?(s.startIndex=t,s.endIndex=r-i+t):t>o&&t<r&&i>=r&&(s.endIndex=t))}for(const t of n)this.hyperlinks.delete(t),this.emit("hyperlink-removed",{id:t})}clear(){this.hyperlinks.clear(),this.emit("hyperlinks-cleared")}toJSON(){return this.getAll().map(t=>({id:t.id,url:t.url,startIndex:t.startIndex,endIndex:t.endIndex,title:t.title,formatting:t.formatting}))}fromJSON(t){this.hyperlinks.clear();for(const e of t){const t={id:e.id,url:e.url,startIndex:e.startIndex,endIndex:e.endIndex,title:e.title,formatting:e.formatting};this.hyperlinks.set(e.id,t)}this.emit("hyperlinks-loaded")}generateId(){return"hyperlink-"+this.nextId++}}class C{flowText(t,e){if(!t)return[this.createEmptyPage(e)];const i=this.splitIntoLogicalLines(t),n=[];let s=0;for(let t=0;t<i.length;t++){const o=i[t],{text:r,delimiter:a}=o,l=s+r.length,h=e.paragraphFormatting.getFormattingForParagraph(s),d=h.alignment,c=h.listFormatting,g=c?e.paragraphFormatting.getListNumber(s,e.content):void 0,u=this.wrapLogicalLine(r,s,e,d,"end"===a,c,g);if("end"!==a&&u.length>0){const t=u[u.length-1];"newline"===a?t.endsWithNewline=!0:"pagebreak"===a&&(t.endsWithPageBreak=!0)}n.push(...u),s=l+("end"!==a?1:0)}return this.paginateLines(n,e.availableHeight)}splitIntoLogicalLines(t){const e=[];let i=0;for(let n=0;n<t.length;n++){const s=t[n];"\n"!==s&&s!==c||(e.push({text:t.substring(i,n),delimiter:"\n"===s?"newline":"pagebreak"}),i=n+1)}return e.push({text:t.substring(i),delimiter:"end"}),e}wrapLogicalLine(t,e,i,n,s,o,r){const{availableWidth:a,formatting:l,measurer:h}=i,d=[],c=o?this.calculateListIndent(o.nestingLevel):0;let g="",u=0;if(o){g=this.getListMarkerText(o,r);const t=l.getFormattingAt(e);u=h.measureText(g,t)}const f=a-c;if(0===t.length){const t=this.createEmptyLine(e,l,n);if(o){const i=l.getFormattingAt(e>0?e-1:e);t.listMarker={text:g,width:u,indent:c,isFirstLineOfListItem:!0,formatting:i}}return d.push(t),d}const p=this.splitIntoSegments(t,e,i);let m=this.createLineBuilder(e,l),b=0;const x=(t,e)=>{o&&(t.listMarker={text:e?g:"",width:u,indent:c,isFirstLineOfListItem:e}),d.push(t)};for(let t=0;t<p.length;t++){const e=p[t],i=e.text.length>0&&/^\s+$/.test(e.text),s=e.embeddedObjects.find(t=>t.isBlock);if(s){if(m.text.length>0){x(this.finalizeLineBuilder(m,n,!0,f),0===d.length)}x(this.createBlockObjectLine(s,e,n),0===d.length),m=this.createLineBuilder(e.startIndex+1,l),b=0;continue}if(m.width+e.width>f&&m.text.length>0){if(i){if(this.addSegmentToLine(m,e,b),b+=e.width,t+1<p.length){x(this.finalizeLineBuilder(m,n,!1,f),0===d.length);const e=p[t+1];m=this.createLineBuilder(e.startIndex,l),b=0}continue}x(this.finalizeLineBuilder(m,n,!1,f),0===d.length),m=this.createLineBuilder(e.startIndex,l),b=0}this.addSegmentToLine(m,e,b),b+=e.width}if(m.text.length>0||0===d.length){x(this.finalizeLineBuilder(m,n,!0,f),0===d.length)}return d}createBlockObjectLine(t,e,i){const n=t.object;return{text:e.text,width:n.width,height:n.height,baseline:n.height,runs:e.runs,substitutionFields:e.substitutionFields,embeddedObjects:[t],startIndex:e.startIndex,endIndex:e.startIndex+e.text.length,alignment:i,isBlockObjectLine:!0,allowPageBreakBefore:!0}}splitIntoSegments(t,e,i){const n=[];let s=0;for(;s<t.length;){const o=t[s],r=/\s/.test(o);if(o===d){const t=this.measureSegment(o,e+s,i);n.push(t),s++;continue}let a=s+1;for(;a<t.length;){const e=t[a];if(/\s/.test(e)!==r||e===d)break;a++}const l=this.measureSegment(t.substring(s,a),e+s,i);n.push(l),s=a}return n}measureSegment(t,e,i){const{formatting:n,substitutionFields:s,embeddedObjects:o,measurer:r}=i;let a=0,l=0,h=0;const d=[],c=[],g=[];let u=null;for(let i=0;i<t.length;i++){const f=e+i,p=t[i],m=n.getFormattingAt(f),b=s.getFieldAt(f),x=o.getObjectAt(f);if(b){u&&u.text.length>0&&(d.push({text:u.text,formatting:u.formatting,startIndex:u.startIndex,endIndex:u.startIndex+u.text.length}),u=null);const t=r.measureSubstitutionField(b,m);c.push({field:b,textIndex:f,x:a,width:t.width}),d.push({text:p,formatting:m,startIndex:f,endIndex:f+1}),a+=t.width,l=Math.max(l,t.height),h=Math.max(h,.8*m.fontSize)}else if(x)if(u&&u.text.length>0&&(d.push({text:u.text,formatting:u.formatting,startIndex:u.startIndex,endIndex:u.startIndex+u.text.length}),u=null),"block"===x.position)g.push({object:x,textIndex:f,x:0,isBlock:!0}),d.push({text:p,formatting:m,startIndex:f,endIndex:f+1}),h=Math.max(h,.8*m.fontSize);else if("relative"===x.position)g.push({object:x,textIndex:f,x:a,isAnchor:!0}),d.push({text:p,formatting:m,startIndex:f,endIndex:f+1}),h=Math.max(h,.8*m.fontSize);else{const t=x.width+2;g.push({object:x,textIndex:f,x:a}),d.push({text:p,formatting:m,startIndex:f,endIndex:f+1}),a+=t,l=Math.max(l,x.height),h=Math.max(h,.8*m.fontSize)}else{if(""===p)continue;{const t=r.measureCharacter(p,m),e=r.getLineHeight(m);u&&this.formattingEquals(u.formatting,m)||(u&&u.text.length>0&&d.push({text:u.text,formatting:u.formatting,startIndex:u.startIndex,endIndex:u.startIndex+u.text.length}),u={text:"",formatting:m,startIndex:f}),u.text+=p,a+=t,l=Math.max(l,e),h=Math.max(h,.8*m.fontSize)}}}if(u&&u.text.length>0&&d.push({text:u.text,formatting:u.formatting,startIndex:u.startIndex,endIndex:u.startIndex+u.text.length}),0===l){const t=n.getFormattingAt(e);l=1.2*t.fontSize,h=.8*t.fontSize}return{text:t,startIndex:e,width:a,height:l,baseline:h,runs:d,substitutionFields:c,embeddedObjects:g}}addSegmentToLine(t,e,i){t.text+=e.text,t.width+=e.width,t.height=Math.max(t.height,e.height),t.baseline=Math.max(t.baseline,e.baseline),t.endIndex=e.startIndex+e.text.length;for(const i of e.runs)t.runs.push(i);for(const n of e.substitutionFields)t.substitutionFields.push({...n,x:i+n.x});for(const n of e.embeddedObjects)t.embeddedObjects.push({...n,x:i+n.x})}formattingEquals(t,e){return t.fontFamily===e.fontFamily&&t.fontSize===e.fontSize&&t.fontWeight===e.fontWeight&&t.fontStyle===e.fontStyle&&t.color===e.color&&t.backgroundColor===e.backgroundColor}createLineBuilder(t,e){const i=e.getFormattingAt(t);return{text:"",width:0,height:1.2*i.fontSize,baseline:.8*i.fontSize,runs:[],substitutionFields:[],embeddedObjects:[],startIndex:t,endIndex:t}}finalizeLineBuilder(t,e,i,n){const s={text:t.text,width:t.width,height:t.height,baseline:t.baseline,runs:t.runs,substitutionFields:t.substitutionFields,embeddedObjects:t.embeddedObjects,startIndex:t.startIndex,endIndex:t.endIndex,alignment:e};if("justify"===e&&!i&&s.text.length>0){const e=this.countWordGaps(s.text);if(e>0){const i=n-this.getTrimmedLineWidth(t);i>0&&(s.extraWordSpacing=i/e)}}return s}countWordGaps(t){const e=t.trimEnd();let i=0,n=!1;for(const t of e){const e=/\s/.test(t);e||n?e&&n&&(i++,n=!1):n=!0}return i}getTrimmedLineWidth(t){const e=t.text.trimEnd(),i=t.text.length-e.length;if(0===i)return t.width;let n=0,s=i;for(let e=t.runs.length-1;e>=0&&s>0;e--){const i=t.runs[e],o=Math.min(s,i.text.length);n+=o*i.formatting.fontSize*.3,s-=o}return Math.max(0,t.width-n)}createEmptyLine(t,e,i){const n=e.getFormattingAt(t);return{text:"",width:0,height:1.2*n.fontSize,baseline:.8*n.fontSize,runs:[],substitutionFields:[],embeddedObjects:[],startIndex:t,endIndex:t,alignment:i}}createEmptyPage(t){const e=t.paragraphFormatting.getFormattingForParagraph(0).alignment,i={text:"",width:0,height:1.2*t.formatting.defaultFormatting.fontSize,baseline:.8*t.formatting.defaultFormatting.fontSize,runs:[],substitutionFields:[],embeddedObjects:[],startIndex:0,endIndex:0,alignment:e};return{lines:[i],height:i.height,startIndex:0,endIndex:0}}paginateLines(t,e){const i=[];let n={lines:[],height:0,startIndex:t.length>0?t[0].startIndex:0,endIndex:0};for(const s of t){const t=!0===s.isBlockObjectLine;if(n.height+s.height>e&&n.lines.length>0){const t=e-n.height,o=s.embeddedObjects?.some(e=>{if("table"!==e.object.objectType||e.object.height<=t)return!1;const i=e.object;if(i.getHeaderHeight&&i.getFirstDataRowHeight){return i.getHeaderHeight()+i.getFirstDataRowHeight()<=t}return!0});o||(n.endIndex=n.lines[n.lines.length-1].endIndex,i.push(n),n={lines:[],height:0,startIndex:s.startIndex,endIndex:0})}else t&&n.lines.length;n.lines.push(s),n.height+=s.height,s.endsWithPageBreak&&n.lines.length>0&&(n.endIndex=s.endIndex,i.push(n),n={lines:[],height:0,startIndex:s.endIndex+1,endIndex:0})}return n.lines.length>0&&(n.endIndex=n.lines[n.lines.length-1].endIndex,i.push(n)),0===i.length&&i.push({lines:[],height:0,startIndex:0,endIndex:0}),i}findPositionForIndex(t,e){for(let i=0;i<t.length;i++){const n=t[i];for(let t=0;t<n.lines.length;t++){const s=n.lines[t];if(e>=s.startIndex&&e<=s.endIndex)return{pageIndex:i,lineIndex:t}}}if(t.length>0){const e=t[t.length-1];return{pageIndex:t.length-1,lineIndex:Math.max(0,e.lines.length-1)}}return null}getParagraphBoundaries(t){const e=[0];for(let i=0;i<t.length;i++)"\n"===t[i]&&e.push(i+1);return e}calculateListIndent(t){return 24*(t+1)}getListMarkerText(t,e){return"bullet"===t.listType?this.getBulletCharacter(t.bulletStyle,t.nestingLevel)+" ":"number"===t.listType&&void 0!==e?this.formatNumber(e,t.numberStyle)+" ":""}getBulletCharacter(t,e){switch(t||["disc","circle","square"][(e||0)%3]){case"disc":default:return"•";case"circle":return"◦";case"square":return"▪";case"dash":return"–";case"none":return""}}formatNumber(t,e){switch(e){case"lower-alpha":return this.toAlpha(t,!1)+".";case"upper-alpha":return this.toAlpha(t,!0)+".";case"lower-roman":return this.toRoman(t,!1)+".";case"upper-roman":return this.toRoman(t,!0)+".";default:return t+"."}}toAlpha(t,e){let i="";for(;t>0;)t--,i=String.fromCharCode(t%26+(e?65:97))+i,t=Math.floor(t/26);return i}toRoman(t,e){const i=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]];let n="";for(const[e,s]of i)for(;t>=e;)n+=s,t-=e;return e?n:n.toLowerCase()}}class S{constructor(t){this.fontCache=new Map,this.ctx=t}toFontString(t){const e=`${t.fontStyle}-${t.fontWeight}-${t.fontSize}-${t.fontFamily}`;let i=this.fontCache.get(e);return i||(i=`${t.fontStyle||""} ${t.fontWeight||""} ${t.fontSize}px ${t.fontFamily}`.trim(),this.fontCache.set(e,i)),i}measureText(t,e){return this.ctx.font=this.toFontString(e),this.ctx.measureText(t).width}measureCharacter(t,e){return"\t"===t?this.measureText(" ",e):this.measureText(t,e)}getLineHeight(t){return 1.2*t.fontSize}getBaseline(t){return.8*t.fontSize}getCharacterIndexAtX(t,e,i,n=0){if(e<=0)return n;this.ctx.font=this.toFontString(i);let s=0;for(let i=0;i<t.length;i++){const o=this.ctx.measureText(t[i]).width;if(e<s+o/2)return n+i;s+=o}return n+t.length}getXPositionForIndex(t,e,i,n=0){const s=e-n;return s<=0?0:s>=t.length?this.measureText(t,i):this.measureText(t.substring(0,s),i)}setContext(t){this.ctx=t}getFieldDisplayText(t,e,i){return"pageNumber"===t.fieldType?void 0!==e?t.displayFormat?t.displayFormat.replace(/%d/g,String(e)):String(e):t.displayFormat?t.displayFormat.replace(/%d/g,"00"):"00":"pageCount"===t.fieldType?void 0!==i?t.displayFormat?t.displayFormat.replace(/%d/g,String(i)):String(i):t.displayFormat?t.displayFormat.replace(/%d/g,"00"):"00":`{{field: ${t.fieldName}}}`}measureSubstitutionField(t,e,i,n){const s=this.getFieldDisplayText(t,i,n),o=t.formatting||e||l;return{width:this.measureText(s,o),height:this.getLineHeight(o)}}measureEmbeddedObject(t){return{width:t.width,height:t.height}}measureEmbeddedAt(t,e,i,n){const s=e.get(t);if(s){return{...this.measureSubstitutionField(s,n),type:"field",field:s}}const o=i.get(t);if(o){return{...this.measureEmbeddedObject(o),type:"object",object:o}}return{width:0,height:0,type:"none"}}measureWordWithEmbedded(t,e,i,n,s){let o=0,r=this.getLineHeight(e);const a=[],l=[];for(let h=0;h<t.length;h++){const c=t[h],g=s+h;if(c===d){const t=this.measureEmbeddedAt(g,i,n,e);"field"===t.type&&t.field?(a.push({field:t.field,textIndex:g,width:t.width,xOffset:o}),o+=t.width,r=Math.max(r,t.height)):"object"===t.type&&t.object&&(l.push({object:t.object,textIndex:g,xOffset:o}),o+=t.width,"inline"===t.object.position&&(r=Math.max(r,t.height)))}else o+=this.measureCharacter(c,e)}return{width:o,height:r,fields:a,objects:l}}}const v={width:1,color:"#cccccc",style:"solid"};class F extends o{constructor(t){super(),this._relativeOffset={x:0,y:0},this._selected=!1,this._locked=!1,this._renderedPosition=null,this._renderedPageIndex=-1,this._id=t.id,this._textIndex=t.textIndex,this._position=t.position||"inline",this._size={...t.size},t.relativeOffset&&(this._relativeOffset={...t.relativeOffset})}get id(){return this._id}get textIndex(){return this._textIndex}set textIndex(t){this._textIndex=t,this.emit("text-index-changed",{textIndex:t})}get position(){return this._position}set position(t){this._position=t,this.emit("position-changed",{position:t})}get relativeOffset(){return{...this._relativeOffset}}set relativeOffset(t){this._relativeOffset={...t},this.emit("offset-changed",{offset:{...t}})}get size(){return{...this._size}}set size(t){this._size={...t},this.emit("size-changed",{size:{...t}})}get width(){return this._size.width}set width(t){this._size.width=t,this.emit("size-changed",{size:{...this._size}})}get height(){return this._size.height}set height(t){this._size.height=t,this.emit("size-changed",{size:{...this._size}})}get selected(){return this._selected}set selected(t){this._selected!==t&&(this._selected=t,this.emit("selection-changed",{selected:t}))}get locked(){return this._locked}set locked(t){this._locked=t,this.emit("locked-changed",{locked:t})}get renderedPosition(){return this._renderedPosition}set renderedPosition(t){this._renderedPosition=t?{...t}:null}get renderedPageIndex(){return this._renderedPageIndex}set renderedPageIndex(t){this._renderedPageIndex=t}getBounds(){return{x:0,y:0,width:this._size.width,height:this._size.height}}containsPoint(t,e){return t.x>=e.x&&t.x<=e.x+this._size.width&&t.y>=e.y&&t.y<=e.y+this._size.height}resize(t){const e=this.getMinSize(),i=this.getMaxSize();let n=Math.max(t.width,e.width),s=Math.max(t.height,e.height);i&&(n=Math.min(n,i.width),s=Math.min(s,i.height)),this.size={width:n,height:s}}handleClick(t){this._locked||(this.selected=!0)}handleDoubleClick(t){}getMinSize(){return{width:20,height:20}}getMaxSize(){return null}get resizable(){return!this._locked}getResizeHandles(){return this._locked?[]:["nw","n","ne","e","se","s","sw","w"]}renderSelectionBorder(t){const{width:e,height:i}=this._size;if(t.strokeStyle="#0066ff",t.lineWidth=2,t.setLineDash([4,4]),t.strokeRect(0,0,e,i),t.setLineDash([]),this.resizable){const e=8,i=this.getResizeHandles();t.fillStyle="#ffffff",t.strokeStyle="#0066ff",t.lineWidth=1;for(const n of i){const i=this.getHandlePosition(n,e);t.fillRect(i.x,i.y,e,e),t.strokeRect(i.x,i.y,e,e)}}}getHandlePosition(t,e){const{width:i,height:n}=this._size,s=e/2;switch(t){case"nw":return{x:-s,y:-s};case"n":return{x:i/2-s,y:-s};case"ne":return{x:i-s,y:-s};case"e":return{x:i-s,y:n/2-s};case"se":return{x:i-s,y:n-s};case"s":return{x:i/2-s,y:n-s};case"sw":return{x:-s,y:n-s};case"w":return{x:-s,y:n/2-s}}}getResizeHandleAtPoint(t,e=12){if(!this.resizable)return null;const i=this.getResizeHandles(),n=e/2;for(const s of i){const i=this.getHandlePosition(s,e);if(t.x>=i.x-n&&t.x<=i.x+e+n&&t.y>=i.y-n&&t.y<=i.y+e+n)return s}return null}}class I extends F{constructor(t){super(t),this._image=null,this._loaded=!1,this._error=!1,this._src=t.src,this._fit=t.fit||"contain",this._resizeMode=t.resizeMode||"locked-aspect-ratio",this._alt=t.alt||"",this.loadImage()}get objectType(){return"image"}get src(){return this._src}set src(t){this._src!==t&&(this._src=t,this._loaded=!1,this._error=!1,this.loadImage())}get fit(){return this._fit}set fit(t){this._fit=t,this.emit("fit-changed",{fit:t})}get resizeMode(){return this._resizeMode}set resizeMode(t){this._resizeMode=t,this.emit("resize-mode-changed",{resizeMode:t})}get alt(){return this._alt}set alt(t){this._alt=t}get loaded(){return this._loaded}get hasError(){return this._error}get imageElement(){return this._loaded?this._image:null}toPngDataUrl(){if(!this._loaded||!this._image)return null;try{const t=document.createElement("canvas");t.width=this._image.naturalWidth||this._size.width,t.height=this._image.naturalHeight||this._size.height;const e=t.getContext("2d");return e?(e.drawImage(this._image,0,0,t.width,t.height),t.toDataURL("image/png")):null}catch{return null}}loadImage(){this._src?(this._image=new Image,this._image.onload=()=>{this._loaded=!0,this._error=!1,this.emit("image-loaded",{src:this._src})},this._image.onerror=()=>{this._loaded=!1,this._error=!0,this.emit("image-error",{src:this._src})},this._image.src=this._src):this._error=!0}render(t){this._loaded&&this._image?this.drawImage(t):this._error?this.drawErrorPlaceholder(t):this.drawLoadingPlaceholder(t),this._selected&&this.renderSelectionBorder(t)}drawImage(t){if(!this._image)return;const{width:e,height:i}=this._size,n=this._image.naturalWidth,s=this._image.naturalHeight;let o=0,r=0,a=n,l=s,h=0,d=0,c=e,g=i,u=!1;switch(this._fit){case"fill":break;case"contain":{const t=Math.min(e/n,i/s);c=n*t,g=s*t,h=(e-c)/2,d=(i-g)/2;break}case"cover":{const t=Math.max(e/n,i/s);a=e/t,l=i/t,o=(n-a)/2,r=(s-l)/2;break}case"none":c=n,g=s,h=(e-n)/2,d=(i-s)/2,(n>e||s>i)&&(u=!0);break;case"tile":return void this.drawTiledImage(t,e,i)}u&&(t.save(),t.beginPath(),t.rect(0,0,e,i),t.clip()),t.drawImage(this._image,o,r,a,l,h,d,c,g),u&&t.restore()}drawTiledImage(t,e,i){if(!this._image)return;const n=this._image.naturalWidth,s=this._image.naturalHeight;for(let o=0;o<i;o+=s)for(let r=0;r<e;r+=n){const a=Math.min(n,e-r),l=Math.min(s,i-o);t.drawImage(this._image,0,0,a,l,r,o,a,l)}}drawLoadingPlaceholder(t){const{width:e,height:i}=this._size;t.fillStyle="#f0f0f0",t.fillRect(0,0,e,i),t.strokeStyle="#cccccc",t.lineWidth=1,t.strokeRect(0,0,e,i),t.fillStyle="#888888",t.font="12px Arial",t.textAlign="center",t.textBaseline="middle",t.fillText("Loading...",e/2,i/2)}drawErrorPlaceholder(t){const{width:e,height:i}=this._size;t.fillStyle="#fff0f0",t.fillRect(0,0,e,i),t.strokeStyle="#ffcccc",t.lineWidth=1,t.strokeRect(0,0,e,i),t.strokeStyle="#ff6666",t.lineWidth=2,t.beginPath(),t.moveTo(.3*e,.3*i),t.lineTo(.7*e,.7*i),t.moveTo(.7*e,.3*i),t.lineTo(.3*e,.7*i),t.stroke(),i>40&&(t.fillStyle="#cc0000",t.font="10px Arial",t.textAlign="center",t.textBaseline="bottom",t.fillText("Image failed",e/2,i-5))}toData(){return{id:this._id,objectType:"image",textIndex:this._textIndex,position:this._position,size:{...this._size},relativeOffset:"relative"===this._position?{...this._relativeOffset}:void 0,data:{src:this._src,fit:this._fit,resizeMode:this._resizeMode,alt:this._alt,naturalWidth:this._image?.naturalWidth,naturalHeight:this._image?.naturalHeight}}}restoreFromData(t){this._size={...t.size},t.position&&(this._position=t.position),t.relativeOffset&&(this._relativeOffset={...t.relativeOffset});const e=t.data;if(e){const t=void 0!==e.src&&e.src!==this._src;void 0!==e.fit&&(this._fit=e.fit),void 0!==e.resizeMode&&(this._resizeMode=e.resizeMode),void 0!==e.alt&&(this._alt=e.alt),t&&this.setSource(e.src)}this.emit("state-restored",{data:t})}clone(){return new I({id:`${this._id}-clone-${Date.now()}`,textIndex:this._textIndex,position:this._position,size:{...this._size},relativeOffset:"relative"===this._position?{...this._relativeOffset}:void 0,src:this._src,fit:this._fit,resizeMode:this._resizeMode,alt:this._alt})}setSource(t,e){this._src=t,this._loaded=!1,this._error=!1,this._image=new Image,this._image.onload=()=>{if(this._loaded=!0,this._error=!1,void 0!==e?.maxWidth||void 0!==e?.maxHeight){const t=this.getNaturalSize();if(t){const i=e.maxWidth??t.width,n=e.maxHeight??t.height,s=Math.min(i/t.width,n/t.height,1);this.size={width:t.width*s,height:t.height*s}}}this.emit("image-loaded",{src:this._src})},this._image.onerror=()=>{this._loaded=!1,this._error=!0,this.emit("image-error",{src:this._src})},this._image.src=t}getNaturalSize(){return this._loaded&&this._image?{width:this._image.naturalWidth,height:this._image.naturalHeight}:null}resizeToNatural(){const t=this.getNaturalSize();t&&(this.size=t)}resizeToFit(t,e){const i=this.getNaturalSize();if(!i)return;const n=Math.min(t/i.width,e/i.height,1);this.size={width:i.width*n,height:i.height*n}}}class _{static getFontString(t){return`${t.fontStyle||""} ${t.fontWeight||""} ${t.fontSize}px ${t.fontFamily}`.trim()}static getAlignmentOffset(t,e){switch(t.alignment){case"center":return(e-t.width)/2;case"right":return e-t.width;default:return 0}}static findLineAtY(t,e){if(0===t.length)return null;let i=0;for(let n=0;n<t.length;n++){const s=t[n];if(e>=i&&e<i+s.height)return{line:s,lineIndex:n,lineY:i};i+=s.height}if(e>=i&&t.length>0){const e=t.length-1,n=t[e];return{line:n,lineIndex:e,lineY:i-n.height}}return null}static getXPositionForTextIndex(t,e,i){if(e<=t.startIndex)return 0;if(e>=t.endIndex)return"justify"===t.alignment&&t.extraWordSpacing?t.width+this.countWordGapsUpTo(t,t.endIndex)*t.extraWordSpacing:t.width;const n=this.buildSubstitutionFieldMap(t),s=this.buildEmbeddedObjectMap(t);let o=0;for(const r of t.runs){i.font=this.getFontString(r.formatting);for(let a=0;a<r.text.length;a++){const l=r.startIndex+a;if(l>=e)return o;const h=r.text[a];o+=this.getCharWidth(h,l,i,n,s),"justify"===t.alignment&&t.extraWordSpacing&&/\s/.test(h)&&(o+=t.extraWordSpacing)}}return o}static getTextIndexAtX(t,e,i){if(e<=0)return t.startIndex;const n=this.buildSubstitutionFieldMap(t),s=this.buildEmbeddedObjectMap(t);let o=0;const r=t.extraWordSpacing||0;for(const a of t.runs){i.font=this.getFontString(a.formatting);for(let t=0;t<a.text.length;t++){const l=a.startIndex+t,h=a.text[t],d=n.get(l);if(d){const t=d.width;if(e>=o&&e<o+t)return l+1;o+=t,r>0&&/\s/.test(h)&&(o+=r);continue}const c=this.getCharWidth(h,l,i,n,s);if(e>=o&&e<o+c)return e<o+c/2?l:l+1;o+=c,r>0&&/\s/.test(h)&&(o+=r)}}return t.endIndex}static getCharWidth(t,e,i,n,s){const o=n.get(e);if(o)return o.width;const r=s.get(e);return r?r.object.width+2:""!==t?"\t"===t?i.measureText(" ").width:i.measureText(t).width:0}static buildSubstitutionFieldMap(t){const e=new Map;return t.substitutionFields&&t.substitutionFields.forEach(t=>e.set(t.textIndex,t)),e}static buildEmbeddedObjectMap(t){const e=new Map;return t.embeddedObjects&&t.embeddedObjects.forEach(t=>e.set(t.textIndex,t)),e}static countWordGapsUpTo(t,e){let i=0,n=!1;for(let s=t.startIndex;s<Math.min(e,t.endIndex);s++){const e=s-t.startIndex;if(e>=t.text.length)break;const o=t.text[e],r=/\s/.test(o);r||n?r&&n&&(i++,n=!1):n=!0}return i}}const T="Arial",P=14,R="#000000",k="#ffffff",M=4;class E extends F{constructor(t){super(t),this._editing=!1,this._flowedLines=[],this._flowedPage=null,this.type="textbox",this._content=t.content||"",this._fontFamily=t.fontFamily||T,this._fontSize=t.fontSize||P,this._color=t.color||R,this._backgroundColor=t.backgroundColor||k,this._border=function(t,e){const i=e?{...v,color:e}:{...v};return{top:t?.top?{...i,...t.top}:{...i},right:t?.right?{...i,...t.right}:{...i},bottom:t?.bottom?{...i,...t.bottom}:{...i},left:t?.left?{...i,...t.left}:{...i}}}(t.border,t.borderColor),this._padding=t.padding??M,this._flowingContent=new $(this._content),this._flowingContent.setDefaultFormatting({fontFamily:this._fontFamily,fontSize:this._fontSize,color:this._color}),this._flowingContent.on("content-changed",()=>{this._content=this._flowingContent.getText(),this.emit("content-changed",{content:this._content})})}get objectType(){return"textbox"}get content(){return this._content}set content(t){this._content=t,this._flowingContent.setText(t),this.emit("content-changed",{content:t})}get fontFamily(){return this._fontFamily}set fontFamily(t){this._fontFamily=t,this._flowingContent.setDefaultFormatting({fontFamily:t}),this.emit("style-changed",{fontFamily:t})}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize=t,this._flowingContent.setDefaultFormatting({fontSize:t}),this.emit("style-changed",{fontSize:t})}get color(){return this._color}set color(t){this._color=t,this._flowingContent.setDefaultFormatting({color:t}),this.emit("style-changed",{color:t})}get backgroundColor(){return this._backgroundColor}set backgroundColor(t){this._backgroundColor=t,this.emit("style-changed",{backgroundColor:t})}get border(){return this._border}set border(t){this._border=t,this.emit("style-changed",{border:t})}get borderColor(){return this._border.top.color}set borderColor(t){this._border={top:{...this._border.top,color:t},right:{...this._border.right,color:t},bottom:{...this._border.bottom,color:t},left:{...this._border.left,color:t}},this.emit("style-changed",{borderColor:t})}get padding(){return this._padding}set padding(t){this._padding=t,this.emit("style-changed",{padding:t})}get editing(){return this._editing}set editing(t){this._editing!==t&&(this._editing=t,t?this._flowingContent.focus():this._flowingContent.blur(),this.emit("editing-changed",{editing:t}))}get flowingContent(){return this._flowingContent}getTextBounds(){const t="none"!==this._border.left.style?this._border.left.width:0,e="none"!==this._border.right.style?this._border.right.width:0,i="none"!==this._border.top.style?this._border.top.width:0,n="none"!==this._border.bottom.style?this._border.bottom.width:0;return{width:this._size.width-2*this._padding-t-e,height:this._size.height-2*this._padding-i-n}}getTextOffset(){const t="none"!==this._border.left.style?this._border.left.width:0,e="none"!==this._border.top.style?this._border.top.width:0;return{x:this._padding+t,y:this._padding+e}}getTextAreaBounds(){if(!this._renderedPosition)return null;const t=this.getTextOffset(),e=this.getTextBounds();return{x:this._renderedPosition.x+t.x,y:this._renderedPosition.y+t.y,width:e.width,height:e.height}}render(t){this.renderBackground(t),this.renderBorder(t),this._selected&&this.renderSelectionBorder(t),this._editing&&this.renderEditingBorder(t)}renderBackground(t){const{width:e,height:i}=this._size;t.fillStyle=this._backgroundColor,t.fillRect(0,0,e,i)}renderBorder(t){const{width:e,height:i}=this._size;this.drawBorderSide(t,"top",0,0,e,0),this.drawBorderSide(t,"right",e,0,e,i),this.drawBorderSide(t,"bottom",e,i,0,i),this.drawBorderSide(t,"left",0,i,0,0)}drawBorderSide(t,e,i,n,s,o){const r=this._border[e];if(!("none"===r.style||r.width<=0)){switch(t.strokeStyle=r.color,t.lineWidth=r.width,r.style){case"dashed":t.setLineDash([3*r.width,2*r.width]);break;case"dotted":t.setLineDash([r.width,r.width]);break;default:t.setLineDash([])}t.beginPath(),t.moveTo(i,n),t.lineTo(s,o),t.stroke(),t.setLineDash([])}}getXPositionInLine(t,e,i){const n=this.getTextBounds();return _.getAlignmentOffset(e,n.width)+_.getXPositionForTextIndex(e,i,t)}renderEditingBorder(t){const{width:e,height:i}=this._size;t.strokeStyle="#0099ff",t.lineWidth=2,t.setLineDash([]),t.strokeRect(1,1,e-2,i-2)}moveCursorVertical(t,e){if(0===this._flowedLines.length)return!1;const i=this._flowingContent.getCursorPosition();let n=-1;for(let t=0;t<this._flowedLines.length;t++){const e=this._flowedLines[t];if(i>=e.startIndex&&i<=e.endIndex){n=t;break}}-1===n&&(n=this._flowedLines.length-1);const s=n+t;if(s<0||s>=this._flowedLines.length)return!1;const o=this._flowedLines[n],r=this._flowedLines[s],a=this.getXPositionInLine(e,o,i),l=this.getTextIndexAtX(e,r,a);return this._flowingContent.setCursorPosition(l),this._flowingContent.resetCursorBlink(),!0}getTextIndexAtX(t,e,i){const n=this.getTextBounds(),s=i-_.getAlignmentOffset(e,n.width);return _.getTextIndexAtX(e,s,t)}focus(){this.editing=!0}blur(){this.editing=!1}hasFocus(){return this._editing&&this._flowingContent.hasFocus()}handleKeyDown(t){return!!this._editing&&("Escape"===t.key?(t.preventDefault(),this.finishEditing(),!0):this._flowingContent.handleKeyDown(t))}onCursorBlink(t){this._flowingContent.onCursorBlink(t)}offCursorBlink(t){this._flowingContent.offCursorBlink(t)}handleDoubleClick(t){this._locked||(this.editing=!0,this.emit("edit-requested",{object:this}))}finishEditing(){this.editing=!1}toData(){const t=this._flowingContent.getText(),e=this._flowingContent.getFormattingManager().getCompressedRuns(t.length).map(t=>[t.index,{...t.formatting}]),i=this._flowingContent.getSubstitutionFieldManager().getFieldsArray();return{id:this._id,objectType:"textbox",textIndex:this._textIndex,position:this._position,size:{...this._size},relativeOffset:"relative"===this._position?{...this._relativeOffset}:void 0,data:{content:this._content,fontFamily:this._fontFamily,fontSize:this._fontSize,color:this._color,backgroundColor:this._backgroundColor,border:this._border,padding:this._padding,formattingRuns:e,substitutionFields:i}}}restoreFromData(t){this._size={...t.size},t.position&&(this._position=t.position),t.relativeOffset&&(this._relativeOffset={...t.relativeOffset});const e=t.data;if(e){if(void 0!==e.content&&(this._content=e.content,this._flowingContent.setText(e.content)),void 0!==e.fontFamily&&(this._fontFamily=e.fontFamily),void 0!==e.fontSize&&(this._fontSize=e.fontSize),void 0!==e.color&&(this._color=e.color),void 0!==e.backgroundColor&&(this._backgroundColor=e.backgroundColor),void 0!==e.border&&(this._border={...e.border}),void 0!==e.padding&&(this._padding=e.padding),e.formattingRuns&&e.formattingRuns.length>0){const t=this._flowingContent.getFormattingManager();t.clear();const i=this._flowingContent.getText().length;for(let n=0;n<e.formattingRuns.length;n++){const[s,o]=e.formattingRuns[n],r=n+1<e.formattingRuns.length?e.formattingRuns[n+1][0]:i;s<r&&t.applyFormatting(s,r,o)}}if(e.substitutionFields){const t=this._flowingContent.getSubstitutionFieldManager();t.clear();for(const i of e.substitutionFields)t.insertAt(i.textIndex,i)}}this._flowedLines=[],this._flowedPage=null,this.emit("state-restored",{data:t})}clone(){return new E({id:`${this._id}-clone-${Date.now()}`,textIndex:this._textIndex,position:this._position,size:{...this._size},relativeOffset:"relative"===this._position?{...this._relativeOffset}:void 0,content:this._content,fontFamily:this._fontFamily,fontSize:this._fontSize,color:this._color,backgroundColor:this._backgroundColor,border:this._border,padding:this._padding})}getContentSize(t){if(!this._content)return{width:50,height:1.2*this._fontSize+2*this._padding};t.font=`${this._fontSize}px ${this._fontFamily}`;const e=this._content.split("\n");let i=0;for(const n of e){const e=t.measureText(n);i=Math.max(i,e.width)}const n=e.length*this._fontSize*1.2,s=("none"!==this._border.top.style?this._border.top.width:0)+("none"!==this._border.bottom.style?this._border.bottom.width:0),o=("none"!==this._border.left.style?this._border.left.width:0)+("none"!==this._border.right.style?this._border.right.width:0);return{width:i+2*this._padding+o,height:n+2*this._padding+s}}resizeToContent(t){const e=this.getContentSize(t),i=this.getMinSize();this.size={width:Math.max(e.width,i.width),height:Math.max(e.height,i.height)}}getRegionBounds(t){return this.getTextAreaBounds()}globalToLocal(t,e){const i=this.getRegionBounds(e);return i?t.x<i.x||t.x>i.x+i.width||t.y<i.y||t.y>i.y+i.height?null:{x:t.x-i.x,y:t.y-i.y}:null}localToGlobal(t,e){const i=this.getRegionBounds(e);return i?{x:t.x+i.x,y:t.y+i.y}:t}getFlowedLines(t){return this._flowedLines}getFlowedPages(){return this._flowedPage?[this._flowedPage]:[]}getAvailableWidth(){return this.getTextBounds().width}spansMultiplePages(){return!1}getPageCount(){return 1}containsPointInRegion(t,e){return!!this._renderedPosition&&(t.x>=this._renderedPosition.x&&t.x<=this._renderedPosition.x+this._size.width&&t.y>=this._renderedPosition.y&&t.y<=this._renderedPosition.y+this._size.height)}reflow(t){const e=this.getTextBounds();if(e.width<=0||e.height<=0)return this._flowedLines=[],void(this._flowedPage=null);const i=this._flowingContent.flowText(e.width,1e4,t);this._flowedLines=i.length>0?i[0].lines:[],this._flowedPage=i.length>0?i[0]:null}}const A={cellPadding:4,borderColor:"#000000",borderWidth:1,fontFamily:"Arial",fontSize:12,color:"#000000",backgroundColor:"#ffffff",minColumnWidth:20,minRowHeight:20,defaultColumnWidth:100},L={width:1,color:"#000000",style:"solid"};function B(t){return t.top+t.bottom}let z=!1;const O={setEnabled(t){z=t},isEnabled:()=>z,log(...t){z&&console.log(...t)},warn(...t){z&&console.warn(...t)},error(...t){console.error(...t)}};class j extends o{constructor(t){super(),this.type="tablecell",this._flowedLines=[],this._flowedPage=null,this._bounds=null,this._renderedPosition=null,this._renderedPageIndex=0,this._editing=!1,this._reflowDirty=!0,this._lastReflowWidth=0,this._cachedContentHeight=null,this._id=t.id||`cell_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,this._rowSpan=t.rowSpan??1,this._colSpan=t.colSpan??1,this._backgroundColor=t.backgroundColor??A.backgroundColor,this._border=function(t){const e=L;return{top:t?.top||{...e},right:t?.right||{...e},bottom:t?.bottom||{...e},left:t?.left||{...e}}}(t.border),this._padding=function(t,e){const i=e??A.cellPadding;return"number"==typeof t?{top:t,right:t,bottom:t,left:t}:{top:t?.top??i,right:t?.right??i,bottom:t?.bottom??i,left:t?.left??i}}(t.padding,A.cellPadding),this._verticalAlign=t.verticalAlign??"top",this._fontFamily=t.fontFamily??A.fontFamily,this._fontSize=t.fontSize??A.fontSize,this._color=t.color??A.color,this._flowingContent=new $,this._flowingContent.setDefaultFormatting({fontFamily:this._fontFamily,fontSize:this._fontSize,color:this._color}),this._flowingContent.insertEmbeddedObject=()=>{O.warn("[pc-editor:TableCell] Embedded objects are not allowed in table cells. Use insertSubstitutionField instead.")},t.content&&this._flowingContent.setText(t.content),this._flowingContent.on("content-changed",()=>{this._reflowDirty=!0,this._cachedContentHeight=null,this.emit("content-changed",{cellId:this._id})}),this._flowingContent.on("cursor-moved",()=>{this.emit("cursor-moved",{cellId:this._id})})}get id(){return this._id}get rowSpan(){return this._rowSpan}set rowSpan(t){t>=1&&t!==this._rowSpan&&(this._rowSpan=t,this.emit("span-changed",{cellId:this._id,rowSpan:t,colSpan:this._colSpan}))}get colSpan(){return this._colSpan}set colSpan(t){t>=1&&t!==this._colSpan&&(this._colSpan=t,this.emit("span-changed",{cellId:this._id,rowSpan:this._rowSpan,colSpan:t}))}get backgroundColor(){return this._backgroundColor}set backgroundColor(t){this._backgroundColor!==t&&(this._backgroundColor=t,this.emit("style-changed",{cellId:this._id,backgroundColor:t}))}get border(){return this._border}set border(t){this._border=t,this.emit("style-changed",{cellId:this._id,border:t})}get padding(){return this._padding}set padding(t){this._padding=t,this.emit("style-changed",{cellId:this._id,padding:t})}get verticalAlign(){return this._verticalAlign}set verticalAlign(t){this._verticalAlign!==t&&(this._verticalAlign=t,this.emit("style-changed",{cellId:this._id,verticalAlign:t}))}get fontFamily(){return this._fontFamily}set fontFamily(t){this._fontFamily=t,this._flowingContent.setDefaultFormatting({fontFamily:t}),this.emit("style-changed",{cellId:this._id,fontFamily:t})}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize=t,this._flowingContent.setDefaultFormatting({fontSize:t}),this.emit("style-changed",{cellId:this._id,fontSize:t})}get color(){return this._color}set color(t){this._color=t,this._flowingContent.setDefaultFormatting({color:t}),this.emit("style-changed",{cellId:this._id,color:t})}get flowingContent(){return this._flowingContent}get content(){return this._flowingContent.getText()}set content(t){this._flowingContent.setText(t)}insertSubstitutionField(t,e){this._flowingContent.insertSubstitutionField(t,e)}setBounds(t){this._bounds=t}getBounds(){return this._bounds}setRenderedPosition(t){this._renderedPosition=t}getRenderedPosition(){return this._renderedPosition}set renderedPageIndex(t){this._renderedPageIndex=t}get renderedPageIndex(){return this._renderedPageIndex}getContentBounds(){if(!this._bounds)return null;const t="none"!==this._border.left.style?this._border.left.width:0,e="none"!==this._border.top.style?this._border.top.width:0;return{x:this._bounds.x+t+this._padding.left,y:this._bounds.y+e+this._padding.top,width:this._bounds.width-(i=this._padding,i.left+i.right)-("none"!==this._border.left.style?this._border.left.width:0)-("none"!==this._border.right.style?this._border.right.width:0),height:this._bounds.height-B(this._padding)-("none"!==this._border.top.style?this._border.top.width:0)-("none"!==this._border.bottom.style?this._border.bottom.width:0)};var i}getContentHeight(t){if(null!==this._cachedContentHeight&&!this._reflowDirty)return this._cachedContentHeight;(this._reflowDirty||0===this._flowedLines.length&&this._flowingContent.getText().length>0)&&this.reflow(t);let e=0;for(const t of this._flowedLines)e+=t.height;return e+=B(this._padding),e+="none"!==this._border.top.style?this._border.top.width:0,e+="none"!==this._border.bottom.style?this._border.bottom.width:0,this._cachedContentHeight=Math.max(e,A.minRowHeight),this._cachedContentHeight}getRegionBounds(t){if(!this._renderedPosition||!this._bounds)return null;const e="none"!==this._border.left.style?this._border.left.width:0,i="none"!==this._border.top.style?this._border.top.width:0,n="none"!==this._border.right.style?this._border.right.width:0,s="none"!==this._border.bottom.style?this._border.bottom.width:0;return{x:this._renderedPosition.x+e+this._padding.left,y:this._renderedPosition.y+i+this._padding.top,width:this._bounds.width-this._padding.left-this._padding.right-e-n,height:this._bounds.height-this._padding.top-this._padding.bottom-i-s}}globalToLocal(t,e){const i=this.getRegionBounds(e);return i?t.x<i.x||t.x>i.x+i.width||t.y<i.y||t.y>i.y+i.height?null:{x:t.x-i.x,y:t.y-i.y}:null}localToGlobal(t,e){const i=this.getRegionBounds(e);return i?{x:t.x+i.x,y:t.y+i.y}:t}getFlowedLines(t){return this._flowedLines}getFlowedPages(){return this._flowedPage?[this._flowedPage]:[]}getAvailableWidth(){if(!this._bounds)return 0;const t="none"!==this._border.left.style?this._border.left.width:0,e="none"!==this._border.right.style?this._border.right.width:0;return this._bounds.width-this._padding.left-this._padding.right-t-e}spansMultiplePages(){return!1}getPageCount(){return 1}containsPointInRegion(t,e){const i=this.getRegionBounds(e);return!!i&&(t.x>=i.x&&t.x<=i.x+i.width&&t.y>=i.y&&t.y<=i.y+i.height)}reflow(t){const e=this.getAvailableWidth();if(e<=0)return this._flowedLines=[],this._flowedPage=null,void(this._reflowDirty=!1);if(!this._reflowDirty&&this._lastReflowWidth===e&&this._flowedLines.length>0)return;const i=this._flowingContent.flowText(e,1e4,t);this._flowedLines=i.length>0?i[0].lines:[],this._flowedPage=i.length>0?i[0]:null,this._reflowDirty=!1,this._lastReflowWidth=e,this._cachedContentHeight=null,O.log("[pc-editor:TableCell.reflow] cellId:",this._id,"text:",JSON.stringify(this._flowingContent.getText()),"lines:",this._flowedLines.length)}markReflowDirty(){this._reflowDirty=!0,this._cachedContentHeight=null}get editing(){return this._editing}set editing(t){this._editing!==t&&(this._editing=t,t?this._flowingContent.focus():this._flowingContent.blur(),this.emit("editing-changed",{cellId:this._id,editing:t}))}focus(){this.editing=!0}blur(){this.editing=!1}hasFocus(){return this._editing&&this._flowingContent.hasFocus()}handleKeyDown(t){if(O.log("[pc-editor:TableCell.handleKeyDown] Key:",t.key,"_editing:",this._editing,"flowingContent.hasFocus:",this._flowingContent.hasFocus()),!this._editing)return!1;if("Tab"===t.key)return!1;O.log("[pc-editor:TableCell.handleKeyDown] Delegating to FlowingTextContent.handleKeyDown");const e=this._flowingContent.handleKeyDown(t);return O.log("[pc-editor:TableCell.handleKeyDown] FlowingTextContent handled:",e),e}onCursorBlink(t){this._flowingContent.onCursorBlink(t)}offCursorBlink(t){this._flowingContent.offCursorBlink(t)}render(t){this._bounds&&(this.renderBackground(t),this.renderBorder(t))}renderBackground(t){this._bounds&&(t.fillStyle=this._backgroundColor,t.fillRect(0,0,this._bounds.width,this._bounds.height))}renderBorder(t){if(!this._bounds)return;const{width:e,height:i}=this._bounds;"none"!==this._border.top.style&&this.renderBorderSide(t,this._border.top,0,0,e,0),"none"!==this._border.right.style&&this.renderBorderSide(t,this._border.right,e,0,e,i),"none"!==this._border.bottom.style&&this.renderBorderSide(t,this._border.bottom,0,i,e,i),"none"!==this._border.left.style&&this.renderBorderSide(t,this._border.left,0,0,0,i)}renderBorderSide(t,e,i,n,s,o){switch(t.strokeStyle=e.color,t.lineWidth=e.width,e.style){case"dashed":t.setLineDash([4,4]);break;case"dotted":t.setLineDash([2,2]);break;default:t.setLineDash([])}t.beginPath(),t.moveTo(i,n),t.lineTo(s,o),t.stroke(),t.setLineDash([])}toData(){const t=this._flowingContent.getText(),e=this._flowingContent.getFormattingManager().getCompressedRuns(t.length).map(t=>[t.index,t.formatting]),i=this._flowingContent.getSubstitutionFieldManager().getFieldsArray(),n=A,s=L,o=t=>t.width===s.width&&t.color===s.color&&t.style===s.style,r=o(this._border.top)&&o(this._border.right)&&o(this._border.bottom)&&o(this._border.left),a=this._padding.top===n.cellPadding&&this._padding.right===n.cellPadding&&this._padding.bottom===n.cellPadding&&this._padding.left===n.cellPadding,l={};return 1!==this._rowSpan&&(l.rowSpan=this._rowSpan),1!==this._colSpan&&(l.colSpan=this._colSpan),this._backgroundColor!==n.backgroundColor&&(l.backgroundColor=this._backgroundColor),r||(l.border=this._border),a||(l.padding=this._padding),"top"!==this._verticalAlign&&(l.verticalAlign=this._verticalAlign),t&&(l.content=t),this._fontFamily!==n.fontFamily&&(l.fontFamily=this._fontFamily),this._fontSize!==n.fontSize&&(l.fontSize=this._fontSize),this._color!==n.color&&(l.color=this._color),e.length>0&&(l.formattingRuns=e),i.length>0&&(l.substitutionFields=i),l}static fromData(t){const e=new j({id:t.id,rowSpan:t.rowSpan,colSpan:t.colSpan,backgroundColor:t.backgroundColor,border:t.border,padding:t.padding,verticalAlign:t.verticalAlign,content:t.content,fontFamily:t.fontFamily,fontSize:t.fontSize,color:t.color});if(t.formattingRuns&&t.formattingRuns.length>0){const i=e._flowingContent.getFormattingManager(),n=(t.content||"").length;for(let e=0;e<t.formattingRuns.length;e++){const[s,o]=t.formattingRuns[e],r=e+1<t.formattingRuns.length?t.formattingRuns[e+1][0]:n;s<r&&i.applyFormatting(s,r,o)}}if(t.substitutionFields&&Array.isArray(t.substitutionFields)){const i=e._flowingContent.getSubstitutionFieldManager();for(const e of t.substitutionFields)void 0!==e.textIndex&&e.fieldName&&(i.insert(e.fieldName,e.textIndex,{defaultValue:e.defaultValue,displayFormat:e.displayFormat}),e.formatting&&i.setFieldFormatting(e.textIndex,e.formatting))}return e}clone(){return j.fromData(this.toData())}}class D extends o{constructor(t,e,i){if(super(),this._calculatedHeight=0,this._id=t.id||`row_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,this._height=t.height??null,this._minHeight=t.minHeight??A.minRowHeight,this._isHeader=t.isHeader??!1,this._cells=[],t.cells&&t.cells.length>0)for(let n=0;n<e;n++){const e=t.cells[n]||{},s={...i,...e},o=new j(s);this.setupCellListeners(o),this._cells.push(o)}else for(let t=0;t<e;t++){const t=new j(i||{});this.setupCellListeners(t),this._cells.push(t)}}setupCellListeners(t){t.on("content-changed",t=>{this.emit("cell-content-changed",{rowId:this._id,...t})}),t.on("style-changed",t=>{this.emit("cell-style-changed",{rowId:this._id,...t})}),t.on("span-changed",t=>{this.emit("cell-span-changed",{rowId:this._id,...t})}),t.on("editing-changed",t=>{this.emit("cell-editing-changed",{rowId:this._id,...t})})}get id(){return this._id}get cells(){return this._cells}get cellCount(){return this._cells.length}get height(){return this._height}set height(t){this._height!==t&&(this._height=t,this.emit("height-changed",{rowId:this._id,height:t}))}get minHeight(){return this._minHeight}set minHeight(t){this._minHeight!==t&&(this._minHeight=t,this.emit("min-height-changed",{rowId:this._id,minHeight:t}))}get isHeader(){return this._isHeader}set isHeader(t){this._isHeader!==t&&(this._isHeader=t,this.emit("header-changed",{rowId:this._id,isHeader:t}))}get calculatedHeight(){return this._calculatedHeight}getCell(t){return t<0||t>=this._cells.length?null:this._cells[t]}addCell(t,e){this.setupCellListeners(t),void 0!==e&&e>=0&&e<=this._cells.length?this._cells.splice(e,0,t):this._cells.push(t),this.emit("cell-added",{rowId:this._id,cellId:t.id,index:e??this._cells.length-1})}removeCell(t){if(t<0||t>=this._cells.length)return null;const[e]=this._cells.splice(t,1);return this.emit("cell-removed",{rowId:this._id,cellId:e.id,index:t}),e}insertCell(t,e){const i=new j(e||{});return this.setupCellListeners(i),t<0?t=0:t>this._cells.length&&(t=this._cells.length),this._cells.splice(t,0,i),this.emit("cell-added",{rowId:this._id,cellId:i.id,index:t}),i}calculateHeight(t,e){if(null!==this._height)return this._calculatedHeight=Math.max(this._height,this._minHeight),this._calculatedHeight;let i=this._minHeight;for(let n=0;n<this._cells.length;n++){const s=this._cells[n];let o=0;for(let t=n;t<n+s.colSpan&&t<e.length;t++)o+=e[t]||A.defaultColumnWidth;s.setBounds({x:0,y:0,width:o,height:1e3});const r=s.getContentHeight(t);r>i&&(i=r)}return this._calculatedHeight=i,this._calculatedHeight}setCellBounds(t,e,i,n){for(let s=0;s<this._cells.length;s++){const o=this._cells[s],r=e[s]||0,a=i[s]||A.defaultColumnWidth;o.setBounds({x:r,y:t,width:a,height:n})}}toData(){const t={cells:this._cells.map(t=>t.toData())};return null!==this._height&&(t.height=this._height),this._minHeight!==A.minRowHeight&&(t.minHeight=this._minHeight),this._isHeader&&(t.isHeader=this._isHeader),t}static fromData(t){const e=new D({id:t.id,height:t.height,minHeight:t.minHeight,isHeader:t.isHeader},t.cells.length);return e._cells=t.cells.map(t=>{const i=j.fromData(t);return e.setupCellListeners(i),i}),e}clone(){return D.fromData(this.toData())}}class H{static normalizeRange(t){return{start:{row:Math.min(t.start.row,t.end.row),col:Math.min(t.start.col,t.end.col)},end:{row:Math.max(t.start.row,t.end.row),col:Math.max(t.start.col,t.end.col)}}}static isValidRange(t,e){const i=this.normalizeRange(e);return i.start.row>=0&&i.start.col>=0&&i.end.row<t.rowCount&&i.end.col<t.columnCount}static canMerge(t,e){const i=this.normalizeRange(e);if(!this.isValidRange(t,i))return"Range is out of table bounds";const n=i.end.row-i.start.row+1,s=i.end.col-i.start.col+1;if(1===n&&1===s)return"Selection must include at least 2 cells to merge";for(let e=i.start.row;e<=i.end.row;e++)for(let n=i.start.col;n<=i.end.col;n++){const s=t.resolveCell(e,n);if(!s)continue;if(s.isSpanned){const t=s.rowIndex,e=s.colIndex;if(t<i.start.row||t>i.end.row||e<i.start.col||e>i.end.col)return"Cannot merge: selection overlaps with existing merged cells"}const o=t.getCell(e,n);if(o){const t=e+o.rowSpan-1,s=n+o.colSpan-1;if(t>i.end.row||s>i.end.col)return"Cannot merge: selection overlaps with existing merged cells"}}return null}static mergeCells(t,e){const i=this.normalizeRange(e),n=this.canMerge(t,i);if(n)return{success:!1,error:n};const s=i.end.row-i.start.row+1,o=i.end.col-i.start.col+1,r=t.getCell(i.start.row,i.start.col);if(!r)return{success:!1,error:"Could not find origin cell"};for(let e=i.start.row;e<=i.end.row;e++)for(let n=i.start.col;n<=i.end.col;n++){if(e===i.start.row&&n===i.start.col)continue;const s=t.getCell(e,n);s&&(s.content="",s.rowSpan=1,s.colSpan=1)}return r.rowSpan=s,r.colSpan=o,{success:!0,mergedCell:r}}static canSplit(t,e,i){const n=t.getCell(e,i);return n?1===n.rowSpan&&1===n.colSpan?"Cell is not merged":null:"Cell not found"}static splitCell(t,e,i){const n=this.canSplit(t,e,i);if(n)return{success:!1,error:n};const s=t.getCell(e,i);if(!s)return{success:!1,error:"Cell not found"};const o=s.rowSpan,r=s.colSpan;s.rowSpan=1,s.colSpan=1;const a=[s];for(let n=e;n<e+o&&n<t.rowCount;n++)for(let s=i;s<i+r&&s<t.columnCount;s++){if(n===e&&s===i)continue;const o=t.getCell(n,s);o&&(o.rowSpan=1,o.colSpan=1,a.push(o))}return{success:!0,newCells:a}}static getCellsInRange(t,e){const i=this.normalizeRange(e),n=[],s=new Set;for(let e=i.start.row;e<=i.end.row;e++)for(let o=i.start.col;o<=i.end.col;o++){const i=t.resolveCell(e,o);if(!i)continue;const r=`${i.rowIndex},${i.colIndex}`;s.has(r)||(s.add(r),n.push(i.cell))}return n}static rangesOverlap(t,e){const i=this.normalizeRange(t),n=this.normalizeRange(e);return!(i.end.row<n.start.row||i.start.row>n.end.row||i.end.col<n.start.col||i.start.col>n.end.col)}static getMergedCellRange(t,e,i){return{start:{row:e,col:i},end:{row:e+t.rowSpan-1,col:i+t.colSpan-1}}}}function N(){return`col_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}class W extends F{constructor(t){super(t),this._rows=[],this._columns=[],this._focusedCell=null,this._editing=!1,this._selectedRange=null,this._coveredCells=new Map,this._rowLoops=new Map,this._layoutDirty=!0,this._cachedRowHeights=[],this._cachedRowPositions=[],this._renderedSlices=new Map,this._position="block",this._defaultCellPadding=t.defaultCellPadding??A.cellPadding,this._defaultBorderColor=t.defaultBorderColor??A.borderColor,this._defaultBorderWidth=t.defaultBorderWidth??A.borderWidth,this._defaultFontFamily=t.defaultFontFamily??A.fontFamily,this._defaultFontSize=t.defaultFontSize??A.fontSize,this._defaultColor=t.defaultColor??A.color;const e=t.columns??2;if(t.columnConfig&&t.columnConfig.length>0)this._columns=t.columnConfig.map(t=>({id:t.id||N(),width:t.width,minWidth:t.minWidth??A.minColumnWidth}));else if(t.columnWidths&&t.columnWidths.length>0)this._columns=t.columnWidths.map(t=>({id:N(),width:t,minWidth:A.minColumnWidth}));else for(let t=0;t<e;t++)this._columns.push({id:N(),width:A.defaultColumnWidth,minWidth:A.minColumnWidth});const i=t.rows??2,n={fontFamily:this._defaultFontFamily,fontSize:this._defaultFontSize,color:this._defaultColor,padding:this._defaultCellPadding};if(t.rowData&&t.rowData.length>0)for(const e of t.rowData){const t=new D(e,this._columns.length,n);this.setupRowListeners(t),this._rows.push(t)}else for(let t=0;t<i;t++){const t=new D({},this._columns.length,n);this.setupRowListeners(t),this._rows.push(t)}this.updateSizeFromLayout()}get objectType(){return"table"}set position(t){"block"!==t&&O.warn(`[pc-editor:TableObject] Tables only support 'block' positioning. Ignoring attempt to set '${t}'.`),super.position="block"}get position(){return super.position}get rows(){return this._rows}get rowCount(){return this._rows.length}get columns(){return this._columns}get columnCount(){return this._columns.length}get headerRows(){return this._rows.filter(t=>t.isHeader)}get headerRowCount(){return this._rows.filter(t=>t.isHeader).length}setHeaderRow(t,e=!0){const i=this._rows[t];i&&(i.isHeader=e,this.emit("header-changed",{rowIndex:t,isHeader:e}))}setHeaderRowCount(t){for(let e=0;e<this._rows.length;e++)this._rows[e].isHeader=e<t;this.emit("headers-changed",{count:t})}getHeaderHeight(){let t=0;for(const e of this._rows)e.isHeader&&(t+=e.calculatedHeight);return t}getFirstDataRowHeight(){for(const t of this._rows)if(!t.isHeader)return t.calculatedHeight;return 0}getHeaderRowIndices(){const t=[];for(let e=0;e<this._rows.length;e++)this._rows[e].isHeader&&t.push(e);return t}get headerColumns(){return this._columns.filter(t=>t.isHeader)}get headerColumnCount(){return this._columns.filter(t=>t.isHeader).length}setHeaderColumn(t,e=!0){const i=this._columns[t];i&&(i.isHeader=e,this.emit("header-column-changed",{colIndex:t,isHeader:e}))}setHeaderColumnCount(t){for(let e=0;e<this._columns.length;e++)this._columns[e].isHeader=e<t;this.emit("header-columns-changed",{count:t})}getHeaderColumnIndices(){const t=[];for(let e=0;e<this._columns.length;e++)this._columns[e].isHeader&&t.push(e);return t}isHeaderCell(t,e){const i=this._rows[t],n=this._columns[e];return!0===i?.isHeader||!0===n?.isHeader}get defaultCellPadding(){return this._defaultCellPadding}set defaultCellPadding(t){this._defaultCellPadding=t,this.emit("style-changed",{defaultCellPadding:t})}get defaultBorderColor(){return this._defaultBorderColor}set defaultBorderColor(t){this._defaultBorderColor=t,this.emit("style-changed",{defaultBorderColor:t})}get defaultBorderWidth(){return this._defaultBorderWidth}set defaultBorderWidth(t){this._defaultBorderWidth=t,this.emit("style-changed",{defaultBorderWidth:t})}get defaultFontFamily(){return this._defaultFontFamily}set defaultFontFamily(t){this._defaultFontFamily=t,this.emit("style-changed",{defaultFontFamily:t})}get defaultFontSize(){return this._defaultFontSize}set defaultFontSize(t){this._defaultFontSize=t,this.emit("style-changed",{defaultFontSize:t})}get defaultColor(){return this._defaultColor}set defaultColor(t){this._defaultColor=t,this.emit("style-changed",{defaultColor:t})}set size(t){const e=this._columns.reduce((t,e)=>t+e.width,0),i=this._rows.reduce((t,e)=>t+(e.calculatedHeight||e.minHeight),0);if(e>0&&i>0&&this._columns.length>0&&this._rows.length>0){const n=t.width-e,s=this._columns.length-1,o=this._columns[s],r=Math.max(o.minWidth||20,o.width+n);o.width=r;const a=t.height-i,l=this._rows[this._rows.length-1],h=l.calculatedHeight||l.minHeight,d=Math.max(l.minHeight,h+a);l.height=d}this._size={...t},this.markLayoutDirty(),this.emit("size-changed",{size:{...t}})}get size(){return{...this._size}}getCell(t,e){const i=this._rows[t];return i?i.getCell(e):null}resolveCell(t,e){const i=`${t},${e}`,n=this._coveredCells.get(i);if(n){const t=this.getCell(n.row,n.col);return t?{cell:t,rowIndex:n.row,colIndex:n.col,isSpanned:!0}:null}const s=this.getCell(t,e);return s?{cell:s,rowIndex:t,colIndex:e,isSpanned:!1}:null}getCellAtPoint(t){let e=0,i=-1;for(let n=0;n<this._columns.length;n++){const s=this._columns[n].width;if(t.x>=e&&t.x<e+s){i=n;break}e+=s}if(-1===i)return null;let n=0,s=-1;for(let e=0;e<this._rows.length;e++){const i=this._rows[e].calculatedHeight;if(t.y>=n&&t.y<n+i){s=e;break}n+=i}return-1===s?null:{row:s,col:i}}setupRowListeners(t){t.on("cell-content-changed",t=>{this._layoutDirty=!0,this.emit("cell-content-changed",t),this.emit("content-changed",{})}),t.on("cell-style-changed",t=>{this.emit("cell-style-changed",t)}),t.on("cell-span-changed",t=>{this._layoutDirty=!0,this.updateCoveredCells(),this.emit("cell-span-changed",t)}),t.on("cell-editing-changed",t=>{this.emit("cell-editing-changed",t)}),t.on("height-changed",()=>{this._layoutDirty=!0,this.updateSizeFromLayout(),this.emit("layout-changed",{})})}setColumnWidth(t,e){if(t<0||t>=this._columns.length)return;const i=this._columns[t].minWidth??A.minColumnWidth;this._columns[t].width=Math.max(e,i),this._layoutDirty=!0;for(const e of this._rows){const i=e.getCell(t);i&&i.markReflowDirty()}this.updateSizeFromLayout(),this.emit("column-width-changed",{colIndex:t,width:this._columns[t].width})}getColumnPositions(){const t=[];let e=0;for(const i of this._columns)t.push(e),e+=i.width;return t}getColumnWidths(){return this._columns.map(t=>t.width)}insertColumn(t,e){const i=e??A.defaultColumnWidth,n={id:N(),width:i,minWidth:A.minColumnWidth};t<0&&(t=0),t>this._columns.length&&(t=this._columns.length);for(let e=0;e<this._rows.length;e++){const i=this._rows[e];for(let e=0;e<t;e++){const n=i.getCell(e);n&&n.colSpan>1&&e+n.colSpan>t&&n.colSpan++}}this._columns.splice(t,0,n);const s={fontFamily:this._defaultFontFamily,fontSize:this._defaultFontSize,color:this._defaultColor,padding:this._defaultCellPadding};for(const e of this._rows)e.insertCell(t,s);this._layoutDirty=!0,this.updateCoveredCells(),this.updateSizeFromLayout(),this.emit("column-inserted",{colIndex:t})}removeColumn(t){if(!(t<0||t>=this._columns.length||this._columns.length<=1)){this._columns.splice(t,1);for(const e of this._rows)e.removeCell(t);if(this._selectedRange){const{start:e,end:i}=this._selectedRange;(e.col>=this._columns.length||i.col>=this._columns.length||t>=e.col&&t<=i.col)&&(this._selectedRange=null)}this._focusedCell&&this._focusedCell.col>=this._columns.length&&(this._focusedCell=null),this._layoutDirty=!0,this.updateCoveredCells(),this.updateSizeFromLayout(),this.emit("column-removed",{colIndex:t})}}insertRow(t,e){const i={fontFamily:this._defaultFontFamily,fontSize:this._defaultFontSize,color:this._defaultColor,padding:this._defaultCellPadding},n=new D(e||{},this._columns.length,i);this.setupRowListeners(n),t<0&&(t=0),t>this._rows.length&&(t=this._rows.length);for(let e=0;e<t;e++){const i=this._rows[e];for(let n=0;n<i.cellCount;n++){const s=i.getCell(n);s&&s.rowSpan>1&&e+s.rowSpan>t&&s.rowSpan++}}return this._rows.splice(t,0,n),this.shiftRowLoopIndices(t,1),this._layoutDirty=!0,this.updateCoveredCells(),this.updateSizeFromLayout(),this.emit("row-inserted",{rowIndex:t,rowId:n.id}),n}removeRow(t){if(t<0||t>=this._rows.length)return null;if(this._rows.length<=1)return null;const[e]=this._rows.splice(t,1);if(this.shiftRowLoopIndices(t,-1),this._selectedRange){const{start:e,end:i}=this._selectedRange;(e.row>=this._rows.length||i.row>=this._rows.length||t>=e.row&&t<=i.row)&&(this._selectedRange=null)}return this._focusedCell&&this._focusedCell.row>=this._rows.length&&(this._focusedCell=null),this._layoutDirty=!0,this.updateCoveredCells(),this.updateSizeFromLayout(),this.emit("row-removed",{rowIndex:t,rowId:e.id}),e}generateRowLoopId(){return`rowloop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}createRowLoop(t,e,i){if(t<0||e>=this._rows.length)return O.warn("[pc-editor:TableObject.createRowLoop] Invalid row range"),null;if(t>e)return O.warn("[pc-editor:TableObject.createRowLoop] Start index must be <= end index"),null;for(const i of this._rowLoops.values())if(this.loopRangesOverlap(t,e,i.startRowIndex,i.endRowIndex))return O.warn("[pc-editor:TableObject.createRowLoop] Loop range overlaps with existing loop"),null;for(let i=t;i<=e;i++)if(this._rows[i]?.isHeader)return O.warn("[pc-editor:TableObject.createRowLoop] Loop rows cannot be header rows"),null;const n={id:this.generateRowLoopId(),fieldPath:i,startRowIndex:t,endRowIndex:e};return this._rowLoops.set(n.id,n),this.emit("row-loop-created",{loop:n}),this.emit("content-changed",{}),n}removeRowLoop(t){return!!this._rowLoops.get(t)&&(this._rowLoops.delete(t),this.emit("row-loop-removed",{loopId:t}),this.emit("content-changed",{}),!0)}getRowLoop(t){return this._rowLoops.get(t)}getAllRowLoops(){return Array.from(this._rowLoops.values())}getRowLoopAtRow(t){for(const e of this._rowLoops.values())if(t>=e.startRowIndex&&t<=e.endRowIndex)return e}updateRowLoopFieldPath(t,e){const i=this._rowLoops.get(t);return!!i&&(i.fieldPath=e,this.emit("row-loop-updated",{loop:i}),this.emit("content-changed",{}),!0)}loopRangesOverlap(t,e,i,n){return t<=n&&i<=e}shiftRowLoopIndices(t,e){const i=[];for(const n of this._rowLoops.values())if(e<0){const s=t+Math.abs(e)-1;if(t<=n.endRowIndex&&s>=n.startRowIndex){i.push(n.id);continue}t<n.startRowIndex&&(n.startRowIndex+=e,n.endRowIndex+=e)}else t<=n.startRowIndex?(n.startRowIndex+=e,n.endRowIndex+=e):t<=n.endRowIndex&&(n.endRowIndex+=e);for(const t of i)this._rowLoops.delete(t),this.emit("row-loop-removed",{loopId:t,reason:"row-deleted"})}getRowsInRange(t,e){const i=[];for(let n=t;n<=e&&n<this._rows.length;n++)i.push(this._rows[n]);return i}removeRowsInRange(t,e){const i=e-t+1,n=this._rows.splice(t,i);if(this._selectedRange){const{start:i,end:n}=this._selectedRange;(i.row>=this._rows.length||n.row>=this._rows.length||i.row<=e&&n.row>=t)&&(this._selectedRange=null)}return this._focusedCell&&this._focusedCell.row>=this._rows.length&&(this._focusedCell=null),this._layoutDirty=!0,this.updateCoveredCells(),n}insertRowsAt(t,e){for(const t of e)this.setupRowListeners(t);this._rows.splice(t,0,...e),this._layoutDirty=!0,this.updateCoveredCells(),this.updateSizeFromLayout()}calculateLayout(t,e=!1){if(!e&&!this._layoutDirty&&this._cachedRowHeights.length===this._rows.length)return;const i=this.getColumnWidths(),n=this.getColumnPositions(),s=[];let o=0;for(const e of this._rows){const n=e.calculateHeight(t,i);s.push(n),o+=n}const r=[];let a=0;for(const t of s)r.push(a),a+=t;this._cachedRowHeights=s,this._cachedRowPositions=r,this._layoutDirty=!1;for(let t=0;t<this._rows.length;t++){const e=this._rows[t];for(let o=0;o<e.cellCount;o++){const a=e.getCell(o);if(!a)continue;let l=0;const h=a.colSpan;for(let t=o;t<o+h&&t<this._columns.length;t++)l+=i[t];let d=0;const c=a.rowSpan;for(let e=t;e<t+c&&e<this._rows.length;e++)d+=s[e];a.setBounds({x:n[o],y:r[t],width:l,height:d})}}const l=i.reduce((t,e)=>t+e,0);this._size={width:l,height:o}}markLayoutDirty(){this._layoutDirty=!0}get layoutDirty(){return this._layoutDirty}get cachedRowHeights(){return this._cachedRowHeights}get cachedRowPositions(){return this._cachedRowPositions}updateSizeFromLayout(){const t=this._columns.reduce((t,e)=>t+e.width,0);let e=0;for(const t of this._rows)e+=t.calculatedHeight||t.minHeight;this._size={width:t,height:e}}updateCoveredCells(){this._coveredCells.clear();for(let t=0;t<this._rows.length;t++){const e=this._rows[t];for(let i=0;i<e.cellCount;i++){const n=e.getCell(i);if(!n)continue;const s=n.rowSpan,o=n.colSpan;if(s>1||o>1)for(let e=t;e<t+s&&e<this._rows.length;e++)for(let n=i;n<i+o&&n<this._columns.length;n++)e===t&&n===i||this._coveredCells.set(`${e},${n}`,{row:t,col:i})}}}updateCellRenderedPositions(){if(!this._renderedPosition)return;const t=this.getColumnPositions();let e=0;for(const i of this._rows){for(let n=0;n<i.cellCount;n++){const s=i.getCell(n);s&&s.setRenderedPosition({x:this._renderedPosition.x+t[n],y:this._renderedPosition.y+e})}e+=i.calculatedHeight}}calculatePageLayout(t,e){const i=this.getHeaderHeight(),n=this.getHeaderRowIndices(),s=this._size.height;if(s<=t)return{slices:[{startRow:0,endRow:this._rows.length,isContinuation:!1,height:s,yOffset:0}],totalHeight:s,headerHeight:i,headerRowIndices:n};let o=0;for(;o<this._rows.length&&this._rows[o].isHeader;)o++;const r=i+(o<this._rows.length?this._rows[o].calculatedHeight:0)<=t?t:e,a=[];let l=0,h=0,d=!0;for(;l<this._rows.length;){const t=d?r:e,n=!d;let s=n?i:0,c=l;const g=h;for(n&&l<o&&(l=o,c=l);c<this._rows.length;){const e=this._rows[c];if(n&&e.isHeader){c++;continue}const i=e.calculatedHeight;if(s+i>t)break;s+=i,h+=i,c++}if(c=this.adjustSliceEndForMergedCells(l,c),c<this._rows.length){s=n?i:0,h=g;for(let t=l;t<c;t++)n&&this._rows[t].isHeader||(s+=this._rows[t].calculatedHeight,h+=this._rows[t].calculatedHeight)}if(c===l&&l<this._rows.length){for(;c<this._rows.length&&this._rows[c].isHeader;)c++;c<this._rows.length&&(s+=this._rows[c].calculatedHeight,h+=this._rows[c].calculatedHeight,c++)}((d?c>o:c>l)||c===this._rows.length)&&(a.push({startRow:l,endRow:c,isContinuation:n,height:s,yOffset:g}),d=!1),l=c}return{slices:a,totalHeight:s,headerHeight:i,headerRowIndices:n}}adjustSliceEndForMergedCells(t,e){for(let i=t;i<e;i++){const n=this._rows[i];for(let s=0;s<n.cellCount;s++){const o=n.getCell(s);if(o&&o.rowSpan>1){const n=i+o.rowSpan;if(n>e&&n<=this._rows.length&&i>t)return i}}}return e}renderSlice(t,e,i){const n=this.getColumnPositions(),s=this.getColumnWidths();let o=0;if(e.isContinuation&&i.headerRowIndices.length>0)for(const e of i.headerRowIndices){const i=this._rows[e];if(i){for(let r=0;r<i.cellCount;r++){const a=`${e},${r}`;if(this._coveredCells.has(a))continue;const l=i.getCell(r);if(!l)continue;let h=0;for(let t=r;t<r+l.colSpan&&t<this._columns.length;t++)h+=s[t];t.save(),t.translate(n[r],o);const d=l.getBounds();l.setBounds({x:n[r],y:o,width:h,height:i.calculatedHeight}),l.render(t),d&&l.setBounds(d),t.restore()}o+=i.calculatedHeight}}for(let i=e.startRow;i<e.endRow;i++){const r=this._rows[i];if(r&&(!e.isContinuation||!r.isHeader)){for(let e=0;e<r.cellCount;e++){const a=`${i},${e}`;if(this._coveredCells.has(a))continue;const l=r.getCell(e);if(!l)continue;let h=0;for(let t=e;t<e+l.colSpan&&t<this._columns.length;t++)h+=s[t];let d=0;for(let t=i;t<i+l.rowSpan&&t<this._rows.length;t++)d+=this._rows[t].calculatedHeight;t.save(),t.translate(n[e],o);const c=l.getBounds();l.setBounds({x:n[e],y:o,width:h,height:d}),l.render(t),c&&l.setBounds(c),t.restore()}o+=r.calculatedHeight}}this._selectedRange&&this.renderRangeSelectionForSlice(t,e,i)}renderRangeSelectionForSlice(t,e,i){if(!this._selectedRange)return;const{start:n,end:s}=this._selectedRange,o=this.getColumnPositions(),r=this.getColumnWidths(),a=o[n.col],l=o[s.col]+r[s.col],h=new Map;let d=0;if(e.isContinuation&&i.headerRowIndices.length>0)for(const t of i.headerRowIndices){const e=this._rows[t];e&&(h.set(t,d),d+=e.calculatedHeight)}for(let t=e.startRow;t<e.endRow;t++){const i=this._rows[t];i&&(e.isContinuation&&i.isHeader||(h.set(t,d),d+=i.calculatedHeight))}let c=null,g=null;for(let t=n.row;t<=s.row;t++){const e=h.get(t);if(void 0!==e){const i=this._rows[t];i&&(null===c&&(c=e),g=e+i.calculatedHeight)}}null!==c&&null!==g&&(t.fillStyle="rgba(0, 120, 215, 0.2)",t.fillRect(a,c,l-a,g-c),t.strokeStyle="rgba(0, 120, 215, 0.8)",t.lineWidth=2,t.setLineDash([]),t.strokeRect(a+1,c+1,l-a-2,g-c-2))}getRowsForSlice(t,e){const i=[];if(t.isContinuation)for(const t of e.headerRowIndices)this._rows[t]&&i.push(this._rows[t]);for(let e=t.startRow;e<t.endRow;e++){const n=this._rows[e];!n||t.isContinuation&&n.isHeader||i.push(n)}return i}needsPageSplit(t){return this._size.height>t}setRenderedSlice(t,e,i,n,s=0,o=0,r=0){this._renderedSlices.set(t,{position:e,height:i,slicePosition:n,sliceIndex:s,yOffset:o,headerHeight:r})}getRenderedSlice(t){return this._renderedSlices.get(t)}clearRenderedSlices(){this._renderedSlices.clear()}getRenderedPageIndices(){return Array.from(this._renderedSlices.keys())}get editing(){return this._editing}set editing(t){if(this._editing!==t){if(this._editing=t,!t&&this._focusedCell){const t=this.getCell(this._focusedCell.row,this._focusedCell.col);t&&t.blur(),this._focusedCell=null}this.emit("editing-changed",{editing:t})}}get focusedCell(){return this._focusedCell}focusCell(t,e){if(this._focusedCell){const t=this.getCell(this._focusedCell.row,this._focusedCell.col);t&&(t.flowingContent.clearSelection(),t.blur())}const i=this.resolveCell(t,e);i&&(this._focusedCell={row:i.rowIndex,col:i.colIndex},i.cell.focus(),this._editing=!0,this.emit("cell-focused",{rowIndex:i.rowIndex,colIndex:i.colIndex,cellId:i.cell.id}))}moveFocus(t){if(!this._focusedCell)return this._rows.length>0&&this._columns.length>0&&(this.focusCell(0,0),!0);let{row:e,col:i}=this._focusedCell;switch(t){case"next":case"right":if(i++,i>=this._columns.length&&(i=0,e++,e>=this._rows.length))return!1;break;case"previous":case"left":if(i--,i<0&&(i=this._columns.length-1,e--,e<0))return!1;break;case"up":if(e--,e<0)return!1;break;case"down":if(e++,e>=this._rows.length)return!1}return this.focusCell(e,i),!0}focus(){this._editing=!0,!this._focusedCell&&this._rows.length>0&&this._columns.length>0&&this.focusCell(0,0),this.emit("focus",{})}blur(){this.editing=!1,this.clearSelection(),this.emit("blur",{})}hasFocus(){return this._editing}handleKeyDown(t){if(O.log("[pc-editor:TableObject.handleKeyDown] Key:",t.key,"_editing:",this._editing,"_focusedCell:",this._focusedCell),!this._editing)return!1;if("Tab"===t.key)return t.preventDefault(),this.moveFocus(t.shiftKey?"previous":"next"),!0;if("Escape"===t.key)return t.preventDefault(),this.blur(),!0;if(this._focusedCell){const e=this.getCell(this._focusedCell.row,this._focusedCell.col);if(e){const i=e.flowingContent,n=i.getCursorPosition(),s=i.getText().length;return"ArrowLeft"===t.key&&0===n&&!t.shiftKey&&this.moveFocus("left")||"ArrowRight"===t.key&&n>=s&&!t.shiftKey&&this.moveFocus("right")?(t.preventDefault(),!0):e.handleKeyDown(t)}}return!1}onCursorBlink(t){for(const e of this._rows)for(const i of e.cells)i.onCursorBlink(t)}offCursorBlink(t){for(const e of this._rows)for(const i of e.cells)i.offCursorBlink(t)}handleDoubleClick(t){if(this._locked)return;const e=this.getCellAtPoint(t);e&&this.focusCell(e.row,e.col)}get selectedRange(){return this._selectedRange}selectRange(t){this._selectedRange=H.normalizeRange(t),this.emit("selection-changed",{range:this._selectedRange})}clearSelection(){this._selectedRange=null,this.emit("selection-changed",{range:null})}mergeCells(t){const e=t||this._selectedRange;if(!e)return{success:!1,error:"No range specified for merge"};const i=H.mergeCells(this,e);return i.success&&(this.updateCoveredCells(),this.markLayoutDirty(),i.mergedCell&&i.mergedCell.markReflowDirty(),this.clearSelection(),this.emit("cells-merged",{range:e}),this.emit("content-changed",{})),i}splitCell(t,e){const i=H.splitCell(this,t,e);if(i.success){if(this.updateCoveredCells(),this.markLayoutDirty(),i.newCells)for(const t of i.newCells)t.markReflowDirty();this.emit("cell-split",{row:t,col:e}),this.emit("content-changed",{})}return i}canMergeRange(t){const e=t||this._selectedRange;if(!e)return{canMerge:!1,error:"No range specified"};const i=H.canMerge(this,e);return{canMerge:null===i,error:i||void 0}}canSplitCell(t,e){const i=H.canSplit(this,t,e);return{canSplit:null===i,error:i||void 0}}render(t,e){let i=0,n=this._rows.length;e&&this._cachedRowPositions.length>0&&(i=this.findFirstVisibleRow(e.y),n=this.findLastVisibleRow(e.y+e.height)+1);for(let e=i;e<n&&e<this._rows.length;e++){const i=this._rows[e];for(let n=0;n<i.cellCount;n++){const s=`${e},${n}`;if(this._coveredCells.has(s))continue;const o=i.getCell(n);if(!o)continue;const r=o.getBounds();r&&(t.save(),t.translate(r.x,r.y),o.render(t),t.restore())}}this._rowLoops.size>0&&this.renderRowLoopIndicators(t),this._selectedRange&&this.renderRangeSelection(t),this._selected&&this.renderSelectionBorder(t),this._editing&&this.renderEditingIndicator(t)}renderRowLoopIndicators(t){let e=this._cachedRowPositions;if(0===e.length){e=[];let t=0;for(const i of this._rows)e.push(t),t+=i.calculatedHeight}const i=["#9b59b6","#3498db","#e67e22","#1abc9c","#e74c3c"];let n=0;for(const s of this._rowLoops.values()){const o=i[n%i.length];n++;const r=e[s.startRowIndex]||0;let a=r;for(let t=s.startRowIndex;t<=s.endRowIndex&&t<this._rows.length;t++)a+=this._rows[t].calculatedHeight;const l=a-r;t.fillStyle=o,t.fillRect(-6,r,4,l),t.save(),t.font="10px Arial",t.fillStyle=o;const h=`⟳ ${s.fieldPath}`,d=t.measureText(h);t.translate(-8-d.width-4,r+l/2),t.fillText(h,0,4),t.restore(),t.strokeStyle=o,t.lineWidth=1,t.beginPath(),t.moveTo(-6,r),t.lineTo(-10,r),t.lineTo(-10,r+6),t.moveTo(-6,a),t.lineTo(-10,a),t.lineTo(-10,a-6),t.stroke()}}findFirstVisibleRow(t){const e=this._cachedRowPositions,i=this._cachedRowHeights;if(0===e.length)return 0;let n=0,s=e.length-1;for(;n<s;){const o=Math.floor((n+s)/2);e[o]+(i[o]||0)<=t?n=o+1:s=o}return n}findLastVisibleRow(t){const e=this._cachedRowPositions;if(0===e.length)return 0;let i=0,n=e.length-1;for(;i<n;){const s=Math.ceil((i+n)/2);e[s]>t?n=s-1:i=s}return i}getVisibleRowRange(t,e){if(0===this._cachedRowPositions.length)return{startRow:0,endRow:this._rows.length};return{startRow:this.findFirstVisibleRow(t),endRow:Math.min(this.findLastVisibleRow(t+e)+1,this._rows.length)}}renderRangeSelection(t){if(!this._selectedRange)return;const{start:e,end:i}=this._selectedRange,n=this.getColumnPositions(),s=this.getColumnWidths(),o=[];let r=0;for(const t of this._rows)o.push(r),r+=t.calculatedHeight;const a=n[e.col],l=n[i.col]+s[i.col],h=o[e.row],d=o[i.row]+this._rows[i.row].calculatedHeight;t.fillStyle="rgba(0, 120, 215, 0.2)",t.fillRect(a,h,l-a,d-h),t.strokeStyle="rgba(0, 120, 215, 0.8)",t.lineWidth=2,t.setLineDash([]),t.strokeRect(a+1,h+1,l-a-2,d-h-2)}renderEditingIndicator(t){const{width:e,height:i}=this._size;t.strokeStyle="#0099ff",t.lineWidth=2,t.setLineDash([]),t.strokeRect(1,1,e-2,i-2)}toData(){const t=this._rowLoops.size>0?Array.from(this._rowLoops.values()).map(t=>({id:t.id,fieldPath:t.fieldPath,startRowIndex:t.startRowIndex,endRowIndex:t.endRowIndex})):void 0;return{id:this._id,objectType:"table",textIndex:this._textIndex,position:this._position,size:{...this._size},data:{columns:this._columns.map(t=>({...t})),rows:this._rows.map(t=>t.toData()),rowLoops:t,defaultCellPadding:this._defaultCellPadding,defaultBorderColor:this._defaultBorderColor,defaultBorderWidth:this._defaultBorderWidth,defaultFontFamily:this._defaultFontFamily,defaultFontSize:this._defaultFontSize,defaultColor:this._defaultColor}}}static fromData(t){const e={id:t.id,textIndex:t.textIndex,position:t.position,size:t.size,columnConfig:t.data.columns,defaultCellPadding:t.data.defaultCellPadding,defaultBorderColor:t.data.defaultBorderColor,defaultBorderWidth:t.data.defaultBorderWidth,defaultFontFamily:t.data.defaultFontFamily,defaultFontSize:t.data.defaultFontSize,defaultColor:t.data.defaultColor},i=new W(e);i._rows=[];for(const e of t.data.rows){const t=D.fromData(e);i.setupRowListeners(t),i._rows.push(t)}if(t.data.rowLoops)for(const e of t.data.rowLoops)i._rowLoops.set(e.id,{id:e.id,fieldPath:e.fieldPath,startRowIndex:e.startRowIndex,endRowIndex:e.endRowIndex});return i.updateCoveredCells(),i}restoreFromSnapshot(t){this._columns=t.data.columns.map(t=>({...t})),this._rows=[];for(const e of t.data.rows){const t=D.fromData(e);this.setupRowListeners(t),this._rows.push(t)}if(this._rowLoops.clear(),t.data.rowLoops)for(const e of t.data.rowLoops)this._rowLoops.set(e.id,{id:e.id,fieldPath:e.fieldPath,startRowIndex:e.startRowIndex,endRowIndex:e.endRowIndex});void 0!==t.data.defaultCellPadding&&(this._defaultCellPadding=t.data.defaultCellPadding),void 0!==t.data.defaultBorderColor&&(this._defaultBorderColor=t.data.defaultBorderColor),void 0!==t.data.defaultBorderWidth&&(this._defaultBorderWidth=t.data.defaultBorderWidth),this._layoutDirty=!0,this.updateCoveredCells(),this.updateSizeFromLayout(),this.emit("structure-restored",{})}clone(){return W.fromData(this.toData())}}class G{constructor(){this._resizeState=null}get resizeState(){return this._resizeState}get isResizing(){return null!==this._resizeState}detectResizeHandle(t,e,i,n){const s=e.x-i.x,o=e.y-i.y,r=void 0!==n?n:t.size.height;if(s<0||o<0||s>t.size.width||o>r)return null;const a=t.getColumnPositions(),l=t.getColumnWidths();for(let t=0;t<a.length;t++){const e=a[t]+l[t];if(Math.abs(s-e)<=4)return{type:"column",index:t,position:e}}let h=0;const d=t.rows;for(let t=0;t<d.length;t++)if(h+=d[t].calculatedHeight,Math.abs(o-h)<=4)return{type:"row",index:t,position:h};return null}startResize(t,e,i){if(!e.type)return;let n,s;if("column"===e.type)n=t.columns[e.index].width,e.index<t.columns.length-1&&(s=t.columns[e.index+1].width);else{if(n=t.rows[e.index].calculatedHeight,e.index<t.rows.length-1){const i=t.rows[e.index+1];s=i.calculatedHeight||i.minHeight}}this._resizeState={table:t,handleType:e.type,index:e.index,startPosition:e.position,startSize:n,nextStartSize:s,tablePosition:i}}updateResize(t){if(!this._resizeState)return!1;const{table:e,handleType:i,index:n,startPosition:s,startSize:o,nextStartSize:r,tablePosition:a}=this._resizeState;if("column"===i){const i=n===e.columns.length-1,l=t.x-a.x-s;if(i){const t=Math.max(o+l,e.columns[n].minWidth||20);e.setColumnWidth(n,t)}else if(void 0!==r){const t=e.columns[n+1],i=e.columns[n].minWidth||20,s=r-(t.minWidth||20),a=-(o-i),h=Math.max(a,Math.min(s,l)),d=o+h,c=r-h;e.setColumnWidth(n,d),e.setColumnWidth(n+1,c)}return!0}if("row"===i){const i=n===e.rows.length-1,l=t.y-a.y-s,h=e.rows[n];if(i){const t=Math.max(o+l,h.minHeight);h.height=t}else if(void 0!==r){const t=e.rows[n+1],i=r-t.minHeight,s=-(o-h.minHeight),a=Math.max(s,Math.min(i,l)),d=o+a,c=r-a;h.height=d,t.height=c}return!0}return!1}endResize(){this._resizeState=null}cancelResize(){if(!this._resizeState)return;const{table:t,handleType:e,index:i,startSize:n,nextStartSize:s}=this._resizeState;"column"===e?(t.setColumnWidth(i,n),void 0!==s&&i<t.columns.length-1&&t.setColumnWidth(i+1,s)):"row"===e&&(t.rows[i].height=n,void 0!==s&&i<t.rows.length-1&&(t.rows[i+1].height=s)),this._resizeState=null}static getCursorForHandle(t){switch(t){case"column":return"col-resize";case"row":return"row-resize";default:return"default"}}}class U{static register(t,e){this.registry.set(t,e)}static unregister(t){return this.registry.delete(t)}static isRegistered(t){return this.ensureInitialized(),this.registry.has(t)}static getRegisteredTypes(){return this.ensureInitialized(),Array.from(this.registry.keys())}static create(t){this.ensureInitialized();const e=this.registry.get(t.objectType);if(!e)throw new Error(`Unknown object type: ${t.objectType}. Registered types: ${this.getRegisteredTypes().join(", ")}`);return e(t)}static tryCreate(t){try{return this.create(t)}catch{return null}}static initialize(){this.initialized||(this.register("image",t=>new I({id:t.id,textIndex:t.textIndex,position:t.position,size:t.size,relativeOffset:t.relativeOffset,src:t.data.src,fit:t.data.fit,resizeMode:t.data.resizeMode,alt:t.data.alt})),this.register("textbox",t=>{const e=new E({id:t.id,textIndex:t.textIndex,position:t.position,size:t.size,relativeOffset:t.relativeOffset,content:t.data.content,fontFamily:t.data.fontFamily,fontSize:t.data.fontSize,color:t.data.color,backgroundColor:t.data.backgroundColor,borderColor:t.data.borderColor,border:t.data.border,padding:t.data.padding});if(t.data.formattingRuns&&Array.isArray(t.data.formattingRuns)){const i=t.data.formattingRuns;if(i.length>0){const t=e.flowingContent.getFormattingManager(),n=e.flowingContent.getText().length;for(let e=0;e<i.length;e++){const[s,o]=i[e],r=e+1<i.length?i[e+1][0]:n;s<r&&t.applyFormatting(s,r,o)}}}if(t.data.substitutionFields&&Array.isArray(t.data.substitutionFields)){const i=e.flowingContent.getSubstitutionFieldManager();for(const e of t.data.substitutionFields)void 0!==e.textIndex&&e.fieldName&&i.insert(e.fieldName,e.textIndex,{defaultValue:e.defaultValue,displayFormat:e.displayFormat})}return e}),this.register("table",t=>W.fromData(t)),this.initialized=!0)}static ensureInitialized(){this.initialized||this.initialize()}static reset(){this.registry.clear(),this.initialized=!1}}U.registry=new Map,U.initialized=!1;class $ extends o{constructor(t){super(),this._hasFocus=!1,this._cursorBlinkTimer=null,this._cursorVisible=!0,this._cursorBlinkHandlers=new Set,this.textState=new g(t),this.formatting=new u,this.paragraphFormatting=new m,this.substitutionFields=new b,this.embeddedObjects=new x,this.repeatingSections=new y,this.hyperlinks=new w,this.layout=new C,this.setupEventForwarding(),this.setupFieldCheckCallback()}setupFieldCheckCallback(){this.textState.setFieldCheckCallback(t=>this.substitutionFields.hasFieldAt(t))}setupEventForwarding(){this.textState.on("text-changed",t=>{this.emit("content-changed",{text:t.text,cursorPosition:t.cursorPosition})}),this.textState.on("text-inserted",t=>{this.emit("content-changed",{text:this.textState.getText(),cursorPosition:t.newCursorPosition})}),this.textState.on("text-deleted",t=>{this.formatting.handleDeletion(t.start,t.length),this.substitutionFields.handleDeletion(t.start,t.length),this.embeddedObjects.handleDeletion(t.start,t.length),this.repeatingSections.handleDeletion(t.start,t.length),this.paragraphFormatting.handleDeletion(t.start,t.length),this.hyperlinks.handleDeletion(t.start,t.length),this.emit("content-changed",{text:this.textState.getText(),cursorPosition:t.newCursorPosition})}),this.textState.on("cursor-moved",t=>{this.emit("cursor-moved",{position:t.position})}),this.textState.on("selection-changed",t=>{this.emit("selection-changed",t)}),this.formatting.on("formatting-changed",t=>{this.emit("formatting-changed",t)}),this.substitutionFields.on("field-added",t=>{this.emit("substitution-field-added",t)}),this.substitutionFields.on("field-removed",t=>{this.emit("substitution-field-removed",t)}),this.substitutionFields.on("field-updated",t=>{this.emit("substitution-field-updated",t)}),this.embeddedObjects.on("object-added",t=>{this.emit("embedded-object-added",t)}),this.embeddedObjects.on("object-removed",t=>{this.emit("embedded-object-removed",t)}),this.embeddedObjects.on("object-updated",t=>{this.emit("embedded-object-updated",t),this.emit("content-changed",{type:"object-updated",...t})}),this.repeatingSections.on("section-added",t=>{this.emit("repeating-section-added",t)}),this.repeatingSections.on("section-removed",t=>{this.emit("repeating-section-removed",t)}),this.repeatingSections.on("section-updated",t=>{this.emit("repeating-section-updated",t)}),this.hyperlinks.on("hyperlink-added",t=>{this.emit("hyperlink-added",t)}),this.hyperlinks.on("hyperlink-removed",t=>{this.emit("hyperlink-removed",t)}),this.hyperlinks.on("hyperlink-updated",t=>{this.emit("hyperlink-updated",t)})}getText(){return this.textState.getText()}setText(t){this.textState.setText(t)}insertText(t,e){const i=e??this.textState.getCursorPosition(),n=this.formatting.getPendingFormatting();let s=null;if(n)s=n;else{const t=this.textState.getText();i>0?s=this.formatting.getFormattingAt(i-1):t.length>0&&(s=this.formatting.getFormattingAt(0))}this.formatting.shiftFormatting(i,t.length),this.substitutionFields.shiftFields(i,t.length),this.embeddedObjects.shiftObjects(i,t.length),this.repeatingSections.shiftSections(i,t.length),this.hyperlinks.shiftHyperlinks(i,t.length),this.textState.insertText(t,i),this.paragraphFormatting.shiftParagraphs(i,t.length,this.textState.getText()),s&&t.length>0&&this.formatting.applyFormatting(i,i+t.length,s,!0),this.emit("text-inserted",{position:i,text:t,formatting:s})}insertPageBreak(){this.insertText(c)}deleteText(t,e,i=!0){const n=this.textState.substring(t,t+e),s=new Map;for(let i=0;i<e;i++){const e=this.formatting.getFormattingAt(t+i);e&&s.set(i,e)}const o=this.embeddedObjects.getObjectsInRange(t,t+e).map(e=>({offset:e.textIndex-t,object:e.object})),r=this.substitutionFields.getFieldsInRange(t,t+e).map(e=>({offset:e.textIndex-t,field:e.field}));this.textState.deleteText(t,e),this.emit("text-deleted",{position:t,deletedText:n,deletedFormatting:s,deletedObjects:o,deletedFields:r,isBackspace:i})}insertTextAt(t,e){this.formatting.shiftFormatting(t,e.length),this.substitutionFields.shiftFields(t,e.length),this.embeddedObjects.shiftObjects(t,e.length),this.repeatingSections.shiftSections(t,e.length),this.hyperlinks.shiftHyperlinks(t,e.length);const i=this.textState.getText();this.textState.setText(i.slice(0,t)+e+i.slice(t)),this.paragraphFormatting.shiftParagraphs(t,e.length,this.textState.getText())}deleteTextAt(t,e){this.formatting.handleDeletion(t,e),this.substitutionFields.handleDeletion(t,e),this.embeddedObjects.handleDeletion(t,e),this.repeatingSections.handleDeletion(t,e),this.paragraphFormatting.handleDeletion(t,e),this.hyperlinks.handleDeletion(t,e);const i=this.textState.getText();this.textState.setText(i.slice(0,t)+i.slice(t+e))}getCursorPosition(){return this.textState.getCursorPosition()}setCursorPosition(t){this.formatting.clearPendingFormatting(),this.textState.setCursorPosition(t)}moveCursorLeft(){this.formatting.clearPendingFormatting(),this.textState.moveCursorLeft()}moveCursorRight(){this.formatting.clearPendingFormatting(),this.textState.moveCursorRight()}getSelection(){return this.textState.getSelection()}setSelectionAnchor(t){this.textState.setSelectionAnchor(t)}hasSelection(){return this.textState.hasSelection()}hasSelectionAnchor(){return this.textState.hasSelectionAnchor()}clearSelection(){this.textState.clearSelection()}setSelection(t,e){this.textState.setSelectionAnchor(t),this.textState.setCursorPosition(e)}getSelectedText(){return this.textState.getSelectedText()}deleteSelection(){const t=this.getSelection();return!!t&&(this.deleteText(t.start,t.end-t.start),this.clearSelection(),!0)}replaceSelection(t){const e=this.hasSelection();e&&(this.emit("compound-operation-start",{}),this.deleteSelection()),this.insertText(t),e&&this.emit("compound-operation-end",{description:"Replace"})}beginCompoundOperation(t){this.emit("compound-operation-start",{description:t})}endCompoundOperation(){this.emit("compound-operation-end",{})}selectLeft(){this.textState.selectLeft()}selectRight(){this.textState.selectRight()}selectWord(){this.textState.selectWord()}selectParagraph(){this.textState.selectParagraph()}selectAll(){this.textState.selectAll()}getWordBoundaries(t){return this.textState.getWordBoundaries(t)}getParagraphBoundariesAt(t){return this.textState.getParagraphBoundaries(t)}moveCursorToLineStart(){this.textState.moveCursorToLineStart()}moveCursorToLineEnd(){this.textState.moveCursorToLineEnd()}moveCursorToDocumentStart(){this.textState.moveCursorToDocumentStart()}moveCursorToDocumentEnd(){this.textState.moveCursorToDocumentEnd()}selectToLineStart(){this.textState.selectToLineStart()}selectToLineEnd(){this.textState.selectToLineEnd()}selectToDocumentStart(){this.textState.selectToDocumentStart()}selectToDocumentEnd(){this.textState.selectToDocumentEnd()}moveCursorWordLeft(){this.textState.moveCursorWordLeft()}moveCursorWordRight(){this.textState.moveCursorWordRight()}selectWordLeft(){this.textState.selectWordLeft()}selectWordRight(){this.textState.selectWordRight()}getFormattingAt(t){return this.formatting.getFormattingAt(t)}applyFormatting(t,e,i){const n=new Map;for(let i=t;i<e;i++){const e=this.formatting.getFormattingAt(i);e&&n.set(i-t,e)}this.formatting.applyFormatting(t,e,i);for(const n of this.substitutionFields.getFieldsArray())if(n.textIndex>=t&&n.textIndex<e){const t={...n.formatting||this.formatting.defaultFormatting,...i};this.substitutionFields.setFieldFormatting(n.textIndex,t)}this.emit("formatting-changed",{start:t,end:e,newFormatting:i,previousFormatting:n}),this.emit("content-changed",{type:"formatting",start:t,end:e})}getDefaultFormatting(){return this.formatting.defaultFormatting}setDefaultFormatting(t){this.formatting.setDefaultFormatting(t)}setPendingFormatting(t){this.formatting.setPendingFormatting(t)}getPendingFormatting(){return this.formatting.getPendingFormatting()}hasPendingFormatting(){return this.formatting.hasPendingFormatting()}clearPendingFormatting(){this.formatting.clearPendingFormatting()}getEffectiveFormattingAtCursor(){const t=this.getCursorPosition(),e=this.getPendingFormatting();let i;if(t>0)i=this.formatting.getFormattingAt(t-1);else{i=this.getText().length>0?this.formatting.getFormattingAt(0):this.formatting.defaultFormatting}return e?{...i,...e}:i}getSubstitutionFields(){return this.substitutionFields.getFields()}insertSubstitutionField(t,e){const i=this.textState.getCursorPosition(),n=e?.formatting||this.formatting.getFormattingAt(i);this.formatting.shiftFormatting(i,1),this.substitutionFields.shiftFields(i,1),this.embeddedObjects.shiftObjects(i,1),this.repeatingSections.shiftSections(i,1),this.textState.insertText(d,i),this.paragraphFormatting.shiftParagraphs(i,1,this.textState.getText());const s=this.substitutionFields.insert(t,i,{...e,formatting:n});return n&&this.formatting.applyFormatting(i,i+1,n,!0),this.emit("substitution-field-inserted",{position:i,field:s}),this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()}),s}insertPageNumberField(t){return this.insertSubstitutionField("page",{fieldType:"pageNumber",displayFormat:t})}insertPageCountField(t){return this.insertSubstitutionField("pages",{fieldType:"pageCount",displayFormat:t})}insertSubstitutionFieldAt(t,e,i){const n=this.substitutionFields.insert(t,e,i);return i?.formatting&&this.formatting.applyFormatting(e,e+1,i.formatting),this.emit("substitution-field-inserted",{position:e,field:n}),n}removeSubstitutionField(t){return!!this.substitutionFields.remove(t)&&(this.textState.deleteText(t,1),!0)}getSubstitutionFieldAt(t){return this.substitutionFields.getFieldAt(t)}updateSubstitutionFieldConfig(t,e){return this.substitutionFields.updateFieldConfig(t,e)}getEmbeddedObjects(){return this.embeddedObjects.getObjects()}getEmbeddedObjectsInRange(t,e){return this.embeddedObjects.getObjectsInRange(t,e)}getSubstitutionFieldsInRange(t,e){return this.substitutionFields.getFieldsInRange(t,e).map(t=>({...t.field,textIndex:t.textIndex,field:t.field}))}insertEmbeddedObject(t,e="inline"){const i=this.textState.getCursorPosition();this.substitutionFields.shiftFields(i,1),this.embeddedObjects.shiftObjects(i,1),this.textState.insertText(d,i);const n="table"===t.objectType?"block":e;t.position=n,this.embeddedObjects.insert(t,i),this.emit("embedded-object-inserted",{position:i,object:t,objectPosition:n}),this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()})}insertEmbeddedObjectAt(t,e,i="inline"){this.substitutionFields.shiftFields(e,1),this.embeddedObjects.shiftObjects(e,1);const n=this.textState.getText();this.textState.setText(n.slice(0,e)+d+n.slice(e)),t.position=i,this.embeddedObjects.insert(t,e),this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()})}removeEmbeddedObject(t){return!!this.embeddedObjects.remove(t)&&(this.textState.deleteText(t,1),!0)}getEmbeddedObjectAt(t){return this.embeddedObjects.getObjectAt(t)}findEmbeddedObjectById(t){return this.embeddedObjects.findById(t)}getSelectedEmbeddedObject(){return this.embeddedObjects.getSelectedObject()}deselectAllEmbeddedObjects(){this.embeddedObjects.deselectAll()}flowText(t,e,i){const n=new S(i),s=this.textState.getText(),o={availableWidth:t,availableHeight:e,measurer:n,formatting:this.formatting,paragraphFormatting:this.paragraphFormatting,substitutionFields:this.substitutionFields,embeddedObjects:this.embeddedObjects,content:s};return this.layout.flowText(s,o)}findPositionForIndex(t,e){return this.layout.findPositionForIndex(t,e)}get length(){return this.textState.length}get isEmpty(){return this.textState.isEmpty}clear(){this.textState.clear(),this.formatting.clear(),this.paragraphFormatting.clear(),this.substitutionFields.clear(),this.embeddedObjects.clear(),this.repeatingSections.clear(),this.hyperlinks.clear()}focus(){this._hasFocus||(this._hasFocus=!0,this._cursorVisible=!0,this.startCursorBlink(),this.emit("focus"))}blur(){this._hasFocus&&(this._hasFocus=!1,this._cursorVisible=!1,this.stopCursorBlink(),this.emit("blur"))}hasFocus(){return this._hasFocus}isCursorVisible(){return this._hasFocus&&this._cursorVisible}handleKeyDown(t){if(O.log("[pc-editor:FlowingTextContent.handleKeyDown] Key:",t.key,"_hasFocus:",this._hasFocus),!this._hasFocus)return O.log("[pc-editor:FlowingTextContent.handleKeyDown] No focus, returning false"),!1;switch(t.key){case"Backspace":if(t.preventDefault(),!this.deleteSelection()){const t=this.getCursorPosition();t>0&&this.deleteText(t-1,1)}return!0;case"Delete":if(t.preventDefault(),!this.deleteSelection()){const t=this.getCursorPosition();t<this.getText().length&&this.deleteText(t,1,!1)}return!0;case"ArrowLeft":return t.preventDefault(),t.ctrlKey||t.metaKey?t.shiftKey?this.selectWordLeft():(this.clearSelection(),this.moveCursorWordLeft()):t.shiftKey?this.selectLeft():(this.clearSelection(),this.moveCursorLeft()),this.resetCursorBlink(),!0;case"ArrowRight":return t.preventDefault(),t.ctrlKey||t.metaKey?t.shiftKey?this.selectWordRight():(this.clearSelection(),this.moveCursorWordRight()):t.shiftKey?this.selectRight():(this.clearSelection(),this.moveCursorRight()),this.resetCursorBlink(),!0;case"Home":return t.preventDefault(),t.ctrlKey||t.metaKey?t.shiftKey?this.selectToDocumentStart():(this.clearSelection(),this.moveCursorToDocumentStart()):t.shiftKey?this.selectToLineStart():(this.clearSelection(),this.moveCursorToLineStart()),this.resetCursorBlink(),!0;case"End":return t.preventDefault(),t.ctrlKey||t.metaKey?t.shiftKey?this.selectToDocumentEnd():(this.clearSelection(),this.moveCursorToDocumentEnd()):t.shiftKey?this.selectToLineEnd():(this.clearSelection(),this.moveCursorToLineEnd()),this.resetCursorBlink(),!0;case"ArrowUp":case"ArrowDown":return t.shiftKey&&!this.hasSelectionAnchor()?this.setSelectionAnchor():t.shiftKey||this.clearSelection(),!1;case"Enter":return t.preventDefault(),t.ctrlKey||t.metaKey?this.replaceSelection(c):this.replaceSelection("\n"),!0;case"Tab":{t.preventDefault();const e=this.textState.getCursorPosition(),i=this.textState.getText(),n=this.paragraphFormatting.getParagraphStart(e,i);return this.paragraphFormatting.getFormattingForParagraph(n).listFormatting?t.shiftKey?this.outdentParagraph():this.indentParagraph():t.shiftKey||this.replaceSelection("\t"),!0}default:return!(1!==t.key.length||t.ctrlKey||t.altKey||t.metaKey)&&(t.preventDefault(),this.replaceSelection(t.key),!0)}}onCursorBlink(t){this._cursorBlinkHandlers.add(t)}offCursorBlink(t){this._cursorBlinkHandlers.delete(t)}startCursorBlink(){this.stopCursorBlink(),this._cursorVisible=!0,this._cursorBlinkTimer=setInterval(()=>{this._cursorVisible=!this._cursorVisible;for(const t of this._cursorBlinkHandlers)t();this.emit("cursor-blink",{visible:this._cursorVisible})},530)}stopCursorBlink(){this._cursorBlinkTimer&&(clearInterval(this._cursorBlinkTimer),this._cursorBlinkTimer=null)}resetCursorBlink(){this._hasFocus&&(this._cursorVisible=!0,this.startCursorBlink())}getAlignmentAt(t){return this.paragraphFormatting.getFormattingAt(t,this.textState.getText()).alignment}setAlignment(t){const e=this.textState.getCursorPosition(),i=this.textState.getText(),n=this.paragraphFormatting.getParagraphStart(e,i),s=this.paragraphFormatting.getFormattingAt(e,i).alignment;this.paragraphFormatting.setAlignment(n,t),this.emit("alignment-changed",{paragraphIndex:n,newAlignment:t,previousAlignment:s}),this.emit("content-changed",{text:i,cursorPosition:e})}setAlignmentForRange(t,e,i){const n=this.textState.getText();this.paragraphFormatting.applyToRange(t,e,n,{alignment:i}),this.emit("content-changed",{text:n,cursorPosition:this.textState.getCursorPosition()})}getTextState(){return this.textState}getFormattingManager(){return this.formatting}getParagraphFormattingManager(){return this.paragraphFormatting}getSubstitutionFieldManager(){return this.substitutionFields}getEmbeddedObjectManager(){return this.embeddedObjects}getRepeatingSectionManager(){return this.repeatingSections}getLayoutEngine(){return this.layout}getHyperlinkManager(){return this.hyperlinks}toggleBulletList(){const t=this.textState.getCursorPosition(),e=this.textState.getText(),i=this.paragraphFormatting.getParagraphStart(t,e);this.paragraphFormatting.toggleList(i,"bullet"),this.emit("content-changed",{text:e,cursorPosition:t})}toggleNumberedList(){const t=this.textState.getCursorPosition(),e=this.textState.getText(),i=this.paragraphFormatting.getParagraphStart(t,e);this.paragraphFormatting.toggleList(i,"number"),this.emit("content-changed",{text:e,cursorPosition:t})}indentParagraph(){const t=this.textState.getCursorPosition(),e=this.textState.getText(),i=this.paragraphFormatting.getParagraphStart(t,e);this.paragraphFormatting.indentParagraph(i),this.emit("content-changed",{text:e,cursorPosition:t})}outdentParagraph(){const t=this.textState.getCursorPosition(),e=this.textState.getText(),i=this.paragraphFormatting.getParagraphStart(t,e);this.paragraphFormatting.outdentParagraph(i),this.emit("content-changed",{text:e,cursorPosition:t})}getListFormatting(){const t=this.textState.getCursorPosition(),e=this.textState.getText(),i=this.paragraphFormatting.getParagraphStart(t,e);return this.paragraphFormatting.getFormattingForParagraph(i).listFormatting}insertHyperlink(t,e){const i=this.getSelection();if(!i||i.start===i.end)return null;const n=this.hyperlinks.insert(t,i.start,i.end,e);return this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()}),n}insertHyperlinkAt(t,e,i,n){const s=this.hyperlinks.insert(t,e,i,n);return this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()}),s}removeHyperlink(t){this.hyperlinks.remove(t),this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()})}updateHyperlink(t,e){this.hyperlinks.update(t,e),this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()})}getHyperlinkAt(t){return this.hyperlinks.getHyperlinkAt(t)}getHyperlinkById(t){return this.hyperlinks.getHyperlinkById(t)}getHyperlinksInRange(t,e){return this.hyperlinks.getHyperlinksInRange(t,e)}getAllHyperlinks(){return this.hyperlinks.getAll()}getParagraphBoundaries(){return this.layout.getParagraphBoundaries(this.textState.getText())}getRepeatingSections(){return this.repeatingSections.getSections()}createRepeatingSection(t,e,i){const n=this.textState.getText();if(!this.repeatingSections.validateBoundaries(t,e,n))return null;const s=this.repeatingSections.create(t,e,i);return this.emit("content-changed",{text:n,cursorPosition:this.textState.getCursorPosition()}),s}removeRepeatingSection(t){return!!this.repeatingSections.remove(t)&&(this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()}),!0)}getRepeatingSection(t){return this.repeatingSections.getSection(t)}getRepeatingSectionAtBoundary(t){return this.repeatingSections.getSectionAtBoundary(t)}updateRepeatingSectionFieldPath(t,e){const i=this.repeatingSections.updateFieldPath(t,e);return i&&this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()}),i}toData(){const t=this.textState.getText(),e=this.formatting.getCompressedRuns(t.length).map(t=>({index:t.index,formatting:{fontFamily:t.formatting.fontFamily,fontSize:t.formatting.fontSize,fontWeight:t.formatting.fontWeight,fontStyle:t.formatting.fontStyle,color:t.formatting.color,backgroundColor:t.formatting.backgroundColor}})),i=this.paragraphFormatting.toJSON(),n=this.substitutionFields.toJSON().map(t=>({id:t.id,textIndex:t.textIndex,fieldName:t.fieldName,fieldType:t.fieldType,displayFormat:t.displayFormat,defaultValue:t.defaultValue,formatting:t.formatting?{fontFamily:t.formatting.fontFamily,fontSize:t.formatting.fontSize,fontWeight:t.formatting.fontWeight,fontStyle:t.formatting.fontStyle,color:t.formatting.color,backgroundColor:t.formatting.backgroundColor}:void 0,formatConfig:t.formatConfig?{valueType:t.formatConfig.valueType,numberFormat:t.formatConfig.numberFormat,decimalPlaces:t.formatConfig.decimalPlaces,useGrouping:t.formatConfig.useGrouping,currencyFormat:t.formatConfig.currencyFormat,currencySymbol:t.formatConfig.currencySymbol,currencyPosition:t.formatConfig.currencyPosition,dateFormat:t.formatConfig.dateFormat,locale:t.formatConfig.locale}:void 0})),s=this.repeatingSections.toJSON(),o=[];this.embeddedObjects.getObjects().forEach((t,e)=>{o.push({textIndex:e,object:t.toData()})});const r=this.hyperlinks.toJSON();return{text:t,formattingRuns:e.length>0?e:void 0,paragraphFormatting:i.length>0?i:void 0,substitutionFields:n.length>0?n:void 0,repeatingSections:s.length>0?s:void 0,embeddedObjects:o.length>0?o:void 0,hyperlinks:r.length>0?r:void 0}}static fromData(t){const e=new $(t.text);if(t.formattingRuns&&t.formattingRuns.length>0){const i=t.text.length,n=e.getFormattingManager();for(let e=0;e<t.formattingRuns.length;e++){const s=t.formattingRuns[e],o=t.formattingRuns[e+1],r=s.index,a=o?o.index:i;r<a&&n.applyFormatting(r,a,s.formatting)}}if(t.paragraphFormatting&&t.paragraphFormatting.length>0&&e.getParagraphFormattingManager().fromJSON(t.paragraphFormatting),t.substitutionFields&&t.substitutionFields.length>0&&e.getSubstitutionFieldManager().fromJSON(t.substitutionFields),t.repeatingSections&&t.repeatingSections.length>0&&e.getRepeatingSectionManager().fromJSON(t.repeatingSections),t.embeddedObjects&&t.embeddedObjects.length>0)for(const i of t.embeddedObjects){const t=U.tryCreate(i.object);t?e.getEmbeddedObjectManager().insert(t,i.textIndex):O.warn(`[pc-editor:FlowingTextContent] Failed to create embedded object of type: ${i.object.objectType}`)}return t.hyperlinks&&t.hyperlinks.length>0&&e.getHyperlinkManager().fromJSON(t.hyperlinks),e}loadFromData(t){if(this.clear(),this.textState.setText(t.text),t.formattingRuns&&t.formattingRuns.length>0){const e=t.text.length;for(let i=0;i<t.formattingRuns.length;i++){const n=t.formattingRuns[i],s=t.formattingRuns[i+1],o=n.index,r=s?s.index:e;o<r&&this.formatting.applyFormatting(o,r,n.formatting)}}if(t.paragraphFormatting&&t.paragraphFormatting.length>0&&this.paragraphFormatting.fromJSON(t.paragraphFormatting),t.substitutionFields&&t.substitutionFields.length>0&&this.substitutionFields.fromJSON(t.substitutionFields),t.repeatingSections&&t.repeatingSections.length>0&&this.repeatingSections.fromJSON(t.repeatingSections),t.embeddedObjects&&t.embeddedObjects.length>0)for(const e of t.embeddedObjects){const t=U.tryCreate(e.object);t?this.embeddedObjects.insert(t,e.textIndex):O.warn(`[pc-editor:FlowingTextContent] Failed to create embedded object of type: ${e.object.objectType}`)}t.hyperlinks&&t.hyperlinks.length>0&&this.hyperlinks.fromJSON(t.hyperlinks)}}class V{globalToLocal(t,e){const i=this.getRegionBounds(e);return i?t.x<i.x||t.x>i.x+i.width||t.y<i.y||t.y>i.y+i.height?null:{x:t.x-i.x,y:t.y-i.y}:null}localToGlobal(t,e){const i=this.getRegionBounds(e);return i?{x:t.x+i.x,y:t.y+i.y}:t}getPageCount(){return this.getFlowedPages().length||1}containsPointInRegion(t,e){const i=this.getRegionBounds(e);return!!i&&(t.x>=i.x&&t.x<=i.x+i.width&&t.y>=i.y&&t.y<=i.y+i.height)}}class X{constructor(){this._bodyRegion=null,this._headerRegion=null,this._footerRegion=null,this._textBoxRegions=new Map}setBodyRegion(t){this._bodyRegion=t}getBodyRegion(){return this._bodyRegion}setHeaderRegion(t){this._headerRegion=t}getHeaderRegion(){return this._headerRegion}setFooterRegion(t){this._footerRegion=t}getFooterRegion(){return this._footerRegion}registerTextBox(t){this._textBoxRegions.set(t.id,t)}unregisterTextBox(t){this._textBoxRegions.delete(t)}getTextBoxRegion(t){return this._textBoxRegions.get(t)||null}getAllTextBoxRegions(){return Array.from(this._textBoxRegions.values())}getAllRegions(){const t=[];this._bodyRegion&&t.push(this._bodyRegion),this._headerRegion&&t.push(this._headerRegion),this._footerRegion&&t.push(this._footerRegion);for(const e of this._textBoxRegions.values())t.push(e);return t}getRegionAtPoint(t,e){for(const i of this._textBoxRegions.values())if(i.containsPointInRegion(t,e))return i;return this._headerRegion&&this._headerRegion.containsPointInRegion(t,e)?this._headerRegion:this._footerRegion&&this._footerRegion.containsPointInRegion(t,e)?this._footerRegion:this._bodyRegion&&this._bodyRegion.containsPointInRegion(t,e)?this._bodyRegion:null}findRegionByFlowingContent(t){if(this._bodyRegion&&this._bodyRegion.flowingContent===t)return this._bodyRegion;if(this._headerRegion&&this._headerRegion.flowingContent===t)return this._headerRegion;if(this._footerRegion&&this._footerRegion.flowingContent===t)return this._footerRegion;for(const e of this._textBoxRegions.values())if(e.flowingContent===t)return e;return null}clear(){this._bodyRegion=null,this._headerRegion=null,this._footerRegion=null,this._textBoxRegions.clear()}}class K extends V{constructor(t,e){super(),this.id="body",this.type="body",this._flowedPages=[],this._availableWidth=0,this._flowingContent=t,this._getPage=e}get flowingContent(){return this._flowingContent}getRegionBounds(t){const e=this._getPage(t);if(!e)return null;const i=e.getContentBounds();return{x:i.position.x,y:i.position.y,width:i.size.width,height:i.size.height}}getFlowedLines(t){return t<0||t>=this._flowedPages.length?[]:this._flowedPages[t].lines}getFlowedPages(){return this._flowedPages}getAvailableWidth(){return this._availableWidth}spansMultiplePages(){return!0}reflow(t){const e=this.getRegionBounds(0);if(!e)return this._flowedPages=[],void(this._availableWidth=0);this._availableWidth=e.width,this._flowedPages=this._flowingContent.flowText(e.width,100*e.height,t)}setFlowedPages(t,e){this._flowedPages=t,this._availableWidth=e}}class Y extends V{constructor(t,e){super(),this.id="header",this.type="header",this._flowedPage=null,this._availableWidth=0,this._flowingContent=t,this._getPage=e}get flowingContent(){return this._flowingContent}getRegionBounds(t){const e=this._getPage(t);if(!e)return null;const i=e.getHeaderBounds();return{x:i.position.x,y:i.position.y,width:i.size.width,height:i.size.height}}getFlowedLines(t){return this._flowedPage?.lines||[]}getFlowedPages(){return this._flowedPage?[this._flowedPage]:[]}getAvailableWidth(){return this._availableWidth}spansMultiplePages(){return!1}reflow(t){const e=this.getRegionBounds(0);if(!e)return this._flowedPage=null,void(this._availableWidth=0);this._availableWidth=e.width;const i=this._flowingContent.flowText(e.width,e.height,t);this._flowedPage=i.length>0?i[0]:null}setFlowedPage(t,e){this._flowedPage=t,this._availableWidth=e}}class q extends V{constructor(t,e){super(),this.id="footer",this.type="footer",this._flowedPage=null,this._availableWidth=0,this._flowingContent=t,this._getPage=e}get flowingContent(){return this._flowingContent}getRegionBounds(t){const e=this._getPage(t);if(!e)return null;const i=e.getFooterBounds();return{x:i.position.x,y:i.position.y,width:i.size.width,height:i.size.height}}getFlowedLines(t){return this._flowedPage?.lines||[]}getFlowedPages(){return this._flowedPage?[this._flowedPage]:[]}getAvailableWidth(){return this._availableWidth}spansMultiplePages(){return!1}reflow(t){const e=this.getRegionBounds(0);if(!e)return this._flowedPage=null,void(this._availableWidth=0);this._availableWidth=e.width;const i=this._flowingContent.flowText(e.width,e.height,t);this._flowedPage=i.length>0?i[0]:null}setFlowedPage(t,e){this._flowedPage=t,this._availableWidth=e}}const J={USD:"USD",EUR:"EUR",GBP:"GBP",JPY:"JPY"};function Z(t,e){if(null==t)return"";if(!e||!e.valueType)return String(t);const i=e.locale||"en-US";switch(e.valueType){case"number":return Q(t,e,i);case"currency":return function(t,e,i){const n=tt(t);if(isNaN(n))return String(t);const s=e.currencyFormat||"USD";if("custom"===s){const t=e.currencySymbol||"$",s=e.currencyPosition||"before",o=Q(n,{decimalPlaces:e.decimalPlaces??2,useGrouping:e.useGrouping??!0},i);return"before"===s?`${t}${o}`:`${o}${t}`}const o={style:"currency",currency:J[s],minimumFractionDigits:e.decimalPlaces,maximumFractionDigits:e.decimalPlaces};"JPY"===s&&void 0===e.decimalPlaces&&(o.minimumFractionDigits=0,o.maximumFractionDigits=0);try{return new Intl.NumberFormat(i,o).format(n)}catch{return String(n)}}(t,e,i);case"date":return function(t,e,i){const n=function(t){if(t instanceof Date)return t;if("string"==typeof t||"number"==typeof t){const e=new Date(t);return isNaN(e.getTime())?null:e}return null}(t);if(!n||isNaN(n.getTime()))return String(t);const s=e.dateFormat;if("iso"===s)return n.toISOString().split("T")[0];const o=function(t){switch(t){case"short":return{dateStyle:"short"};case"medium":default:return{dateStyle:"medium"};case"long":return{dateStyle:"long"};case"full":return{dateStyle:"full"};case"time-short":return{timeStyle:"short"};case"time-long":return{timeStyle:"medium"};case"datetime-short":return{dateStyle:"short",timeStyle:"short"};case"datetime-long":return{dateStyle:"long",timeStyle:"short"}}}(s);try{return new Intl.DateTimeFormat(i,o).format(n)}catch{return n.toLocaleDateString()}}(t,e,i);default:return String(t)}}function Q(t,e,i){const n=tt(t);if(isNaN(n))return String(t);const s={};switch(e.numberFormat){case"integer":s.maximumFractionDigits=0,s.useGrouping=e.useGrouping??!1;break;case"decimal":s.minimumFractionDigits=e.decimalPlaces??2,s.maximumFractionDigits=e.decimalPlaces??2,s.useGrouping=e.useGrouping??!1;break;case"decimal-1":s.minimumFractionDigits=1,s.maximumFractionDigits=1,s.useGrouping=e.useGrouping??!1;break;case"decimal-3":s.minimumFractionDigits=3,s.maximumFractionDigits=3,s.useGrouping=e.useGrouping??!1;break;case"thousands":s.maximumFractionDigits=0,s.useGrouping=!0;break;case"percent":s.style="percent",s.minimumFractionDigits=e.decimalPlaces??2,s.maximumFractionDigits=e.decimalPlaces??2;break;case"scientific":s.notation="scientific",s.minimumFractionDigits=e.decimalPlaces??2,s.maximumFractionDigits=e.decimalPlaces??2;break;default:void 0!==e.decimalPlaces&&(s.minimumFractionDigits=e.decimalPlaces,s.maximumFractionDigits=e.decimalPlaces),void 0!==e.useGrouping&&(s.useGrouping=e.useGrouping)}try{return new Intl.NumberFormat(i,s).format(n)}catch{return String(n)}}function tt(t){if("number"==typeof t)return t;if("string"==typeof t){const e=t.replace(/[^0-9.-]/g,"");return parseFloat(e)}return NaN}class et extends o{constructor(t){super(),this._pages=[],this._version="1.0.0",this._bodyFlowingContent=new $,this._headerFlowingContent=new $,this._footerFlowingContent=new $,this.setupFlowingContentListeners(),t?(this._version=t.version||this._version,this._settings=t.settings||this.getDefaultSettings(),t.pages.forEach(t=>{this.addPage(new r(t,this._settings))}),t.bodyContent&&this._bodyFlowingContent.loadFromData(t.bodyContent),t.headerContent&&this._headerFlowingContent.loadFromData(t.headerContent),t.footerContent&&this._footerFlowingContent.loadFromData(t.footerContent)):(this._settings=this.getDefaultSettings(),this.addPage(new r(this.createEmptyPageData(),this._settings)))}setupFlowingContentListeners(){this._bodyFlowingContent.on("content-changed",()=>{this.emit("body-content-changed"),this.emit("change")}),this._bodyFlowingContent.on("cursor-moved",t=>{this.emit("cursor-moved",t)}),this._bodyFlowingContent.on("formatting-changed",t=>{this.emit("formatting-changed",t),this.emit("change")}),this._bodyFlowingContent.on("inline-element-added",t=>{this.emit("inline-element-added",t),this.emit("change")}),this._headerFlowingContent.on("content-changed",()=>{this.emit("header-content-changed"),this.emit("change")}),this._footerFlowingContent.on("content-changed",()=>{this.emit("footer-content-changed"),this.emit("change")})}getDefaultSettings(){return{pageSize:"A4",pageOrientation:"portrait",margins:{top:20,right:20,bottom:20,left:20},units:"mm"}}createEmptyPageData(){return{id:this.generateId()}}generateId(){return`page_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}get pages(){return this._pages}get pageCount(){return this._pages.length}get settings(){return{...this._settings}}get version(){return this._version}get bodyFlowingContent(){return this._bodyFlowingContent}get headerFlowingContent(){return this._headerFlowingContent}get footerFlowingContent(){return this._footerFlowingContent}addPage(t,e){void 0!==e&&e>=0&&e<=this._pages.length?this._pages.splice(e,0,t):this._pages.push(t),t.on("change",()=>this.handlePageChange()),this.emit("page-added",{page:t,index:e}),this.emit("change")}removePage(t){const e=this._pages.findIndex(e=>e.id===t);if(-1===e)return null;const[i]=this._pages.splice(e,1);return i.removeAllListeners(),this.emit("page-removed",{page:i,index:e}),this.emit("change"),i}getPage(t){return this._pages.find(e=>e.id===t)}getPageByIndex(t){return this._pages[t]}movePage(t,e){const i=this._pages.findIndex(e=>e.id===t);if(-1===i||e<0||e>=this._pages.length)return!1;const[n]=this._pages.splice(i,1);return this._pages.splice(e,0,n),this.emit("page-moved",{page:n,fromIndex:i,toIndex:e}),this.emit("change"),!0}updateSettings(t){this._settings={...this._settings,...t},this._pages.forEach(t=>{t.updateSettings(this._settings)}),this.emit("settings-changed",{settings:this._settings}),this.emit("change")}handlePageChange(){this.emit("change")}toData(){return{version:this._version,settings:{...this._settings},pages:this._pages.map(t=>t.toData()),bodyContent:this._bodyFlowingContent.toData(),headerContent:this._headerFlowingContent.toData(),footerContent:this._footerFlowingContent.toData(),metadata:{modifiedAt:(new Date).toISOString()}}}clear(){this._pages.forEach(t=>t.removeAllListeners()),this._pages=[],this._bodyFlowingContent.setText(""),this._headerFlowingContent.setText(""),this._footerFlowingContent.setText(""),this.emit("cleared"),this.emit("change")}}class it{constructor(){this.targets=new Map}clear(){this.targets.clear()}clearCategory(t){for(const[e,i]of this.targets){const n=i.filter(e=>e.category!==t);0===n.length?this.targets.delete(e):this.targets.set(e,n)}}register(t,e){let i=this.targets.get(t);i||(i=[],this.targets.set(t,i)),i.push(e)}queryAtPoint(t,e){const i=this.targets.get(t);if(!i)return null;const n=[];for(const t of i)this.containsPoint(t.bounds,e)&&n.push(t);return 0===n.length?null:(n.sort((t,e)=>e.priority-t.priority),n[0])}queryAllAtPoint(t,e){const i=this.targets.get(t);if(!i)return[];const n=[];for(const t of i)this.containsPoint(t.bounds,e)&&n.push(t);return n.sort((t,e)=>e.priority-t.priority),n}queryByType(t,e,i){const n=this.targets.get(t);if(!n)return null;let s=null;for(const t of n)t.type===i&&this.containsPoint(t.bounds,e)&&(!s||t.priority>s.priority)&&(s=t);return s}getTargetsForPage(t){return this.targets.get(t)||[]}getPageIndices(){return Array.from(this.targets.keys()).sort((t,e)=>t-e)}getTotalTargetCount(){let t=0;for(const e of this.targets.values())t+=e.length;return t}containsPoint(t,e){return e.x>=t.x&&e.x<=t.x+t.width&&e.y>=t.y&&e.y<=t.y+t.height}}const nt=100,st=90,ot=80,rt="#87CEEB",at="#888888",lt="Page Break",ht="#6B46C1",dt=[4,4];class ct extends o{constructor(t){super(),this.flowedPages=new Map,this.headerFlowedPage=null,this.footerFlowedPage=null,this._focusedRegion=null,this.selectedText=null,this.showControlCharacters=!1,this.tableContinuations=new Map,this.pageTextOffsets=new Map,this._hitTestManager=new it,this.document=t,this.setupFlowingContentListeners()}get hitTestManager(){return this._hitTestManager}setShowControlCharacters(t){this.showControlCharacters=t}findCursorLocationInBody(t){const e=this.document.pages[0];if(!e)return null;const i=this.flowedPages.get(e.id);if(!i||0===i.length)return null;for(let e=0;e<i.length;e++){const n=i[e];for(let i=0;i<n.lines.length;i++){const s=n.lines[i];if(t>=s.startIndex&&t<=s.endIndex)return{pageIndex:e,lineIndex:i,line:s,flowedPage:n}}}if(i.length>0){const t=i.length-1,e=i[t];if(e.lines.length>0){const i=e.lines.length-1;return{pageIndex:t,lineIndex:i,line:e.lines[i],flowedPage:e}}}return null}findCursorLocationInSection(t,e){const i="header"===e?this.headerFlowedPage:this.footerFlowedPage;if(!i||0===i.lines.length)return null;for(let e=0;e<i.lines.length;e++){const n=i.lines[e];if(t>=n.startIndex&&t<=n.endIndex)return{lineIndex:e,line:n,flowedPage:i}}const n=i.lines.length-1;return{lineIndex:n,line:i.lines[n],flowedPage:i}}calculateCursorPosition(t){const e=this.getActiveFlowingContent();if(!e)return null;const i=e.getCursorPosition(),n=this.document.pages[0];if(!n)return null;if("body"===this.getActiveSection()){const e=this.findCursorLocationInBody(i);if(!e)return null;const s=n.getContentBounds(),o=s.size.width,r=_.getAlignmentOffset(e.line,o),a=_.getXPositionForTextIndex(e.line,i,t),l=e.line.listMarker?.indent??0;let h=s.position.y;h+=this.getPageTextOffset(e.pageIndex);for(let t=0;t<e.lineIndex;t++)h+=e.flowedPage.lines[t].height;return{x:s.position.x+r+l+a,y:h,height:e.line.height,pageIndex:e.pageIndex}}{const e=this.getActiveSection(),s=this.findCursorLocationInSection(i,e);if(!s)return null;const o="header"===e?n.getHeaderBounds():n.getFooterBounds(),r=o.size.width,a=_.getAlignmentOffset(s.line,r),l=_.getXPositionForTextIndex(s.line,i,t),h=s.line.listMarker?.indent??0;let d=o.position.y;for(let t=0;t<s.lineIndex;t++)d+=s.flowedPage.lines[t].height;return{x:o.position.x+a+h+l,y:d,height:s.line.height,pageIndex:0}}}setFocusedRegion(t){this._focusedRegion=t}getFocusedRegion(){return this._focusedRegion}getActiveSection(){if(this._focusedRegion){const t=this._focusedRegion.type;return"textbox"===t||"tablecell"===t?"body":t}return"body"}getActiveFlowingContent(){return this._focusedRegion?this._focusedRegion.flowingContent:this.document.bodyFlowingContent}setupFlowingContentListeners(){const t=this.document.bodyFlowingContent;t.on("content-changed",()=>{this.emit("content-changed")}),t.on("selection-changed",t=>{"body"===this.getActiveSection()&&(t.selection?this.setTextSelection(t.selection.start,t.selection.end):this.clearTextSelection(),this.emit("selection-changed",t))}),this.document.headerFlowingContent.on("content-changed",()=>{this.emit("header-content-changed"),this.emit("content-changed")}),this.document.headerFlowingContent.on("selection-changed",t=>{"header"===this.getActiveSection()&&(t.selection?this.setTextSelection(t.selection.start,t.selection.end):this.clearTextSelection(),this.emit("selection-changed",t))}),this.document.footerFlowingContent.on("content-changed",()=>{this.emit("footer-content-changed"),this.emit("content-changed")}),this.document.footerFlowingContent.on("selection-changed",t=>{"footer"===this.getActiveSection()&&(t.selection?this.setTextSelection(t.selection.start,t.selection.end):this.clearTextSelection(),this.emit("selection-changed",t))})}renderPageFlowingText(t,e,i){const n=this.document.pages.findIndex(e=>e.id===t.id);if(0===n){this.clearTableContinuations(),this._hitTestManager.clearCategory("content");const n=this.flowTextForPage(t,e,i);this.flowedPages.set(t.id,n),n.length>1&&this.emit("text-overflow",{pageId:t.id,overflowPages:n.slice(1),totalPages:n.length}),n.length>0&&this.renderFlowedPage(n[0],e,i,0,this.document.bodyFlowingContent)}else{const t=this.flowedPages.get(this.document.pages[0].id);t&&t.length>n?this.renderFlowedPage(t[n],e,i,n,this.document.bodyFlowingContent):this.renderTableContinuationsForPage(e,n,i)}const s=this.document.bodyFlowingContent;if(s&&"body"===this.getActiveSection()&&s.isCursorVisible()&&this.renderCursor(e,n),"body"===this.getActiveSection()&&this.selectedText){const s=0===n?this.flowedPages.get(t.id):this.flowedPages.get(this.document.pages[0].id);if(s&&s.length>n){const t=this.getPageTextOffset(n),o=t>0?{...i,y:i.y+t}:i;this.renderTextSelection(s[n],e,o)}}}renderHeaderText(t,e,i,n,s=0){const o=t.getHeaderBounds(),r={x:o.position.x,y:o.position.y,width:o.size.width,height:o.size.height},a=this.document.headerFlowingContent.flowText(r.width,r.height,e);a.length>0?(this.headerFlowedPage=a[0],n?this.renderRegion(n,e,s,{renderCursor:i,renderSelection:i}):(this.renderFlowedPage(a[0],e,r,s,this.document.headerFlowingContent),i&&this.document.headerFlowingContent.isCursorVisible()&&this.renderCursor(e,0),i&&this.selectedText&&this.renderTextSelection(a[0],e,r))):this.headerFlowedPage=null}renderFooterText(t,e,i,n,s=0){const o=t.getFooterBounds(),r={x:o.position.x,y:o.position.y,width:o.size.width,height:o.size.height},a=this.document.footerFlowingContent.flowText(r.width,r.height,e);a.length>0?(this.footerFlowedPage=a[0],n?this.renderRegion(n,e,s,{renderCursor:i,renderSelection:i}):(this.renderFlowedPage(a[0],e,r,s,this.document.footerFlowingContent),i&&this.document.footerFlowingContent.isCursorVisible()&&this.renderCursor(e,0),i&&this.selectedText&&this.renderTextSelection(a[0],e,r))):this.footerFlowedPage=null}handleRegionClick(t,e,i,n){const s=t.globalToLocal(e,i);if(!s)return null;if("body"===t.type){const t=this.getPageTextOffset(i);t>0&&(s.y-=t)}const o=this.getFlowedLinesForRegion(t,i),r=this.getAvailableWidthForRegion(t,i);if(0===o.length)return t.flowingContent.setCursorPosition(0),t.flowingContent.resetCursorBlink(),this.emit("text-clicked",{textIndex:0,line:0,section:t.type}),this.emit("cursor-changed",{textIndex:0,section:t.type}),{textIndex:0,lineIndex:0};const a=_.findLineAtY(o,s.y);if(a){const{line:o,lineIndex:l}=a,h=_.getAlignmentOffset(o,r),d=t.getRegionBounds(i);if(d){const i=d.y+a.lineY,n=d.x+h,s=this.getInlineElementAtPoint(o,e,i,n);if(s)return this.emit("inline-element-clicked",{element:s,point:e,section:t.type}),null;const r=this.getSubstitutionFieldAtPoint(o,e,i,n);r&&this.emit("substitution-field-clicked",{field:r,point:e,section:t.type})}const c=s.x-h,g=_.getTextIndexAtX(o,c,n);return t.flowingContent.setCursorPosition(g),t.flowingContent.resetCursorBlink(),this.emit("text-clicked",{textIndex:g,line:l,section:t.type}),this.emit("cursor-changed",{textIndex:g,section:t.type}),{textIndex:g,lineIndex:l}}const l=o.length-1,h=o[l].endIndex;return t.flowingContent.setCursorPosition(h),t.flowingContent.resetCursorBlink(),this.emit("text-clicked",{textIndex:h,line:l,section:t.type}),this.emit("cursor-changed",{textIndex:h,section:t.type}),{textIndex:h,lineIndex:l}}getFlowedLinesForRegion(t,e){switch(t.type){case"header":return this.headerFlowedPage?.lines||[];case"footer":return this.footerFlowedPage?.lines||[];case"body":{const t=this.document.pages[0];if(!t)return[];const i=this.flowedPages.get(t.id);return i&&i.length>e&&i[e]?.lines||[]}case"textbox":case"tablecell":return t.getFlowedLines(e);default:return[]}}getAvailableWidthForRegion(t,e){const i=t.getRegionBounds(e);return i?.width||0}renderRegion(t,e,i,n={}){const{renderCursor:s=!0,renderSelection:o=!0,clipToBounds:r=!1}=n,a=t.getRegionBounds(i);if(!a)return;const l=this.getFlowedLinesForRegion(t,i),h=this.getAvailableWidthForRegion(t,i),d=t.flowingContent,c=d.hasFocus()?d.getCursorPosition():void 0;if(r&&(e.save(),e.beginPath(),e.rect(a.x,a.y,a.width,a.height),e.clip()),o&&d.hasFocus()){const t=d.getSelection();t&&t.start!==t.end&&this.renderRegionSelection(l,e,a,h,t)}const g=this.document.pages[0],u=g&&this.flowedPages.get(g.id)?.length||1,f=d.getAllHyperlinks();let p=a.y;for(let t=0;t<l.length;t++){const n=l[t];if(r&&p+n.height<a.y)p+=n.height;else{if(r&&p>a.y+a.height)break;this.renderFlowedLine(n,e,{x:a.x,y:p},h,i,c,u,f),p+=n.height}}s&&d.hasFocus()&&d.isCursorVisible()&&this.renderRegionCursor(l,e,a,h,d.getCursorPosition()),r&&e.restore()}renderRegionSelection(t,e,i,n,s){const o=Math.min(s.start,s.end),r=Math.max(s.start,s.end);e.save(),e.fillStyle="rgba(0, 102, 204, 0.3)";let a=i.y;for(const s of t){if(r>s.startIndex&&o<s.endIndex){const t=Math.max(o,s.startIndex),l=Math.min(r,s.endIndex),h=_.getAlignmentOffset(s,n),d=s.listMarker?.indent??0,c=i.x+h+d+_.getXPositionForTextIndex(s,t,e),g=i.x+h+d+_.getXPositionForTextIndex(s,l,e);e.fillRect(c,a,g-c,s.height)}a+=s.height}e.restore()}renderRegionCursor(t,e,i,n,s){let o=i.y;for(const r of t){if(s>=r.startIndex&&s<=r.endIndex){const t=_.getAlignmentOffset(r,n),a=r.listMarker?.indent??0,l=i.x+t+a+_.getXPositionForTextIndex(r,s,e);return e.save(),e.strokeStyle="#000000",e.lineWidth=1,e.beginPath(),e.moveTo(l,o),e.lineTo(l,o+r.height),e.stroke(),void e.restore()}o+=r.height}if(t.length>0){const r=t[t.length-1],a=_.getAlignmentOffset(r,n),l=r.listMarker?.indent??0,h=i.x+a+l+_.getXPositionForTextIndex(r,s,e);o=i.y;for(let e=0;e<t.length-1;e++)o+=t[e].height;e.save(),e.strokeStyle="#000000",e.lineWidth=1,e.beginPath(),e.moveTo(h,o),e.lineTo(h,o+r.height),e.stroke(),e.restore()}else e.save(),e.strokeStyle="#000000",e.lineWidth=1,e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x,i.y+14),e.stroke(),e.restore()}flowTextForPage(t,e,i){return this.document.bodyFlowingContent.flowText(i.width,i.height,e)}renderFlowedPage(t,e,i,n,s){let o=i.y;if(n>0&&this.tableContinuations.size>0){const t=this.renderTableContinuationsAtPosition(e,n,i,o);o+=t,this.pageTextOffsets.set(n,t)}else this.pageTextOffsets.set(n,0);const r=s||this.document.bodyFlowingContent,a=(r?.hasFocus()??!1)&&r?r.getCursorPosition():void 0,l=this.document.pages[0],h=l&&this.flowedPages.get(l.id)?.length||1,d=r?r.getAllHyperlinks():[],c=[];for(let s=0;s<t.lines.length;s++){const r=t.lines[s];if(r.embeddedObjects)for(const t of r.embeddedObjects)t.isAnchor&&"relative"===t.object.position&&c.push({object:t.object,anchorX:i.x,anchorY:o});this.renderFlowedLine(r,e,{x:i.x,y:o},i.width,n,a,h,d),o+=r.height}this.renderRelativeObjects(c,e,n)}renderRelativeObjects(t,e,i){for(const{object:n,anchorX:s,anchorY:o}of t){const t=n.relativeOffset,r=s+t.x,a=o+t.y;if(n.renderedPosition={x:r,y:a},n.renderedPageIndex=i,n instanceof W||this._hitTestManager.register(i,{type:"embedded-object",category:"content",bounds:{x:r,y:a,width:n.width,height:n.height},priority:ot,data:{type:"embedded-object",object:n}}),e.save(),e.translate(r,a),n instanceof E){const t=n;t.reflow(e),t.render(e),e.restore(),this.renderRegion(t,e,i,{renderCursor:!0,renderSelection:!0,clipToBounds:!0})}else n.render(e),e.restore()}}renderFlowedLine(t,e,i,n,s,o,r,a){const h=t.listMarker?.indent||0,d=n-h;let c=i.x+h+this.getAlignmentOffset(t,d);e.save(),e.textBaseline="alphabetic",t.listMarker?.isFirstLineOfListItem&&t.listMarker.text&&this.renderListMarker(t.listMarker,e,i,t.baseline,t.runs[0]?.formatting||t.listMarker.formatting);const g=new Map;t.substitutionFields&&t.substitutionFields.forEach(t=>{g.set(t.textIndex,t)});const u=new Map;t.embeddedObjects&&t.embeddedObjects.forEach(t=>{u.set(t.textIndex,t)});for(const l of t.runs){e.font=this.getFontString(l.formatting),e.fillStyle=l.formatting.color;for(let h=0;h<l.text.length;h++){const d=l.startIndex+h,f=l.text[h],p=g.get(d);if(p){const n=o===d+1,a=s+1;c=this.renderSubstitutionField(p,e,{x:c,y:i.y},t,n,a,r);continue}const m=u.get(d);if(m)c=this.renderEmbeddedObject(m,e,{x:c,y:i.y},t,n,i.x,s);else if(""!==f){const n="\t"===f?e.measureText(" ").width:e.measureText(f).width;let s;if(a)for(const t of a)if(d>=t.startIndex&&d<t.endIndex){s=t;break}if(l.formatting.backgroundColor){const s=.8*l.formatting.fontSize,o=1.2*l.formatting.fontSize,r=i.y+t.baseline-s;e.fillStyle=l.formatting.backgroundColor,e.fillRect(c,r,n,o),e.fillStyle=l.formatting.color}if(this.showControlCharacters){if(" "===f){e.fillStyle=rt,e.fillText("·",c,i.y+t.baseline),e.fillStyle=l.formatting.color,c+=n,"justify"===t.alignment&&t.extraWordSpacing&&(c+=t.extraWordSpacing);continue}if("\t"===f){e.fillStyle=rt,e.fillText("→",c,i.y+t.baseline),e.fillStyle=l.formatting.color,c+=n,"justify"===t.alignment&&t.extraWordSpacing&&(c+=t.extraWordSpacing);continue}if("\n"===f){e.fillStyle=rt,e.fillText("¶",c,i.y+t.baseline),e.fillStyle=l.formatting.color,c+=n;continue}}else if("\t"===f){c+=n,"justify"===t.alignment&&t.extraWordSpacing&&(c+=t.extraWordSpacing);continue}if(s){const o=s.formatting?.color||"#0066CC";if(e.fillStyle=o,e.fillText(f,c,i.y+t.baseline),!1!==s.formatting?.underline){const s=i.y+t.baseline+2;e.beginPath(),e.strokeStyle=o,e.lineWidth=1,e.moveTo(c,s),e.lineTo(c+n,s),e.stroke()}e.fillStyle=l.formatting.color}else e.fillText(f,c,i.y+t.baseline);c+=n,"justify"===t.alignment&&t.extraWordSpacing&&/\s/.test(f)&&(c+=t.extraWordSpacing)}}}if(this.showControlCharacters&&t.endsWithNewline){e.fillStyle=rt;const s=t.runs[t.runs.length-1]?.formatting||l;e.font=this.getFontString(s);const o=e.measureText("¶").width,r=i.x+n-o,a=Math.min(c,r);e.fillText("¶",a,i.y+t.baseline)}t.endsWithPageBreak&&this.renderPageBreakIndicator(e,i,t,n),e.restore()}renderListMarker(t,e,i,n,s){const o=s||l;e.save(),e.font=this.getFontString(o),e.fillStyle=o.color,e.textBaseline="alphabetic";const r=e.measureText(t.text).width,a=i.x+t.indent-r-6,h=i.y+n;e.fillText(t.text,a,h),e.restore()}renderPageBreakIndicator(t,e,i,n){const s=e.y+i.height+8;if(t.save(),this.showControlCharacters){t.strokeStyle=at,t.lineWidth=1,t.setLineDash([4,4]),t.beginPath(),t.moveTo(e.x,s),t.lineTo(e.x+n,s),t.stroke(),t.setLineDash([]),t.font="11px Arial";const i=t.measureText(lt).width+8,o=14,r=e.x+(n-i)/2,a=s-o/2;t.fillStyle="#FFFFFF",t.fillRect(r,a,i,o),t.strokeStyle=at,t.lineWidth=1,t.strokeRect(r,a,i,o),t.fillStyle=at,t.textAlign="center",t.textBaseline="middle",t.fillText(lt,e.x+n/2,s)}else t.strokeStyle="#CCCCCC",t.lineWidth=1,t.setLineDash([]),t.beginPath(),t.moveTo(e.x,s),t.lineTo(e.x+n,s),t.stroke();t.restore()}renderSubstitutionField(t,e,i,n,s=!1,o,r){let a;const h=t.field.fieldType;a="pageNumber"===h?void 0!==o?t.field.displayFormat?t.field.displayFormat.replace(/%d/g,String(o)):String(o):"{{page}}":"pageCount"===h?void 0!==r?t.field.displayFormat?t.field.displayFormat.replace(/%d/g,String(r)):String(r):"{{pages}}":`{{field: ${t.field.fieldName}}}`;const d=t.field.formatting||l;e.save(),e.font=this.getFontString(d);const c=.8*d.fontSize,g=1.2*d.fontSize,u=e.measureText(a).width,f=i.y+n.baseline,p=f-c,m="pageNumber"===h||"pageCount"===h,b=m?"#d4ebff":"#e8e8e8",x=m?"#87CEEB":"#cccccc";return e.fillStyle=d.backgroundColor||b,e.fillRect(i.x,p,u,g),d.backgroundColor||(e.strokeStyle=x,e.lineWidth=1,e.strokeRect(i.x,p,u,g)),s&&(e.strokeStyle="#0066ff",e.lineWidth=2,e.setLineDash([4,2]),e.strokeRect(i.x-1,p-1,u+2,g+2),e.setLineDash([])),e.fillStyle=d.color,e.fillText(a,i.x,f),e.restore(),i.x+u}renderEmbeddedObject(t,e,i,n,s,o,r){const a=t.object;let l=i.x,h=i.y+(n.height-a.height)/2;if(t.isAnchor){if(this.showControlCharacters){e.save(),e.fillStyle=rt,e.font="12px Arial";const t=e.measureText("⚓").width||12,s=o-t-4;e.fillText("⚓",s,i.y+n.baseline),e.restore(),this._hitTestManager.register(r,{type:"embedded-object",category:"content",bounds:{x:s,y:i.y,width:t,height:n.height},priority:ot,data:{type:"embedded-object",object:a}})}return i.x}switch(a.position){case"block":l="right"===n.alignment?o+s-a.width:"center"===n.alignment?o+(s-a.width)/2:o,h=i.y;break;case"relative":{const t=a.relativeOffset;l=o+t.x,h=i.y+t.y;break}default:l=i.x}if(a.renderedPosition={x:l,y:h},a.renderedPageIndex=r,a instanceof W||this._hitTestManager.register(r,{type:"embedded-object",category:"content",bounds:{x:l,y:h,width:a.width,height:a.height},priority:ot,data:{type:"embedded-object",object:a}}),a instanceof E){const t=a;t.reflow(e),e.save(),e.translate(l,h),t.render(e),e.restore(),this.renderRegion(t,e,r,{renderCursor:!0,renderSelection:!0,clipToBounds:!0})}else if(a instanceof W){const t=a;t.calculateLayout(e,!0);for(const i of t.rows)for(const t of i.cells)t.reflow(e);t.calculateLayout(e,!0);const i=this.document.pages[r],n=i?.getContentBounds(),s=t.id,o=this.tableContinuations.get(s);if(o&&o.sliceIndex<o.pageLayout.slices.length){const i=o.pageLayout.slices[o.sliceIndex];t.renderedPosition={x:l,y:h},t.renderedPageIndex=r,e.save(),e.translate(l,h),t.renderSlice(e,i,o.pageLayout),e.restore();const n=t.getRowsForSlice(i,o.pageLayout);this.renderTableCellText(t,n,e,r,l,h,i,o.pageLayout);let a=0;for(const t of n)a+=t.calculatedHeight;const d=o.sliceIndex===o.pageLayout.slices.length-1?"last":"middle",c=o.pageLayout.slices[o.sliceIndex].yOffset,g=o.pageLayout.headerHeight;t.setRenderedSlice(r,{x:l,y:h},a,d,o.sliceIndex,c,g),this.registerTableSliceHitTarget(t,r,{x:l,y:h},a),t.selected&&this.drawEmbeddedObjectHandles(e,t,{x:l,y:h},{width:t.width,height:a},d),o.sliceIndex+1<o.pageLayout.slices.length?this.tableContinuations.set(s,{...o,sliceIndex:o.sliceIndex+1}):this.tableContinuations.delete(s)}else if(n){const i=n.position.y+n.size.height-h;if(t.needsPageSplit(i)){const o=n.size.height,a=t.calculatePageLayout(i,o);t.renderedPosition={x:l,y:h},t.renderedPageIndex=r;const d=a.slices[0];e.save(),e.translate(l,h),t.renderSlice(e,d,a),e.restore();const c=t.getRowsForSlice(d,a);this.renderTableCellText(t,c,e,r,l,h,d,a);let g=0;for(const t of c)g+=t.calculatedHeight;const u=1===a.slices.length?"only":"first";if(t.setRenderedSlice(r,{x:l,y:h},g,u,0,0,0),this.registerTableSliceHitTarget(t,r,{x:l,y:h},g),t.selected&&this.drawEmbeddedObjectHandles(e,t,{x:l,y:h},{width:t.width,height:g},u),a.slices.length>1){this.tableContinuations.set(s,{table:t,sliceIndex:1,pageLayout:a});const e=this.document.pages[0];e&&this.emit("text-overflow",{pageId:e.id,overflowPages:[],totalPages:r+a.slices.length})}}else{t.renderedPosition={x:l,y:h},t.renderedPageIndex=r,t.updateCellRenderedPositions(),t.setRenderedSlice(r,{x:l,y:h},t.height,"only",0,0,0),this.registerTableSliceHitTarget(t,r,{x:l,y:h},t.height),e.save(),e.translate(l,h),t.render(e),e.restore();for(const i of t.rows)for(const t of i.cells)this.renderRegion(t,e,r,{renderCursor:t.editing,renderSelection:t.editing,clipToBounds:!0});t.selected&&this.drawEmbeddedObjectHandles(e,t,{x:l,y:h}),this.tableContinuations.delete(s)}}else{t.renderedPosition={x:l,y:h},t.renderedPageIndex=r,t.updateCellRenderedPositions(),t.setRenderedSlice(r,{x:l,y:h},t.height,"only",0,0,0),this.registerTableSliceHitTarget(t,r,{x:l,y:h},t.height),e.save(),e.translate(l,h),t.render(e),e.restore();for(const i of t.rows)for(const t of i.cells)this.renderRegion(t,e,r,{renderCursor:t.editing,renderSelection:t.editing,clipToBounds:!0});t.selected&&this.drawEmbeddedObjectHandles(e,t,{x:l,y:h})}}else e.save(),e.translate(l,h),a.render(e),e.restore();return!a.selected||a instanceof W||this.drawEmbeddedObjectHandles(e,a,{x:l,y:h}),"inline"===a.position?i.x+a.width+2:i.x}renderTableCellText(t,e,i,n,s,o,r,a){const l=t.getColumnPositions(),h=t.getColumnWidths();let d=0;const c=new Set;if(r.isContinuation&&a.headerRowIndices.length>0)for(const e of a.headerRowIndices){const r=t.rows[e];if(r){c.add(r.id);for(let e=0;e<r.cellCount;e++){const a=r.getCell(e);if(!a)continue;let c=0;for(let i=e;i<e+a.colSpan&&i<t.columnCount;i++)c+=h[i];a.setRenderedPosition({x:s+l[e],y:o+d}),a.renderedPageIndex=n,a.setBounds({x:l[e],y:d,width:c,height:r.calculatedHeight}),this.renderRegion(a,i,n,{renderCursor:a.editing,renderSelection:a.editing,clipToBounds:!0})}d+=r.calculatedHeight}}for(const r of e)if(!c.has(r.id)){for(let e=0;e<r.cellCount;e++){const a=r.getCell(e);if(!a)continue;let c=0;for(let i=e;i<e+a.colSpan&&i<t.columnCount;i++)c+=h[i];a.setRenderedPosition({x:s+l[e],y:o+d}),a.renderedPageIndex=n,a.setBounds({x:l[e],y:d,width:c,height:r.calculatedHeight}),this.renderRegion(a,i,n,{renderCursor:a.editing,renderSelection:a.editing,clipToBounds:!0})}d+=r.calculatedHeight}}clearTableContinuations(){this.tableContinuations.clear(),this.pageTextOffsets.clear()}hasTableContinuations(){return this.tableContinuations.size>0}getPageTextOffset(t){return this.pageTextOffsets.get(t)||0}registerTableSliceHitTarget(t,e,i,n){this._hitTestManager.register(e,{type:"embedded-object",category:"content",bounds:{x:i.x,y:i.y,width:t.width,height:n},priority:ot,data:{type:"embedded-object",object:t}})}updateResizeHandleTargets(t){this._hitTestManager.clearCategory("resize-handles"),O.log("[pc-editor:FlowingTextRenderer] updateResizeHandleTargets selectedObjects:",t.length);for(const e of t)if(e.resizable)if(e instanceof W)this.registerTableResizeHandles(e);else{const t=e.renderedPosition,i=e.renderedPageIndex;O.log("[pc-editor:FlowingTextRenderer] updateResizeHandleTargets object:",e.id,"pageIndex:",i,"pos:",t),t&&i>=0&&this.registerObjectResizeHandles(e,i,t)}}registerObjectResizeHandles(t,e,i){const n=t.getResizeHandles();for(const s of n){const n=this.getHandlePosition(s,i,t.width,t.height,12);this._hitTestManager.register(e,{type:"resize-handle",category:"resize-handles",bounds:{x:n.x,y:n.y,width:12,height:12},priority:nt,data:{type:"resize-handle",handle:s,element:t}})}}registerTableResizeHandles(t){for(const e of this._hitTestManager.getPageIndices()){const i=t.getRenderedSlice(e);if(!i)continue;let n;switch(i.slicePosition){case"first":n=["nw","n","ne","w","e"];break;case"middle":n=["w","e"];break;case"last":n=["w","e","sw","s","se"];break;default:n=t.getResizeHandles().map(t=>t)}for(const s of n){const n=this.getHandlePosition(s,i.position,t.width,i.height,12);this._hitTestManager.register(e,{type:"resize-handle",category:"resize-handles",bounds:{x:n.x,y:n.y,width:12,height:12},priority:nt,data:{type:"resize-handle",handle:s,element:t}})}}}updateTableDividerTargets(t){if(this._hitTestManager.clearCategory("table-dividers"),!t)return;const e=t.getRenderedPageIndices();for(const i of e){const e=t.getRenderedSlice(i);if(!e)continue;const{position:n,height:s}=e,o=t.getColumnPositions(),r=t.getColumnWidths();for(let e=0;e<o.length;e++){const a=n.x+o[e]+r[e];this._hitTestManager.register(i,{type:"table-divider",category:"table-dividers",bounds:{x:a-4,y:n.y,width:8,height:s},priority:st,data:{type:"table-divider",table:t,dividerType:"column",index:e}})}let a=0;const l=t.rows,h="only"===e.slicePosition||"first"===e.slicePosition,d=t.headerRowCount;for(let o=0;o<l.length;o++){if(a+=l[o].calculatedHeight,h){if(a>s)continue;this._hitTestManager.register(i,{type:"table-divider",category:"table-dividers",bounds:{x:n.x,y:n.y+a-4,width:t.width,height:8},priority:st,data:{type:"table-divider",table:t,dividerType:"row",index:o}})}else{const r=e.yOffset,h=r+s-(d>0?e.headerHeight:0);if(o<d){let s=0;for(let t=0;t<=o;t++)s+=l[t].calculatedHeight;s<=e.headerHeight&&this._hitTestManager.register(i,{type:"table-divider",category:"table-dividers",bounds:{x:n.x,y:n.y+s-4,width:t.width,height:8},priority:st,data:{type:"table-divider",table:t,dividerType:"row",index:o}});continue}if(a<r||a>h+r)continue;const c=e.headerHeight+(a-r);if(c>s)continue;this._hitTestManager.register(i,{type:"table-divider",category:"table-dividers",bounds:{x:n.x,y:n.y+c-4,width:t.width,height:8},priority:st,data:{type:"table-divider",table:t,dividerType:"row",index:o}})}}}}renderTableContinuationsForPage(t,e,i){for(const[n,s]of this.tableContinuations.entries()){if(s.sliceIndex>=s.pageLayout.slices.length)continue;const o=s.table,r=s.pageLayout.slices[s.sliceIndex],a=i.x,l=i.y;o.renderedPosition={x:a,y:l},o.renderedPageIndex=e,t.save(),t.translate(a,l),o.renderSlice(t,r,s.pageLayout),t.restore();const h=o.getRowsForSlice(r,s.pageLayout);this.renderTableCellText(o,h,t,e,a,l,r,s.pageLayout);let d=0;for(const t of h)d+=t.calculatedHeight;const c=s.sliceIndex===s.pageLayout.slices.length-1?"last":"middle",g=s.pageLayout.slices[s.sliceIndex].yOffset,u=s.pageLayout.headerHeight;if(o.setRenderedSlice(e,{x:a,y:l},d,c,s.sliceIndex,g,u),this.registerTableSliceHitTarget(o,e,{x:a,y:l},d),o.selected&&this.drawEmbeddedObjectHandles(t,o,{x:a,y:l},{width:o.width,height:d},c),s.sliceIndex+1<s.pageLayout.slices.length){this.tableContinuations.set(n,{...s,sliceIndex:s.sliceIndex+1});const t=this.document.pages[0];t&&this.emit("text-overflow",{pageId:t.id,overflowPages:[],totalPages:e+s.pageLayout.slices.length-s.sliceIndex})}else this.tableContinuations.delete(n)}}renderTableContinuationsAtPosition(t,e,i,n){let s=0;for(const[o,r]of this.tableContinuations.entries()){if(r.sliceIndex>=r.pageLayout.slices.length)continue;const a=r.table,l=r.pageLayout.slices[r.sliceIndex],h=i.x,d=n+s;a.renderedPosition={x:h,y:d},a.renderedPageIndex=e,t.save(),t.translate(h,d),a.renderSlice(t,l,r.pageLayout),t.restore();const c=a.getRowsForSlice(l,r.pageLayout);this.renderTableCellText(a,c,t,e,h,d,l,r.pageLayout);let g=0;for(const t of c)g+=t.calculatedHeight;s+=g;const u=r.sliceIndex===r.pageLayout.slices.length-1?"last":"middle",f=r.pageLayout.slices[r.sliceIndex].yOffset,p=r.pageLayout.headerHeight;if(a.setRenderedSlice(e,{x:h,y:d},g,u,r.sliceIndex,f,p),this.registerTableSliceHitTarget(a,e,{x:h,y:d},g),a.selected&&this.drawEmbeddedObjectHandles(t,a,{x:h,y:d},{width:a.width,height:g},u),r.sliceIndex+1<r.pageLayout.slices.length){this.tableContinuations.set(o,{...r,sliceIndex:r.sliceIndex+1});const t=this.document.pages[0];t&&this.emit("text-overflow",{pageId:t.id,overflowPages:[],totalPages:e+r.pageLayout.slices.length-r.sliceIndex})}else this.tableContinuations.delete(o)}return s}drawEmbeddedObjectHandles(t,e,i,n,s="only"){const o=n?.width??e.size.width,r=n?.height??e.size.height;if(t.save(),t.setTransform(1,0,0,1,0,0),t.strokeStyle="#0066ff",t.lineWidth=2,t.setLineDash([4,4]),t.strokeRect(i.x,i.y,o,r),t.setLineDash([]),e.resizable){let n;switch(s){case"first":n=["nw","n","ne","w","e"];break;case"middle":n=["w","e"];break;case"last":n=["w","e","sw","s","se"];break;default:n=e.getResizeHandles()}t.fillStyle="#0066ff",t.strokeStyle="#ffffff",t.lineWidth=1;for(const e of n){const n=this.getHandlePosition(e,i,o,r,8);t.fillRect(n.x,n.y,8,8),t.strokeRect(n.x,n.y,8,8)}}t.restore()}getHandlePosition(t,e,i,n,s){const o=s/2;switch(t){case"nw":return{x:e.x-o,y:e.y-o};case"n":return{x:e.x+i/2-o,y:e.y-o};case"ne":return{x:e.x+i-o,y:e.y-o};case"e":return{x:e.x+i-o,y:e.y+n/2-o};case"se":return{x:e.x+i-o,y:e.y+n-o};case"s":return{x:e.x+i/2-o,y:e.y+n-o};case"sw":return{x:e.x-o,y:e.y+n-o};case"w":return{x:e.x-o,y:e.y+n/2-o};default:return e}}getFontString(t){return`${t.fontStyle||""} ${t.fontWeight||""} ${t.fontSize}px ${t.fontFamily}`.trim()}getAlignmentOffset(t,e){switch(t.alignment){case"center":return(e-t.width)/2;case"right":return e-t.width;default:return 0}}isCursorAfterFieldOrObject(){let t;if("body"===this.getActiveSection()?t=this.document.bodyFlowingContent:"header"===this.getActiveSection()?t=this.document.headerFlowingContent:"footer"===this.getActiveSection()&&(t=this.document.footerFlowingContent),!t)return!1;const e=t.getCursorPosition();if(e<=0)return!1;if(void 0!==t.getSubstitutionFieldManager().getFieldAt(e-1))return!0;const i=t.getEmbeddedObjects();for(const[,t]of i.entries())if(t.textIndex===e-1&&t.selected)return!0;return!1}renderCursor(t,e){const i=this.getActiveFlowingContent();if(!i||!i.isCursorVisible())return;if(this.isCursorAfterFieldOrObject())return;const n=this.calculateCursorPosition(t);n&&n.pageIndex===e&&(t.save(),t.strokeStyle="#000000",t.lineWidth=1,t.beginPath(),t.moveTo(n.x,n.y),t.lineTo(n.x,n.y+n.height),t.stroke(),t.restore())}renderTextSelection(t,e,i){if(!this.selectedText)return;e.save(),e.fillStyle="rgba(0, 100, 255, 0.3)";let n=i.y;for(const s of t.lines){if(this.lineContainsSelection(s,this.selectedText)){const t=this.getSelectionBoundsInLine(s,this.selectedText),o=s.listMarker?.indent??0,r=i.width-o,a=this.getAlignmentOffset(s,r),l=i.x+o;e.fillRect(l+a+t.x,n,t.width,s.height)}n+=s.height}e.restore()}lineContainsSelection(t,e){return!(t.endIndex<=e.start||t.startIndex>=e.end)}getSelectionBoundsInLine(t,e){const i=Math.max(e.start,t.startIndex),n=Math.min(e.end,t.endIndex),s=this.getXPositionForTextIndex(t,i);return{x:s,width:this.getXPositionForTextIndex(t,n)-s}}getTextIndexAtPoint(t,e){const i=this.document.pages[0];if(!i)return null;const n=this.flowedPages.get(i.id);if(!n||0===n.length)return null;const s=this.document.getPage(e);if(!s)return null;const o=this.document.pages.findIndex(t=>t.id===e);if(o<0||o>=n.length)return null;const r=n[o];if(!r||0===r.lines.length)return null;const a=s.getContentBounds(),l=t.y-a.position.y,h=t.x-a.position.x,d=a.size.width;if(l<0&&r.lines.length>0)return r.lines[0].startIndex;let c=0;for(let t=0;t<r.lines.length;t++){const e=r.lines[t];if(l>=c&&l<c+e.height){const t=this.getAlignmentOffset(e,d);return this.getTextIndexInLine(e,h-t)}c+=e.height}if(r.lines.length>0){return r.lines[r.lines.length-1].endIndex}return null}getTextIndexInLine(t,e){const i=document.createElement("canvas").getContext("2d");if(!i)return t.startIndex;const n=new Map;t.substitutionFields&&t.substitutionFields.forEach(t=>n.set(t.textIndex,t));const s=new Map;t.embeddedObjects&&t.embeddedObjects.forEach(t=>s.set(t.textIndex,t));let o=0;const r=t.extraWordSpacing||0;for(const a of t.runs){i.font=this.getFontString(a.formatting);for(let t=0;t<a.text.length;t++){const l=a.startIndex+t,h=a.text[t];let d;const c=n.get(l);if(c){if(d=c.width,e>=o&&e<o+d)return l+1;o+=d,r>0&&/\s/.test(h)&&(o+=r)}else{if(s.has(l)){d=s.get(l).object.width+2}else d=""!==h?"\t"===h?i.measureText(" ").width:i.measureText(h).width:0;if(e>=o&&e<o+d)return e<o+d/2?l:l+1;o+=d,r>0&&/\s/.test(h)&&(o+=r)}}}return t.endIndex}getInlineElementAtPoint(t,e,i,n){if(t.embeddedObjects&&void 0!==i&&void 0!==n)for(const s of t.embeddedObjects){const o=s.object,r=s.x+n,a=i+(t.height-o.height)/2;if(o.containsPoint(e,{x:r,y:a}))return{type:"embedded-object",object:o,textIndex:s.textIndex}}return null}getEmbeddedObjectAtPoint(t,e,i,n){if(!t.embeddedObjects)return null;for(const s of t.embeddedObjects){const o=s.object,r=s.x+n,a=i+(t.height-o.height)/2;if(o.containsPoint(e,{x:r,y:a}))return o}return null}getSubstitutionFieldAtPoint(t,e,i,n){if(!t.substitutionFields)return null;for(const s of t.substitutionFields)if(e.x>=s.x+n&&e.x<=s.x+n+s.width&&e.y>=i&&e.y<=i+t.height)return s;return null}getXPositionForTextIndex(t,e){if(e<=t.startIndex)return 0;if(e>=t.endIndex)return"justify"===t.alignment&&t.extraWordSpacing?t.width+this.countWordGapsUpTo(t,t.endIndex)*t.extraWordSpacing:t.width;const i=document.createElement("canvas").getContext("2d");if(!i)return 0;const n=new Map;t.substitutionFields&&t.substitutionFields.forEach(t=>n.set(t.textIndex,t));const s=new Map;t.embeddedObjects&&t.embeddedObjects.forEach(t=>s.set(t.textIndex,t));let o=0;for(const r of t.runs){i.font=this.getFontString(r.formatting);for(let a=0;a<r.text.length;a++){const l=r.startIndex+a;if(l>=e)return o;const h=r.text[a];let d;const c=n.get(l);if(c)d=c.width;else if(s.has(l)){d=s.get(l).object.width+2}else d=""!==h?"\t"===h?i.measureText(" ").width:i.measureText(h).width:0;o+=d,"justify"===t.alignment&&t.extraWordSpacing&&/\s/.test(h)&&(o+=t.extraWordSpacing)}}return o}countWordGapsUpTo(t,e){let i=0,n=!1;for(let s=t.startIndex;s<Math.min(e,t.endIndex);s++){const e=s-t.startIndex;if(e>=t.text.length)break;const o=t.text[e],r=/\s/.test(o);r||n?r&&n&&(i++,n=!1):n=!0}return i}moveCursorVertical(t,e){if("header"===this.getActiveSection())return this.moveCursorVerticalInSection(t,this.headerFlowedPage,e,"header");if("footer"===this.getActiveSection())return this.moveCursorVerticalInSection(t,this.footerFlowedPage,e,"footer");const i=this.flowedPages.get(e);if(!i||0===i.length)return null;const n=this.document.getPage(e);if(!n)return null;const s=this.document.bodyFlowingContent.getCursorPosition(),o=this.findCursorLocationInBody(s);if(!o)return null;const r=o.lineIndex,a=o.pageIndex,l=i[a];if(!l)return null;const h=r+t,d=n.getContentBounds().size.width,c=this.calculateCursorRelativeX();if(h<0){if(a>0){const t=i[a-1];if(t&&t.lines.length>0){const e=t.lines.length-1,i=t.lines[e];return this.getTextIndexAtVisualX(i,c,d)}}return i[0].lines.length>0?i[0].lines[0].startIndex:null}if(h>=l.lines.length){if(a<i.length-1){const t=i[a+1];if(t&&t.lines.length>0){const e=t.lines[0];return this.getTextIndexAtVisualX(e,c,d)}}const t=i[i.length-1];if(t&&t.lines.length>0){return t.lines[t.lines.length-1].endIndex}return null}const g=l.lines[h];return this.getTextIndexAtVisualX(g,c,d)}moveCursorVerticalInSection(t,e,i,n){if(!e||0===e.lines.length)return null;const s=this.document.pages[0];if(!s)return null;const o=("header"===n?s.getHeaderBounds():s.getFooterBounds()).size.width,r=("header"===n?this.document.headerFlowingContent:this.document.footerFlowingContent).getCursorPosition(),a=this.findCursorLocationInSection(r,n),l=(a?a.lineIndex:0)+t;if(l<0)return e.lines[0].startIndex;if(l>=e.lines.length){return e.lines[e.lines.length-1].endIndex}const h=e.lines[l],d=this.calculateCursorRelativeXForSection(n);return this.getTextIndexAtVisualX(h,d,o)}calculateCursorRelativeXForSection(t){const e=("header"===t?this.document.headerFlowingContent:this.document.footerFlowingContent).getCursorPosition(),i=this.findCursorLocationInSection(e,t);if(!i)return 0;const n=document.createElement("canvas").getContext("2d");if(!n)return 0;const s=this.document.pages[0];if(!s)return 0;const o=("header"===t?s.getHeaderBounds():s.getFooterBounds()).size.width;return _.getAlignmentOffset(i.line,o)+_.getXPositionForTextIndex(i.line,e,n)}calculateCursorRelativeX(){const t=this.document.pages[0];if(!t)return 0;const e=this.document.bodyFlowingContent.getCursorPosition(),i=this.findCursorLocationInBody(e);if(!i)return 0;const n=document.createElement("canvas").getContext("2d");if(!n)return 0;const s=t.getContentBounds().size.width;return _.getAlignmentOffset(i.line,s)+_.getXPositionForTextIndex(i.line,e,n)}getTextIndexAtVisualX(t,e,i){const n=e-this.getAlignmentOffset(t,i);return this.getTextIndexInLine(t,n)}setTextSelection(t,e){this.selectedText={start:Math.min(t,e),end:Math.max(t,e)},this.emit("selection-changed",this.selectedText)}clearTextSelection(){this.selectedText=null,this.emit("selection-cleared")}getFlowedPagesForPage(t){return this.flowedPages.get(t)||[]}getFlowedPagesSnapshot(){const t=this.document.pages[0],e=t&&this.flowedPages.get(t.id)||[],i=this.document.bodyFlowingContent?.getAllHyperlinks().map(t=>({url:t.url,startIndex:t.startIndex,endIndex:t.endIndex})),n=this.document.headerFlowingContent?.getAllHyperlinks().map(t=>({url:t.url,startIndex:t.startIndex,endIndex:t.endIndex})),s=this.document.footerFlowingContent?.getAllHyperlinks().map(t=>({url:t.url,startIndex:t.startIndex,endIndex:t.endIndex}));return{body:e,header:this.headerFlowedPage,footer:this.footerFlowedPage,bodyHyperlinks:i?.length?i:void 0,headerHyperlinks:n?.length?n:void 0,footerHyperlinks:s?.length?s:void 0}}renderRepeatingSectionIndicators(t,e,i,n,s,o,r=null){for(const a of t)this.renderSectionIndicator(a,e,i,n,s,o,a.id===r)}renderSectionIndicator(t,e,i,n,s,o,r=!1){const a=this.findLineYForTextIndex(s,t.startIndex,n),l=this.findLineYForTextIndex(s,t.endIndex,n);if(!(t.startIndex<s.endIndex&&t.endIndex>s.startIndex))return;const h=null!==a,d=null!==l,c=t.startIndex<s.startIndex,g=t.endIndex>s.endIndex;i.save(),i.strokeStyle=ht,i.fillStyle=ht,i.lineWidth=1;const u=o.x+5,f=u+16;if(h){const t=a.y;i.setLineDash(dt),i.beginPath(),i.moveTo(n.x,t),i.lineTo(n.x+n.width,t),i.stroke(),i.setLineDash([]),i.beginPath(),i.moveTo(u+32,t),i.lineTo(n.x,t),i.stroke()}else if(c){const t=n.y;i.setLineDash(dt),i.beginPath(),i.moveTo(n.x,t),i.lineTo(n.x+n.width,t),i.stroke(),i.setLineDash([]),i.beginPath(),i.moveTo(f,t),i.lineTo(n.x,t),i.stroke()}if(d){const t=l.y;i.setLineDash(dt),i.beginPath(),i.moveTo(n.x,t),i.lineTo(n.x+n.width,t),i.stroke(),i.setLineDash([]),i.beginPath(),i.moveTo(f,t),i.lineTo(n.x,t),i.stroke()}else if(g){const t=n.y+n.height;i.setLineDash(dt),i.beginPath(),i.moveTo(n.x,t),i.lineTo(n.x+n.width,t),i.stroke(),i.setLineDash([]),i.beginPath(),i.moveTo(f,t),i.lineTo(n.x,t),i.stroke()}let p,m;if(p=h?a.y:n.y,m=d?l.y:g?n.y+n.height:p,m>p&&(i.beginPath(),i.moveTo(f,p),i.lineTo(f,m),i.stroke()),h){const t=a.y;this.drawLoopLabel(i,u,t-10,"Loop",r)}t.visualState={startPageIndex:h?e:-1,startY:h?a.y:0,endPageIndex:d?e:-1,endY:d?l.y:0,spansMultiplePages:!h||!d},i.restore()}drawLoopLabel(t,e,i,n,s=!1){t.save(),t.font="10px Arial";const o=t.measureText(n).width+8;t.beginPath(),this.roundRect(t,e,i,o,18,4),s?(t.fillStyle=ht,t.fill(),t.fillStyle="#ffffff"):(t.fillStyle="#ffffff",t.fill(),t.strokeStyle=ht,t.lineWidth=1.5,t.stroke(),t.fillStyle=ht),t.textBaseline="middle",t.fillText(n,e+4,i+9),t.restore()}roundRect(t,e,i,n,s,o){t.moveTo(e+o,i),t.lineTo(e+n-o,i),t.quadraticCurveTo(e+n,i,e+n,i+o),t.lineTo(e+n,i+s-o),t.quadraticCurveTo(e+n,i+s,e+n-o,i+s),t.lineTo(e+o,i+s),t.quadraticCurveTo(e,i+s,e,i+s-o),t.lineTo(e,i+o),t.quadraticCurveTo(e,i,e+o,i),t.closePath()}findLineYForTextIndex(t,e,i){let n=i.y;for(let i=0;i<t.lines.length;i++){const s=t.lines[i];if(e>=s.startIndex&&e<=s.endIndex)return{y:n,lineIndex:i};if(e===s.startIndex)return{y:n,lineIndex:i};n+=s.height}if(t.lines.length>0){if(e===t.lines[t.lines.length-1].endIndex+1)return{y:n,lineIndex:t.lines.length-1}}return null}sectionSpansPage(t,e){if(0===e.lines.length)return!1;const i=e.startIndex,n=e.endIndex;return t.startIndex<i&&t.endIndex>n}getRepeatingSectionAtPoint(t,e,i,n,s,o){const r=n.x+5,a=r+16;for(const i of e){const e=this.findLineYForTextIndex(o,i.startIndex,s),n=this.findLineYForTextIndex(o,i.endIndex,s),l=this.sectionSpansPage(i,o);if(!e&&!n&&!l)continue;if(e){const n=e.y-10,s=18;if(t.x>=r&&t.x<=r+32&&t.y>=n&&t.y<=n+s)return i}let h,d;if(h=e?e.y:s.y,n)d=n.y;else{if(!l)continue;d=s.y+o.height}if(Math.abs(t.x-a)<=10&&t.y>=h&&t.y<=d)return i}return null}destroy(){this.removeAllListeners()}}class gt extends o{constructor(t,e,i){super(),this.canvases=new Map,this.contexts=new Map,this.zoomLevel=1,this.selectedElements=new Set,this.isDragging=!1,this.dragStart=null,this.isResizing=!1,this.wasResizing=!1,this.resizeHandle=null,this.resizeStartSize=null,this.resizeStartPos=null,this.resizingElementId=null,this.showMargins=!0,this.isHandlingOverflow=!1,this.isSelectingText=!1,this.textSelectionStartPageId=null,this.selectedSectionId=null,this._activeSection="body",this.lastClickTime=0,this.lastClickPosition=null,this.clickCount=0,this.editingTextBox=null,this._editingTextBoxPageId=null,this._focusedControl=null,this._cursorSuspended=!1,this.isSelectingTextInTextBox=!1,this.tableResizeHandler=new G,this.isSelectingTableCells=!1,this.tableCellSelectionPending=!1,this.tableCellSelectionStart=null,this.tableCellSelectionStartPoint=null,this.tableCellSelectionTable=null,this.isSelectingTextInTableCell=!1,this.isDraggingRelativeObject=!1,this.relativeObjectDragPending=!1,this.relativeObjectDragStart=null,this.relativeObjectBeingDragged=null,this.relativeObjectDragStartOffset=null,this.handleFocusedCursorBlink=()=>{this.render()},this.container=t,this.document=e,this.options=i,this.flowingTextRenderer=new ct(e),this.regionManager=new X,this.setupFlowingTextListeners(),this.initializeRegions()}initializeRegions(){const t=new K(this.document.bodyFlowingContent,t=>this.document.pages[t]||null);this.regionManager.setBodyRegion(t);const e=new Y(this.document.headerFlowingContent,t=>this.document.pages[t]||null);this.regionManager.setHeaderRegion(e);const i=new q(this.document.footerFlowingContent,t=>this.document.pages[t]||null);this.regionManager.setFooterRegion(i)}initialize(){this.createCanvases(),this.setupEventListeners(),this.setupScrollListener(),this.updateCanvasScale(),this.setFocus(this.document.bodyFlowingContent),this.render()}createCanvases(){this.document.pages.forEach(t=>{const e=document.createElement("canvas");e.id=`canvas-${t.id}`,e.style.display="block",e.style.margin="20px auto",e.style.boxShadow="0 2px 8px rgba(0,0,0,0.1)";const i=t.getPageDimensions();e.width=i.width,e.height=i.height,this.container.appendChild(e),this.canvases.set(t.id,e);const n=e.getContext("2d");n&&this.contexts.set(t.id,n)})}setDocument(t){this.clearCanvases(),this.document=t,this.flowingTextRenderer.destroy(),this.flowingTextRenderer=new ct(t),this.setupFlowingTextListeners(),this.initializeRegions(),this.createCanvases(),this.setupEventListeners(),this.updateCanvasScale(),this._activeSection="body",this.selectedElements.clear(),this.editingTextBox=null,this._editingTextBoxPageId=null,this._focusedControl=null,this.setFocus(this.document.bodyFlowingContent),this.render()}clearCanvases(){this.canvases.forEach(t=>t.remove()),this.canvases.clear(),this.contexts.clear()}updateCanvasSizes(){this.document.pages.forEach(t=>{const e=this.canvases.get(t.id);if(!e)return;const i=t.getPageDimensions();e.width===i.width&&e.height===i.height||(e.width=i.width,e.height=i.height)}),this.updateCanvasScale()}render(){this.document.pages.forEach(t=>{const e=this.contexts.get(t.id);if(!e)return;const i=this.canvases.get(t.id);if(!i)return;e.clearRect(0,0,i.width,i.height),e.fillStyle="white",e.fillRect(0,0,i.width,i.height),this.options.showGrid&&this.drawGrid(e,i.width,i.height);const n=this.document.pages.findIndex(e=>e.id===t.id),s=this.regionManager.getHeaderRegion();this.flowingTextRenderer.renderHeaderText(t,e,"header"===this._activeSection,s??void 0,n);const o=t.getContentBounds(),r={x:o.position.x,y:o.position.y,width:o.size.width,height:o.size.height};this.flowingTextRenderer.renderPageFlowingText(t,e,r);const a=this.regionManager.getFooterRegion();this.flowingTextRenderer.renderFooterText(t,e,"footer"===this._activeSection,a??void 0,n);const l=this.document.bodyFlowingContent,h=l?.getRepeatingSections()??[];if(h.length>0){const i=this.flowingTextRenderer.getFlowedPagesForPage(this.document.pages[0].id);if(i&&i[n]){const s=t.getPageDimensions(),o={x:0,y:0,width:s.width,height:s.height};this.flowingTextRenderer.renderRepeatingSectionIndicators(h,n,e,r,i[n],o,this.selectedSectionId)}}this.renderPageElements(t,e),this.drawInactiveSectionOverlays(e,t),this.drawMarginLines(e,t),this.renderSelectionMarks(t,e)})}drawInactiveSectionOverlays(t,e){t.save(),t.fillStyle="rgba(255, 255, 255, 0.6)";const i=e.getPageDimensions(),n=e.getContentBounds(),s=n.position.y,o=n.position.y+n.size.height,r=i.height-o;"header"!==this._activeSection&&t.fillRect(0,0,i.width,s),"body"!==this._activeSection&&t.fillRect(0,s,i.width,n.size.height),"footer"!==this._activeSection&&t.fillRect(0,o,i.width,r),t.restore()}drawGrid(t,e,i){t.save(),t.strokeStyle="#e0e0e0",t.lineWidth=.5;const n=this.options.gridSize*this.zoomLevel;for(let s=0;s<=e;s+=n)t.beginPath(),t.moveTo(s,0),t.lineTo(s,i),t.stroke();for(let s=0;s<=i;s+=n)t.beginPath(),t.moveTo(0,s),t.lineTo(e,s),t.stroke();t.restore()}renderPageElements(t,e){}renderSelectionMarks(t,e){const i=this.document.pages.indexOf(t),n=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const t of n){const n=t.getEmbeddedObjects();for(const[,t]of n.entries())t instanceof W||t.selected&&!t.locked&&t.renderedPosition&&t.renderedPageIndex===i&&this.drawBaseEmbeddedObjectResizeHandles(e,t)}}drawBaseEmbeddedObjectResizeHandles(t,e){if(!e.renderedPosition)return;const i={x:e.renderedPosition.x,y:e.renderedPosition.y,width:e.width,height:e.height},n=this.getResizeHandles(i);t.save(),t.fillStyle="#0066ff",t.strokeStyle="#ffffff",t.lineWidth=1,Object.entries(n).forEach(([e,i])=>{t.fillRect(i.x-4,i.y-4,8,8),t.strokeRect(i.x-4,i.y-4,8,8)}),t.restore()}getResizeHandles(t){return{nw:{x:t.x,y:t.y},n:{x:t.x+t.width/2,y:t.y},ne:{x:t.x+t.width,y:t.y},e:{x:t.x+t.width,y:t.y+t.height/2},se:{x:t.x+t.width,y:t.y+t.height},s:{x:t.x+t.width/2,y:t.y+t.height},sw:{x:t.x,y:t.y+t.height},w:{x:t.x,y:t.y+t.height/2}}}setupEventListeners(){this.canvases.forEach((t,e)=>{t.addEventListener("mousedown",t=>this.handleMouseDown(t,e)),t.addEventListener("mousemove",t=>this.handleMouseMove(t,e)),t.addEventListener("mouseup",t=>this.handleMouseUp(t,e)),t.addEventListener("mouseleave",t=>this.handleMouseLeave(t,e)),t.addEventListener("click",t=>this.handleClick(t,e))})}handleMouseDown(t,e){const i=this.getMousePosition(t),n=this.getResizeHandleAt(i,e);if(n){this.isResizing=!0,this.resizeHandle=n.handle,this.dragStart=i;const s=this.getSelectedElementAt(e);return s&&s.renderedPosition&&(this.resizeStartSize={width:s.width,height:s.height},this.resizeStartPos={...s.renderedPosition},this.resizingElementId=s.id),void t.preventDefault()}const s=this.getTableResizeHandleAt(i,e);if(s&&s.handleInfo){const{table:e,handleInfo:i,tablePosition:n}=s;return this.tableResizeHandler.startResize(e,i,n),void t.preventDefault()}if(this._focusedControl instanceof W){const n=this._focusedControl,s=this.document.pages.findIndex(t=>t.id===e),o=n.getRenderedSlice(s),r=o?.position||n.renderedPosition,a=o?.height||n.height;if(r&&i.x>=r.x&&i.x<=r.x+n.width&&i.y>=r.y&&i.y<=r.y+a&&r){const a={x:i.x-r.x,y:i.y-r.y};if(o&&("middle"===o.slicePosition||"last"===o.slicePosition)){const t=o.headerHeight;a.y>=t&&(a.y=o.yOffset+(a.y-t))}const l=n.getCellAtPoint(a);if(l){const o=this.contexts.get(e);if(t.shiftKey&&n.focusedCell)return n.selectRange({start:n.focusedCell,end:l}),this.render(),void t.preventDefault();if(n.focusedCell&&n.focusedCell.row===l.row&&n.focusedCell.col===l.col){const e=n.getCell(l.row,l.col);if(e&&o&&s>=0){const r=e.flowingContent;t.shiftKey?(r.hasSelectionAnchor()||r.setSelectionAnchor(),this.flowingTextRenderer.handleRegionClick(e,i,s,o)):(r.clearSelection(),this.flowingTextRenderer.handleRegionClick(e,i,s,o),r.setSelectionAnchor()),this.isSelectingTextInTableCell=!0,this.tableCellSelectionTable=n,this.emit("tablecell-cursor-changed",{table:n,cell:e,cursorPosition:r.getCursorPosition()})}}else{this.tableCellSelectionPending=!0,this.tableCellSelectionStart=l,this.tableCellSelectionStartPoint={...i},this.tableCellSelectionTable=n,n.clearSelection(),n.focusCell(l.row,l.col);const t=n.getCell(l.row,l.col);t&&o&&s>=0&&(this.flowingTextRenderer.handleRegionClick(t,i,s,o),this.emit("tablecell-cursor-changed",{table:n,cell:t,cursorPosition:t.flowingContent.getCursorPosition()}))}return this.render(),void t.preventDefault()}}}if(this.editingTextBox&&this._editingTextBoxPageId===e){const n=this.editingTextBox,s=this.document.pages.findIndex(t=>t.id===e),o=this.contexts.get(e);if(o&&s>=0&&n.containsPointInRegion(i,s)){const e=n.flowingContent;return t.shiftKey?(e.hasSelectionAnchor()||e.setSelectionAnchor(),this.flowingTextRenderer.handleRegionClick(n,i,s,o)):(e.clearSelection(),this.flowingTextRenderer.handleRegionClick(n,i,s,o),e.setSelectionAnchor()),this.isSelectingTextInTextBox=!0,this.render(),void t.preventDefault()}}const o=this.document.pages.findIndex(t=>t.id===e),r=this.flowingTextRenderer.hitTestManager.queryByType(o,i,"embedded-object");if(r&&"embedded-object"===r.data.type){const t=r.data.object,e=this.getSectionForEmbeddedObject(t);if(e&&e!==this._activeSection)return;return void("relative"===t.position&&(this.relativeObjectDragPending=!0,this.relativeObjectDragStart={...i},this.relativeObjectBeingDragged=t,this.relativeObjectDragStartOffset={...t.relativeOffset}))}const a=this.getFlowingContentForActiveSection();if(a){const n=this.getRegionForActiveSection(),s=this.contexts.get(e),o=this.document.pages.findIndex(t=>t.id===e);if(n&&s&&o>=0)if(t.shiftKey){a.hasSelectionAnchor()||a.setSelectionAnchor();if(this.flowingTextRenderer.handleRegionClick(n,i,o,s))return this.clearSelection(),this.emit("text-selection-changed",{selection:a.getSelection(),section:this._activeSection}),this.isSelectingText=!0,this.textSelectionStartPageId=e,this.render(),void t.preventDefault()}else{const r=this.flowingTextRenderer.handleRegionClick(n,i,o,s);if(r)return this.clearSelection(),a.clearSelection(),a.setSelectionAnchor(r.textIndex),this.isSelectingText=!0,this.textSelectionStartPageId=e,this.render(),void t.preventDefault()}}this.isDragging=!0,this.dragStart=i}handleMouseMove(t,e){const i=this.getMousePosition(t),n=this.getViewportMousePosition(t);if(this.emit("mouse-move",{x:n.x,y:n.y}),this.relativeObjectDragPending&&this.relativeObjectDragStart&&this.relativeObjectBeingDragged){Math.sqrt(Math.pow(i.x-this.relativeObjectDragStart.x,2)+Math.pow(i.y-this.relativeObjectDragStart.y,2))>=gt.RELATIVE_DRAG_THRESHOLD&&(this.relativeObjectDragPending=!1,this.isDraggingRelativeObject=!0)}if(this.isDraggingRelativeObject&&this.relativeObjectBeingDragged&&this.relativeObjectDragStart&&this.relativeObjectDragStartOffset){const e=i.x-this.relativeObjectDragStart.x,n=i.y-this.relativeObjectDragStart.y;return this.relativeObjectBeingDragged.relativeOffset={x:this.relativeObjectDragStartOffset.x+e,y:this.relativeObjectDragStartOffset.y+n},this.render(),void t.preventDefault()}if(this.isSelectingTextInTextBox&&this.editingTextBox&&this._editingTextBoxPageId===e){const n=this.editingTextBox,s=this.document.pages.findIndex(t=>t.id===e),o=this.contexts.get(e);return o&&s>=0&&(this.flowingTextRenderer.handleRegionClick(n,i,s,o),this.render()),void t.preventDefault()}if(this.isSelectingTextInTableCell&&this.tableCellSelectionTable){const n=this.tableCellSelectionTable;if(n.focusedCell){const t=n.getCell(n.focusedCell.row,n.focusedCell.col);if(t){const n=this.document.pages.findIndex(t=>t.id===e),s=this.contexts.get(e);s&&n>=0&&(this.flowingTextRenderer.handleRegionClick(t,i,n,s),this.render())}}return void t.preventDefault()}if(this.isSelectingText&&this.textSelectionStartPageId){const n=this.getRegionForActiveSection(),s=this.contexts.get(e),o=this.document.pages.findIndex(t=>t.id===e);if(n&&s&&o>=0){this.flowingTextRenderer.handleRegionClick(n,i,o,s)&&this.render()}return void t.preventDefault()}if(this.tableResizeHandler.isResizing)return this.tableResizeHandler.updateResize(i)&&this.render(),void t.preventDefault();if(this.tableCellSelectionPending&&this.tableCellSelectionStartPoint&&this.tableCellSelectionTable){const e=i.x-this.tableCellSelectionStartPoint.x,n=i.y-this.tableCellSelectionStartPoint.y;if(!(Math.sqrt(e*e+n*n)>=gt.CELL_SELECTION_THRESHOLD))return void t.preventDefault();this.tableCellSelectionPending=!1,this.isSelectingTableCells=!0}if(this.isSelectingTableCells&&this.tableCellSelectionStart&&this.tableCellSelectionTable){const n=this.tableCellSelectionTable,s=this.document.pages.findIndex(t=>t.id===e),o=n.getRenderedSlice(s),r=o?.position||n.renderedPosition,a=o?.height||n.height;if(r){if(i.x>=r.x&&i.x<=r.x+n.width&&i.y>=r.y&&i.y<=r.y+a){const t={x:i.x-r.x,y:i.y-r.y};if(o&&("middle"===o.slicePosition||"last"===o.slicePosition)){const e=o.headerHeight;t.y>=e&&(t.y=o.yOffset+(t.y-e))}const e=n.getCellAtPoint(t);e&&(n.selectRange({start:this.tableCellSelectionStart,end:e}),this.render())}}return void t.preventDefault()}if(this.isResizing&&this.dragStart&&this.resizeHandle){const t=i.x-this.dragStart.x,n=i.y-this.dragStart.y,s=this.getSelectedElementAt(e);if(s&&this.resizeStartSize&&this.resizeStartPos){const e=this.calculateNewSize(this.resizeHandle,this.resizeStartSize,this.resizeStartPos,t,n);if(e.size.width>20&&e.size.height>20){const t=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent];for(const i of t)if(i){const t=i.getEmbeddedObjectManager().findById(s.id);if(t){t.object.size={width:e.size.width,height:e.size.height};break}}}}return void this.render()}this.isDragging&&this.dragStart&&(this.dragStart=i,this.render()),this.updateCursor(i,e)}handleMouseUp(t,e){if(this.isSelectingTextInTextBox&&(this.isSelectingTextInTextBox=!1),this.isSelectingTextInTableCell&&(this.isSelectingTextInTableCell=!1),this.isSelectingText&&(this.isSelectingText=!1,this.textSelectionStartPageId=null),this.tableResizeHandler.isResizing&&this.tableResizeHandler.endResize(),(this.isSelectingTableCells||this.tableCellSelectionPending)&&(this.isSelectingTableCells=!1,this.tableCellSelectionPending=!1,this.tableCellSelectionStart=null,this.tableCellSelectionStartPoint=null,this.tableCellSelectionTable=null),(this.isDraggingRelativeObject||this.relativeObjectDragPending)&&(this.isDraggingRelativeObject&&(this.wasResizing=!0,this.emit("selection-change",{selectedElements:Array.from(this.selectedElements)})),this.isDraggingRelativeObject=!1,this.relativeObjectDragPending=!1,this.relativeObjectDragStart=null,this.relativeObjectBeingDragged=null,this.relativeObjectDragStartOffset=null),this.isDragging=!1,this.isResizing&&this.resizingElementId&&this.resizeStartSize){this.wasResizing=!0;const t=this.findEmbeddedObjectById(this.resizingElementId);if(t){const e={width:t.size.width,height:t.size.height};e.width===this.resizeStartSize.width&&e.height===this.resizeStartSize.height||this.emit("object-resized",{object:t,previousSize:this.resizeStartSize,newSize:e})}this.render(),this.updateResizeHandleHitTargets()}this.isResizing=!1,this.dragStart=null,this.resizeHandle=null,this.resizeStartSize=null,this.resizeStartPos=null,this.resizingElementId=null}handleMouseLeave(t,e){this.emit("mouse-leave"),this.isSelectingTextInTextBox&&(this.isSelectingTextInTextBox=!1),this.isSelectingTextInTableCell&&(this.isSelectingTextInTableCell=!1),this.isSelectingText&&(this.isSelectingText=!1,this.textSelectionStartPageId=null),this.tableResizeHandler.isResizing&&this.tableResizeHandler.cancelResize(),(this.isSelectingTableCells||this.tableCellSelectionPending)&&(this.isSelectingTableCells=!1,this.tableCellSelectionPending=!1,this.tableCellSelectionStart=null,this.tableCellSelectionStartPoint=null,this.tableCellSelectionTable=null),(this.isDraggingRelativeObject||this.relativeObjectDragPending)&&(this.isDraggingRelativeObject=!1,this.relativeObjectDragPending=!1,this.relativeObjectDragStart=null,this.relativeObjectBeingDragged=null,this.relativeObjectDragStartOffset=null),this.isDragging=!1,this.isResizing=!1,this.dragStart=null,this.resizeHandle=null,this.resizeStartSize=null,this.resizeStartPos=null;const i=this.canvases.get(e);i&&(i.style.cursor="default")}handleClick(t,e){if(this.wasResizing)return void(this.wasResizing=!1);if(this.isResizing)return;const i=this.getMousePosition(t),n=Date.now();let s=1;if(this.lastClickPosition){const t=n-this.lastClickTime,e=Math.sqrt(Math.pow(i.x-this.lastClickPosition.x,2)+Math.pow(i.y-this.lastClickPosition.y,2));t<300&&e<5&&(s=this.clickCount%3+1)}if(this.clickCount=s,this.lastClickTime=n,this.lastClickPosition={...i},2===s)return void this.handleDoubleClick(i,e);if(3===s)return void this.handleTripleClick(i,e);if(this._focusedControl instanceof W){const t=this._focusedControl,n=this.document.pages.findIndex(t=>t.id===e);let s=!1;const o=t.getRenderedSlice(n);if(o){const e=o.height;s=i.x>=o.position.x&&i.x<=o.position.x+t.width&&i.y>=o.position.y&&i.y<=o.position.y+e}else t.renderedPosition&&t.renderedPageIndex===n&&(s=t.containsPoint(i,t.renderedPosition));if(s)return;this.setFocus(null)}if(this.editingTextBox){const t=this.editingTextBox,e=t.renderedPosition;if(e){const n={x:e.x,y:e.y,width:t.width,height:t.height};if(i.x>=n.x&&i.x<=n.x+n.width&&i.y>=n.y&&i.y<=n.y+n.height){const e=t.flowingContent.getSelection();return void(e&&(e.start,e.end))}this.setEditingTextBox(null)}}const o=this.document.getPage(e),r=this.getFlowingContentForActiveSection();if(r){const t=r.getSelection();if(t&&t.start!==t.end)return}const a=this.document.pages.findIndex(t=>t.id===e),l=this.flowingTextRenderer.hitTestManager.queryByType(a,i,"embedded-object");if(l&&"embedded-object"===l.data.type){const t=l.data.object,e=this.getSectionForEmbeddedObject(t);if(e&&e!==this._activeSection)return;const i=this.getFlowingContentForActiveSection();return i&&i.clearSelection(),this.clearSelection(),void this.selectInlineElement(t)}const h=this.document.bodyFlowingContent;if(h){const t=h.getRepeatingSections();if(t.length>0&&o){const n=this.document.pages.findIndex(t=>t.id===e),s=this.flowingTextRenderer.getFlowedPagesForPage(this.document.pages[0].id);if(s&&s[n]){const e=o.getContentBounds(),r={x:e.position.x,y:e.position.y,width:e.size.width,height:e.size.height},a=o.getPageDimensions(),l={x:0,y:0,width:a.width,height:a.height},h=this.flowingTextRenderer.getRepeatingSectionAtPoint(i,t,n,l,r,s[n]);if(h)return this.clearSelection(),this.selectedSectionId=h.id,this.render(),void this.emit("repeating-section-clicked",{section:h})}}}const d=this.contexts.get(e),c=this.document.pages.findIndex(t=>t.id===e);if(d&&c>=0&&o){const t=this.getSectionAtPoint(i,o);t!==this._activeSection&&this.setActiveSection(t);const e=this.getRegionForActiveSection();if(e){if(this.flowingTextRenderer.handleRegionClick(e,i,c,d)){this.clearSelection();const t=this.getFlowingContentForActiveSection();return t&&t.clearSelection(),void this.render()}}const n=this.getRegionForActiveSection();if(n){if(n.globalToLocal(i,c))return}}this.clearSelection()}getRegionForActiveSection(){switch(this._activeSection){case"header":return this.regionManager.getHeaderRegion();case"footer":return this.regionManager.getFooterRegion();default:return this.regionManager.getBodyRegion()}}getFlowingContentForActiveSection(){switch(this._activeSection){case"header":return this.document.headerFlowingContent;case"footer":return this.document.footerFlowingContent;default:return this.document.bodyFlowingContent||null}}getMousePosition(t){const e=t.target.getBoundingClientRect();return{x:(t.clientX-e.left)/this.zoomLevel,y:(t.clientY-e.top)/this.zoomLevel}}getViewportMousePosition(t){const e=this.findScrollContainer();if(!e)return{x:t.clientX,y:t.clientY};const i=e.getBoundingClientRect();return{x:t.clientX-i.left,y:t.clientY-i.top}}getResizeHandleAt(t,e){const i=this.document.getPage(e);if(!i)return null;const n=this.document.pages.indexOf(i),s=this.flowingTextRenderer.hitTestManager.queryByType(n,t,"resize-handle");return s&&"resize-handle"===s.data.type?{handle:s.data.handle,element:s.data.element}:null}getSelectedElementAt(t){if(0===this.selectedElements.size)return null;if(!this.document.getPage(t))return null;const e=Array.from(this.selectedElements)[0],i=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent];for(const t of i)if(t){const i=t.getEmbeddedObjects();for(const[,t]of i.entries())if(t.id===e)return t}return null}calculateNewSize(t,e,i,n,s){const o={...e},r={...i};switch(t){case"nw":o.width=e.width-n,o.height=e.height-s,r.x=i.x+n,r.y=i.y+s;break;case"n":o.height=e.height-s,r.y=i.y+s;break;case"ne":o.width=e.width+n,o.height=e.height-s,r.y=i.y+s;break;case"e":o.width=e.width+n;break;case"se":o.width=e.width+n,o.height=e.height+s;break;case"s":o.height=e.height+s;break;case"sw":o.width=e.width-n,o.height=e.height+s,r.x=i.x+n;break;case"w":o.width=e.width-n,r.x=i.x+n}return{size:o,position:r}}updateCursor(t,e){const i=this.canvases.get(e);if(!i)return;const n=this.getResizeHandleAt(t,e);if(n){const t={nw:"nw-resize",n:"n-resize",ne:"ne-resize",e:"e-resize",se:"se-resize",s:"s-resize",sw:"sw-resize",w:"w-resize"};return void(i.style.cursor=t[n.handle]||"default")}const s=this.getTableResizeHandleAt(t,e);if(s&&s.handleInfo)return void(i.style.cursor=G.getCursorForHandle(s.handleInfo.type));const o=this.document.pages.findIndex(t=>t.id===e),r=this.flowingTextRenderer.hitTestManager,a=r.queryByType(o,t,"embedded-object");if(a&&"embedded-object"===a.data.type){const t=a.data.object,e=this.getSectionForEmbeddedObject(t);if(e&&e!==this._activeSection);else{if("relative"===t.position)return void(i.style.cursor="move");if(t instanceof E)return void(i.style.cursor="text")}}const l=r.queryByType(o,t,"table-cell");if(l&&"table-cell"===l.data.type)return void(i.style.cursor="text");const h=r.queryByType(o,t,"text-region");if(h&&"text-region"===h.data.type)return void(i.style.cursor="text");const d=this.regionManager.getBodyRegion();if(d&&d.containsPointInRegion(t,o))return void(i.style.cursor="text");const c=this.regionManager.getHeaderRegion();if(c&&c.containsPointInRegion(t,o))return void(i.style.cursor="text");const g=this.regionManager.getFooterRegion();g&&g.containsPointInRegion(t,o)?i.style.cursor="text":i.style.cursor="default"}getTableResizeHandleAt(t,e){const i=this.document.pages.findIndex(t=>t.id===e),n=this.flowingTextRenderer.hitTestManager.queryByType(i,t,"table-divider");if(n&&"table-divider"===n.data.type){const{table:t,dividerType:e,index:s}=n.data,o=t.getRenderedSlice(i),r=o?.position||t.renderedPosition;if(r){let i;if("column"===e){const e=t.getColumnPositions(),n=t.getColumnWidths();i=e[s]+n[s]}else{let e=0;for(let i=0;i<=s;i++)e+=t.rows[i].calculatedHeight;i=e}return{table:t,handleInfo:{type:e,index:s,position:i},tablePosition:r}}}return null}removeEmbeddedObject(t){const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjectManager().findById(t);if(e){i.deleteTextAt(e.textIndex,1);break}}this.selectedElements.delete(t),this.render(),this.emit("element-removed",{elementId:t})}selectElement(t){O.log("[pc-editor:CanvasManager] Selecting element:",t),this.selectedElements.add(t);const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjects();for(const[,i]of e.entries())i.id===t&&(O.log("[pc-editor:CanvasManager] Found embedded object to select:",i.id),i.selected=!0)}O.log("[pc-editor:CanvasManager] Selected elements after selection:",Array.from(this.selectedElements)),this.render(),this.updateResizeHandleHitTargets(),this.emit("selection-change",{selectedElements:Array.from(this.selectedElements)})}findEmbeddedObjectById(t){const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjectManager().findById(t);if(e)return e.object}return null}updateResizeHandleHitTargets(){const t=[],e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of this.selectedElements)for(const n of e){const e=n.getEmbeddedObjects();for(const[,n]of e.entries())if(n.id===i){t.push(n);break}}this.flowingTextRenderer.updateResizeHandleTargets(t)}clearSelection(){O.log("[pc-editor:CanvasManager] clearSelection called, current selected elements:",Array.from(this.selectedElements)),this.selectedElements.forEach(t=>{O.log("[pc-editor:CanvasManager] Clearing selection for element:",t);const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjects();for(const[,i]of e.entries())i.id===t&&(O.log("[pc-editor:CanvasManager] Clearing selection on embedded object:",t),i.selected=!1)}}),this.selectedElements.clear(),this.selectedSectionId=null,O.log("[pc-editor:CanvasManager] About to render after clearing selection..."),this.render(),this.updateResizeHandleHitTargets(),this.emit("selection-change",{selectedElements:[]})}getSelectedElements(){return Array.from(this.selectedElements)}hasSelectedElements(){return this.selectedElements.size>0}selectBaseEmbeddedObject(t,e=!1){this.setFocus(null);const i=t.object||t;i.selected=!0,this.selectedElements.add(i.id);const n=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);let s=null;for(const t of n){const e=t.getEmbeddedObjects();for(const[,n]of e.entries())if(n.id===i.id){n.selected=!0,s=t;break}if(s)break}if(!e&&s){const e=t.textIndex??i.textIndex;void 0!==e&&(s.setCursorPosition(e+1),s.clearSelection())}this.render(),this.updateResizeHandleHitTargets(),this.emit("selection-change",{selectedElements:Array.from(this.selectedElements)})}selectInlineElement(t){this.selectBaseEmbeddedObject(t)}getBaseEmbeddedObjectAtPoint(t,e){const i=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const e of i){const i=e.getEmbeddedObjects();for(const[,e]of i.entries())if(e.renderedPosition){const i={x:e.renderedPosition.x,y:e.renderedPosition.y,width:e.width,height:e.height};if(t.x>=i.x&&t.x<=i.x+i.width&&t.y>=i.y&&t.y<=i.y+i.height)return e}}return null}getZoom(){return this.zoomLevel}getScrollPosition(){const t=this.findScrollContainer();return t?{x:t.scrollLeft,y:t.scrollTop}:{x:0,y:0}}getContentOffset(){const t=this.findScrollContainer(),e=this.canvases.values().next().value;if(!t||!e)return{x:0,y:0};const i=t.getBoundingClientRect(),n=e.getBoundingClientRect();return{x:n.left-i.left+t.scrollLeft,y:n.top-i.top+t.scrollTop}}findScrollContainer(){let t=this.container;for(;t;){const e=getComputedStyle(t),i=e.overflowY,n=e.overflowX;if("auto"===i||"scroll"===i||"auto"===n||"scroll"===n)return t;t=t.parentElement}return this.container.parentElement||this.container}setupScrollListener(){const t=this.findScrollContainer();t&&t.addEventListener("scroll",()=>{const t=this.getScrollPosition();this.emit("scroll",t)})}zoomIn(){this.setZoom(1.2*this.zoomLevel)}zoomOut(){this.setZoom(this.zoomLevel/1.2)}setZoom(t){this.zoomLevel=Math.max(.1,Math.min(5,t)),this.updateCanvasScale(),this.emit("zoom-change",{zoom:this.zoomLevel})}updateCanvasScale(){this.canvases.forEach(t=>{t.style.transform=`scale(${this.zoomLevel})`,t.style.transformOrigin="top center";const e=t.height*(this.zoomLevel-1);t.style.marginBottom=`${20+e}px`})}fitToWidth(){if(0===this.canvases.size)return;const t=this.canvases.values().next().value;if(!t)return;const e=this.container.clientWidth-40,i=t.width;this.setZoom(e/i)}fitToPage(){if(0===this.canvases.size)return;const t=this.canvases.values().next().value;if(!t)return;const e=this.container.clientWidth-40,i=this.container.clientHeight-40,n=e/t.width,s=i/t.height;this.setZoom(Math.min(n,s))}setupFlowingTextListeners(){this.flowingTextRenderer.on("text-clicked",t=>{this.emit("text-clicked",t)}),this.flowingTextRenderer.on("cursor-changed",t=>{this.emit("cursor-changed",t),this.render()}),this.flowingTextRenderer.on("cursor-blink",()=>{this.render()}),this.flowingTextRenderer.on("selection-changed",t=>{this.emit("text-selection-changed",t),this.render()}),this.flowingTextRenderer.on("text-overflow",t=>{this.handleTextOverflow(t)}),this.flowingTextRenderer.on("content-changed",()=>{this.checkForEmptyPages()}),this.flowingTextRenderer.on("inline-element-clicked",t=>{this.isSelectingText||this.isSelectingTextInTextBox||this.isSelectingTextInTableCell||this._focusedControl instanceof W&&this._focusedControl===t.element||this.editingTextBox!==t.element&&(this.clearSelection(),this.selectInlineElement(t.element))}),this.flowingTextRenderer.on("substitution-field-clicked",t=>{O.log("[pc-editor:CanvasManager] substitution-field-clicked Field:",t.field?.fieldName,"Section:",t.section),this.emit("substitution-field-clicked",t)})}handleTextOverflow(t){if(this.isHandlingOverflow)return;const{pageId:e,totalPages:i}=t,n=this.document.pages.findIndex(t=>t.id===e);if(-1===n)return;const s=this.document.pages.length,o=n+i;if(!(o<=s)){this.isHandlingOverflow=!0;try{for(let t=s;t<o;t++)this.createNewPage();this.clearCanvases(),this.createCanvases(),this.setupEventListeners(),this.updateCanvasScale(),setTimeout(()=>{this.isHandlingOverflow=!1,this.render()},0),this.emit("pages-added",{newPageCount:this.document.pages.length-s})}catch(t){throw this.isHandlingOverflow=!1,t}}}createNewPage(){if(!this.document.pages[0])return;const t={id:`page_${Date.now()}_${Math.random().toString(36).substr(2,9)}`},e=new r(t,this.document.settings);this.document.addPage(e)}showTextCursor(){const t=this.getFlowingContentForActiveSection();t&&this.setFocus(t),this.render()}hideTextCursor(){this.suspendCursor(),this.render()}suspendCursor(){this._focusedControl&&!this._cursorSuspended&&(this._focusedControl.offCursorBlink(this.handleFocusedCursorBlink),this._cursorSuspended=!0)}resumeCursor(){this._focusedControl&&this._cursorSuspended&&(this._focusedControl.onCursorBlink(this.handleFocusedCursorBlink),this._cursorSuspended=!1,this.render())}isCursorSuspended(){return this._cursorSuspended}moveCursorVertical(t){if(0===this.document.pages.length)return null;const e=this.document.pages[0].id;return this.flowingTextRenderer.moveCursorVertical(t,e)}drawMarginLines(t,e){if(!this.showMargins)return;const i=e.getContentBounds(),n=e.getPageDimensions();t.save(),t.setLineDash([5,5]),t.strokeStyle="#999999",t.lineWidth=1,t.beginPath(),t.moveTo(0,i.position.y),t.lineTo(n.width,i.position.y),t.stroke();const s=i.position.y+i.size.height;t.beginPath(),t.moveTo(0,s),t.lineTo(n.width,s),t.stroke(),t.beginPath(),t.moveTo(i.position.x,0),t.lineTo(i.position.x,n.height),t.stroke();const o=i.position.x+i.size.width;t.beginPath(),t.moveTo(o,0),t.lineTo(o,n.height),t.stroke(),t.restore()}checkForEmptyPages(){if(this.isHandlingOverflow)return;if(this.document.pages.length<=1)return;const t=this.flowingTextRenderer.getFlowedPagesForPage(this.document.pages[0].id);if(!t)return;const e=t.length,i=this.document.pages.length;if(i!==e&&i>e&&e>=1){for(let t=i-1;t>=e;t--)this.document.removePage(this.document.pages[t].id);this.clearCanvases(),this.createCanvases(),this.setupEventListeners(),this.updateCanvasScale(),setTimeout(()=>{this.render()},0),this.emit("pages-removed",{removedCount:i-e})}}setShowControlCharacters(t){this.options.showControlCharacters=t,this.flowingTextRenderer.setShowControlCharacters(t),this.render()}setShowGrid(t){this.options.showGrid=t,this.render()}getShowGrid(){return this.options.showGrid}setShowMarginLines(t){this.showMargins=t,this.render()}getShowMarginLines(){return this.showMargins}getActiveSection(){return this._activeSection}setActiveSection(t){if(this._activeSection!==t){const e=this._activeSection;this._activeSection=t;let i=null;"body"===t?i=this.regionManager.getBodyRegion():"header"===t?i=this.regionManager.getHeaderRegion():"footer"===t&&(i=this.regionManager.getFooterRegion()),this.flowingTextRenderer.setFocusedRegion(i);const n=i?.flowingContent;this.setFocus(n),this.render(),this.emit("section-focus-changed",{section:t,previousSection:e})}}getSectionForEmbeddedObject(t){const e=[{content:this.document.bodyFlowingContent,section:"body"},{content:this.document.headerFlowingContent,section:"header"},{content:this.document.footerFlowingContent,section:"footer"}];for(const{content:i,section:n}of e){if(!i)continue;const e=i.getEmbeddedObjects();for(const[,i]of e.entries())if(i.id===t.id)return n}return null}getSectionAtPoint(t,e){const i=e.getContentBounds();return t.y<i.position.y?"header":t.y>=i.position.y+i.size.height?"footer":"body"}handleDoubleClick(t,e){const i=this.document.getPage(e);if(!i)return;if(this.editingTextBox){const i=this.editingTextBox,n=this.document.pages.findIndex(t=>t.id===e),s=this.contexts.get(e);if(i.containsPointInRegion(t,n)&&s&&n>=0)return this.flowingTextRenderer.handleRegionClick(i,t,n,s),i.flowingContent.selectWord(),void this.render()}if(this._focusedControl instanceof W){const i=this._focusedControl,n=this.document.pages.findIndex(t=>t.id===e),s=this.contexts.get(e);if(i.focusedCell&&s&&n>=0){const e=i.getCell(i.focusedCell.row,i.focusedCell.col);if(e)return this.flowingTextRenderer.handleRegionClick(e,t,n,s),e.flowingContent.selectWord(),void this.render()}}const n=this.getFlowingContentForActiveSection();if(n){const i=n.getEmbeddedObjects(),s=this.document.pages.findIndex(t=>t.id===e);for(const[,n]of i.entries()){if(n instanceof E&&n.renderedPosition&&n.containsPointInRegion(t,s)){this.setEditingTextBox(n,e);const i=this.contexts.get(e);return i&&s>=0&&this.flowingTextRenderer.handleRegionClick(n,t,s,i),void this.render()}if(n instanceof W){const i=n.getRenderedSlice(s),o=i?.position||n.renderedPosition;if(o){const r=i?.height||n.height;if(t.x>=o.x&&t.x<=o.x+n.width&&t.y>=o.y&&t.y<=o.y+r){const r=this.contexts.get(e);if(r&&s>=0){const e={x:t.x-o.x,y:t.y-o.y};if(i&&("middle"===i.slicePosition||"last"===i.slicePosition)){const t=i.headerHeight;e.y>=t&&(e.y=i.yOffset+(e.y-t))}const a=n.getCellAtPoint(e);if(a){this.editingTextBox&&this.setEditingTextBox(null),n.focusCell(a.row,a.col);const e=n.getCell(a.row,a.col);return e&&(this.setFocus(n),this.flowingTextRenderer.handleRegionClick(e,t,s,r)),void this.render()}}}}}}}const s=this.getSectionAtPoint(t,i);if(s!==this._activeSection&&this.setActiveSection(s),"header"===s||"footer"===s){const i=this.contexts.get(e),n=this.document.pages.findIndex(t=>t.id===e),o="header"===s?this.regionManager.getHeaderRegion():this.regionManager.getFooterRegion();if(i&&n>=0&&o){this.flowingTextRenderer.handleRegionClick(o,t,n,i)&&this.render()}}const o=this.getFlowingContentForActiveSection();if(o){const i=this.contexts.get(e),n=this.document.pages.findIndex(t=>t.id===e),s=this.getRegionForActiveSection();i&&n>=0&&s&&this.flowingTextRenderer.handleRegionClick(s,t,n,i),o.selectWord(),this.emit("text-selection-changed",{selection:o.getSelection(),section:this._activeSection}),this.render()}}handleTripleClick(t,e){if(this.editingTextBox)return this.editingTextBox.flowingContent.selectParagraph(),void this.render();if(this._focusedControl instanceof W){const t=this._focusedControl;if(t.focusedCell){const e=t.getCell(t.focusedCell.row,t.focusedCell.col);if(e)return e.flowingContent.selectParagraph(),void this.render()}}const i=this.getFlowingContentForActiveSection();i&&(i.selectParagraph(),this.emit("text-selection-changed",{selection:i.getSelection(),section:this._activeSection}),this.render())}setEditingTextBox(t,e){if(this.editingTextBox!==t)if(this.editingTextBox=t,this._editingTextBoxPageId=e||null,t)this.document.bodyFlowingContent.clearSelection(),this.clearSelection(),this.selectInlineElement({type:"embedded-object",object:t,textIndex:t.textIndex}),this.setFocus(t),this.emit("textbox-editing-started",{textBox:t});else{const t=this.getFlowingContentForActiveSection();t?this.setFocus(t):this.setFocus(null),this.emit("textbox-editing-ended",{})}}getEditingTextBox(){return this.editingTextBox}isEditingTextBox(){return null!==this.editingTextBox}getEditingTextBoxPageId(){return this._editingTextBoxPageId}getContext(t){return this.contexts.get(t)||null}setFocus(t){this._focusedControl!==t&&(this._focusedControl instanceof W&&this.flowingTextRenderer.updateTableDividerTargets(null),this._focusedControl&&(this._focusedControl.offCursorBlink(this.handleFocusedCursorBlink),this._focusedControl.blur()),this._focusedControl=t,t instanceof W&&this.flowingTextRenderer.updateTableDividerTargets(t),t?(t.focus(),t.onCursorBlink(this.handleFocusedCursorBlink),this.emit("focus-changed",{control:t})):this.emit("focus-changed",{control:null}))}getFocusedControl(){return this._focusedControl}getFlowedPagesSnapshot(){return this.flowingTextRenderer.getFlowedPagesSnapshot()}destroy(){this.flowingTextRenderer.destroy(),this.clearCanvases(),this.removeAllListeners()}}gt.CELL_SELECTION_THRESHOLD=5,gt.RELATIVE_DRAG_THRESHOLD=3;class ut{bind(t,e){return{version:t.version,settings:t.settings,pages:t.pages.map(t=>({...t})),headerContent:t.headerContent,footerContent:t.footerContent}}}function ft(t,e){return e-t}function pt(t,e,i,n,s){return{x:t,y:s-e-n,width:i,height:n}}const mt={arial:{normal:e.StandardFonts.Helvetica,bold:e.StandardFonts.HelveticaBold,italic:e.StandardFonts.HelveticaOblique,boldItalic:e.StandardFonts.HelveticaBoldOblique},helvetica:{normal:e.StandardFonts.Helvetica,bold:e.StandardFonts.HelveticaBold,italic:e.StandardFonts.HelveticaOblique,boldItalic:e.StandardFonts.HelveticaBoldOblique},"sans-serif":{normal:e.StandardFonts.Helvetica,bold:e.StandardFonts.HelveticaBold,italic:e.StandardFonts.HelveticaOblique,boldItalic:e.StandardFonts.HelveticaBoldOblique},times:{normal:e.StandardFonts.TimesRoman,bold:e.StandardFonts.TimesRomanBold,italic:e.StandardFonts.TimesRomanItalic,boldItalic:e.StandardFonts.TimesRomanBoldItalic},"times new roman":{normal:e.StandardFonts.TimesRoman,bold:e.StandardFonts.TimesRomanBold,italic:e.StandardFonts.TimesRomanItalic,boldItalic:e.StandardFonts.TimesRomanBoldItalic},serif:{normal:e.StandardFonts.TimesRoman,bold:e.StandardFonts.TimesRomanBold,italic:e.StandardFonts.TimesRomanItalic,boldItalic:e.StandardFonts.TimesRomanBoldItalic},georgia:{normal:e.StandardFonts.TimesRoman,bold:e.StandardFonts.TimesRomanBold,italic:e.StandardFonts.TimesRomanItalic,boldItalic:e.StandardFonts.TimesRomanBoldItalic},courier:{normal:e.StandardFonts.Courier,bold:e.StandardFonts.CourierBold,italic:e.StandardFonts.CourierOblique,boldItalic:e.StandardFonts.CourierBoldOblique},"courier new":{normal:e.StandardFonts.Courier,bold:e.StandardFonts.CourierBold,italic:e.StandardFonts.CourierOblique,boldItalic:e.StandardFonts.CourierBoldOblique},monospace:{normal:e.StandardFonts.Courier,bold:e.StandardFonts.CourierBold,italic:e.StandardFonts.CourierOblique,boldItalic:e.StandardFonts.CourierBoldOblique}};function bt(t){if(!t)return e.rgb(0,0,0);const i=t.trim().toLowerCase();if(i.startsWith("#")){const t=i.slice(1);let n,s,o;if(3===t.length)n=parseInt(t[0]+t[0],16)/255,s=parseInt(t[1]+t[1],16)/255,o=parseInt(t[2]+t[2],16)/255;else{if(6!==t.length&&8!==t.length)return e.rgb(0,0,0);n=parseInt(t.slice(0,2),16)/255,s=parseInt(t.slice(2,4),16)/255,o=parseInt(t.slice(4,6),16)/255}return e.rgb(n,s,o)}const n=i.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(n)return e.rgb(parseInt(n[1])/255,parseInt(n[2])/255,parseInt(n[3])/255);const s={black:[0,0,0],white:[1,1,1],red:[1,0,0],green:[0,.5,0],blue:[0,0,1],yellow:[1,1,0],cyan:[0,1,1],magenta:[1,0,1],gray:[.5,.5,.5],grey:[.5,.5,.5],orange:[1,.65,0],purple:[.5,0,.5],pink:[1,.75,.8],brown:[.65,.16,.16],transparent:[0,0,0]};if(s[i]){const[t,n,o]=s[i];return e.rgb(t,n,o)}return e.rgb(0,0,0)}function xt(t,e,i,n,s,o,r){const a=pt(e,i,n,s,r);t.drawRectangle({x:a.x,y:a.y,width:a.width,height:a.height,color:o})}function yt(t,e,i,n,s,o,r,a){t.drawLine({start:{x:e,y:ft(i,a)},end:{x:n,y:ft(s,a)},color:o,thickness:r})}class wt{constructor(){this.fontCache=new Map}async generate(t,i,n){const s=await e.PDFDocument.create();this.fontCache.clear(),await this.embedStandardFonts(s);for(let n=0;n<t.pages.length;n++)try{const o=t.pages[n],r=o.getPageDimensions(),a=s.addPage([r.width,r.height]);a.drawRectangle({x:0,y:0,width:r.width,height:r.height,color:e.rgb(1,1,1)});const l=o.getContentBounds(),h={x:l.position.x,y:l.position.y,width:l.size.width,height:l.size.height};if(i?.header&&t.headerFlowingContent){const e=o.getHeaderBounds(),s={x:e.position.x,y:e.position.y,width:e.size.width,height:e.size.height};await this.renderFlowedPage(a,i.header,s,r.height,n,t.pages.length,i.headerHyperlinks)}if(i?.body&&i.body[n]&&await this.renderFlowedPage(a,i.body[n],h,r.height,n,t.pages.length,i.bodyHyperlinks),i?.footer&&t.footerFlowingContent){const e=o.getFooterBounds(),s={x:e.position.x,y:e.position.y,width:e.size.width,height:e.size.height};await this.renderFlowedPage(a,i.footer,s,r.height,n,t.pages.length,i.footerHyperlinks)}}catch(t){throw console.error(`[PDFGenerator] Error rendering page ${n+1}:`,t),t}return function(t,e){try{return new Blob([t],{type:e})}catch(i){const n=new ArrayBuffer(t.length),s=new Uint8Array(n);for(let e=0;e<t.length;e++)s[e]=t[e];return new Blob([n],{type:e})}}(await s.save(),"application/pdf")}async embedStandardFonts(t){const i=[e.StandardFonts.Helvetica,e.StandardFonts.HelveticaBold,e.StandardFonts.HelveticaOblique,e.StandardFonts.HelveticaBoldOblique,e.StandardFonts.TimesRoman,e.StandardFonts.TimesRomanBold,e.StandardFonts.TimesRomanItalic,e.StandardFonts.TimesRomanBoldItalic,e.StandardFonts.Courier,e.StandardFonts.CourierBold,e.StandardFonts.CourierOblique,e.StandardFonts.CourierBoldOblique];for(const e of i){const i=await t.embedFont(e);this.fontCache.set(e,i)}}filterToWinAnsi(t){let e="";for(let i=0;i<t.length;i++){const n=t.charCodeAt(i);if(n>=32&&n<=126)e+=t[i];else if(n>=160&&n<=255)e+=t[i];else if(9===n)e+=" ";else{if(10===n||13===n)continue;if(12===n)continue;e+=" "}}return e}getFont(t){const i=function(t,e,i){const n=t.toLowerCase().trim(),s="bold"===e||"700"===e||"800"===e||"900"===e,o="italic"===i||"oblique"===i;let r="normal";s&&o?r="boldItalic":s?r="bold":o&&(r="italic");const a=mt[n];return a?a[r]:mt.helvetica[r]}(t.fontFamily||"Arial",t.fontWeight,t.fontStyle);return this.fontCache.get(i)||this.fontCache.get(e.StandardFonts.Helvetica)}async renderFlowedPage(t,e,i,n,s,o,r){let a=i.y;const l=[],h=[];for(const d of e.lines){if(d.embeddedObjects)for(const t of d.embeddedObjects)t.isAnchor&&"relative"===t.object.position&&l.push({object:t.object,anchorX:i.x,anchorY:a});const e=this.getAlignmentOffset(d,i.width),c=i.x+e;let g=c;for(const e of d.runs){if(!e.text)continue;const i=this.filterToWinAnsi(e.text);if(!i)continue;const s=e.formatting||{},o=this.getFont(s),l=s.fontSize||14,c=bt(s.color||"#000000"),u=o.widthOfTextAtSize(i,l);if(s.backgroundColor){const e=bt(s.backgroundColor);xt(t,g,a,u,d.height,e,n)}const f=a+d.baseline;if(t.drawText(i,{x:g,y:ft(f,n),font:o,size:l,color:c}),r&&r.length>0&&h.push({x:g,y:a,width:u,height:d.height,startIndex:e.startIndex,endIndex:e.endIndex}),g+=u,d.extraWordSpacing&&i.includes(" ")){g+=(i.match(/ /g)||[]).length*d.extraWordSpacing}}for(const e of d.substitutionFields)this.renderSubstitutionField(t,e,c,a,d,n,s,o);for(const e of d.embeddedObjects){if(e.isAnchor)continue;let r=c+e.x;if(e.isBlock)switch(d.alignment){case"center":r=i.x+(i.width-e.object.width)/2;break;case"right":r=i.x+i.width-e.object.width;break;default:r=i.x}await this.renderEmbeddedObject(t,e.object,r,a,n,s,o)}a+=d.height}await this.renderRelativeObjects(t,l,n,s,o),r&&r.length>0&&h.length>0&&this.createHyperlinkAnnotations(t,h,r,n)}createHyperlinkAnnotations(t,e,i,n){for(const s of i){const i=e.filter(t=>t.startIndex<s.endIndex&&t.endIndex>s.startIndex);if(0===i.length)continue;const o=new Map;for(const t of i){const e=t.y;o.has(e)||o.set(e,[]),o.get(e).push(t)}for(const[e,i]of o){const o=Math.min(...i.map(t=>t.x)),r=Math.max(...i.map(t=>t.x+t.width)),a=i[0].height,l=n-e-a,h=t.doc.context.obj({Type:"Annot",Subtype:"Link",Rect:[o,l,r,l+a],Border:[0,0,0],A:{Type:"Action",S:"URI",URI:s.url}}),d=t.node.get(t.doc.context.obj("Annots"));d?d.push(h):t.node.set(t.doc.context.obj("Annots"),t.doc.context.obj([h]))}}}getAlignmentOffset(t,e){switch(t.alignment){case"center":return(e-t.width)/2;case"right":return e-t.width;default:return 0}}renderSubstitutionField(t,e,i,n,s,o,r,a){const l=e.field;let h="";if(h="pageNumber"===l.fieldType?String(r+1):"pageCount"===l.fieldType?String(a):l.defaultValue||"",!h)return;const d=this.filterToWinAnsi(h);if(!d)return;const c=l.formatting||{fontFamily:"Arial",fontSize:14,color:"#000000"},g=this.getFont(c),u=c.fontSize,f=bt(c.color),p=i+e.x,m=n+s.baseline;t.drawText(d,{x:p,y:ft(m,o),font:g,size:u,color:f})}async renderEmbeddedObject(t,e,i,n,s,o,r){e instanceof I?await this.renderImage(t,e,i,n,s):e instanceof E?await this.renderTextBox(t,e,i,n,s,o,r):e instanceof W&&await this.renderTable(t,e,i,n,s,o,r)}async renderRelativeObjects(t,e,i,n,s){for(const{object:o,anchorX:r,anchorY:a}of e){const e=o.relativeOffset,l=r+e.x,h=a+e.y;await this.renderEmbeddedObject(t,o,l,h,i,n,s)}}async renderImage(t,i,n,s,o){const r=t.doc,a=i.src;if(a.startsWith("data:"))try{let e=await this.embedImageFromDataUrl(r,a);if(!e){const t=i.toPngDataUrl();t&&(e=await this.embedImageFromDataUrl(r,t))}if(e){const r=this.calculateImageDrawParams(e.width,e.height,i.width,i.height,i.fit),a=n+r.dx,l=o-(s+r.dy+r.dh);return void("tile"===i.fit?this.drawTiledImage(t,e,n,s,i.width,i.height,o):t.drawImage(e,{x:a,y:l,width:r.dw,height:r.dh}))}}catch(t){O.warn("[pc-editor:PDFGenerator] Failed to embed image:",t)}const l=pt(n,s,i.width,i.height,o);t.drawRectangle({x:l.x,y:l.y,width:l.width,height:l.height,borderColor:e.rgb(.8,.8,.8),borderWidth:1})}async embedImageFromDataUrl(t,e){const i=e.match(/^data:([^;,]+)?(?:;base64)?,(.*)$/);if(!i)return null;const n=i[1]||"",s=i[2],o=atob(s),r=new Uint8Array(o.length);for(let t=0;t<o.length;t++)r[t]=o.charCodeAt(t);return n.includes("jpeg")||n.includes("jpg")?await t.embedJpg(r):n.includes("png")?await t.embedPng(r):null}calculateImageDrawParams(t,e,i,n,s){let o=0,r=0,a=i,l=n;switch(s){case"fill":break;case"contain":{const s=Math.min(i/t,n/e);a=t*s,l=e*s,o=(i-a)/2,r=(n-l)/2;break}case"cover":{const s=Math.max(i/t,n/e);a=t*s,l=e*s,o=(i-a)/2,r=(n-l)/2;break}case"none":a=t,l=e,o=(i-t)/2,r=(n-e)/2;break;case"tile":a=t,l=e}return{dx:o,dy:r,dw:a,dh:l}}drawTiledImage(t,e,i,n,s,o,r){const a=e.width,l=e.height;for(let h=0;h<o;h+=l)for(let d=0;d<s;d+=a){const c=Math.min(a,s-d),g=Math.min(l,o-h),u=i+d,f=r-(n+h+g);t.drawImage(e,{x:u,y:f,width:c,height:g})}}async renderTextBox(t,e,i,n,s,o,r){if(e.backgroundColor){const o=bt(e.backgroundColor);xt(t,i,n,e.width,e.height,o,s)}const a=e.border;a&&("none"!==a.top.style&&a.top.width>0&&yt(t,i,n,i+e.width,n,bt(a.top.color),a.top.width,s),"none"!==a.right.style&&a.right.width>0&&yt(t,i+e.width,n,i+e.width,n+e.height,bt(a.right.color),a.right.width,s),"none"!==a.bottom.style&&a.bottom.width>0&&yt(t,i,n+e.height,i+e.width,n+e.height,bt(a.bottom.color),a.bottom.width,s),"none"!==a.left.style&&a.left.width>0&&yt(t,i,n,i,n+e.height,bt(a.left.color),a.left.width,s));const l=e.flowingContent;if(l){const a="undefined"!=typeof document?document.createElement("canvas"):null,h=a?.getContext("2d");if(h){const a=e.padding||4,d=l.flowText(e.width-2*a,e.height-2*a,h);if(d.length>0){const l={x:i+a,y:n+a,width:e.width-2*a,height:e.height-2*a};await this.renderFlowedPage(t,d[0],l,s,o,r)}}}}async renderTable(t,e,i,n,s,o,r){const a=e.getColumnPositions(),l=e.getColumnWidths(),h=e.getRenderedSlice(o);let d;d=h&&"only"!==h.slicePosition?this.getTableRowsForSlice(e,{slicePosition:h.slicePosition,sliceIndex:h.sliceIndex,yOffset:h.yOffset,headerHeight:h.headerHeight}):e.rows.map((t,e)=>({row:t,originalIndex:e}));let c=n;const g=new Set;for(const{row:t,originalIndex:e}of d)for(let i=0;i<t.cells.length;i++){const n=t.cells[i];if(n&&(n.rowSpan>1||n.colSpan>1))for(let t=e;t<e+n.rowSpan;t++)for(let s=i;s<i+n.colSpan;s++)t===e&&s===i||g.add(`${t},${s}`)}for(const{row:n,originalIndex:h}of d){for(let u=0;u<n.cells.length;u++){const f=n.cells[u],p=`${h},${u}`;if(g.has(p))continue;if(!f)continue;let m=0;for(let t=u;t<u+f.colSpan;t++)m+=l[t]||0;let b=n.calculatedHeight;if(f.rowSpan>1){b=0;for(let t=h;t<h+f.rowSpan&&t<e.rows.length;t++){d.some(e=>e.originalIndex===t)&&(b+=e.rows[t].calculatedHeight)}}const x=i+a[u];if(f.backgroundColor){xt(t,x,c,m,b,bt(f.backgroundColor),s)}this.renderCellBorders(t,f,x,c,m,b,s);const y=f.flowingContent;if(y){const e="undefined"!=typeof document?document.createElement("canvas"):null,i=e?.getContext("2d");if(i){const e=f.padding,n=e.left+e.right,a=e.top+e.bottom,l=y.flowText(m-n,b-a,i);if(l.length>0){const i={x:x+e.left,y:c+e.top,width:m-n,height:b-a};await this.renderFlowedPage(t,l[0],i,s,o,r)}}}}c+=n.calculatedHeight}}getTableRowsForSlice(t,e){const i=[];if("first"!==e.slicePosition&&"only"!==e.slicePosition)for(let e=0;e<t.rows.length;e++)t.rows[e].isHeader&&i.push({row:t.rows[e],originalIndex:e});let n=0;for(const e of t.rows)e.isHeader&&(n+=e.calculatedHeight);const s=e.yOffset;let o=t.height-n;const r=t.getRenderedPageIndices().sort((t,e)=>t-e),a=r.findIndex(i=>t.getRenderedSlice(i)?.sliceIndex===e.sliceIndex);if(a>=0&&a<r.length-1){const e=r[a+1],i=t.getRenderedSlice(e);i&&(o=i.yOffset)}let l=0;for(let e=0;e<t.rows.length;e++){const n=t.rows[e];if(n.isHeader)continue;const r=l,a=l+n.calculatedHeight;r<o&&a>s&&i.push({row:n,originalIndex:e}),l=a}return i}renderCellBorders(t,e,i,n,s,o,r){const a=e.border;"none"!==a.top.style&&a.top.width>0&&yt(t,i,n,i+s,n,bt(a.top.color),a.top.width,r),"none"!==a.right.style&&a.right.width>0&&yt(t,i+s,n,i+s,n+o,bt(a.right.color),a.right.width,r),"none"!==a.bottom.style&&a.bottom.width>0&&yt(t,i,n+o,i+s,n+o,bt(a.bottom.color),a.bottom.width,r),"none"!==a.left.style&&a.left.width>0&&yt(t,i,n,i,n+o,bt(a.left.color),a.left.width,r)}}class Ct extends o{constructor(t){super(),this.autoFlow=!0}setAutoFlow(t){this.autoFlow=t,this.emit("auto-flow-changed",{enabled:t})}getAutoFlow(){return this.autoFlow}checkContentOverflow(){return!1}insertPageBreak(t){}reflowDocument(){this.emit("document-reflowed")}getPageMetrics(t){return{contentHeight:0,availableHeight:t.getContentBounds().size.height,utilizationPercent:0,hasOverflow:!1}}}class St extends o{constructor(t,e){super(),this.isLayouting=!1,this.document=t,this.flowManager=new Ct(t),this.options={autoFlow:!0,snapToGrid:!1,gridSize:10,allowOrphans:!1,minimumContentHeight:50,...e},this.setupEventListeners()}setupEventListeners(){this.document.on("change",()=>{!this.isLayouting&&this.options.autoFlow&&this.requestLayout()}),this.flowManager.on("page-overflow-handled",t=>{this.emit("page-added",t)}),this.flowManager.on("page-break-inserted",t=>{this.emit("page-break-created",t)})}requestLayout(){this.isLayouting||setTimeout(()=>{this.performLayout()},100)}performLayout(){this.isLayouting=!0,this.emit("layout-start");try{this.emit("layout-complete",{hadOverflow:!1})}catch(t){this.emit("layout-error",{error:t})}finally{this.isLayouting=!1}}insertPageBreak(t){}setAutoFlow(t){this.options.autoFlow=t,this.flowManager.setAutoFlow(t),t&&this.performLayout()}setSnapToGrid(t,e){this.options.snapToGrid=t,e&&(this.options.gridSize=e)}getLayoutOptions(){return{...this.options}}updateLayoutOptions(t){this.options={...this.options,...t},this.emit("layout-options-changed",{options:this.options})}reflowDocument(){this.performLayout()}getDocumentMetrics(){return{totalPages:this.document.pages.length,totalContentHeight:0,averagePageUtilization:0,hasOverflow:!1}}destroy(){this.removeAllListeners(),this.flowManager.removeAllListeners()}}const vt={maxTimeGap:500,maxCharacters:50};function Ft(){return`${Date.now()}_${Math.random().toString(36).substr(2,9)}`}class It extends o{constructor(t,e,i,n=100){super(),this.undoStack=[],this.redoStack=[],this.maxHistory=100,this.isPerformingUndoRedo=!1,this.coalesceConfig=vt,this.pendingTransaction=null,this.transactionStack=[],this.focusTracker=t,this._getContent=e,this._getObject=i,this.maxHistory=n}getContent(t){return this._getContent(t)}getObject(t){return this._getObject(t)}get isUndoRedoInProgress(){return this.isPerformingUndoRedo}recordMutation(t){if(!this.isPerformingUndoRedo){if(t.id||(t.id=Ft()),this.transactionStack.length>0){const e=this.transactionStack[this.transactionStack.length-1];return e.mutations.push(t),e.endTime=t.timestamp,void(e.focusStateAfter=this.focusTracker.capture())}this.shouldCoalesce(t)?this.coalesceMutation(t):(this.flushPendingTransaction(),this.canStartCoalesce(t)?this.pendingTransaction=this.createTransactionFromMutation(t):this.commitTransaction(this.createTransactionFromMutation(t)),this.redoStack.length>0&&(this.redoStack=[],this.emitStateChange()))}}createTransactionFromMutation(t){const e=this.focusTracker.capture();return{id:Ft(),startTime:t.timestamp,endTime:t.timestamp,mutations:[t],focusStateBefore:e,focusStateAfter:e,description:this.getDescriptionForMutation(t)}}shouldCoalesce(t){if(!this.pendingTransaction)return!1;const e=this.pendingTransaction,i=e.mutations[e.mutations.length-1];if(!this.sameSource(t.sourceId,i.sourceId))return!1;if(t.type!==i.type)return!1;if(t.timestamp-i.timestamp>this.coalesceConfig.maxTimeGap)return!1;if("insert"===t.type){const n=i.data,s=t.data;if(s.position!==n.position+n.text.length)return!1;if(e.mutations.reduce((t,e)=>"insert"===e.type?t+(e.data.text?.length||0):t,0)+s.text.length>this.coalesceConfig.maxCharacters)return!1}if("delete"===t.type){const e=i.data,n=t.data,s=n.position===e.position-1,o=n.position===e.position;if(!s&&!o)return!1}return!0}sameSource(t,e){if("type"in t&&"type"in e){const i=t,n=e;return i.type===n.type&&(i.objectId===n.objectId&&(i.cellAddress&&n.cellAddress?i.cellAddress.row===n.cellAddress.row&&i.cellAddress.col===n.cellAddress.col:i.cellAddress===n.cellAddress))}return!1}canStartCoalesce(t){return"insert"===t.type||"delete"===t.type}coalesceMutation(t){this.pendingTransaction&&(this.pendingTransaction.mutations.push(t),this.pendingTransaction.endTime=t.timestamp,this.pendingTransaction.focusStateAfter=this.focusTracker.capture())}flushPendingTransaction(){this.pendingTransaction&&(this.commitTransaction(this.pendingTransaction),this.pendingTransaction=null)}commitTransaction(t){if(0!==t.mutations.length){for(this.undoStack.push(t);this.undoStack.length>this.maxHistory;)this.undoStack.shift();this.emit("transaction-committed",{transaction:t}),this.emitStateChange()}}createBoundary(){this.flushPendingTransaction()}beginCompoundOperation(t){this.flushPendingTransaction();const e={id:Ft(),startTime:Date.now(),endTime:0,mutations:[],focusStateBefore:this.focusTracker.capture(),focusStateAfter:this.focusTracker.capture(),description:t||"Multiple Changes"};this.transactionStack.push(e)}endCompoundOperation(t){if(0===this.transactionStack.length)return;const e=this.transactionStack.pop();if(e.endTime=Date.now(),e.focusStateAfter=this.focusTracker.capture(),t&&(e.description=t),this.transactionStack.length>0){this.transactionStack[this.transactionStack.length-1].mutations.push(...e.mutations)}else e.mutations.length>0&&(this.commitTransaction(e),this.redoStack.length>0&&(this.redoStack=[],this.emitStateChange()))}undo(){if(this.flushPendingTransaction(),0===this.undoStack.length)return!1;const t=this.undoStack.pop();this.isPerformingUndoRedo=!0;try{for(let e=t.mutations.length-1;e>=0;e--)this.undoMutation(t.mutations[e]);return this.focusTracker.restore(t.focusStateBefore),this.redoStack.push(t),this.emit("undo-performed",{transaction:t}),this.emitStateChange(),!0}finally{this.isPerformingUndoRedo=!1}}redo(){if(0===this.redoStack.length)return!1;const t=this.redoStack.pop();this.isPerformingUndoRedo=!0;try{for(const e of t.mutations)this.redoMutation(e);return this.focusTracker.restore(t.focusStateAfter),this.undoStack.push(t),this.emit("redo-performed",{transaction:t}),this.emitStateChange(),!0}finally{this.isPerformingUndoRedo=!1}}undoMutation(t){this.emit("undo-mutation",{mutation:t})}redoMutation(t){this.emit("redo-mutation",{mutation:t})}canUndo(){return this.undoStack.length>0||null!==this.pendingTransaction}canRedo(){return this.redoStack.length>0}getUndoDescription(){return this.pendingTransaction?this.pendingTransaction.description:0===this.undoStack.length?null:this.undoStack[this.undoStack.length-1].description}getRedoDescription(){return 0===this.redoStack.length?null:this.redoStack[this.redoStack.length-1].description}clear(){this.undoStack=[],this.redoStack=[],this.pendingTransaction=null,this.transactionStack=[],this.emit("history-cleared",void 0),this.emitStateChange()}getDescriptionForMutation(t){return{insert:"Typing",delete:"Delete",format:"Format",alignment:"Alignment","field-insert":"Insert Field","field-delete":"Delete Field","field-update":"Update Field","object-insert":"Insert Object","object-delete":"Delete Object","object-resize":"Resize","object-move":"Move","object-property":"Change Property","table-add-row":"Add Row","table-add-column":"Add Column","table-delete-row":"Delete Row","table-delete-column":"Delete Column","table-merge":"Merge Cells","table-split":"Split Cell"}[t.type]||"Change"}emitStateChange(){this.emit("state-changed",{canUndo:this.canUndo(),canRedo:this.canRedo()})}setCoalesceConfig(t){this.coalesceConfig={...this.coalesceConfig,...t}}setMaxHistory(t){for(this.maxHistory=t;this.undoStack.length>this.maxHistory;)this.undoStack.shift()}}class _t{constructor(t,e){this.getActiveContent=t,this.restoreFocus=e}capture(){const t=this.getActiveContent();if(!t.content)return{activeSection:"body",focusedObjectId:null,tableCellAddress:null,cursorPosition:0,selection:null};const e=t.content.getSelection();return{activeSection:t.section,focusedObjectId:t.focusedObjectId,tableCellAddress:t.tableCellAddress,cursorPosition:t.content.getCursorPosition(),selection:e?{start:e.start,end:e.end}:null}}restore(t){this.restoreFocus(t)}captureFromContent(t,e,i=null,n=null){const s=t.getSelection();return{activeSection:e,focusedObjectId:i,tableCellAddress:n,cursorPosition:t.getCursorPosition(),selection:s?{start:s.start,end:s.end}:null}}}class Tt{constructor(t){this.observedContents=new WeakMap,this.manager=t}observe(t,e){if(this.observedContents.has(t)){return void(this.observedContents.get(t).sourceId=e)}const i={insertText:t.insertText.bind(t),deleteText:t.deleteText.bind(t),insertTextAt:t.insertTextAt.bind(t),deleteTextAt:t.deleteTextAt.bind(t),applyFormatting:t.applyFormatting.bind(t),setAlignment:t.setAlignment.bind(t),setAlignmentForRange:t.setAlignmentForRange.bind(t),insertSubstitutionField:t.insertSubstitutionField.bind(t),removeSubstitutionField:t.removeSubstitutionField.bind(t),insertEmbeddedObject:t.insertEmbeddedObject.bind(t),removeEmbeddedObject:t.removeEmbeddedObject.bind(t)};this.observedContents.set(t,{sourceId:e,originalMethods:i}),t.insertText=(e,n)=>{if(this.manager.isUndoRedoInProgress)return i.insertText(e,n);const s=this.captureState(t),o=n??t.getCursorPosition();i.insertText(e,n);const r=this.captureState(t);this.recordMutation(t,{id:Ft(),sourceId:this.getSourceId(t),type:"insert",timestamp:Date.now(),beforeState:s,afterState:r,data:{position:o,text:e,formatting:t.getFormattingManager().getFormattingAt(o)}})},t.deleteText=(e,n,s=!0)=>{if(this.manager.isUndoRedoInProgress)return i.deleteText(e,n,s);const o=this.captureState(t),r=t.getText().substring(e,e+n),a=this.captureFormattingInRange(t,e,n),l=this.captureFieldsInRange(t,e,n),h=this.captureObjectsInRange(t,e,n);i.deleteText(e,n,s);const d=this.captureState(t);this.recordMutation(t,{id:Ft(),sourceId:this.getSourceId(t),type:"delete",timestamp:Date.now(),beforeState:o,afterState:d,data:{position:e,deletedText:r,deletedFormatting:a,deletedFields:l,deletedObjects:h}})},t.insertTextAt=(e,n)=>{if(this.manager.isUndoRedoInProgress)return i.insertTextAt(e,n);const s=this.captureState(t);i.insertTextAt(e,n);const o=this.captureState(t);this.recordMutation(t,{id:Ft(),sourceId:this.getSourceId(t),type:"insert",timestamp:Date.now(),beforeState:s,afterState:o,data:{position:e,text:n}})},t.deleteTextAt=(e,n)=>{if(this.manager.isUndoRedoInProgress)return i.deleteTextAt(e,n);const s=this.captureState(t),o=t.getText().substring(e,e+n),r=this.captureFormattingInRange(t,e,n);i.deleteTextAt(e,n);const a=this.captureState(t);this.recordMutation(t,{id:Ft(),sourceId:this.getSourceId(t),type:"delete",timestamp:Date.now(),beforeState:s,afterState:a,data:{position:e,deletedText:o,deletedFormatting:r}})},t.applyFormatting=(e,n,s)=>{if(this.manager.isUndoRedoInProgress)return i.applyFormatting(e,n,s);const o=this.captureState(t),r=this.captureFormattingInRange(t,e,n-e);this.manager.createBoundary(),i.applyFormatting(e,n,s);const a=this.captureState(t);this.recordMutation(t,{id:Ft(),sourceId:this.getSourceId(t),type:"format",timestamp:Date.now(),beforeState:o,afterState:a,data:{start:e,end:n,newFormatting:s,previousFormatting:r}})},t.setAlignment=e=>{if(this.manager.isUndoRedoInProgress)return i.setAlignment(e);const n=this.captureState(t),s=t.getCursorPosition(),o=t.getParagraphBoundaries(),r=this.getParagraphIndexFromBoundaries(s,o),a=t.getAlignmentAt(s);this.manager.createBoundary(),i.setAlignment(e);const l=this.captureState(t);this.recordMutation(t,{id:Ft(),sourceId:this.getSourceId(t),type:"alignment",timestamp:Date.now(),beforeState:n,afterState:l,data:{paragraphIndex:r,newAlignment:e,previousAlignment:a}})},t.insertSubstitutionField=(e,n)=>{if(this.manager.isUndoRedoInProgress)return i.insertSubstitutionField(e,n);const s=this.captureState(t),o=t.getCursorPosition();this.manager.createBoundary();const r=i.insertSubstitutionField(e,n),a=this.captureState(t),l=t.getSubstitutionFieldManager().getFieldAt(o);return l&&this.recordMutation(t,{id:Ft(),sourceId:this.getSourceId(t),type:"field-insert",timestamp:Date.now(),beforeState:s,afterState:a,data:{position:o,field:{...l}}}),r},t.insertEmbeddedObject=(e,n="inline")=>{if(this.manager.isUndoRedoInProgress)return i.insertEmbeddedObject(e,n);const s=this.captureState(t),o=t.getCursorPosition();i.insertEmbeddedObject(e,n);const r=this.captureState(t),a=e.toData();this.recordMutation(t,{id:Ft(),sourceId:this.getSourceId(t),type:"object-insert",timestamp:Date.now(),beforeState:s,afterState:r,data:{position:o,objectData:a}})},t.removeEmbeddedObject=e=>{if(this.manager.isUndoRedoInProgress)return i.removeEmbeddedObject(e);const n=t.getEmbeddedObjectAt(e);if(!n)return i.removeEmbeddedObject(e);const s=this.captureState(t),o=n.toData();this.manager.createBoundary();const r=i.removeEmbeddedObject(e),a=this.captureState(t);return this.recordMutation(t,{id:Ft(),sourceId:this.getSourceId(t),type:"object-delete",timestamp:Date.now(),beforeState:s,afterState:a,data:{position:e,objectData:o}}),r}}unobserve(t){const e=this.observedContents.get(t);if(!e)return;const{originalMethods:i}=e;t.insertText=i.insertText,t.deleteText=i.deleteText,t.insertTextAt=i.insertTextAt,t.deleteTextAt=i.deleteTextAt,t.applyFormatting=i.applyFormatting,t.setAlignment=i.setAlignment,t.setAlignmentForRange=i.setAlignmentForRange,t.insertSubstitutionField=i.insertSubstitutionField,t.removeSubstitutionField=i.removeSubstitutionField,t.insertEmbeddedObject=i.insertEmbeddedObject,t.removeEmbeddedObject=i.removeEmbeddedObject,this.observedContents.delete(t)}isObserving(t){return this.observedContents.has(t)}getSourceId(t){const e=this.observedContents.get(t);return e?.sourceId??{type:"body"}}captureState(t){const e=t.getSelection();return{cursorPosition:t.getCursorPosition(),selection:e?{start:e.start,end:e.end}:null}}captureFormattingInRange(t,e,i){const n=new Map,s=t.getFormattingManager();for(let t=0;t<i;t++){const i=s.getFormattingAt(e+t);i&&n.set(t,{...i})}return n}captureFieldsInRange(t,e,i){return t.getSubstitutionFieldManager().getFieldsInRange(e,e+i).map(t=>({offset:t.textIndex-e,field:{...t.field}}))}captureObjectsInRange(t,e,i){const n=[],s=t.getEmbeddedObjects();for(const[t,o]of s)t>=e&&t<e+i&&n.push({offset:t-e,objectData:o.toData()});return n}getParagraphIndexFromBoundaries(t,e){for(let i=0;i<e.length;i++)if(t<e[i])return Math.max(0,i-1);return Math.max(0,e.length-1)}recordMutation(t,e){this.manager.recordMutation(e)}}class Pt{constructor(t){this.observedObjects=new WeakMap,this.manager=t}findPropertyDescriptor(t,e){let i=Object.getPrototypeOf(t);for(;i;){const t=Object.getOwnPropertyDescriptor(i,e);if(t)return t;i=Object.getPrototypeOf(i)}}observe(t){if(this.observedObjects.has(t))return;const e={type:this.getObjectType(t),objectId:t.id},i=this.findPropertyDescriptor(t,"size"),n=this.findPropertyDescriptor(t,"width"),s=this.findPropertyDescriptor(t,"height"),o=this.findPropertyDescriptor(t,"relativeOffset"),r={resize:t.resize.bind(t),sizeSetter:i?.set?.bind(t)||(()=>{}),widthSetter:n?.set?.bind(t)||(()=>{}),heightSetter:s?.set?.bind(t)||(()=>{}),relativeOffsetSetter:o?.set?.bind(t)||(()=>{})},a={sourceId:e,originalMethods:r};t instanceof W&&(a.originalTableMethods={insertRow:t.insertRow.bind(t),removeRow:t.removeRow.bind(t),insertColumn:t.insertColumn.bind(t),removeColumn:t.removeColumn.bind(t),mergeCells:t.mergeCells.bind(t),splitCell:t.splitCell.bind(t)},this.wrapTableMethods(t,a.originalTableMethods)),t instanceof I&&(a.originalImageProperties=this.wrapImageProperties(t)),t instanceof E&&(a.originalTextBoxProperties=this.wrapTextBoxProperties(t)),this.observedObjects.set(t,a),this.wrapCommonMethods(t,r,i,n,s,o)}wrapCommonMethods(t,e,i,n,s,o){t.resize=i=>{if(this.manager.isUndoRedoInProgress)return e.resize(i);const n={...t.size};e.resize(i);const s={...t.size};n.width===s.width&&n.height===s.height||this.recordResizeMutation(t,n,s)},Object.defineProperty(t,"size",{get:i?.get?.bind(t),set:i=>{if(this.manager.isUndoRedoInProgress)return void e.sizeSetter(i);const n={...t.size};e.sizeSetter(i),n.width===i.width&&n.height===i.height||this.recordResizeMutation(t,n,i)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"width",{get:n?.get?.bind(t),set:i=>{if(this.manager.isUndoRedoInProgress)return void e.widthSetter(i);const n={...t.size};e.widthSetter(i),n.width!==i&&this.recordResizeMutation(t,n,{width:i,height:t.height})},configurable:!0,enumerable:!0}),Object.defineProperty(t,"height",{get:s?.get?.bind(t),set:i=>{if(this.manager.isUndoRedoInProgress)return void e.heightSetter(i);const n={...t.size};e.heightSetter(i),n.height!==i&&this.recordResizeMutation(t,n,{width:t.width,height:i})},configurable:!0,enumerable:!0}),Object.defineProperty(t,"relativeOffset",{get:o?.get?.bind(t),set:i=>{if(this.manager.isUndoRedoInProgress)return void e.relativeOffsetSetter(i);const n={...t.relativeOffset};e.relativeOffsetSetter(i),n.x===i.x&&n.y===i.y||this.recordMoveMutation(t,n,i)},configurable:!0,enumerable:!0})}wrapImageProperties(t){const e=this.findPropertyDescriptor(t,"fit"),i=this.findPropertyDescriptor(t,"resizeMode"),n=this.findPropertyDescriptor(t,"alt"),s={fitSetter:e?.set?.bind(t)||(()=>{}),resizeModeSetter:i?.set?.bind(t)||(()=>{}),altSetter:n?.set?.bind(t)||(()=>{})};return Object.defineProperty(t,"fit",{get:e?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void s.fitSetter(e);const i=t.fit;s.fitSetter(e),i!==e&&this.recordPropertyMutation(t,"fit",i,e)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"resizeMode",{get:i?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void s.resizeModeSetter(e);const i=t.resizeMode;s.resizeModeSetter(e),i!==e&&this.recordPropertyMutation(t,"resizeMode",i,e)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"alt",{get:n?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void s.altSetter(e);const i=t.alt;s.altSetter(e),i!==e&&this.recordPropertyMutation(t,"alt",i,e)},configurable:!0,enumerable:!0}),s}wrapTextBoxProperties(t){const e=this.findPropertyDescriptor(t,"fontFamily"),i=this.findPropertyDescriptor(t,"fontSize"),n=this.findPropertyDescriptor(t,"color"),s=this.findPropertyDescriptor(t,"backgroundColor"),o=this.findPropertyDescriptor(t,"border"),r=this.findPropertyDescriptor(t,"padding"),a={fontFamilySetter:e?.set?.bind(t)||(()=>{}),fontSizeSetter:i?.set?.bind(t)||(()=>{}),colorSetter:n?.set?.bind(t)||(()=>{}),backgroundColorSetter:s?.set?.bind(t)||(()=>{}),borderSetter:o?.set?.bind(t)||(()=>{}),paddingSetter:r?.set?.bind(t)||(()=>{})};return Object.defineProperty(t,"fontFamily",{get:e?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void a.fontFamilySetter(e);const i=t.fontFamily;a.fontFamilySetter(e),i!==e&&this.recordPropertyMutation(t,"fontFamily",i,e)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"fontSize",{get:i?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void a.fontSizeSetter(e);const i=t.fontSize;a.fontSizeSetter(e),i!==e&&this.recordPropertyMutation(t,"fontSize",i,e)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"color",{get:n?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void a.colorSetter(e);const i=t.color;a.colorSetter(e),i!==e&&this.recordPropertyMutation(t,"color",i,e)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"backgroundColor",{get:s?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void a.backgroundColorSetter(e);const i=t.backgroundColor;a.backgroundColorSetter(e),i!==e&&this.recordPropertyMutation(t,"backgroundColor",i,e)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"border",{get:o?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void a.borderSetter(e);const i={...t.border};a.borderSetter(e),JSON.stringify(i)!==JSON.stringify(e)&&this.recordPropertyMutation(t,"border",i,e)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"padding",{get:r?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void a.paddingSetter(e);const i=t.padding;a.paddingSetter(e),i!==e&&this.recordPropertyMutation(t,"padding",i,e)},configurable:!0,enumerable:!0}),a}wrapTableMethods(t,e){t.insertRow=(i,n)=>{if(this.manager.isUndoRedoInProgress)return e.insertRow(i,n);const s=this.captureTableSnapshot(t),o=e.insertRow(i,n),r=this.captureTableSnapshot(t);return this.recordTableStructureMutation(t,"table-add-row",s,r),o},t.removeRow=i=>{if(this.manager.isUndoRedoInProgress)return e.removeRow(i);const n=this.captureTableSnapshot(t),s=e.removeRow(i),o=this.captureTableSnapshot(t);return this.recordTableStructureMutation(t,"table-delete-row",n,o),s},t.insertColumn=(i,n)=>{if(this.manager.isUndoRedoInProgress)return e.insertColumn(i,n);const s=this.captureTableSnapshot(t);e.insertColumn(i,n);const o=this.captureTableSnapshot(t);this.recordTableStructureMutation(t,"table-add-column",s,o)},t.removeColumn=i=>{if(this.manager.isUndoRedoInProgress)return e.removeColumn(i);const n=this.captureTableSnapshot(t);e.removeColumn(i);const s=this.captureTableSnapshot(t);this.recordTableStructureMutation(t,"table-delete-column",n,s)},t.mergeCells=i=>{if(this.manager.isUndoRedoInProgress)return e.mergeCells(i);const n=this.captureTableSnapshot(t),s=e.mergeCells(i);if(s.success){const e=this.captureTableSnapshot(t);this.recordTableStructureMutation(t,"table-merge",n,e)}return s},t.splitCell=(i,n)=>{if(this.manager.isUndoRedoInProgress)return e.splitCell(i,n);const s=this.captureTableSnapshot(t),o=e.splitCell(i,n);if(o.success){const e=this.captureTableSnapshot(t);this.recordTableStructureMutation(t,"table-split",s,e)}return o}}unobserve(t){const e=this.observedObjects.get(t);if(!e)return;const{originalMethods:i,originalTableMethods:n,originalImageProperties:s,originalTextBoxProperties:o}=e;t.resize=i.resize;const r=Object.getPrototypeOf(t),a=["size","width","height","relativeOffset"];for(const e of a){const i=Object.getOwnPropertyDescriptor(r,e);i&&Object.defineProperty(t,e,i)}if(n&&t instanceof W&&(t.insertRow=n.insertRow,t.removeRow=n.removeRow,t.insertColumn=n.insertColumn,t.removeColumn=n.removeColumn,t.mergeCells=n.mergeCells,t.splitCell=n.splitCell),s&&t instanceof I){const e=["fit","resizeMode","alt"];for(const i of e){const e=Object.getOwnPropertyDescriptor(r,i);e&&Object.defineProperty(t,i,e)}}if(o&&t instanceof E){const e=["fontFamily","fontSize","color","backgroundColor","border","padding"];for(const i of e){const e=Object.getOwnPropertyDescriptor(r,i);e&&Object.defineProperty(t,i,e)}}this.observedObjects.delete(t)}isObserving(t){return this.observedObjects.has(t)}getObjectType(t){return t instanceof W?"table":t instanceof E?"textbox":t instanceof I?"image":"textbox"}createObjectState(t){return{data:t.toData()}}recordResizeMutation(t,e,i){this.manager.createBoundary();const n={id:Ft(),sourceId:{type:this.getObjectType(t),objectId:t.id},type:"object-resize",timestamp:Date.now(),beforeState:this.createObjectState(t),afterState:this.createObjectState(t),data:{previousSize:e,newSize:i}};this.manager.recordMutation(n)}recordMoveMutation(t,e,i){this.manager.createBoundary();const n={id:Ft(),sourceId:{type:this.getObjectType(t),objectId:t.id},type:"object-move",timestamp:Date.now(),beforeState:this.createObjectState(t),afterState:this.createObjectState(t),data:{previousOffset:e,newOffset:i}};this.manager.recordMutation(n)}recordPropertyMutation(t,e,i,n){this.manager.createBoundary();const s={id:Ft(),sourceId:{type:this.getObjectType(t),objectId:t.id},type:"object-property",timestamp:Date.now(),beforeState:this.createObjectState(t),afterState:this.createObjectState(t),data:{propertyName:e,previousValue:i,newValue:n}};this.manager.recordMutation(s)}recordTableStructureMutation(t,e,i,n){this.manager.createBoundary();const s={id:Ft(),sourceId:{type:"table",objectId:t.id},type:e,timestamp:Date.now(),beforeState:{data:i},afterState:{data:n},data:{beforeSnapshot:i,afterSnapshot:n}};this.manager.recordMutation(s)}captureTableSnapshot(t){return t.toData()}}class Rt{constructor(t,e){this.getContent=t,this.getObject=e}undoMutation(t){switch(t.type){case"insert":this.undoInsert(t);break;case"delete":this.undoDelete(t);break;case"format":this.undoFormat(t);break;case"alignment":this.undoAlignment(t);break;case"field-insert":this.undoFieldInsert(t);break;case"field-update":this.undoFieldUpdate(t);break;case"object-insert":this.undoObjectInsert(t);break;case"object-delete":this.undoObjectDelete(t);break;case"object-resize":this.undoResize(t);break;case"object-move":this.undoMove(t);break;case"object-property":this.undoProperty(t);break;case"table-add-row":case"table-add-column":case"table-delete-row":case"table-delete-column":case"table-merge":case"table-split":this.undoTableStructure(t);break;default:O.warn("[pc-editor:MutationUndo] Unknown mutation type for undo:",t.type)}}redoMutation(t){switch(t.type){case"insert":this.redoInsert(t);break;case"delete":this.redoDelete(t);break;case"format":this.redoFormat(t);break;case"alignment":this.redoAlignment(t);break;case"field-insert":this.redoFieldInsert(t);break;case"field-update":this.redoFieldUpdate(t);break;case"object-insert":this.redoObjectInsert(t);break;case"object-delete":this.redoObjectDelete(t);break;case"object-resize":this.redoResize(t);break;case"object-move":this.redoMove(t);break;case"object-property":this.redoProperty(t);break;case"table-add-row":case"table-add-column":case"table-delete-row":case"table-delete-column":case"table-merge":case"table-split":this.redoTableStructure(t);break;default:O.warn("[pc-editor:MutationUndo] Unknown mutation type for redo:",t.type)}}undoInsert(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.deleteTextAt(i.position,i.text.length)}redoInsert(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;if(e.insertTextAt(i.position,i.text),i.formatting){e.getFormattingManager().applyFormatting(i.position,i.position+i.text.length,i.formatting)}}undoDelete(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;if(e.insertTextAt(i.position,i.deletedText),i.deletedFormatting){const t=e.getFormattingManager();i.deletedFormatting.forEach((e,n)=>{t.setFormattingAt(i.position+n,e,!0)})}if(i.deletedFields){const t=e.getSubstitutionFieldManager();for(const{offset:e,field:n}of i.deletedFields)t.insertAt(i.position+e,n)}}redoDelete(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.deleteTextAt(i.position,i.deletedText.length)}undoFormat(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data,n=e.getFormattingManager();i.previousFormatting.forEach((t,e)=>{n.setFormattingAt(i.start+e,t,!0)})}redoFormat(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.getFormattingManager().applyFormatting(i.start,i.end,i.newFormatting)}undoAlignment(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data,n=e.getParagraphFormattingManager(),s=e.getParagraphBoundaries();i.paragraphIndex<s.length&&n.setAlignment(s[i.paragraphIndex],i.previousAlignment)}redoAlignment(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data,n=e.getParagraphFormattingManager(),s=e.getParagraphBoundaries();i.paragraphIndex<s.length&&n.setAlignment(s[i.paragraphIndex],i.newAlignment)}undoFieldInsert(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.removeSubstitutionField(i.position)}redoFieldInsert(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.setCursorPosition(i.position),e.insertSubstitutionField(i.field.fieldName,{fieldType:i.field.fieldType,displayFormat:i.field.displayFormat,defaultValue:i.field.defaultValue,formatting:i.field.formatting})}undoFieldUpdate(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.getSubstitutionFieldManager().updateFieldConfig(i.textIndex,i.previousData)}redoFieldUpdate(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.getSubstitutionFieldManager().updateFieldConfig(i.textIndex,i.newData)}undoObjectInsert(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.deleteTextAt(i.position,1)}redoObjectInsert(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data,n=i.objectData,s=U.create(n);e.insertEmbeddedObjectAt(s,i.position,s.position)}undoObjectDelete(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data,n=i.objectData,s=U.create(n);e.insertEmbeddedObjectAt(s,i.position,s.position)}redoObjectDelete(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.deleteTextAt(i.position,1)}undoResize(t){const e=this.getObject(t.sourceId);if(!e)return;const i=t.data;e.width=i.previousSize.width,e.height=i.previousSize.height}redoResize(t){const e=this.getObject(t.sourceId);if(!e)return;const i=t.data;e.width=i.newSize.width,e.height=i.newSize.height}undoMove(t){const e=this.getObject(t.sourceId);if(!e)return;const i=t.data;e.relativeOffset=i.previousOffset}redoMove(t){const e=this.getObject(t.sourceId);if(!e)return;const i=t.data;e.relativeOffset=i.newOffset}undoProperty(t){const e=this.getObject(t.sourceId);if(!e)return;const i=t.data;e[i.propertyName]=i.previousValue}redoProperty(t){const e=this.getObject(t.sourceId);if(!e)return;const i=t.data;e[i.propertyName]=i.newValue}undoTableStructure(t){const e=this.getObject(t.sourceId);if(!(e&&e instanceof W))return;const i=t.data;"restoreFromData"in e&&"function"==typeof e.restoreFromData&&e.restoreFromData(i.beforeSnapshot)}redoTableStructure(t){const e=this.getObject(t.sourceId);if(!(e&&e instanceof W))return;const i=t.data;"restoreFromData"in e&&"function"==typeof e.restoreFromData&&e.restoreFromData(i.afterSnapshot)}}class kt{constructor(t,e,i){this.currentFocusedContent=null,this.currentSourceId=null,this.registeredContent=new Map,this.mutationObserver=t,this.document=e,this.focusEventSource=i,this.registerDocumentContent(),this.setupFocusTracking()}registerDocumentContent(){this.registerContent(this.document.bodyFlowingContent,{type:"body"}),this.registerContent(this.document.headerFlowingContent,{type:"header"}),this.registerContent(this.document.footerFlowingContent,{type:"footer"})}setupFocusTracking(){this.focusEventSource.on("tablecell-focused",t=>{if(t.cell&&"flowingContent"in t.cell){const e=t.cell.flowingContent,i={type:"tablecell",objectId:t.table.id,cellAddress:{row:t.row,col:t.col}};this.registerContent(e,i),this.setCurrentFocus(e,i)}}),this.focusEventSource.on("textbox-editing-started",t=>{if(t.textBox){const e=t.textBox.flowingContent,i={type:"textbox",objectId:t.textBox.id};this.registerContent(e,i),this.setCurrentFocus(e,i)}}),this.focusEventSource.on("textbox-editing-ended",()=>{this.clearCurrentFocus()}),this.focusEventSource.on("table-editing-ended",()=>{this.clearCurrentFocus()}),this.focusEventSource.on("section-focused",t=>{const e=this.getContentForSection(t.section);e&&this.setCurrentFocus(e,{type:t.section})})}registerContent(t,e){this.mutationObserver.observe(t,e),this.registeredContent.set(t,e)}unregisterContent(t){this.mutationObserver.unobserve(t),this.registeredContent.delete(t)}setCurrentFocus(t,e){this.currentFocusedContent=t,this.currentSourceId=e}clearCurrentFocus(){this.currentFocusedContent=null,this.currentSourceId=null}getCurrentFocus(){return this.currentFocusedContent&&this.currentSourceId?{content:this.currentFocusedContent,sourceId:this.currentSourceId}:null}getContentForSection(t){switch(t){case"body":return this.document.bodyFlowingContent;case"header":return this.document.headerFlowingContent;case"footer":return this.document.footerFlowingContent}}getContentBySourceId(t){if("body"===t.type)return this.document.bodyFlowingContent;if("header"===t.type)return this.document.headerFlowingContent;if("footer"===t.type)return this.document.footerFlowingContent;for(const[e,i]of this.registeredContent)if(this.sameSourceId(t,i))return e;return null}sameSourceId(t,e){return t.type===e.type&&(t.objectId===e.objectId&&(t.cellAddress&&e.cellAddress?t.cellAddress.row===e.cellAddress.row&&t.cellAddress.col===e.cellAddress.col:t.cellAddress===e.cellAddress))}registerObject(t){if(t instanceof E){const e=t.flowingContent,i={type:"textbox",objectId:t.id};this.registerContent(e,i)}t instanceof W&&this.registerTableCells(t)}registerTableCells(t){const e=t.rowCount,i=t.columnCount;for(let n=0;n<e;n++)for(let e=0;e<i;e++){const i=t.getCell(n,e);if(i&&"flowingContent"in i){const s=i.flowingContent,o={type:"tablecell",objectId:t.id,cellAddress:{row:n,col:e}};this.registerContent(s,o)}}}unregisterObject(t){t instanceof E&&this.unregisterContent(t.flowingContent),t instanceof W&&this.unregisterTableCells(t)}unregisterTableCells(t){const e=t.rowCount,i=t.columnCount;for(let n=0;n<e;n++)for(let e=0;e<i;e++){const i=t.getCell(n,e);if(i&&"flowingContent"in i){const t=i.flowingContent;this.unregisterContent(t)}}}clear(){for(const t of this.registeredContent.keys())this.mutationObserver.unobserve(t);this.registeredContent.clear(),this.currentFocusedContent=null,this.currentSourceId=null}}const Mt="application/x-pceditor-content";class Et{toHtml(t){const{text:e,formattingRuns:i}=t;if(!e)return"";if(!i||0===i.length)return this.escapeHtml(e).replace(/\n/g,"<br>");let n="",s=0;for(let t=0;t<e.length;t++){const o=e[t];if(s<i.length&&i[s].index===t){t>0&&(n+="</span>");const e=i[s].formatting;n+=this.createStyledSpan(e),s++}else 0===t&&(0===i.length||i[0].index>0)&&(n+="<span>");n+="\n"===o?"<br>":""===o?'<span data-object="true">[Object]</span>':this.escapeHtml(o)}return e.length>0&&(n+="</span>"),n}fromHtml(t){const e=(new DOMParser).parseFromString(t,"text/html").body,i={text:"",runs:[]};return this.processNode(e,i,null),{text:i.text,formattingRuns:i.runs.length>0?i.runs:void 0}}processNode(t,e,i){if(t.nodeType===Node.TEXT_NODE){const n=t.textContent||"";if(n&&i){const t=e.runs[e.runs.length-1];t&&this.formattingEquals(t.formatting,i)||e.runs.push({index:e.text.length,formatting:i})}return void(e.text+=n)}if(t.nodeType!==Node.ELEMENT_NODE)return;const n=t,s=n.tagName.toLowerCase();if(["p","div","h1","h2","h3","h4","h5","h6","li"].includes(s)&&e.text.length>0&&!e.text.endsWith("\n")&&(e.text+="\n"),"br"===s)return void(e.text+="\n");const o=this.extractFormatting(n,i);for(const i of Array.from(t.childNodes))this.processNode(i,e,o);["p","div","h1","h2","h3","h4","h5","h6","li","tr"].includes(s)&&(e.text.endsWith("\n")||(e.text+="\n"))}extractFormatting(t,e){const i=t.tagName.toLowerCase(),n=t.style,s=e?{...e}:{fontFamily:"Arial",fontSize:12,color:"#000000"};if("b"!==i&&"strong"!==i||(s.fontWeight="bold"),"i"!==i&&"em"!==i||(s.fontStyle="italic"),n.fontFamily&&(s.fontFamily=n.fontFamily.replace(/['"]/g,"").split(",")[0].trim()),n.fontSize){const t=parseFloat(n.fontSize);isNaN(t)||(s.fontSize=n.fontSize.includes("pt")?t:Math.round(.75*t))}return("bold"===n.fontWeight||parseInt(n.fontWeight)>=700)&&(s.fontWeight="bold"),"italic"===n.fontStyle&&(s.fontStyle="italic"),n.color&&(s.color=this.normalizeColor(n.color)),n.backgroundColor&&(s.backgroundColor=this.normalizeColor(n.backgroundColor)),s}formattingEquals(t,e){return t.fontFamily===e.fontFamily&&t.fontSize===e.fontSize&&t.fontWeight===e.fontWeight&&t.fontStyle===e.fontStyle&&t.color===e.color&&t.backgroundColor===e.backgroundColor}createStyledSpan(t){const e=[];return t.fontFamily&&e.push(`font-family: ${t.fontFamily}`),t.fontSize&&e.push(`font-size: ${t.fontSize}pt`),t.fontWeight&&e.push(`font-weight: ${t.fontWeight}`),t.fontStyle&&e.push(`font-style: ${t.fontStyle}`),t.color&&e.push(`color: ${t.color}`),t.backgroundColor&&e.push(`background-color: ${t.backgroundColor}`),`<span style="${e.join("; ")}">`}escapeHtml(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}normalizeColor(t){const e=t.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(e){return`#${parseInt(e[1]).toString(16).padStart(2,"0")}${parseInt(e[2]).toString(16).padStart(2,"0")}${parseInt(e[3]).toString(16).padStart(2,"0")}`}return t}}class At extends o{constructor(){super(),this.cachedClipboardData=null,this.htmlConverter=new Et}async copy(t,e={}){const{includePlainText:i=!0,includeHtml:n=!0}=e,s=t.getSelection();if(!s||s.start===s.end)return!1;const o=this.extractSelectionContent(t,s.start,s.end),r={},a=JSON.stringify(o);if(r[Mt]=new Blob([a],{type:Mt}),i){const t=this.extractPlainText(o.content.text);r["text/plain"]=new Blob([t],{type:"text/plain"})}if(n){const t=this.htmlConverter.toHtml(o.content);r["text/html"]=new Blob([t],{type:"text/html"})}try{return await navigator.clipboard.write([new ClipboardItem(r)]),this.emit("copy",{success:!0,contentType:o.type}),!0}catch(t){try{const t=this.extractPlainText(o.content.text);return await navigator.clipboard.writeText(t),this.cachedClipboardData=o,this.emit("copy",{success:!0,contentType:o.type,fallback:!0}),!0}catch(t){return console.error("Clipboard write failed:",t),this.emit("copy",{success:!1,error:t}),!1}}}async read(t={}){const{preferredFormat:e,asPlainText:i=!1}=t;if(i)try{return{type:"text",data:await navigator.clipboard.readText()}}catch{return{type:"empty",data:null}}try{const t=await navigator.clipboard.read();for(const i of t){if(i.types.includes(Mt)&&"html"!==e&&"text"!==e){const t=await i.getType(Mt),e=await t.text();return{type:"pceditor",data:JSON.parse(e)}}for(const t of i.types)if(t.startsWith("image/")){return{type:"image",data:await i.getType(t)}}if(i.types.includes("text/html")&&"text"!==e){const t=await i.getType("text/html");return{type:"html",data:await t.text()}}if(i.types.includes("text/plain")){const t=await i.getType("text/plain"),e=await t.text();return this.cachedClipboardData&&this.extractPlainText(this.cachedClipboardData.content.text)===e?{type:"pceditor",data:this.cachedClipboardData}:{type:"text",data:e}}}return{type:"empty",data:null}}catch(t){try{const t=await navigator.clipboard.readText();return this.cachedClipboardData&&this.extractPlainText(this.cachedClipboardData.content.text)===t?{type:"pceditor",data:this.cachedClipboardData}:{type:"text",data:t}}catch{return{type:"empty",data:null}}}}extractSelectionContent(t,e,i){const n=t.getText().substring(e,i);let s="text";const o=n.includes("");o&&""===n.replace(/\uFFFC/g,"").trim()?s="object":o&&(s="mixed");const r=this.extractFormattingRuns(t,e,i),a=this.extractParagraphFormatting(t,e,i),l=this.extractSubstitutionFields(t,e,i),h=this.extractEmbeddedObjects(t,e,i),d=this.extractHyperlinks(t,e,i);return{version:"1.0.0",type:s,content:{text:n,formattingRuns:r.length>0?r:void 0,paragraphFormatting:a.length>0?a:void 0,substitutionFields:l.length>0?l:void 0,embeddedObjects:h.length>0?h:void 0,hyperlinks:d.length>0?d:void 0},metadata:{copiedAt:(new Date).toISOString()}}}extractFormattingRuns(t,e,i){const n=[],s=t.getFormattingManager(),o=s.defaultFormatting;let r=null;for(let t=e;t<i;t++){const i=s.getFormattingAt(t);if(null===r||i.fontFamily!==r.fontFamily||i.fontSize!==r.fontSize||i.fontWeight!==r.fontWeight||i.fontStyle!==r.fontStyle||i.color!==r.color||i.backgroundColor!==r.backgroundColor){(!(i.fontFamily===o.fontFamily&&i.fontSize===o.fontSize&&i.fontWeight===o.fontWeight&&i.fontStyle===o.fontStyle&&i.color===o.color&&i.backgroundColor===o.backgroundColor)||n.length>0)&&n.push({index:t-e,formatting:{fontFamily:i.fontFamily,fontSize:i.fontSize,fontWeight:i.fontWeight,fontStyle:i.fontStyle,color:i.color,backgroundColor:i.backgroundColor}}),r=i}}return n}extractParagraphFormatting(t,e,i){const n=t.getText(),s=t.getParagraphFormattingManager(),o=[],r=new Set;for(let t=e;t<i;t++){const i=s.getParagraphStart(t,n);if(!r.has(i)&&i>=e){r.add(i);const t=s.getFormattingForParagraph(i);o.push({paragraphStart:i-e,formatting:{alignment:t.alignment}})}}const a=s.getParagraphStart(e,n);if(a<e&&!r.has(a)){const t=s.getFormattingForParagraph(a);o.unshift({paragraphStart:0,formatting:{alignment:t.alignment}})}return o}extractSubstitutionFields(t,e,i){return t.getSubstitutionFieldsInRange(e,i).map(t=>({id:t.id,textIndex:t.textIndex-e,fieldName:t.fieldName,fieldType:t.fieldType,displayFormat:t.displayFormat,defaultValue:t.defaultValue,formatting:t.formatting?{fontFamily:t.formatting.fontFamily,fontSize:t.formatting.fontSize,fontWeight:t.formatting.fontWeight,fontStyle:t.formatting.fontStyle,color:t.formatting.color,backgroundColor:t.formatting.backgroundColor}:void 0}))}extractEmbeddedObjects(t,e,i){return t.getEmbeddedObjectsInRange(e,i).map(({textIndex:t,object:i})=>({textIndex:t-e,object:i.toData()}))}extractHyperlinks(t,e,i){return t.getHyperlinksInRange(e,i).map(t=>{const n=Math.max(t.startIndex,e)-e,s=Math.min(t.endIndex,i)-e;return{id:t.id,url:t.url,startIndex:n,endIndex:s,title:t.title,formatting:t.formatting}})}extractPlainText(t){return t.replace(/\uFFFC/g," ").replace(/\s+/g," ").trim()||t.replace(/\uFFFC/g,"")}parseHtml(t){return this.htmlConverter.fromHtml(t)}generateNewIds(t){const e=new Map,i=t=>`${t}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,n={text:t.text,formattingRuns:t.formattingRuns,paragraphFormatting:t.paragraphFormatting};return t.substitutionFields&&(n.substitutionFields=t.substitutionFields.map(t=>{const n=i("field");return e.set(t.id,n),{...t,id:n}})),t.embeddedObjects&&(n.embeddedObjects=t.embeddedObjects.map(t=>{const n=i("obj");return e.set(t.object.id,n),{textIndex:t.textIndex,object:{...t.object,id:n}}})),t.hyperlinks&&(n.hyperlinks=t.hyperlinks.map(t=>{const n=i("link");return e.set(t.id,n),{...t,id:n}})),n}async createImageFromBlob(t){return new Promise((e,i)=>{const n=new FileReader;n.onload=()=>{const t=n.result,s=new Image;s.onload=()=>{e({dataUrl:t,width:s.naturalWidth,height:s.naturalHeight})},s.onerror=i,s.src=t},n.onerror=i,n.readAsDataURL(t)})}}const Lt={detectTables:!0,extractImages:!0,tableConfidenceThreshold:.7,password:""};var Bt;t.PDFImportErrorCode=void 0,(Bt=t.PDFImportErrorCode||(t.PDFImportErrorCode={})).INVALID_PDF="INVALID_PDF",Bt.ENCRYPTED_PDF="ENCRYPTED_PDF",Bt.PASSWORD_REQUIRED="PASSWORD_REQUIRED",Bt.INCORRECT_PASSWORD="INCORRECT_PASSWORD",Bt.EXTRACTION_FAILED="EXTRACTION_FAILED",Bt.IMAGE_EXTRACTION_FAILED="IMAGE_EXTRACTION_FAILED",Bt.PARSING_ERROR="PARSING_ERROR",Bt.UNSUPPORTED_FEATURE="UNSUPPORTED_FEATURE";class zt extends Error{constructor(t,e,i){super(t),this.code=e,this.details=i,this.name="PDFImportError"}}"undefined"!=typeof window&&(s.GlobalWorkerOptions.workerSrc=`//cdnjs.cloudflare.com/ajax/libs/pdf.js/${s.version}/pdf.worker.min.js`);class Ot{async parse(e,i){let n;try{const t=s.getDocument({data:e,password:i||void 0});n=await t.promise}catch(e){const i=e;if("PasswordException"===i.name)throw i.message?.includes("need a password")?new zt("This PDF is encrypted and requires a password",t.PDFImportErrorCode.PASSWORD_REQUIRED):new zt("Incorrect password for encrypted PDF",t.PDFImportErrorCode.INCORRECT_PASSWORD);throw new zt("Failed to load PDF document",t.PDFImportErrorCode.INVALID_PDF,e)}try{const t=[];for(let e=1;e<=n.numPages;e++){const i=await n.getPage(e),s=await this.extractPage(i,e);t.push(s)}const e=await this.extractMetadata(n);return{pageCount:n.numPages,pages:t,metadata:e}}catch(e){throw new zt("Failed to extract content from PDF",t.PDFImportErrorCode.EXTRACTION_FAILED,e)}finally{await n.destroy()}}async extractPage(t,e){const i=t.getViewport({scale:1}),n=await t.getTextContent(),s=[];for(const t of n.items)if("str"in t&&t.str){const e=this.convertTextItem(t,i.height);e.text.trim()&&s.push(e)}const o=await this.extractImages(t,i.height);return{pageNumber:e,width:i.width,height:i.height,textItems:s,images:o}}convertTextItem(t,e){const i=t.transform,[n,s,,,o,r]=i,a=Math.sqrt(n*n+s*s),l=this.parseFontName(t.fontName);return{text:t.str,x:o,y:e-r,width:t.width,height:t.height,fontName:t.fontName,fontSize:Math.round(10*a)/10,fontWeight:l.fontWeight,fontStyle:l.fontStyle,transform:i}}parseFontName(t){const e=t.toLowerCase();return{fontWeight:/bold|black|heavy|semibold|demibold/i.test(e)?"bold":"normal",fontStyle:/italic|oblique/i.test(e)?"italic":"normal"}}async extractImages(t,e){const i=[];try{const n=await t.getOperatorList(),o=t.commonObjs,r=t.objs,a=[[1,0,0,1,0,0]];for(let t=0;t<n.fnArray.length;t++){const l=n.fnArray[t],h=n.argsArray[t];if(l===s.OPS.save)a.push([...a[a.length-1]]);else if(l===s.OPS.restore)a.length>1&&a.pop();else if(l===s.OPS.transform){const t=a[a.length-1],e=this.multiplyTransforms(t,h);a[a.length-1]=e}else if(l===s.OPS.paintImageXObject){const t=h[0];try{let n=null;if(r.has(t)?n=r.get(t):o.has(t)&&(n=o.get(t)),n&&n.width&&n.height){const t=a[a.length-1],s=Math.abs(t[0])||n.width,o=Math.abs(t[3])||n.height,r=t[4],l=e-t[5]-o;if(n.data){const t=this.imageDataToDataUrl(n.data,n.width,n.height);t&&i.push({x:r,y:l,width:s,height:o,dataUrl:t,mimeType:"image/png"})}}}catch{O.warn(`[pc-editor:PDFParser] Failed to extract image: ${t}`)}}}}catch(t){O.warn("[pc-editor:PDFParser] Image extraction failed:",t)}return i}multiplyTransforms(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}imageDataToDataUrl(t,e,i){try{const n=document.createElement("canvas");n.width=e,n.height=i;const s=n.getContext("2d");if(!s)return null;const o=new Uint8ClampedArray(t.length);o.set(t);const r=new ImageData(o,e,i);return s.putImageData(r,0,0),n.toDataURL("image/png")}catch{return null}}async extractMetadata(t){try{const e=(await t.getMetadata()).info;if(!e)return;return{title:e.Title,author:e.Author,subject:e.Subject,keywords:e.Keywords,creationDate:e.CreationDate?this.parseDate(e.CreationDate):void 0,modificationDate:e.ModDate?this.parseDate(e.ModDate):void 0}}catch{return}}parseDate(t){try{const e=t.match(/D:(\d{4})(\d{2})(\d{2})(\d{2})?(\d{2})?(\d{2})?/);if(!e)return;const[,i,n,s,o="00",r="00",a="00"]=e;return new Date(parseInt(i),parseInt(n)-1,parseInt(s),parseInt(o),parseInt(r),parseInt(a))}catch{return}}}class jt{constructor(t){this.options={...Lt,...t}}analyze(t,e){e&&(this.options={...this.options,...e});const i=[],n=[],s=[],o=t.pages[0],r=this.analyzePageLayout(o);for(const e of t.pages){const t=this.groupIntoLines(e.textItems);let o=[];if(this.options.detectTables){o=this.detectTables(t,e.pageNumber);for(const t of o)t.table.confidence>=this.options.tableConfidenceThreshold&&s.push(t.table)}const a=this.groupIntoParagraphs(t,e.pageNumber,r,o);if(i.push(...a),this.options.extractImages){const t=this.analyzeImages(e.images,e.pageNumber);n.push(...t)}}return{paragraphs:i,images:n,tables:s,pageInfo:r}}analyzePageLayout(t){if(0===t.textItems.length)return{width:t.width,height:t.height,margins:{top:72,right:72,bottom:72,left:72}};const e=Math.min(...t.textItems.map(t=>t.x)),i=Math.max(...t.textItems.map(t=>t.x+t.width)),n=Math.min(...t.textItems.map(t=>t.y)),s=Math.max(...t.textItems.map(t=>t.y+t.height));return{width:t.width,height:t.height,margins:{left:Math.max(0,e),right:Math.max(0,t.width-i),top:Math.max(0,n),bottom:Math.max(0,t.height-s)}}}groupIntoLines(t){if(0===t.length)return[];const e=[...t].sort((t,e)=>t.y-e.y||t.x-e.x),i=[];let n=[e[0]],s=e[0].y;const o=t=>.5*t.fontSize;for(let t=1;t<e.length;t++){const r=e[t],a=o(r);Math.abs(r.y-s)<=a?n.push(r):(i.push(this.createLine(n)),n=[r],s=r.y)}return n.length>0&&i.push(this.createLine(n)),i}createLine(t){return t.sort((t,e)=>t.x-e.x),{items:t,y:t[0].y,minX:Math.min(...t.map(t=>t.x)),maxX:Math.max(...t.map(t=>t.x+t.width)),height:Math.max(...t.map(t=>t.height))}}groupIntoParagraphs(t,e,i,n){if(0===t.length)return[];const s=[];let o=[];const r=[];for(let e=1;e<t.length;e++)r.push(t[e].y-t[e-1].y);const a=r.length>0?r.reduce((t,e)=>t+e,0)/r.length:20,l=t=>n.some(e=>t>=e.startLine&&t<=e.endLine);for(let n=0;n<t.length;n++){if(l(n)){o.length>0&&(s.push(this.createParagraph(o,e,i)),o=[]);continue}const r=t[n];if(0===o.length){o.push(r);continue}const h=o[o.length-1],d=r.y-h.y>1.5*a,c=Math.abs(r.minX-h.minX);d||c>20?(s.push(this.createParagraph(o,e,i)),o=[r]):o.push(r)}return o.length>0&&s.push(this.createParagraph(o,e,i)),s}createParagraph(t,e,i){const n=[],s=[];let o=0;for(let e=0;e<t.length;e++){const i=t[e];for(const t of i.items){if(o>0){const t=n[n.length-1];t&&!t.endsWith(" ")&&(n.push(" "),o++)}const e=o;n.push(t.text),o+=t.text.length;const i=this.mapFormatting(t);s.push({startIndex:e,endIndex:o,formatting:i})}e<t.length-1&&(n.push(" "),o++)}const r=this.mergeFormattingRuns(s),a=this.detectAlignment(t,i);return{text:n.join(""),formattingRuns:r,alignment:a,pageNumber:e,y:t[0].y,endsWithNewline:!0}}mapFormatting(t){return{fontFamily:this.mapFontFamily(t.fontName),fontSize:Math.round(t.fontSize),fontWeight:t.fontWeight||"normal",fontStyle:t.fontStyle||"normal",color:t.color?`#${t.color.r.toString(16).padStart(2,"0")}${t.color.g.toString(16).padStart(2,"0")}${t.color.b.toString(16).padStart(2,"0")}`:"#000000"}}mapFontFamily(t){const e={helvetica:"Arial",arial:"Arial",times:"Times New Roman",timesnewroman:"Times New Roman",courier:"Courier New",couriernew:"Courier New",georgia:"Georgia",verdana:"Verdana",tahoma:"Tahoma",trebuchet:"Trebuchet MS",impact:"Impact",comic:"Comic Sans MS"},i=t.toLowerCase().replace(/[-_,.\s]/g,"").replace(/(bold|italic|oblique|regular|medium|light|black|heavy)/gi,"");for(const[t,n]of Object.entries(e))if(i.includes(t))return n;return"Arial"}mergeFormattingRuns(t){if(0===t.length)return[];const e=[t[0]];for(let i=1;i<t.length;i++){const n=t[i],s=e[e.length-1];this.isFormattingEqual(s.formatting,n.formatting)?s.endIndex=n.endIndex:e.push(n)}return e}isFormattingEqual(t,e){return t.fontFamily===e.fontFamily&&t.fontSize===e.fontSize&&t.fontWeight===e.fontWeight&&t.fontStyle===e.fontStyle&&t.color===e.color}detectAlignment(t,e){if(0===t.length)return"left";const i=e.width-e.margins.left-e.margins.right;let n=0,s=0,o=0,r=0;for(const a of t){const t=a.maxX-a.minX,l=Math.abs(a.minX-e.margins.left),h=Math.abs(e.width-e.margins.right-a.maxX),d=Math.abs(a.minX+t/2-e.width/2);t>.9*i&&l<10&&h<10?r++:d<20?o++:h<10&&l>30?s++:n++}const a=Math.max(n,s,o,r);return r===a&&r>0?"justify":o===a?"center":s===a?"right":"left"}detectTables(t,e){const i=[],n=this.detectColumnBoundaries(t);if(n.length<2)return i;let s=-1,o=[];for(let r=0;r<t.length;r++){const a=t[r];if(this.countColumnsUsed(a,n)>=2)-1===s&&(s=r),o.push(a);else{if(o.length>=2){const t=this.createTable(o,n,e);t.confidence>=this.options.tableConfidenceThreshold&&i.push({startLine:s,endLine:r-1,table:t})}s=-1,o=[]}}if(o.length>=2){const r=this.createTable(o,n,e);r.confidence>=this.options.tableConfidenceThreshold&&i.push({startLine:s,endLine:t.length-1,table:r})}return i}detectColumnBoundaries(t){const e=new Map;for(const i of t)for(const t of i.items){const i=5*Math.round(t.x/5);e.set(i,(e.get(i)||0)+1)}const i=Math.max(2,.3*t.length),n=Array.from(e.entries()).filter(([,t])=>t>=i).map(([t])=>t).sort((t,e)=>t-e),s=[];for(const t of n)(0===s.length||t-s[s.length-1]>=30)&&s.push(t);return s}countColumnsUsed(t,e){const i=new Set;for(const n of t.items)for(let t=0;t<e.length;t++){const s=e[t],o=e[t+1]??1/0;if(n.x>=s-15&&n.x<o){i.add(t);break}}return i.size}createTable(t,e,i){const n=[];for(const i of t){const t=e.map(()=>({text:"",items:[]}));for(const n of i.items)for(let i=0;i<e.length;i++){const s=e[i],o=e[i+1]??1/0;if(n.x>=s-15&&n.x<o){t[i].text&&(t[i].text+=" "),t[i].text+=n.text,t[i].items.push(n);break}}n.push({cells:t.map(t=>({text:t.text.trim(),formattingRuns:t.items.length>0?[{startIndex:0,endIndex:t.text.length,formatting:this.mapFormatting(t.items[0])}]:[]}))})}const s=e.map((t,i)=>{const n=e[i+1];return n?n-t:100});let o=0,r=0;for(const t of n)for(const e of t.cells)r++,e.text.length>0&&o++;const a=r>0?o/r:0;return{rows:n,columnWidths:s,pageNumber:i,y:t[0].y,confidence:a}}analyzeImages(t,e){return t.map(t=>({dataUrl:t.dataUrl,width:t.width,height:t.height,pageNumber:e,y:t.y,position:t.width>200?"block":"inline"}))}}class Dt{constructor(){this.nextObjectId=1}build(t,e){const i=this.buildFlowingContent(t);return{version:"1.0",pages:this.createPages(e),settings:this.createSettings(t.pageInfo),bodyContent:i,headerContent:this.createEmptyContent(),footerContent:this.createEmptyContent()}}buildFlowingContent(t){const e=[];for(const i of t.paragraphs)e.push({type:"paragraph",pageNumber:i.pageNumber,y:i.y,data:i});for(const i of t.images)e.push({type:"image",pageNumber:i.pageNumber,y:i.y,data:i});for(const i of t.tables)e.push({type:"table",pageNumber:i.pageNumber,y:i.y,data:i});e.sort((t,e)=>t.pageNumber!==e.pageNumber?t.pageNumber-e.pageNumber:t.y-e.y);let i="";const n=[],s=[],o=[];let r=1;for(const t of e){if(t.pageNumber>r)for(;r<t.pageNumber;)i+=c,r++;if("paragraph"===t.type){const e=t.data,o=i.length;s.push({paragraphStart:o,alignment:e.alignment});for(const t of e.formattingRuns)n.push({index:o+t.startIndex,formatting:t.formatting});i+=e.text,e.endsWithNewline&&(i+="\n")}else if("image"===t.type){const e=t.data,n=i.length,s={id:"imported-image-"+this.nextObjectId++,objectType:"image",textIndex:n,position:e.position,size:{width:e.width,height:e.height},data:{src:e.dataUrl,alt:"Imported image"}};o.push({textIndex:n,object:s}),i+=d,"block"===e.position&&(i+="\n")}else if("table"===t.type){const e=t.data,n=i.length,s={id:"imported-table-"+this.nextObjectId++,objectType:"table",textIndex:n,position:"block",size:{width:e.columnWidths.reduce((t,e)=>t+e,0),height:30*e.rows.length},data:{rows:e.rows.length,columns:e.columnWidths.length,columnWidths:e.columnWidths,cells:this.buildTableCells(e)}};o.push({textIndex:n,object:s}),i+=d,i+="\n"}}return{text:i,formattingRuns:this.convertFormattingRuns(n),paragraphFormatting:this.convertParagraphFormatting(s),substitutionFields:[],embeddedObjects:o,repeatingSections:[],hyperlinks:[]}}buildTableCells(t){const e=[];for(let i=0;i<t.rows.length;i++){const n=t.rows[i];for(let t=0;t<n.cells.length;t++){const s=n.cells[t],o=[];s.formattingRuns.length>0&&o.push({index:0,formatting:{fontFamily:s.formattingRuns[0].formatting.fontFamily||l.fontFamily,fontSize:s.formattingRuns[0].formatting.fontSize||l.fontSize,fontWeight:s.formattingRuns[0].formatting.fontWeight,fontStyle:s.formattingRuns[0].formatting.fontStyle,color:s.formattingRuns[0].formatting.color||l.color}}),e.push({row:i,col:t,content:{text:s.text,formattingRuns:o,paragraphFormatting:[],substitutionFields:[],embeddedObjects:[],repeatingSections:[],hyperlinks:[]}})}}return e}convertFormattingRuns(t){return t.map(t=>({index:t.index,formatting:{fontFamily:t.formatting.fontFamily||l.fontFamily,fontSize:t.formatting.fontSize||l.fontSize,fontWeight:t.formatting.fontWeight,fontStyle:t.formatting.fontStyle,color:t.formatting.color||l.color,backgroundColor:t.formatting.backgroundColor}}))}convertParagraphFormatting(t){return t.map(t=>({paragraphStart:t.paragraphStart,formatting:{alignment:t.alignment}}))}createPages(t){const e=[];for(let i=0;i<t;i++)e.push({id:`imported-page-${i+1}`});return e}createSettings(t){let e="A4";const i=t.width,n=t.height;Math.abs(i-612)<10&&Math.abs(n-792)<10?e="Letter":Math.abs(i-612)<10&&Math.abs(n-1008)<10?e="Legal":Math.abs(i-842)<10&&Math.abs(n-1191)<10&&(e="A3");const s=.352778;return{pageSize:e,pageOrientation:i>n?"landscape":"portrait",margins:{top:Math.round(t.margins.top*s),right:Math.round(t.margins.right*s),bottom:Math.round(t.margins.bottom*s),left:Math.round(t.margins.left*s)},units:"mm"}}createEmptyContent(){return{text:"",formattingRuns:[],paragraphFormatting:[],substitutionFields:[],embeddedObjects:[],repeatingSections:[],hyperlinks:[]}}}class Ht{constructor(){this.parser=new Ot,this.analyzer=new jt,this.builder=new Dt}async import(e,i={},n){const s={...Lt,...i},o=[];try{n?.({stage:"parsing",progress:0,message:"Loading PDF document..."});const t=await this.parser.parse(e,s.password);n?.({stage:"parsing",progress:100,message:"PDF parsed successfully"}),n?.({stage:"analyzing",progress:0,message:"Analyzing document structure..."});const i=this.analyzer.analyze(t,{detectTables:s.detectTables,extractImages:s.extractImages,tableConfidenceThreshold:s.tableConfidenceThreshold});if(i.tables.length>0){const t=i.tables.filter(t=>t.confidence<.8);t.length>0&&o.push(`${t.length} table(s) detected with low confidence - please verify structure`)}n?.({stage:"analyzing",progress:100,message:"Content analysis complete"}),n?.({stage:"building",progress:0,message:"Building document..."});const r=this.builder.build(i,t.pageCount);return n?.({stage:"building",progress:100,message:"Document built successfully"}),{document:r,warnings:o,metadata:{title:t.metadata?.title,author:t.metadata?.author,pageCount:t.pageCount}}}catch(e){if(e instanceof zt)throw e;throw new zt("Failed to import PDF document",t.PDFImportErrorCode.PARSING_ERROR,e)}}async importFile(e,i={},n){if(!e.type.includes("pdf")&&!e.name.toLowerCase().endsWith(".pdf"))throw new zt("Invalid file type. Please select a PDF file.",t.PDFImportErrorCode.INVALID_PDF);const s=await e.arrayBuffer();return this.import(s,i,n)}async importUrl(e,i={},n){try{const s=await fetch(e);if(!s.ok)throw new zt(`Failed to fetch PDF: ${s.statusText}`,t.PDFImportErrorCode.INVALID_PDF);const o=await s.arrayBuffer();return this.import(o,i,n)}catch(e){if(e instanceof zt)throw e;throw new zt("Failed to fetch PDF from URL",t.PDFImportErrorCode.INVALID_PDF,e)}}}class Nt extends o{constructor(t,e={}){super(),this._isAttached=!1,this._isVisible=!0,this.editor=null,this.container=null,this.element=null,this.eventCleanup=[],this.id=t,this._isVisible=!1!==e.visible}get isAttached(){return this._isAttached}get isVisible(){return this._isVisible}attach(t){if(this._isAttached)throw new Error(`Control ${this.id} is already attached`);this.editor=t.editor,this.container=t.container,this.element=this.createElement(),this.container.appendChild(this.element),this.setupEventListeners(),this._isAttached=!0,this.update(),this._isVisible||(this.element.style.display="none"),this.emit("attached",{editor:this.editor})}detach(){this._isAttached&&(this.cleanupEventListeners(),this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this._isAttached=!1,this.editor=null,this.container=null,this.element=null,this.emit("detached",void 0))}show(){this._isVisible=!0,this.element&&(this.element.style.display="",this.update()),this.emit("visibility-changed",{visible:!0})}hide(){this._isVisible=!1,this.element&&(this.element.style.display="none"),this.emit("visibility-changed",{visible:!1})}toggle(){this._isVisible?this.hide():this.show()}destroy(){this.detach(),this.removeAllListeners()}setupEventListeners(){}cleanupEventListeners(){for(const t of this.eventCleanup)t();this.eventCleanup=[]}addEditorListener(t,e){this.editor&&(this.editor.on(t,e),this.eventCleanup.push(()=>this.editor?.off(t,e)))}}const Wt={visible:!0,units:"mm",majorTickInterval:10,minorTicksPerMajor:10,showLabels:!0,thickness:20,backgroundColor:"#f5f5f5",tickColor:"#666666",labelColor:"#333333",activeColor:"#2196f3",labelFontSize:9,showMargins:!0,marginColor:"#666666"},Gt={px:1,pt:96/72,mm:96/25.4,in:96};function Ut(t){return Gt[t]}class $t extends Nt{constructor(t,e={}){super(t,e),this.canvas=null,this.ctx=null,this.currentMousePosition=null,this.zoomLevel=1,this.scrollOffset=0,this.documentSize=0,this.marginStart=0,this.marginEnd=0,this.resizeObserver=null,this.options={...Wt,...e}}createElement(){const t=document.createElement("div");t.className=`pc-ruler pc-ruler-${this.orientation}`,t.style.position="absolute",t.style.overflow="hidden",t.style.backgroundColor=this.options.backgroundColor,"horizontal"===this.orientation?(t.style.height=`${this.options.thickness}px`,t.style.width="100%",t.style.top="0",t.style.left="0",t.style.right="0"):(t.style.width=`${this.options.thickness}px`,t.style.top="0",t.style.bottom="0",t.style.left="0"),this.canvas=document.createElement("canvas"),this.canvas.style.display="block",t.appendChild(this.canvas),this.setupMouseTracking(t),this.resizeObserver=new ResizeObserver(()=>{this.resizeCanvas(),this.render()}),this.resizeObserver.observe(t);const e=()=>{this.update()};return window.addEventListener("resize",e),this.eventCleanup.push(()=>{window.removeEventListener("resize",e)}),t}setupMouseTracking(t){const e=e=>{const i=t.getBoundingClientRect();"horizontal"===this.orientation?this.currentMousePosition=e.clientX-i.left:this.currentMousePosition=e.clientY-i.top,this.render()},i=()=>{this.currentMousePosition=null,this.render()};t.addEventListener("mousemove",e),t.addEventListener("mouseleave",i),this.eventCleanup.push(()=>{t.removeEventListener("mousemove",e),t.removeEventListener("mouseleave",i)})}setupEventListeners(){super.setupEventListeners(),this.addEditorListener("zoom-changed",t=>{this.zoomLevel=t.zoom,this.update()}),this.addEditorListener("settings-changed",()=>{this.update()}),this.addEditorListener("scroll",t=>{this.scrollOffset="horizontal"===this.orientation?t.x:t.y,this.update()}),this.addEditorListener("mouse-move",t=>{this.currentMousePosition="horizontal"===this.orientation?t.x:t.y,this.render()}),this.addEditorListener("mouse-leave",()=>{this.currentMousePosition=null,this.render()})}cleanupEventListeners(){super.cleanupEventListeners(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null)}update(){if(!this._isAttached||!this._isVisible||!this.editor)return;this.zoomLevel=this.editor.getZoomLevel();const t=this.editor.getDocumentMetrics();t&&this.updateFromMetrics(t),this.resizeCanvas(),this.render()}resizeCanvas(){if(!this.canvas||!this.element)return;const t=this.element.getBoundingClientRect();if(0===t.width&&0===t.height)return;const e=window.devicePixelRatio||1;"horizontal"===this.orientation?(this.canvas.width=t.width*e,this.canvas.height=this.options.thickness*e,this.canvas.style.width=`${t.width}px`,this.canvas.style.height=`${this.options.thickness}px`):(this.canvas.width=this.options.thickness*e,this.canvas.height=t.height*e,this.canvas.style.width=`${this.options.thickness}px`,this.canvas.style.height=`${t.height}px`),this.ctx=this.canvas.getContext("2d"),this.ctx&&this.ctx.scale(e,e)}calculateTickMarks(){const t=[],e=Ut(this.options.units)*this.zoomLevel,i=this.options.majorTickInterval,n=i/this.options.minorTicksPerMajor,s=this.getContentOffset(),o=this.getVisibleLength(),r=Math.max(0,-s),a=o-s,l=Math.floor(r/e/n)*n-n,h=Math.ceil(a/e/n)*n+n;for(let s=Math.max(0,l);s<=h;s+=n){const n=s*e,o=Math.abs(s%i)<.001,r={position:n,isMajor:o};o&&this.options.showLabels&&(r.label=String(Math.round(s))),t.push(r)}return t}getVisibleLength(){if(!this.element)return 0;const t=this.element.getBoundingClientRect();return"horizontal"===this.orientation?t.width:t.height}render(){if(!this.ctx||!this.canvas)return;const t="horizontal"===this.orientation?this.canvas.width/(window.devicePixelRatio||1):this.options.thickness,e="horizontal"===this.orientation?this.options.thickness:this.canvas.height/(window.devicePixelRatio||1);this.ctx.fillStyle=this.options.backgroundColor,this.ctx.fillRect(0,0,t,e),this.options.showMargins&&this.renderMargins(t,e);const i=this.calculateTickMarks();this.renderTicks(i,t,e),null!==this.currentMousePosition&&this.renderCursorIndicator(t,e)}}class Vt extends Nt{constructor(t,e={}){super(t,e),this.sectionElement=null,this.className=e.className||""}attach(t){this.sectionElement=t.sectionElement||null,super.attach(t)}show(){this._isVisible=!0,this.sectionElement&&(this.sectionElement.style.display=""),this.element&&(this.element.style.display="",this.update()),this.emit("visibility-changed",{visible:!0})}hide(){this._isVisible=!1,this.sectionElement&&(this.sectionElement.style.display="none"),this.element&&(this.element.style.display="none"),this.emit("visibility-changed",{visible:!1})}createFormGroup(t,e,i){const n=document.createElement("div");n.className="pc-pane-form-group",i?.inline&&n.classList.add("pc-pane-form-group--inline");const s=document.createElement("label");if(s.className="pc-pane-label",s.textContent=t,n.appendChild(s),n.appendChild(e),i?.hint){const t=document.createElement("span");t.className="pc-pane-hint",t.textContent=i.hint,n.appendChild(t)}return n}createTextInput(t){const e=document.createElement("input");return e.type=t?.type||"text",e.className="pc-pane-input",t?.placeholder&&(e.placeholder=t.placeholder),void 0!==t?.value&&(e.value=t.value),e}createNumberInput(t){const e=document.createElement("input");return e.type="number",e.className="pc-pane-input pc-pane-input--number",void 0!==t?.min&&(e.min=String(t.min)),void 0!==t?.max&&(e.max=String(t.max)),void 0!==t?.step&&(e.step=String(t.step)),void 0!==t?.value&&(e.value=String(t.value)),e}createSelect(t,e){const i=document.createElement("select");i.className="pc-pane-select";for(const n of t){const t=document.createElement("option");t.value=n.value,t.textContent=n.label,n.value===e&&(t.selected=!0),i.appendChild(t)}return i}createColorInput(t){const e=document.createElement("input");return e.type="color",e.className="pc-pane-color",t&&(e.value=t),e}createCheckbox(t,e){const i=document.createElement("label");i.className="pc-pane-checkbox";const n=document.createElement("input");n.type="checkbox",e&&(n.checked=!0);const s=document.createElement("span");return s.textContent=t,i.appendChild(n),i.appendChild(s),i}createButton(t,e){const i=document.createElement("button");return i.type="button",i.className="pc-pane-button",e?.variant&&i.classList.add(`pc-pane-button--${e.variant}`),i.textContent=t,i}createButtonGroup(){const t=document.createElement("div");return t.className="pc-pane-button-group",t}createSection(t){const e=document.createElement("div");if(e.className="pc-pane-section",t){const i=document.createElement("div");i.className="pc-pane-section-label",i.textContent=t,e.appendChild(i)}return e}createRow(){const t=document.createElement("div");return t.className="pc-pane-row",t}createHint(t){const e=document.createElement("div");return e.className="pc-pane-hint",e.textContent=t,e}addImmediateApplyListener(t,e){const i=()=>{e(t.value)};if(t instanceof HTMLSelectElement||t instanceof HTMLInputElement&&"color"===t.type)t.addEventListener("change",i),this.eventCleanup.push(()=>t.removeEventListener("change",i));else{t.addEventListener("blur",i);const e=t=>{"Enter"===t.key&&(t.preventDefault(),i())};t.addEventListener("keydown",e),this.eventCleanup.push(()=>{t.removeEventListener("blur",i),t.removeEventListener("keydown",e)})}}addCheckboxListener(t,e){const i=()=>e(t.checked);t.addEventListener("change",i),this.eventCleanup.push(()=>t.removeEventListener("change",i))}addButtonListener(t,e){const i=t=>{t.preventDefault(),this.saveEditorContext()};t.addEventListener("mousedown",i),t.addEventListener("click",e),this.eventCleanup.push(()=>{t.removeEventListener("mousedown",i),t.removeEventListener("click",e)})}saveEditorContext(){this.editor&&this.editor.saveEditingContext()}createElement(){const t=document.createElement("div");t.className="pc-pane",this.className&&t.classList.add(this.className),t.setAttribute("data-pane-id",this.id);const e=this.createContent();return t.appendChild(e),t}}const Xt=["Arial","Times New Roman","Georgia","Verdana","Courier New"],Kt=[10,12,14,16,18,20,24,28,32,36];t.BaseControl=Nt,t.BaseEmbeddedObject=F,t.BasePane=Vt,t.BaseTextRegion=V,t.BodyTextRegion=K,t.ClipboardManager=At,t.ContentAnalyzer=jt,t.DEFAULT_IMPORT_OPTIONS=Lt,t.Document=et,t.DocumentBuilder=Dt,t.DocumentInfoPane=class extends Vt{constructor(t="document-info"){super(t,{className:"pc-pane-document-info"}),this.pageCountEl=null,this.pageSizeEl=null,this.pageOrientationEl=null}attach(t){if(super.attach(t),this.editor){const t=()=>this.update();this.editor.on("document-changed",t),this.editor.on("page-added",t),this.editor.on("page-removed",t),this.eventCleanup.push(()=>{this.editor?.off("document-changed",t),this.editor?.off("page-added",t),this.editor?.off("page-removed",t)}),this.update()}}createContent(){const t=document.createElement("div");return t.className="pc-pane-label-value-grid",t.appendChild(this.createLabel("Pages:")),this.pageCountEl=this.createValue("0"),t.appendChild(this.pageCountEl),t.appendChild(this.createSpacer()),t.appendChild(this.createLabel("Size:")),this.pageSizeEl=this.createValue("-"),t.appendChild(this.pageSizeEl),t.appendChild(this.createSpacer()),t.appendChild(this.createLabel("Orientation:")),this.pageOrientationEl=this.createValue("-"),t.appendChild(this.pageOrientationEl),t.appendChild(this.createSpacer()),t}createLabel(t){const e=document.createElement("span");return e.className="pc-pane-label pc-pane-margin-label",e.textContent=t,e}createValue(t){const e=document.createElement("span");return e.className="pc-pane-info-value",e.textContent=t,e}createSpacer(){return document.createElement("div")}update(){if(!this.editor)return;const t=this.editor.getDocument();if(this.pageCountEl&&(this.pageCountEl.textContent=t.pages.length.toString()),this.pageSizeEl&&t.settings&&(this.pageSizeEl.textContent=t.settings.pageSize),this.pageOrientationEl&&t.settings){const e=t.settings.pageOrientation;this.pageOrientationEl.textContent=e.charAt(0).toUpperCase()+e.slice(1)}}},t.DocumentSettingsPane=class extends Vt{constructor(t="document-settings"){super(t,{className:"pc-pane-document-settings"}),this.marginTopInput=null,this.marginRightInput=null,this.marginBottomInput=null,this.marginLeftInput=null,this.pageSizeSelect=null,this.orientationSelect=null}attach(t){if(super.attach(t),this.editor){this.loadSettings();const t=()=>this.loadSettings();this.editor.on("document-changed",t),this.eventCleanup.push(()=>{this.editor?.off("document-changed",t)})}}createContent(){const t=document.createElement("div"),e=this.createSection("Margins (mm)"),i=document.createElement("div");i.className="pc-pane-margins-grid-5col",this.marginTopInput=this.createNumberInput({min:5,max:50,step:.5,value:20}),this.marginRightInput=this.createNumberInput({min:5,max:50,step:.5,value:20}),this.marginBottomInput=this.createNumberInput({min:5,max:50,step:.5,value:20}),this.marginLeftInput=this.createNumberInput({min:5,max:50,step:.5,value:20});const n=()=>this.applyMargins();this.marginTopInput.addEventListener("blur",n),this.marginRightInput.addEventListener("blur",n),this.marginBottomInput.addEventListener("blur",n),this.marginLeftInput.addEventListener("blur",n),this.eventCleanup.push(()=>{this.marginTopInput?.removeEventListener("blur",n),this.marginRightInput?.removeEventListener("blur",n),this.marginBottomInput?.removeEventListener("blur",n),this.marginLeftInput?.removeEventListener("blur",n)});const s=this.createMarginLabel("Top:"),o=this.createMarginLabel("Right:");i.appendChild(s),i.appendChild(this.marginTopInput),i.appendChild(o),i.appendChild(this.marginRightInput),i.appendChild(this.createSpacer());const r=this.createMarginLabel("Bottom:"),a=this.createMarginLabel("Left:");i.appendChild(r),i.appendChild(this.marginBottomInput),i.appendChild(a),i.appendChild(this.marginLeftInput),i.appendChild(this.createSpacer()),e.appendChild(i),t.appendChild(e);const l=this.createSection(),h=document.createElement("div");return h.className="pc-pane-label-value-grid",this.pageSizeSelect=this.createSelect([{value:"A4",label:"A4"},{value:"Letter",label:"Letter"},{value:"Legal",label:"Legal"},{value:"A3",label:"A3"}],"A4"),this.addImmediateApplyListener(this.pageSizeSelect,()=>this.applyPageSettings()),h.appendChild(this.createMarginLabel("Page Size:")),h.appendChild(this.pageSizeSelect),h.appendChild(this.createSpacer()),this.orientationSelect=this.createSelect([{value:"portrait",label:"Portrait"},{value:"landscape",label:"Landscape"}],"portrait"),this.addImmediateApplyListener(this.orientationSelect,()=>this.applyPageSettings()),h.appendChild(this.createMarginLabel("Orientation:")),h.appendChild(this.orientationSelect),h.appendChild(this.createSpacer()),l.appendChild(h),t.appendChild(l),t}createMarginLabel(t){const e=document.createElement("label");return e.className="pc-pane-label pc-pane-margin-label",e.textContent=t,e}createSpacer(){return document.createElement("div")}loadSettings(){if(this.editor)try{const t=this.editor.getDocumentSettings();this.marginTopInput&&(this.marginTopInput.value=t.margins.top.toString()),this.marginRightInput&&(this.marginRightInput.value=t.margins.right.toString()),this.marginBottomInput&&(this.marginBottomInput.value=t.margins.bottom.toString()),this.marginLeftInput&&(this.marginLeftInput.value=t.margins.left.toString()),this.pageSizeSelect&&(this.pageSizeSelect.value=t.pageSize),this.orientationSelect&&(this.orientationSelect.value=t.pageOrientation)}catch(t){console.error("Failed to load document settings:",t)}}applyMargins(){if(!this.editor)return;const t={top:parseFloat(this.marginTopInput?.value||"20"),right:parseFloat(this.marginRightInput?.value||"20"),bottom:parseFloat(this.marginBottomInput?.value||"20"),left:parseFloat(this.marginLeftInput?.value||"20")};try{this.editor.updateDocumentSettings({margins:t})}catch(t){console.error("Failed to update margins:",t)}}applyPageSettings(){if(!this.editor)return;const t={};this.pageSizeSelect&&(t.pageSize=this.pageSizeSelect.value),this.orientationSelect&&(t.pageOrientation=this.orientationSelect.value);try{this.editor.updateDocumentSettings(t)}catch(t){console.error("Failed to update page settings:",t)}}update(){this.loadSettings()}},t.EmbeddedObjectFactory=U,t.EmbeddedObjectManager=x,t.EventEmitter=o,t.FlowingTextContent=$,t.FooterTextRegion=q,t.FormattingPane=class extends Vt{constructor(t="formatting",e={}){super(t,{className:"pc-pane-formatting",...e}),this.boldBtn=null,this.italicBtn=null,this.alignLeftBtn=null,this.alignCenterBtn=null,this.alignRightBtn=null,this.alignJustifyBtn=null,this.bulletListBtn=null,this.numberedListBtn=null,this.indentBtn=null,this.outdentBtn=null,this.fontFamilySelect=null,this.fontSizeSelect=null,this.colorInput=null,this.highlightInput=null,this.fontFamilies=e.fontFamilies??Xt,this.fontSizes=e.fontSizes??Kt}attach(t){if(super.attach(t),this.editor){const t=()=>this.updateFromEditor();this.editor.on("cursor-changed",t),this.editor.on("selection-changed",t),this.editor.on("text-changed",t),this.editor.on("formatting-changed",t),this.eventCleanup.push(()=>{this.editor?.off("cursor-changed",t),this.editor?.off("selection-changed",t),this.editor?.off("text-changed",t),this.editor?.off("formatting-changed",t)}),this.updateFromEditor()}}createContent(){const t=document.createElement("div"),e=this.createSection("Style"),i=this.createButtonGroup();this.boldBtn=this.createButton("B"),this.boldBtn.title="Bold",this.boldBtn.style.fontWeight="bold",this.addButtonListener(this.boldBtn,()=>this.toggleBold()),this.italicBtn=this.createButton("I"),this.italicBtn.title="Italic",this.italicBtn.style.fontStyle="italic",this.addButtonListener(this.italicBtn,()=>this.toggleItalic()),i.appendChild(this.boldBtn),i.appendChild(this.italicBtn),e.appendChild(i),t.appendChild(e);const n=this.createSection("Alignment"),s=this.createButtonGroup();this.alignLeftBtn=this.createButton(""),this.alignLeftBtn.title="Align Left",this.alignLeftBtn.classList.add("pc-pane-button--icon","pc-pane-button--align-left"),this.addButtonListener(this.alignLeftBtn,()=>this.setAlignment("left")),this.alignCenterBtn=this.createButton(""),this.alignCenterBtn.title="Center",this.alignCenterBtn.classList.add("pc-pane-button--icon","pc-pane-button--align-center"),this.addButtonListener(this.alignCenterBtn,()=>this.setAlignment("center")),this.alignRightBtn=this.createButton(""),this.alignRightBtn.title="Align Right",this.alignRightBtn.classList.add("pc-pane-button--icon","pc-pane-button--align-right"),this.addButtonListener(this.alignRightBtn,()=>this.setAlignment("right")),this.alignJustifyBtn=this.createButton(""),this.alignJustifyBtn.title="Justify",this.alignJustifyBtn.classList.add("pc-pane-button--icon","pc-pane-button--align-justify"),this.addButtonListener(this.alignJustifyBtn,()=>this.setAlignment("justify")),s.appendChild(this.alignLeftBtn),s.appendChild(this.alignCenterBtn),s.appendChild(this.alignRightBtn),s.appendChild(this.alignJustifyBtn),n.appendChild(s),t.appendChild(n);const o=this.createSection("Lists"),r=this.createButtonGroup();this.bulletListBtn=this.createButton("•"),this.bulletListBtn.title="Bullet List",this.addButtonListener(this.bulletListBtn,()=>this.toggleBulletList()),this.numberedListBtn=this.createButton("1."),this.numberedListBtn.title="Numbered List",this.addButtonListener(this.numberedListBtn,()=>this.toggleNumberedList()),this.indentBtn=this.createButton("→"),this.indentBtn.title="Increase Indent",this.addButtonListener(this.indentBtn,()=>this.indent()),this.outdentBtn=this.createButton("←"),this.outdentBtn.title="Decrease Indent",this.addButtonListener(this.outdentBtn,()=>this.outdent()),r.appendChild(this.bulletListBtn),r.appendChild(this.numberedListBtn),r.appendChild(this.indentBtn),r.appendChild(this.outdentBtn),o.appendChild(r),t.appendChild(o);const a=this.createSection("Font");this.fontFamilySelect=this.createSelect(this.fontFamilies.map(t=>({value:t,label:t})),"Arial"),this.addImmediateApplyListener(this.fontFamilySelect,()=>this.applyFontFamily()),a.appendChild(this.createFormGroup("Family",this.fontFamilySelect)),this.fontSizeSelect=this.createSelect(this.fontSizes.map(t=>({value:t.toString(),label:t.toString()})),"14"),this.addImmediateApplyListener(this.fontSizeSelect,()=>this.applyFontSize()),a.appendChild(this.createFormGroup("Size",this.fontSizeSelect)),t.appendChild(a);const l=this.createSection("Color"),h=this.createRow(),d=document.createElement("div");this.colorInput=this.createColorInput("#000000"),this.addImmediateApplyListener(this.colorInput,()=>this.applyTextColor()),d.appendChild(this.createFormGroup("Text",this.colorInput)),h.appendChild(d);const c=document.createElement("div");this.highlightInput=this.createColorInput("#ffff00"),this.addImmediateApplyListener(this.highlightInput,()=>this.applyHighlight());const g=this.createFormGroup("Highlight",this.highlightInput),u=this.createButton("Clear");return u.className="pc-pane-button",u.style.marginLeft="4px",this.addButtonListener(u,()=>this.clearHighlight()),g.appendChild(u),c.appendChild(g),h.appendChild(c),l.appendChild(h),t.appendChild(l),t}updateFromEditor(){if(!this.editor)return;const t=this.editor.getUnifiedFormattingAtCursor();t&&(this.boldBtn?.classList.toggle("pc-pane-button--active","bold"===t.fontWeight),this.italicBtn?.classList.toggle("pc-pane-button--active","italic"===t.fontStyle),this.fontFamilySelect&&t.fontFamily&&(this.fontFamilySelect.value=t.fontFamily),this.fontSizeSelect&&t.fontSize&&(this.fontSizeSelect.value=t.fontSize.toString()),this.colorInput&&t.color&&(this.colorInput.value=t.color),this.highlightInput&&t.backgroundColor&&(this.highlightInput.value=t.backgroundColor));const e=this.editor.getUnifiedAlignmentAtCursor();this.updateAlignmentButtons(e),this.updateListButtons()}updateAlignmentButtons(t){const e=[{btn:this.alignLeftBtn,align:"left"},{btn:this.alignCenterBtn,align:"center"},{btn:this.alignRightBtn,align:"right"},{btn:this.alignJustifyBtn,align:"justify"}];for(const{btn:i,align:n}of e)i?.classList.toggle("pc-pane-button--active",n===t)}updateListButtons(){if(this.editor)try{const t=this.editor.getListFormatting();t&&(this.bulletListBtn?.classList.toggle("pc-pane-button--active","bullet"===t.listType),this.numberedListBtn?.classList.toggle("pc-pane-button--active","number"===t.listType))}catch{}}getSelection(){return this.editor?this.editor.getSavedOrCurrentSelection():null}applyFormatting(t){if(!this.editor)return;const e=this.getSelection();try{e?this.editor.applyFormattingWithFallback(e.start,e.end,t):this.editor.setPendingFormatting(t),this.editor.clearSavedEditingContext(),this.updateFromEditor(),this.editor.enableTextInput()}catch(t){console.error("Formatting error:",t)}}toggleBold(){const t=this.boldBtn?.classList.contains("pc-pane-button--active");this.applyFormatting({fontWeight:t?"normal":"bold"})}toggleItalic(){const t=this.italicBtn?.classList.contains("pc-pane-button--active");this.applyFormatting({fontStyle:t?"normal":"italic"})}applyFontFamily(){this.fontFamilySelect&&this.applyFormatting({fontFamily:this.fontFamilySelect.value})}applyFontSize(){this.fontSizeSelect&&this.applyFormatting({fontSize:parseInt(this.fontSizeSelect.value,10)})}applyTextColor(){this.colorInput&&this.applyFormatting({color:this.colorInput.value})}applyHighlight(){this.highlightInput&&this.applyFormatting({backgroundColor:this.highlightInput.value})}clearHighlight(){this.applyFormatting({backgroundColor:void 0})}setAlignment(t){if(this.editor)try{this.editor.setUnifiedAlignment(t),this.updateAlignmentButtons(t)}catch(t){console.error("Alignment error:",t)}}toggleBulletList(){if(this.editor)try{this.editor.toggleBulletList(),this.updateListButtons()}catch(t){console.error("Bullet list error:",t)}}toggleNumberedList(){if(this.editor)try{this.editor.toggleNumberedList(),this.updateListButtons()}catch(t){console.error("Numbered list error:",t)}}indent(){if(this.editor)try{this.editor.indentParagraph(),this.updateListButtons()}catch(t){console.error("Indent error:",t)}}outdent(){if(this.editor)try{this.editor.outdentParagraph(),this.updateListButtons()}catch(t){console.error("Outdent error:",t)}}update(){this.updateFromEditor()}},t.HeaderTextRegion=Y,t.HorizontalRuler=class extends $t{constructor(t={}){super("horizontal-ruler",t),this.orientation="horizontal",this.contentOffsetX=0}updateScrollOffset(){if(!this.editor)return;const t=this.editor.getScrollPosition();this.scrollOffset=t.x}getContentOffset(){return this.contentOffsetX}updateFromMetrics(t){if(!t||!this.editor)return;const e=Ut("mm");this.documentSize=t.pageWidth*e*this.zoomLevel,this.marginStart=t.margins.left*e*this.zoomLevel,this.marginEnd=(t.pageWidth-t.margins.right)*e*this.zoomLevel;const i=this.editor.getContentOffset(),n=this.editor.getScrollPosition();this.contentOffsetX=i.x-n.x}calculateTickMarks(){const t=[],e=Ut(this.options.units)*this.zoomLevel,i=this.options.majorTickInterval,n=i/this.options.minorTicksPerMajor,s=this.getContentOffset(),o=this.getVisibleLength(),r=Math.max(0,-s),a=Math.min(this.documentSize,o-s),l=Math.floor(r/e/n)*n-n,h=Math.ceil(a/e/n)*n+n;for(let s=Math.max(0,l);s<=h;s+=n){const n=s*e;if(n>this.documentSize)break;const o=Math.abs(s%i)<.001,r={position:n,isMajor:o};o&&this.options.showLabels&&(r.label=String(Math.round(s))),t.push(r)}return t}renderMargins(t,e){if(!this.ctx)return;const i=this.contentOffsetX,n=i+this.documentSize;i>0&&(this.ctx.fillStyle=this.options.marginColor,this.ctx.fillRect(0,0,i,e)),n<t&&(this.ctx.fillStyle=this.options.marginColor,this.ctx.fillRect(n,0,t-n,e));const s=i+this.marginStart,o=i+this.marginEnd;this.ctx.strokeStyle=this.options.tickColor,this.ctx.lineWidth=1,s>=0&&s<=t&&(this.ctx.beginPath(),this.ctx.moveTo(s,0),this.ctx.lineTo(s,e),this.ctx.stroke()),o>=0&&o<=t&&(this.ctx.beginPath(),this.ctx.moveTo(o,0),this.ctx.lineTo(o,e),this.ctx.stroke())}renderTicks(t,e,i){if(!this.ctx)return;const n=.6*i,s=.3*i;this.ctx.strokeStyle=this.options.tickColor,this.ctx.lineWidth=1,this.ctx.font=`${this.options.labelFontSize}px sans-serif`,this.ctx.fillStyle=this.options.labelColor,this.ctx.textAlign="center",this.ctx.textBaseline="top";const o=this.contentOffsetX;for(const r of t){const t=r.position+o;if(t<-10||t>e+10)continue;const a=r.isMajor?n:s;this.ctx.beginPath(),this.ctx.moveTo(t,i),this.ctx.lineTo(t,i-a),this.ctx.stroke(),r.label&&this.ctx.fillText(r.label,t,2)}}renderCursorIndicator(t,e){this.ctx&&null!==this.currentMousePosition&&(this.ctx.fillStyle=this.options.activeColor,this.ctx.fillRect(this.currentMousePosition-1,0,2,e),this.ctx.beginPath(),this.ctx.moveTo(this.currentMousePosition-4,e),this.ctx.lineTo(this.currentMousePosition+4,e),this.ctx.lineTo(this.currentMousePosition,e-6),this.ctx.closePath(),this.ctx.fill())}},t.HtmlConverter=Et,t.HyperlinkPane=class extends Vt{constructor(t="hyperlink",e={}){super(t,{className:"pc-pane-hyperlink",...e}),this.urlInput=null,this.titleInput=null,this.rangeHint=null,this.currentHyperlink=null,this._isUpdating=!1,this.onApply=e.onApply,this.onRemove=e.onRemove}attach(t){if(super.attach(t),this.editor){const t=()=>this.updateFromCursor();this.editor.on("cursor-changed",t),this.editor.on("selection-changed",t),this.eventCleanup.push(()=>{this.editor?.off("cursor-changed",t),this.editor?.off("selection-changed",t)}),this.updateFromCursor()}}createContent(){const t=document.createElement("div");this.urlInput=this.createTextInput({placeholder:"https://example.com"}),t.appendChild(this.createFormGroup("URL",this.urlInput)),this.titleInput=this.createTextInput({placeholder:"Link title (optional)"}),t.appendChild(this.createFormGroup("Title",this.titleInput));const e=this.createButton("Apply Changes",{variant:"primary"});this.addButtonListener(e,()=>this.applyChanges()),t.appendChild(e);const i=this.createButton("Remove Link",{variant:"danger"});return i.style.marginTop="0.5rem",this.addButtonListener(i,()=>this.removeHyperlink()),t.appendChild(i),this.rangeHint=this.createHint(""),t.appendChild(this.rangeHint),t}updateFromCursor(){if(this.editor&&!this._isUpdating){this._isUpdating=!0;try{const t=this.editor.getCursorPosition(),e=this.editor.getHyperlinkAt(t);e?this.showHyperlink(e):this.hideHyperlink()}finally{this._isUpdating=!1}}}showHyperlink(t){this.currentHyperlink=t,this.urlInput&&(this.urlInput.value=t.url),this.titleInput&&(this.titleInput.value=t.title||""),this.rangeHint&&(this.rangeHint.textContent=`Link spans characters ${t.startIndex} to ${t.endIndex}`),this.show()}hideHyperlink(){this.currentHyperlink=null,this.hide()}applyChanges(){if(this.editor&&this.currentHyperlink)try{const t=this.urlInput?.value.trim()||"",e=this.titleInput?.value.trim()||void 0;if(!t)return void this.onApply?.(!1,new Error("URL is required"));this.editor.updateHyperlink(this.currentHyperlink.id,{url:t,title:e}),this.currentHyperlink.url=t,this.currentHyperlink.title=e,this.onApply?.(!0)}catch(t){this.onApply?.(!1,t instanceof Error?t:new Error(String(t)))}}removeHyperlink(){if(this.editor&&this.currentHyperlink)try{this.editor.removeHyperlink(this.currentHyperlink.id),this.hideHyperlink(),this.onRemove?.(!0)}catch{this.onRemove?.(!1)}}getCurrentHyperlink(){return this.currentHyperlink}hasHyperlink(){return null!==this.currentHyperlink}update(){this.updateFromCursor()}},t.ImageObject=I,t.ImagePane=class extends Vt{constructor(t="image",e={}){super(t,{className:"pc-pane-image",...e}),this.positionSelect=null,this.offsetGroup=null,this.offsetXInput=null,this.offsetYInput=null,this.fitModeSelect=null,this.resizeModeSelect=null,this.altTextInput=null,this.fileInput=null,this.currentImage=null,this._isUpdating=!1,this.maxImageWidth=e.maxImageWidth??400,this.maxImageHeight=e.maxImageHeight??400,this.onApplyCallback=e.onApply}attach(t){if(super.attach(t),this.editor){const t=()=>this.updateFromSelection();this.editor.on("selection-change",t),this.editor.on("image-updated",t),this.eventCleanup.push(()=>{this.editor?.off("selection-change",t),this.editor?.off("image-updated",t)}),this.updateFromSelection()}}createContent(){const t=document.createElement("div"),e=this.createSection("Position");this.positionSelect=this.createSelect([{value:"inline",label:"Inline"},{value:"block",label:"Block"},{value:"relative",label:"Relative"}],"inline"),this.addImmediateApplyListener(this.positionSelect,()=>this.updateOffsetVisibility()),e.appendChild(this.createFormGroup("Type",this.positionSelect)),this.offsetGroup=document.createElement("div"),this.offsetGroup.style.display="none";const i=this.createRow();this.offsetXInput=this.createNumberInput({value:0}),this.offsetYInput=this.createNumberInput({value:0}),i.appendChild(this.createFormGroup("X",this.offsetXInput,{inline:!0})),i.appendChild(this.createFormGroup("Y",this.offsetYInput,{inline:!0})),this.offsetGroup.appendChild(i),e.appendChild(this.offsetGroup),t.appendChild(e);const n=this.createSection("Display");this.fitModeSelect=this.createSelect([{value:"contain",label:"Contain"},{value:"cover",label:"Cover"},{value:"fill",label:"Fill"},{value:"none",label:"None (original size)"},{value:"tile",label:"Tile"}],"contain"),n.appendChild(this.createFormGroup("Fit Mode",this.fitModeSelect)),this.resizeModeSelect=this.createSelect([{value:"locked-aspect-ratio",label:"Lock Aspect Ratio"},{value:"free",label:"Free Resize"}],"locked-aspect-ratio"),n.appendChild(this.createFormGroup("Resize Mode",this.resizeModeSelect)),t.appendChild(n);const s=this.createSection("Accessibility");this.altTextInput=this.createTextInput({placeholder:"Description of the image"}),s.appendChild(this.createFormGroup("Alt Text",this.altTextInput)),t.appendChild(s);const o=this.createSection("Source");this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/*",this.fileInput.style.display="none",this.fileInput.addEventListener("change",t=>this.handleFileChange(t)),o.appendChild(this.fileInput);const r=this.createButton("Change Image...");this.addButtonListener(r,()=>this.fileInput?.click()),o.appendChild(r),t.appendChild(o);const a=this.createButton("Apply Changes",{variant:"primary"});return this.addButtonListener(a,()=>this.applyChanges()),t.appendChild(a),t}updateFromSelection(){if(this.editor&&!this._isUpdating){this._isUpdating=!0;try{const t=this.editor.getSelectedImage?.();t?this.showImage(t):this.hideImage()}finally{this._isUpdating=!1}}}showImage(t){this.currentImage=t,this.positionSelect&&(this.positionSelect.value=t.position||"inline"),this.updateOffsetVisibility(),this.offsetXInput&&(this.offsetXInput.value=String(t.relativeOffset?.x??0)),this.offsetYInput&&(this.offsetYInput.value=String(t.relativeOffset?.y??0)),this.fitModeSelect&&(this.fitModeSelect.value=t.fit||"contain"),this.resizeModeSelect&&(this.resizeModeSelect.value=t.resizeMode||"locked-aspect-ratio"),this.altTextInput&&(this.altTextInput.value=t.alt||""),this.show()}hideImage(){this.currentImage=null,this.hide()}updateOffsetVisibility(){this.offsetGroup&&this.positionSelect&&(this.offsetGroup.style.display="relative"===this.positionSelect.value?"block":"none")}handleFileChange(t){if(!this.editor||!this.currentImage)return;const e=t.target,i=e.files?.[0];if(!i)return;const n=new FileReader;n.onload=t=>{const e=t.target?.result;e&&this.currentImage&&this.editor&&this.editor.setImageSource(this.currentImage.id,e,{maxWidth:this.maxImageWidth,maxHeight:this.maxImageHeight})},n.readAsDataURL(i),e.value=""}applyChanges(){if(!this.editor||!this.currentImage)return void this.onApplyCallback?.(!1,new Error("No image selected"));const t={};this.positionSelect&&(t.position=this.positionSelect.value),"relative"===this.positionSelect?.value&&(t.relativeOffset={x:parseInt(this.offsetXInput?.value||"0",10),y:parseInt(this.offsetYInput?.value||"0",10)}),this.fitModeSelect&&(t.fit=this.fitModeSelect.value),this.resizeModeSelect&&(t.resizeMode=this.resizeModeSelect.value),this.altTextInput&&(t.alt=this.altTextInput.value);try{this.editor.updateImage(this.currentImage.id,t)?this.onApplyCallback?.(!0):this.onApplyCallback?.(!1,new Error("Failed to update image"))}catch(t){this.onApplyCallback?.(!1,t instanceof Error?t:new Error(String(t)))}}getCurrentImage(){return this.currentImage}hasImage(){return null!==this.currentImage}update(){this.updateFromSelection()}},t.Logger=O,t.MergeDataPane=class extends Vt{constructor(t="merge-data",e={}){super(t,{className:"pc-pane-merge-data",...e}),this.textarea=null,this.errorHint=null,this.initialData=e.initialData,this.placeholder=e.placeholder||'{"customerName": "John Doe", "orderNumber": "12345"}',this.rows=e.rows??10,this.onApply=e.onApply}createContent(){const t=document.createElement("div"),e=this.createFormGroup("JSON Data",this.createTextarea());t.appendChild(e),this.errorHint=this.createHint(""),this.errorHint.style.display="none",this.errorHint.style.color="#dc3545",t.appendChild(this.errorHint);const i=this.createButton("Apply Merge Data",{variant:"primary"});return this.addButtonListener(i,()=>this.applyMergeData()),t.appendChild(i),t}createTextarea(){return this.textarea=document.createElement("textarea"),this.textarea.className="pc-pane-textarea pc-pane-merge-data-input",this.textarea.rows=this.rows,this.textarea.placeholder=this.placeholder,this.textarea.spellcheck=!1,this.initialData&&(this.textarea.value=JSON.stringify(this.initialData,null,2)),this.textarea.addEventListener("input",()=>{this.errorHint&&(this.errorHint.style.display="none")}),this.textarea}applyMergeData(){if(this.editor&&this.textarea)try{const t=JSON.parse(this.textarea.value);this.editor.applyMergeData(t),this.errorHint&&(this.errorHint.style.display="none"),this.onApply?.(!0)}catch(t){const e=t instanceof Error?t:new Error(String(t));this.errorHint&&(t instanceof SyntaxError?this.errorHint.textContent="Invalid JSON syntax":this.errorHint.textContent=e.message,this.errorHint.style.display="block"),this.onApply?.(!1,e)}}getData(){if(!this.textarea)return null;try{return JSON.parse(this.textarea.value)}catch{return null}}setData(t){this.textarea&&(this.textarea.value=JSON.stringify(t,null,2),this.errorHint&&(this.errorHint.style.display="none"))}update(){}},t.PCEditor=class extends o{constructor(t,e){if(super(),this._isReady=!1,this.keyboardListenerActive=!1,this.currentSelection={type:"none"},this._activeEditingSection="body",this._wasTextEditing=!1,this._textEditingSource=null,this._savedEditingContext=null,!t)throw new Error("Container element is required");this.container=t,this.options=this.mergeOptions(e),O.setEnabled(this.options.enableLogging??!1),this.document=new et,this.document.updateSettings({pageSize:this.options.pageSize,pageOrientation:this.options.pageOrientation,units:this.options.units}),this.dataBinder=new ut,this.pdfGenerator=new wt,this.clipboardManager=new At,this.initialize()}mergeOptions(t){return{pageSize:t?.pageSize||"A4",pageOrientation:t?.pageOrientation||"portrait",customPageSize:t?.customPageSize,units:t?.units||"mm",gridSize:t?.gridSize||10,showGrid:t?.showGrid??!0,showRulers:t?.showRulers??!0,showControlCharacters:t?.showControlCharacters??!1,defaultFont:t?.defaultFont||"Arial",defaultFontSize:t?.defaultFontSize||12,theme:t?.theme||"light",enableLogging:t?.enableLogging??!1}}initialize(){try{this.setupContainer(),this.canvasManager=new gt(this.container,this.document,this.options),this.layoutEngine=new St(this.document,{autoFlow:!0,snapToGrid:this.options.showGrid,gridSize:this.options.gridSize}),this.canvasManager.initialize(),this.setupEventListeners(),this.setupKeyboardListeners(),this.setupTransactionUndo(),this._isReady=!0,queueMicrotask(()=>this.emit("ready"))}catch(t){console.error("Failed to initialize editor:",t),this.emit("error",{error:t})}}setupContainer(){this.container.style.position="relative","dark"===this.options.theme?this.container.classList.add("pc-editor-dark"):this.container.classList.add("pc-editor-light")}setupEventListeners(){this.document.on("change",()=>{this.emit("document-change",{document:this.document.toData()}),this.canvasManager&&this.canvasManager.render()}),this.document.on("settings-changed",()=>{this.canvasManager&&(this.canvasManager.updateCanvasSizes(),this.canvasManager.render(),setTimeout(()=>{this.canvasManager.checkForEmptyPages()},50)),this.emit("settings-changed")}),this.canvasManager.on("selection-change",t=>{this.emitSelectionChange()}),this.canvasManager.on("element-added",t=>{this.emit("element-added",t)}),this.canvasManager.on("element-removed",t=>{this.emit("element-removed",t)}),this.layoutEngine.on("page-added",t=>{this.canvasManager.setDocument(this.document),this.emit("page-added",t)}),this.layoutEngine.on("page-break-created",t=>{this.canvasManager.setDocument(this.document),this.emit("page-break-created",t)}),this.layoutEngine.on("layout-complete",t=>{this.canvasManager.render(),this.emit("layout-complete",t)}),this.canvasManager.on("text-clicked",t=>{this.enableTextInput(),this.emit("text-clicked",t)}),this.canvasManager.on("textbox-editing-started",t=>{this.keyboardListenerActive=!0,this.container.focus(),this.emit("textbox-editing-started",t)}),this.canvasManager.on("textbox-editing-ended",()=>{this.keyboardListenerActive=!1,this.emit("textbox-editing-ended",{})}),this.canvasManager.on("cursor-changed",t=>{if(void 0!==t.textIndex){const e=this.canvasManager.getFlowingContentForActiveSection();if(!(e?.hasSelection()??!1)){const e=t.section||this._activeEditingSection;e!==this._activeEditingSection&&(this._activeEditingSection=e),this.currentSelection={type:"cursor",position:t.textIndex,section:e},this.emitSelectionChange()}}this.emit("cursor-changed",t)}),this.canvasManager.on("text-selection-changed",t=>{if(t.selection&&t.selection.start!==t.selection.end){const e=t.section||this._activeEditingSection;e!==this._activeEditingSection&&(this._activeEditingSection=e),this.currentSelection={type:"text",start:t.selection.start,end:t.selection.end,section:e},this.emitSelectionChange()}}),this.canvasManager.on("tablecell-cursor-changed",t=>{this.emit("tablecell-cursor-changed",t)}),this.canvasManager.on("repeating-section-clicked",t=>{t.section&&t.section.id&&(this.currentSelection={type:"repeating-section",sectionId:t.section.id},this.emitSelectionChange())}),this.canvasManager.on("section-focus-changed",t=>{t.section&&t.section!==this._activeEditingSection&&(this._activeEditingSection=t.section,this.emit("section-focus-changed",t))}),this.canvasManager.on("focus-changed",t=>{t.control&&this.enableTextInput(),this.checkAndEmitTextEditingEvents()}),this.canvasManager.on("textbox-editing-started",()=>{this.checkAndEmitTextEditingEvents()}),this.canvasManager.on("textbox-editing-ended",()=>{this.checkAndEmitTextEditingEvents()}),this.canvasManager.on("zoom-change",t=>{this.emit("zoom-changed",t)}),this.canvasManager.on("scroll",t=>{this.emit("scroll",t)}),this.canvasManager.on("mouse-move",t=>{this.emit("mouse-move",t)}),this.canvasManager.on("mouse-leave",()=>{this.emit("mouse-leave")})}getFlowingContentForSection(t){switch(t){case"header":return this.document.headerFlowingContent;case"footer":return this.document.footerFlowingContent;default:return this.document.bodyFlowingContent}}setupTransactionUndo(){const t=new _t(()=>{const t=this._activeEditingSection,e=this.canvasManager?.getFocusedControl();if(e instanceof W&&e.focusedCell){const i=e.getCell(e.focusedCell.row,e.focusedCell.col);if(i&&"flowingContent"in i)return{content:i.flowingContent,section:t,focusedObjectId:e.id,tableCellAddress:e.focusedCell}}if(this.canvasManager?.isEditingTextBox()){const e=this.canvasManager.getEditingTextBox();if(e)return{content:e.flowingContent,section:t,focusedObjectId:e.id,tableCellAddress:null}}return{content:this.getFlowingContentForSection(t),section:t,focusedObjectId:null,tableCellAddress:null}},t=>{this._activeEditingSection=t.activeSection,t.focusedObjectId;const e=this.getFlowingContentForSection(t.activeSection);e&&(e.setCursorPosition(t.cursorPosition),t.selection&&e.setSelection(t.selection.start,t.selection.end)),this.canvasManager?.render()});this.transactionManager=new It(t,t=>{if("body"===t.type)return this.document.bodyFlowingContent;if("header"===t.type)return this.document.headerFlowingContent;if("footer"===t.type)return this.document.footerFlowingContent;if("tablecell"===t.type&&t.objectId&&t.cellAddress){const e=this.findObjectById(t.objectId);if(e){const i=e.getCell(t.cellAddress.row,t.cellAddress.col);if(i&&"flowingContent"in i)return i.flowingContent}}if("textbox"===t.type&&t.objectId){const e=this.findObjectById(t.objectId);if(e)return e.flowingContent}return null},t=>this.findObjectById(t.objectId)),this.textMutationObserver=new Tt(this.transactionManager),this.objectMutationObserver=new Pt(this.transactionManager),this.observeAllEmbeddedObjects(),this.mutationUndo=new Rt(t=>this.transactionManager.getContent(t),t=>this.transactionManager.getObject(t)),this.transactionManager.on("undo-mutation",t=>{this.mutationUndo.undoMutation(t.mutation)}),this.transactionManager.on("redo-mutation",t=>{this.mutationUndo.redoMutation(t.mutation)}),this.transactionManager.on("state-changed",t=>{this.emit("undo-state-changed",t)}),this._contentDiscovery=new kt(this.textMutationObserver,{bodyFlowingContent:this.document.bodyFlowingContent,headerFlowingContent:this.document.headerFlowingContent,footerFlowingContent:this.document.footerFlowingContent},this.canvasManager),this._contentDiscovery}findObjectById(t){for(const[,e]of this.document.bodyFlowingContent.getEmbeddedObjects())if(e.id===t)return e;for(const[,e]of this.document.headerFlowingContent.getEmbeddedObjects())if(e.id===t)return e;for(const[,e]of this.document.footerFlowingContent.getEmbeddedObjects())if(e.id===t)return e;return null}observeAllEmbeddedObjects(){for(const[,t]of this.document.bodyFlowingContent.getEmbeddedObjects())this.objectMutationObserver.observe(t);for(const[,t]of this.document.headerFlowingContent.getEmbeddedObjects())this.objectMutationObserver.observe(t);for(const[,t]of this.document.footerFlowingContent.getEmbeddedObjects())this.objectMutationObserver.observe(t)}observeEmbeddedObject(t){this.objectMutationObserver&&this.objectMutationObserver.observe(t)}get isReady(){return this._isReady}getSelection(){return this.currentSelection}getTextSelection(){const t=this.getEditingFlowingContent()||this.getActiveFlowingContent();return t?t.getSelection():null}getActiveSection(){return this._activeEditingSection}setActiveSection(t){O.log("[pc-editor] setActiveSection",t),this._activeEditingSection!==t&&(this._activeEditingSection=t,this.canvasManager.setActiveSection(t))}getActiveFlowingContent(){switch(this._activeEditingSection){case"header":return this.document.headerFlowingContent;case"footer":return this.document.footerFlowingContent;default:return this.document.bodyFlowingContent}}emitSelectionChange(){this.emit("selection-change",{selection:this.currentSelection})}emitTableCellCursorChanged(t){if(!t.focusedCell)return;const e=t.getCell(t.focusedCell.row,t.focusedCell.col);e&&this.emit("tablecell-cursor-changed",{table:t,cell:e,cursorPosition:e.flowingContent.getCursorPosition(),selection:e.flowingContent.getSelection()})}getTextEditingSource(){const t=this.canvasManager.getFocusedControl();return t instanceof $?"body":this.canvasManager.isEditingTextBox()?"textbox":t instanceof W&&t.focusedCell?"tablecell":null}checkAndEmitTextEditingEvents(){const t=this.getTextEditingSource(),e=null!==t;if(e&&!this._wasTextEditing)this._wasTextEditing=!0,this._textEditingSource=t,this.emit("text-editing-started",{source:t});else if(!e&&this._wasTextEditing){const t=this._textEditingSource;this._wasTextEditing=!1,this._textEditingSource=null,this.emit("text-editing-ended",{source:t})}else if(e&&this._wasTextEditing&&t!==this._textEditingSource){const e=this._textEditingSource;this._textEditingSource=t,this.emit("text-editing-ended",{source:e}),this.emit("text-editing-started",{source:t})}}loadDocument(t){if(O.log("[pc-editor] loadDocument"),!this._isReady)throw new Error("Editor is not ready");this.document.clear(),this.document=new et(t),this.canvasManager.setDocument(this.document),this._activeEditingSection="body",this.currentSelection={type:"none"},this.clearUndoHistory(),this.layoutEngine.destroy(),this.layoutEngine=new St(this.document,{autoFlow:!0,snapToGrid:this.options.showGrid,gridSize:this.options.gridSize}),this.setupEventListeners(),this.setupTransactionUndo(),this.emit("document-loaded",{document:t})}getDocument(){return this.document.toData()}bindData(t){if(O.log("[pc-editor] bindData"),!this._isReady)throw new Error("Editor is not ready");const e=this.dataBinder.bind(this.document.toData(),t);this.loadDocument(e),this.emit("data-bound",{data:t})}async exportPDF(t){if(O.log("[pc-editor] exportPDF"),!this._isReady)throw new Error("Editor is not ready");let e=null;try{t?.applyMergeData&&t?.mergeData&&(e=this.document.toData(),this.applyMergeData(t.mergeData),this.canvasManager.render());const i=this.canvasManager.getFlowedPagesSnapshot(),n=await this.pdfGenerator.generate(this.document,i,t);return this.emit("pdf-exported"),n}catch(t){throw console.error("Failed to export PDF:",t),this.emit("error",{error:t,context:"pdf-export"}),t}finally{e&&this.loadDocument(e)}}saveDocument(){if(O.log("[pc-editor] saveDocument"),!this._isReady)throw new Error("Editor is not ready");const t=this.document.toData();return JSON.stringify(t,null,2)}saveDocumentToFile(t="document.pceditor.json"){O.log("[pc-editor] saveDocumentToFile",t);const e=this.saveDocument(),i=new Blob([e],{type:"application/json"}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(n),this.emit("document-saved",{filename:t})}loadDocumentFromJSON(t){if(O.log("[pc-editor] loadDocumentFromJSON"),!this._isReady)throw new Error("Editor is not ready");try{const e=JSON.parse(t);this.validateDocumentData(e),this.loadDocument(e),this.emit("document-loaded-from-json",{version:e.version})}catch(t){throw this.emit("error",{error:t,context:"load-document"}),t}}async loadDocumentFromFile(t){if(O.log("[pc-editor] loadDocumentFromFile",t.name),!this._isReady)throw new Error("Editor is not ready");return new Promise((e,i)=>{const n=new FileReader;n.onload=t=>{try{const i=t.target?.result;this.loadDocumentFromJSON(i),e()}catch(t){i(t)}},n.onerror=()=>{const t=new Error("Failed to read file");this.emit("error",{error:t,context:"file-read"}),i(t)},n.readAsText(t)})}async importPDF(e,i,n){if(!this._isReady)throw new Error("Editor is not ready");const s=new Ht;let o;try{if(e instanceof File)o=await s.importFile(e,i,n);else if(e instanceof ArrayBuffer)o=await s.import(e,i,n);else{if("string"!=typeof e)throw new zt("Invalid source type. Expected File, ArrayBuffer, or URL string.",t.PDFImportErrorCode.INVALID_PDF);o=await s.importUrl(e,i,n)}return this.loadDocument(o.document),this.emit("pdf-imported",{pageCount:o.metadata?.pageCount||0,warnings:o.warnings,metadata:o.metadata}),o}catch(t){throw this.emit("error",{error:t,context:"pdf-import"}),t}}validateDocumentData(t){if(!t||"object"!=typeof t)throw new Error("Invalid document data: expected object");const e=t;if("string"!=typeof e.version)throw new Error("Invalid document data: missing or invalid version");if(!Array.isArray(e.pages))throw new Error("Invalid document data: missing or invalid pages array");for(const t of e.pages)if(!t||"object"!=typeof t||"string"!=typeof t.id)throw new Error("Invalid document data: page missing id");const[i]=e.version.split(".").map(Number);i>1&&O.warn(`[pc-editor] Document version ${e.version} may not be fully compatible with this editor`)}selectElement(t){if(O.log("[pc-editor] selectElement",t),!this._isReady)throw new Error("Editor is not ready");this.canvasManager.selectElement(t)}clearSelection(){if(O.log("[pc-editor] clearSelection"),!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection()}removeEmbeddedObject(t){if(O.log("[pc-editor] removeEmbeddedObject",t),!this._isReady)throw new Error("Editor is not ready");this.canvasManager.removeEmbeddedObject(t)}undo(){if(O.log("[pc-editor] undo"),!this._isReady)return;this.transactionManager.undo()&&this.canvasManager.render(),this.emit("undo")}redo(){if(O.log("[pc-editor] redo"),!this._isReady)return;this.transactionManager.redo()&&this.canvasManager.render(),this.emit("redo")}canUndo(){return this.transactionManager.canUndo()}canRedo(){return this.transactionManager.canRedo()}clearUndoHistory(){this.transactionManager.clear()}setMaxUndoHistory(t){this.transactionManager.setMaxHistory(t)}zoomIn(){O.log("[pc-editor] zoomIn"),this._isReady&&this.canvasManager.zoomIn()}zoomOut(){O.log("[pc-editor] zoomOut"),this._isReady&&this.canvasManager.zoomOut()}setZoom(t){O.log("[pc-editor] setZoom",t),this._isReady&&this.canvasManager.setZoom(t)}getZoomLevel(){return this._isReady?this.canvasManager.getZoom():1}getContainer(){return this.container}getScrollPosition(){return this._isReady?this.canvasManager.getScrollPosition():{x:0,y:0}}getContentOffset(){return this._isReady?this.canvasManager.getContentOffset():{x:0,y:0}}fitToWidth(){O.log("[pc-editor] fitToWidth"),this._isReady&&this.canvasManager.fitToWidth()}render(){O.log("[pc-editor] render"),this._isReady&&this.canvasManager.render()}fitToPage(){O.log("[pc-editor] fitToPage"),this._isReady&&this.canvasManager.fitToPage()}setAutoFlow(t){if(O.log("[pc-editor] setAutoFlow",t),!this._isReady)throw new Error("Editor is not ready");this.layoutEngine.setAutoFlow(t)}reflowDocument(){if(O.log("[pc-editor] reflowDocument"),!this._isReady)throw new Error("Editor is not ready");this.layoutEngine.reflowDocument()}setSnapToGrid(t){if(!this._isReady)throw new Error("Editor is not ready");this.layoutEngine.setSnapToGrid(t,this.options.gridSize)}getDocumentMetrics(){if(!this._isReady)return null;const t=this.document.settings,e={A4:{width:210,height:297},Letter:{width:215.9,height:279.4},Legal:{width:215.9,height:355.6},A3:{width:297,height:420}};let i=e[t.pageSize]||e.A4;return"Custom"===t.pageSize&&t.customPageSize&&(i={width:t.customPageSize.width,height:t.customPageSize.height}),"landscape"===t.pageOrientation&&(i={width:i.height,height:i.width}),{pageWidth:i.width,pageHeight:i.height,margins:t.margins,totalPages:this.document.pages.length}}addPage(){if(O.log("[pc-editor] addPage"),!this._isReady)throw new Error("Editor is not ready");const t={id:`page_${Date.now()}_${Math.random().toString(36).substr(2,9)}`},e=new r(t,this.document.settings);this.document.addPage(e),this.canvasManager.setDocument(this.document)}removePage(t){if(O.log("[pc-editor] removePage",t),!this._isReady)throw new Error("Editor is not ready");if(this.document.pages.length<=1)throw new Error("Cannot remove the last page");this.document.removePage(t),this.canvasManager.setDocument(this.document)}setupKeyboardListeners(){this.container.setAttribute("tabindex","0"),this.container.addEventListener("keydown",t=>{this.keyboardListenerActive&&this.handleKeyDown(t)}),this.container.addEventListener("blur",()=>{this.disableTextInput()}),this.container.addEventListener("focus",()=>{this.enableTextInput()})}handleKeyDown(t){if((t.ctrlKey||t.metaKey)&&!t.shiftKey&&"z"===t.key)return t.preventDefault(),void this.undo();if((t.ctrlKey||t.metaKey)&&("y"===t.key||t.shiftKey&&"Z"===t.key))return t.preventDefault(),void this.redo();if((t.ctrlKey||t.metaKey)&&"c"===t.key)return t.preventDefault(),void this.copy();if((t.ctrlKey||t.metaKey)&&"x"===t.key)return t.preventDefault(),void this.cut();if((t.ctrlKey||t.metaKey)&&"v"===t.key)return t.preventDefault(),void this.paste();if((t.ctrlKey||t.metaKey)&&"a"===t.key)return t.preventDefault(),void this.selectAll();if(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(t.key)&&this.canvasManager.hasSelectedElements()){const t=this.canvasManager.getEditingTextBox(),e=this.canvasManager.getFocusedControl();t?.editing||e instanceof W&&e.editing||this.canvasManager.clearSelection()}const e=this.canvasManager.getFocusedControl();if(O.log("[pc-editor:handleKeyDown] Key:",t.key,"focusedControl:",e?.constructor?.name),!e)return;if("ArrowUp"===t.key||"ArrowDown"===t.key)return t.preventDefault(),void this.handleVerticalNavigation(t,e);let i=null,n=null;const s=this.canvasManager.getEditingTextBox();"Escape"===t.key&&(s&&s.editing?(i=s.textIndex,n=s.id):e instanceof W&&e.editing&&(i=e.textIndex,n=e.id)),O.log("[pc-editor:handleKeyDown] Calling focusedControl.handleKeyDown");const o=e.handleKeyDown(t);if(O.log("[pc-editor:handleKeyDown] handled:",o),o){this.canvasManager.render();const s=this.canvasManager.getEditingTextBox();if(s&&(s.editing?this.emit("textbox-cursor-changed",{textBox:s,cursorPosition:s.flowingContent.getCursorPosition(),selection:s.flowingContent.getSelection()}):this.canvasManager.setEditingTextBox(null)),e instanceof W&&e.focusedCell){const t=e.getCell(e.focusedCell.row,e.focusedCell.col);t&&this.emit("tablecell-cursor-changed",{table:e,cell:t,cursorPosition:t.flowingContent.getCursorPosition(),selection:t.flowingContent.getSelection()})}"Escape"===t.key&&null!==n&&null!==i&&this.returnFocusToParentFlowingContent(n,i)}else"Escape"===t.key&&this.handleEscapeForSelectedElements()}handleEscapeForSelectedElements(){const t=this.canvasManager.getSelectedElements();if(0!==t.length){for(const e of t){const t=this.findEmbeddedObjectInfo(e);if(t)return this.canvasManager.clearSelection(),t.content.setCursorPosition(t.textIndex),this.canvasManager.setFocus(t.content),t.section!==this.canvasManager.getActiveSection()&&this.canvasManager.setActiveSection(t.section),void this.canvasManager.render()}this.canvasManager.clearSelection(),this.canvasManager.render()}}findEmbeddedObjectInfo(t){const e=[];this.document.headerFlowingContent&&e.push({content:this.document.headerFlowingContent,section:"header"}),e.push({content:this.document.bodyFlowingContent,section:"body"}),this.document.footerFlowingContent&&e.push({content:this.document.footerFlowingContent,section:"footer"});for(const{content:i,section:n}of e){const e=i.getEmbeddedObjectManager().findById(t);if(e)return{content:i,section:n,textIndex:e.object.textIndex}}return null}returnFocusToParentFlowingContent(t,e){const i=[];this.document.headerFlowingContent&&i.push({content:this.document.headerFlowingContent,section:"header"}),i.push({content:this.document.bodyFlowingContent,section:"body"}),this.document.footerFlowingContent&&i.push({content:this.document.footerFlowingContent,section:"footer"});for(const{content:n,section:s}of i){if(n.getEmbeddedObjectManager().findById(t))return n.setCursorPosition(e),this.canvasManager.setFocus(n),s!==this.canvasManager.getActiveSection()&&this.canvasManager.setActiveSection(s),void this.canvasManager.render()}}handleVerticalNavigation(t,e){const i="ArrowUp"===t.key?-1:1,n=this.canvasManager.getEditingTextBox();if(e instanceof W){const n=e;if(n.focusedCell){const e=n.getCell(n.focusedCell.row,n.focusedCell.col);if(e){const s=e.flowingContent,o=e.getFlowedLines(0),r=s.getCursorPosition();t.shiftKey?s.hasSelectionAnchor()||s.setSelectionAnchor():s.clearSelection();let a=0;for(let t=0;t<o.length;t++){if(r<=o[t].endIndex){a=t;break}t===o.length-1&&(a=t)}const l=0===a,h=a===o.length-1||0===o.length;if(-1===i&&l){const t=n.focusedCell.row-1;if(t>=0){n.focusCell(t,n.focusedCell.col);const e=n.getCell(t,n.focusedCell.col);if(e){const t=e.flowingContent.getText();e.flowingContent.setCursorPosition(t.length)}}return this.canvasManager.render(),void this.emitTableCellCursorChanged(n)}if(1===i&&h){const t=n.focusedCell.row+1;if(t<n.rowCount){n.focusCell(t,n.focusedCell.col);const e=n.getCell(t,n.focusedCell.col);e&&e.flowingContent.setCursorPosition(0)}return this.canvasManager.render(),void this.emitTableCellCursorChanged(n)}const d=a+i;if(d>=0&&d<o.length){const t=o[d],e=r-o[a].startIndex,i=t.endIndex-t.startIndex,n=Math.min(e,i);s.setCursorPosition(t.startIndex+n),s.resetCursorBlink()}this.canvasManager.render(),this.emitTableCellCursorChanged(n)}}return}const s=n?n.flowingContent:this.getActiveFlowingContent();if(t.shiftKey?s.hasSelectionAnchor()||s.setSelectionAnchor():s.clearSelection(),n){const t=this.canvasManager.getEditingTextBoxPageId();if(t){const e=this.canvasManager.getContext(t);e&&(n.moveCursorVertical(i,e),this.canvasManager.render(),this.emit("textbox-cursor-changed",{textBox:n,cursorPosition:n.flowingContent.getCursorPosition(),selection:n.flowingContent.getSelection()}))}}else{const t=this.canvasManager.moveCursorVertical(i);null!==t&&(s.setCursorPosition(t),s.resetCursorBlink()),this.canvasManager.render()}}enableTextInput(){if(this.keyboardListenerActive=!0,this.canvasManager.isEditingTextBox())this.emit("text-input-enabled");else{if(this.canvasManager.getFocusedControl())return this.canvasManager.isCursorSuspended()&&this.canvasManager.resumeCursor(),this.container.focus(),void this.emit("text-input-enabled");this.canvasManager.showTextCursor(),this.container.focus(),this.emit("text-input-enabled")}}disableTextInput(){this.keyboardListenerActive=!1,this.canvasManager.hideTextCursor(),this.emit("text-input-disabled")}isEditingTextBox(){return this.canvasManager.isEditingTextBox()}isTextEditing(){const t=this.canvasManager.getFocusedControl();return t instanceof $||(!!this.canvasManager.isEditingTextBox()||!!(t instanceof W&&t.focusedCell))}getEditingFlowingContent(){const t=this.canvasManager.getFocusedControl();if(t instanceof $)return t;const e=this.canvasManager.getEditingTextBox();if(e)return e.flowingContent;if(t instanceof W&&t.focusedCell){const e=t.getCell(t.focusedCell.row,t.focusedCell.col);if(e)return e.flowingContent}return null}saveEditingContext(){const t=this.getEditingFlowingContent();if(t){const e=t.getSelection();this._savedEditingContext={flowingContent:t,selection:e&&e.start!==e.end?{start:e.start,end:e.end}:null}}}getSavedOrCurrentSelection(){const t=this.getUnifiedSelection();return t||(this._savedEditingContext?.selection?this._savedEditingContext.selection:null)}applyFormattingWithFallback(t,e,i){O.log("[pc-editor] applyFormattingWithFallback",t,e,i);let n=this.getEditingFlowingContent();if(!n&&this._savedEditingContext&&(n=this._savedEditingContext.flowingContent),!n)throw new Error("No text is being edited");n.applyFormatting(t,e,i),this.canvasManager.render()}setPendingFormatting(t){let e=this.getEditingFlowingContent();if(!e&&this._savedEditingContext&&(e=this._savedEditingContext.flowingContent),!e)throw new Error("No text is being edited");e.setPendingFormatting(t)}getPendingFormatting(){const t=this.getEditingFlowingContent();return t?t.getPendingFormatting():null}hasPendingFormatting(){const t=this.getEditingFlowingContent();return!!t&&t.hasPendingFormatting()}clearPendingFormatting(){const t=this.getEditingFlowingContent();t&&t.clearPendingFormatting()}clearSavedEditingContext(){this._savedEditingContext=null}getEditingTextBox(){return this.canvasManager.getEditingTextBox()}getTextBoxSelection(){const t=this.canvasManager.getEditingTextBox();if(!t)return null;const e=t.flowingContent.getSelection();return e?{start:e.start,end:e.end}:null}applyTextBoxFormatting(t,e,i){const n=this.canvasManager.getEditingTextBox();if(!n)throw new Error("No text box is being edited");n.flowingContent.applyFormatting(t,e,i),this.canvasManager.render()}getTextBoxFormattingAtCursor(){const t=this.canvasManager.getEditingTextBox();if(!t)return null;const e=t.flowingContent.getSelection();if(e&&e.start!==e.end)return t.flowingContent.getFormattingAt(e.start);const i=t.flowingContent.getCursorPosition();return t.flowingContent.getFormattingAt(i)}setTextBoxAlignment(t){const e=this.canvasManager.getEditingTextBox();if(!e)throw new Error("No text box is being edited");const i=e.flowingContent.getSelection();i&&i.start!==i.end?e.flowingContent.setAlignmentForRange(i.start,i.end,t):e.flowingContent.setAlignment(t),this.canvasManager.render()}getTextBoxAlignmentAtCursor(){const t=this.canvasManager.getEditingTextBox();if(!t)return"left";const e=t.flowingContent.getCursorPosition();return t.flowingContent.getAlignmentAt(e)}getUnifiedFormattingAtCursor(){const t=this.getEditingFlowingContent();if(!t)return null;const e=t.getSelection();return e&&e.start!==e.end?t.getFormattingAt(e.start):t.getEffectiveFormattingAtCursor()}applyUnifiedFormatting(t,e,i){const n=this.getEditingFlowingContent();if(!n)throw new Error("No text is being edited");n.applyFormatting(t,e,i),this.canvasManager.render()}getUnifiedSelection(){const t=this.getEditingFlowingContent();if(!t)return null;const e=t.getSelection();return e&&e.start!==e.end?{start:e.start,end:e.end}:null}getUnifiedAlignmentAtCursor(){const t=this.getEditingFlowingContent();if(!t)return"left";const e=t.getCursorPosition();return t.getAlignmentAt(e)}setUnifiedAlignment(t){O.log("[pc-editor] setUnifiedAlignment",t);const e=this.getEditingFlowingContent();if(!e)throw new Error("No text is being edited");const i=e.getSelection();i&&i.start!==i.end?e.setAlignmentForRange(i.start,i.end,t):e.setAlignment(t),this.canvasManager.render()}insertText(t){if(O.log("[pc-editor] insertText",t),!this._isReady)throw new Error("Editor is not ready");const e=this.getActiveFlowingContent();e&&e.insertText(t)}getFlowingText(){if(!this._isReady)throw new Error("Editor is not ready");const t=this.getActiveFlowingContent();return t?t.getText():""}setFlowingText(t){if(O.log("[pc-editor] setFlowingText"),!this._isReady)throw new Error("Editor is not ready");const e=this.getActiveFlowingContent();e&&e.setText(t)}setCursorPosition(t){if(O.log("[pc-editor] setCursorPosition",t),!this._isReady)throw new Error("Editor is not ready");let e=this.getEditingFlowingContent();e||(e=this.getActiveFlowingContent()),e&&(e.setCursorPosition(t),this.currentSelection={type:"cursor",position:t,section:this._activeEditingSection},this.emitSelectionChange())}getCursorPosition(){const t=this.currentSelection;if("cursor"===t.type)return t.position;if("text"===t.type)return t.start;const e=this.getEditingFlowingContent()||this.getActiveFlowingContent();return e?e.getCursorPosition():0}insertEmbeddedObject(t,e="inline"){if(O.log("[pc-editor] insertEmbeddedObject",t.id,e),!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection();let i=this.getEditingFlowingContent();if(i||(i=this.getActiveFlowingContent()),!i)throw new Error("No active section available");i.insertEmbeddedObject(t,e),this.observeEmbeddedObject(t),this.canvasManager.render(),this.emit("embedded-object-added",{object:t,position:e,section:this._activeEditingSection})}insertSubstitutionField(t,e){if(O.log("[pc-editor] insertSubstitutionField",t),!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection();let i=this.getEditingFlowingContent();if(i||(i=this.getActiveFlowingContent()),!i)throw new Error("No active section available");const n=i.insertSubstitutionField(t,e);this.canvasManager.render(),this.emit("substitution-field-added",{field:n,section:this._activeEditingSection})}insertPageNumberField(t){if(O.log("[pc-editor] insertPageNumberField"),!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection();let e=this.getEditingFlowingContent();if(e||(e=this.getActiveFlowingContent()),!e)throw new Error("No active section available");const i=e.insertPageNumberField(t);this.canvasManager.render(),this.emit("page-number-field-added",{field:i,section:this._activeEditingSection})}insertPageCountField(t){if(O.log("[pc-editor] insertPageCountField"),!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection();let e=this.getEditingFlowingContent();if(e||(e=this.getActiveFlowingContent()),!e)throw new Error("No active section available");const i=e.insertPageCountField(t);this.canvasManager.render(),this.emit("page-count-field-added",{field:i,section:this._activeEditingSection})}insertPageBreak(){if(O.log("[pc-editor] insertPageBreak"),!this._isReady)throw new Error("Editor is not ready");const t=this.document.bodyFlowingContent;if(!t.hasFocus())throw new Error("Page breaks can only be inserted in body content");t.insertPageBreak(),this.canvasManager.render(),this.emit("page-break-inserted",{position:t.getCursorPosition()})}getFieldAt(t){if(!this._isReady)return null;const e=this.getActiveFlowingContent();if(!e)return null;const i=e.getSubstitutionFieldManager();return i.getFieldAt(t)||i.getFieldAt(t-1)||null}getSelectedField(){const t=this.currentSelection;return"cursor"===t.type?this.getFieldAt(t.position):"text"===t.type?this.getFieldAt(t.start):null}getSelectedTextBox(){const t=this.canvasManager.getSelectedElements();if(0===t.length)return null;const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjects();for(const i of t)for(const[,t]of e.entries())if(t.id===i&&t instanceof E)return t}return null}getSelectedTable(){const t=this.canvasManager.getSelectedElements();if(0===t.length)return null;const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjects();for(const i of t)for(const[,t]of e.entries())if(t.id===i&&t instanceof W)return t}return null}getSelectedImage(){const t=this.canvasManager.getSelectedElements();if(0===t.length)return null;const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjects();for(const i of t)for(const[,t]of e.entries())if(t.id===i&&t instanceof I)return t}return null}getFocusedTable(){const t=this.canvasManager?.getFocusedControl();return t&&t instanceof W?t:null}updateTextBox(t,e){if(!this._isReady)return!1;const i=this.findTextBoxById(t);if(!i)return O.warn(`[pc-editor:updateTextBox] Text box not found: ${t}`),!1;if(void 0!==e.position&&(i.position=e.position),void 0!==e.relativeOffset&&(i.relativeOffset=e.relativeOffset),void 0!==e.backgroundColor&&(i.backgroundColor=e.backgroundColor),void 0!==e.border){const t=i.border;i.border={top:e.border.top||t.top,right:e.border.right||t.right,bottom:e.border.bottom||t.bottom,left:e.border.left||t.left}}return void 0!==e.padding&&(i.padding=e.padding),this.render(),this.emit("textbox-updated",{textBoxId:t,updates:e}),!0}findTextBoxById(t){const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjects();for(const[,i]of e.entries())if(i.id===t&&i instanceof E)return i}return null}updateImage(t,e){if(!this._isReady)return!1;const i=this.findImageById(t);return i?(void 0!==e.position&&(i.position=e.position),void 0!==e.relativeOffset&&(i.relativeOffset=e.relativeOffset),void 0!==e.fit&&(i.fit=e.fit),void 0!==e.resizeMode&&(i.resizeMode=e.resizeMode),void 0!==e.alt&&(i.alt=e.alt),this.render(),this.emit("image-updated",{imageId:t,updates:e}),!0):(O.warn(`[pc-editor:updateImage] Image not found: ${t}`),!1)}setImageSource(t,e,i){if(!this._isReady)return!1;const n=this.findImageById(t);return n?(n.setSource(e,i),this.render(),this.emit("image-source-changed",{imageId:t}),!0):(O.warn(`[pc-editor:setImageSource] Image not found: ${t}`),!1)}findImageById(t){const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjects();for(const[,i]of e.entries())if(i.id===t&&i instanceof I)return i}return null}tableInsertRow(t,e,i){this._isReady&&(t.insertRow(e,i),this.canvasManager.render())}tableRemoveRow(t,e){this._isReady&&(t.removeRow(e),this.canvasManager.render())}tableInsertColumn(t,e,i){this._isReady&&(t.insertColumn(e,i),this.canvasManager.render())}tableRemoveColumn(t,e){this._isReady&&(t.removeColumn(e),this.canvasManager.render())}beginCompoundOperation(t){this.transactionManager.beginCompoundOperation(t)}endCompoundOperation(t){this.transactionManager.endCompoundOperation(t),this.canvasManager.render()}updateField(t,e){if(!this._isReady)return!1;const i=this.getActiveFlowingContent();if(!i)return!1;const n=i.getSubstitutionFieldManager();if(!n.getFieldAt(t))return!1;const s=n.updateFieldConfig(t,e);return s&&(this.canvasManager.render(),this.emit("substitution-field-updated",{textIndex:t,updates:e,section:this._activeEditingSection})),s}insertInlineElement(t,e="inline"){O.warn("[pc-editor] insertInlineElement is deprecated and no longer functional. Use insertEmbeddedObject instead.")}applyMergeData(t){if(!this._isReady)throw new Error("Editor is not ready");const e=this.document.bodyFlowingContent;let i=0;this.expandRepeatingSections(e,t),this.expandTableRowLoops(e,t),this.expandTableRowLoops(this.document.headerFlowingContent,t),this.expandTableRowLoops(this.document.footerFlowingContent,t),i+=this.substituteFieldsInContent(e,t),i+=this.substituteFieldsInEmbeddedObjects(e,t),i+=this.substituteFieldsInContent(this.document.headerFlowingContent,t),i+=this.substituteFieldsInEmbeddedObjects(this.document.headerFlowingContent,t),i+=this.substituteFieldsInContent(this.document.footerFlowingContent,t),i+=this.substituteFieldsInEmbeddedObjects(this.document.footerFlowingContent,t),this.canvasManager.render(),this.emit("merge-data-applied",{data:t,fieldCount:i})}substituteFieldsInContent(t,e){const i=t.getSubstitutionFieldManager().getFieldsArray().filter(t=>!t.fieldType||"data"===t.fieldType).sort((t,e)=>e.textIndex-t.textIndex);for(const n of i){const i=this.resolveFieldPath(n.fieldName,e);let s;s=void 0!==i?Z(i,n.formatConfig):n.defaultValue||`{{${n.fieldName}}}`;const o=n.formatting,r=n.textIndex;t.deleteText(n.textIndex,1),t.setCursorPosition(r),t.insertText(s),o&&t.applyFormatting(r,r+s.length,o)}return i.length}substituteFieldsInEmbeddedObjects(t,e){let i=0;const n=t.getEmbeddedObjects();for(const[,t]of n.entries())if(t instanceof E)i+=this.substituteFieldsInContent(t.flowingContent,e);else if(t instanceof W)for(const n of t.rows)for(const t of n.cells)i+=this.substituteFieldsInContent(t.flowingContent,e);return i}expandTableRowLoops(t,e){const i=t.getEmbeddedObjects();for(const[,t]of i.entries())t instanceof W&&this.expandTableRowLoopsInTable(t,e)}expandTableRowLoopsInTable(t,e){const i=t.getAllRowLoops();if(0===i.length)return;const n=[...i].sort((t,e)=>e.startRowIndex-t.startRowIndex);for(const i of n){const n=this.getValueAtPath(e,i.fieldPath);if(!Array.isArray(n)||0===n.length){t.removeRowLoop(i.id);continue}const s=n.length,o=t.getRowsInRange(i.startRowIndex,i.endRowIndex);t.removeRowsInRange(i.startRowIndex,i.endRowIndex);for(let e=s-1;e>=0;e--){const n=o.map(t=>t.clone());for(const t of n)for(const n of t.cells)this.rewriteFieldsInContent(n.flowingContent,i.fieldPath,e);t.insertRowsAt(i.startRowIndex,n)}t.removeRowLoop(i.id)}t.markLayoutDirty()}rewriteFieldsInContent(t,e,i){const n=t.getSubstitutionFieldManager().getFieldsArray();for(const t of n)if(t.fieldName.startsWith(e+".")||t.fieldName===e){const n=this.rewriteFieldNameWithIndex(t.fieldName,e,i);t.fieldName=n}}expandRepeatingSections(t,e){const i=t.getRepeatingSectionManager(),n=t.getSubstitutionFieldManager(),s=i.getSectionsDescending();for(const o of s){const s=this.getValueAtPath(e,o.fieldPath);if(!Array.isArray(s)||0===s.length){i.remove(o.id);continue}const r=s.length,a=t.getText().substring(o.startIndex,o.endIndex),l=o.endIndex-o.startIndex,h=n.getFieldsArray().filter(t=>t.textIndex>=o.startIndex&&t.textIndex<o.endIndex);if(r>1){const e=o.endIndex;for(let i=1;i<r;i++){t.setCursorPosition(e+(i-1)*l),t.insertText(a);for(const t of h){const s=e+(i-1)*l+(t.textIndex-o.startIndex),r=this.rewriteFieldNameWithIndex(t.fieldName,o.fieldPath,i);n.insert(r,s,{displayFormat:t.displayFormat,defaultValue:t.defaultValue}),t.formatting&&n.setFieldFormatting(s,t.formatting)}}}for(const t of h){const e=this.rewriteFieldNameWithIndex(t.fieldName,o.fieldPath,0);n.updateFieldConfig(t.textIndex,{fieldName:e})}i.remove(o.id)}}getValueAtPath(t,e){const i=e.split(".");let n=t;for(const t of i){if(null==n)return;if("object"!=typeof n||null===n)return;n=n[t]}return n}rewriteFieldNameWithIndex(t,e,i){if(t.startsWith(e+".")){return`${e}[${i}]${t.substring(e.length)}`}return t===e?`${e}[${i}]`:t}resolveFieldPath(t,e){const i=this.parseFieldPath(t);let n=e;for(const t of i){if(null==n)return;const e=t.match(/^\[(\d+)\]$/);if(e){const t=parseInt(e[1],10);if(!Array.isArray(n))return;n=n[t];continue}if(Array.isArray(n)&&(n=n[0],null==n))return;if("object"!=typeof n||null===n)return;n=n[t]}return Array.isArray(n)?n[0]:n}parseFieldPath(t){const e=[];let i="";for(let n=0;n<t.length;n++){const s=t[n];if("."===s)i&&(e.push(i),i="");else if("["===s){i&&(e.push(i),i="");const s=t.indexOf("]",n);-1!==s&&(e.push(t.substring(n,s+1)),n=s)}else i+=s}return i&&e.push(i),e}applyTextFormatting(t,e,i){if(!this._isReady)throw new Error("Editor is not ready");const n=this.getActiveFlowingContent();n&&n.applyFormatting(t,e,i)}getFormattingAt(t){if(!this._isReady)return null;const e=this.getActiveFlowingContent();return e?e.getFormattingAt(t):null}getSelectionFormatting(){if(!this._isReady)return null;const t=this.currentSelection;let e;if("text"===t.type)e=t.start;else{if("cursor"!==t.type)return null;e=t.position}const i=this.getActiveFlowingContent();return i?i.getFormattingAt(e):null}setAlignment(t){if(!this._isReady)throw new Error("Editor is not ready");const e=this.getActiveFlowingContent();e&&(e.setAlignment(t),this.canvasManager.render(),this.emit("alignment-changed",{alignment:t,section:this._activeEditingSection}))}setAlignmentForSelection(t){if(!this._isReady)throw new Error("Editor is not ready");const e=this.currentSelection,i=this.getActiveFlowingContent();i&&("text"===e.type?i.setAlignmentForRange(e.start,e.end,t):i.setAlignment(t),this.canvasManager.render(),this.emit("alignment-changed",{alignment:t,section:this._activeEditingSection}))}getAlignmentAtCursor(){if(!this._isReady)return"left";const t=this.currentSelection,e=this.getActiveFlowingContent();if(!e)return"left";let i;return i="text"===t.type?t.start:"cursor"===t.type?t.position:e.getCursorPosition(),e.getAlignmentAt(i)}toggleBulletList(){if(!this._isReady)return;const t=this.getActiveFlowingContent();t&&(t.toggleBulletList(),this.canvasManager.render(),this.emit("list-changed",{type:"bullet",section:this._activeEditingSection}))}toggleNumberedList(){if(!this._isReady)return;const t=this.getActiveFlowingContent();t&&(t.toggleNumberedList(),this.canvasManager.render(),this.emit("list-changed",{type:"number",section:this._activeEditingSection}))}indentParagraph(){if(!this._isReady)return;const t=this.getActiveFlowingContent();t&&(t.indentParagraph(),this.canvasManager.render(),this.emit("indent-changed",{section:this._activeEditingSection}))}outdentParagraph(){if(!this._isReady)return;const t=this.getActiveFlowingContent();t&&(t.outdentParagraph(),this.canvasManager.render(),this.emit("indent-changed",{section:this._activeEditingSection}))}getListFormatting(){if(!this._isReady)return;const t=this.getActiveFlowingContent();return t?t.getListFormatting():void 0}insertHyperlink(t,e){if(!this._isReady)return null;const i=this.getActiveFlowingContent();if(!i)return null;const n=i.insertHyperlink(t,e);return n&&(this.canvasManager.render(),this.emit("hyperlink-inserted",{hyperlink:n})),n}insertHyperlinkAt(t,e,i,n){if(!this._isReady)return null;const s=this.getActiveFlowingContent();if(!s)return null;const o=s.insertHyperlinkAt(t,e,i,n);return this.canvasManager.render(),this.emit("hyperlink-inserted",{hyperlink:o}),o}removeHyperlink(t){if(!this._isReady)return;const e=this.getActiveFlowingContent();e&&(e.removeHyperlink(t),this.canvasManager.render(),this.emit("hyperlink-removed",{id:t}))}updateHyperlink(t,e){if(!this._isReady)return;const i=this.getActiveFlowingContent();i&&(i.updateHyperlink(t,e),this.canvasManager.render(),this.emit("hyperlink-updated",{id:t,updates:e}))}getHyperlinkAt(t){if(!this._isReady)return;const e=this.getActiveFlowingContent();return e?e.getHyperlinkAt(t):void 0}getHyperlinkById(t){if(!this._isReady)return;const e=this.getActiveFlowingContent();return e?e.getHyperlinkById(t):void 0}getHyperlinksInRange(t,e){if(!this._isReady)return[];const i=this.getActiveFlowingContent();return i?i.getHyperlinksInRange(t,e):[]}getAllHyperlinks(){if(!this._isReady)return[];const t=this.getActiveFlowingContent();return t?t.getAllHyperlinks():[]}updateDocumentSettings(t){if(!this._isReady)throw new Error("Editor is not ready");this.document.updateSettings(t),this.emit("document-settings-changed",{settings:t})}getDocumentSettings(){if(!this._isReady)throw new Error("Editor is not ready");return this.document.settings}setShowControlCharacters(t){this.options.showControlCharacters=t,this.canvasManager&&this.canvasManager.setShowControlCharacters(t),this.emit("control-characters-changed",{show:t})}getShowControlCharacters(){return this.options.showControlCharacters}setShowGrid(t){this.options.showGrid=t,this.canvasManager&&this.canvasManager.setShowGrid(t),this.emit("grid-changed",{show:t})}getShowGrid(){return this.options.showGrid}setShowMarginLines(t){this.canvasManager&&this.canvasManager.setShowMarginLines(t),this.emit("margin-lines-changed",{show:t})}getShowMarginLines(){return!this.canvasManager||this.canvasManager.getShowMarginLines()}getParagraphBoundaries(){return this._isReady?this.document.bodyFlowingContent.getParagraphBoundaries():[]}createRepeatingSection(t,e,i){if(!this._isReady)throw new Error("Editor is not ready");const n=this.getFocusedTable();if(n&&n.focusedCell){O.log("[pc-editor] createRepeatingSection → table row loop",i);const t=n.focusedCell.row,e=n.createRowLoop(t,t,i);return e&&(this.canvasManager.render(),this.emit("table-row-loop-added",{table:n,loop:e})),null}O.log("[pc-editor] createRepeatingSection",t,e,i);const s=this.document.bodyFlowingContent.createRepeatingSection(t,e,i);return s&&(this.canvasManager.render(),this.emit("repeating-section-added",{section:s})),s}getRepeatingSection(t){return this._isReady&&this.document.bodyFlowingContent.getRepeatingSection(t)||null}getRepeatingSections(){return this._isReady?this.document.bodyFlowingContent.getRepeatingSections():[]}updateRepeatingSectionFieldPath(t,e){if(!this._isReady)return!1;const i=this.document.bodyFlowingContent.updateRepeatingSectionFieldPath(t,e);return i&&(this.canvasManager.render(),this.emit("repeating-section-updated",{id:t,fieldPath:e})),i}removeRepeatingSection(t){if(!this._isReady)return!1;const e=this.document.bodyFlowingContent.removeRepeatingSection(t);return e&&(this.canvasManager.render(),this.emit("repeating-section-removed",{id:t})),e}getRepeatingSectionAtBoundary(t){return this._isReady&&this.document.bodyFlowingContent.getRepeatingSectionAtBoundary(t)||null}getHeaderText(){if(!this._isReady)throw new Error("Editor is not ready");return this.document.headerFlowingContent.getText()}setHeaderText(t){if(!this._isReady)throw new Error("Editor is not ready");this.document.headerFlowingContent.setText(t)}getFooterText(){if(!this._isReady)throw new Error("Editor is not ready");return this.document.footerFlowingContent.getText()}setFooterText(t){if(!this._isReady)throw new Error("Editor is not ready");this.document.footerFlowingContent.setText(t)}insertHeaderSubstitutionField(t,e){if(!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection();const i=this.document.headerFlowingContent.insertSubstitutionField(t,e);this.canvasManager.render(),this.emit("substitution-field-added",{field:i,section:"header"})}insertFooterSubstitutionField(t,e){if(!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection();const i=this.document.footerFlowingContent.insertSubstitutionField(t,e);this.canvasManager.render(),this.emit("substitution-field-added",{field:i,section:"footer"})}insertHeaderEmbeddedObject(t,e="inline"){if(!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection(),this.document.headerFlowingContent.insertEmbeddedObject(t,e),this.observeEmbeddedObject(t),this.canvasManager.render(),this.emit("embedded-object-added",{object:t,position:e,section:"header"})}insertFooterEmbeddedObject(t,e="inline"){if(!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection(),this.document.footerFlowingContent.insertEmbeddedObject(t,e),this.observeEmbeddedObject(t),this.canvasManager.render(),this.emit("embedded-object-added",{object:t,position:e,section:"footer"})}async copy(){const t=this.getEditingFlowingContent()||this.getActiveFlowingContent();if(!t)return!1;const e=await this.clipboardManager.copy(t);return e&&this.emit("copy",{success:!0}),e}async cut(){const t=this.getEditingFlowingContent()||this.getActiveFlowingContent();if(!t)return!1;const e=t.getSelection();if(!e||e.start===e.end)return!1;if(!await this.clipboardManager.copy(t))return!1;this.transactionManager.beginCompoundOperation("Cut");try{return t.deleteSelection(),this.transactionManager.endCompoundOperation(),this.canvasManager.render(),this.emit("cut",{success:!0}),!0}catch(t){return this.transactionManager.endCompoundOperation(),console.error("Cut failed:",t),!1}}async paste(){const t=this.getEditingFlowingContent()||this.getActiveFlowingContent();if(!t)return!1;const e=await this.clipboardManager.read();if("empty"===e.type||null===e.data)return!1;this.transactionManager.beginCompoundOperation("Paste");try{t.hasSelection()&&t.deleteSelection();let i=!1;if("pceditor"===e.type)i=this.pasteProprietaryContent(t,e.data);else if("html"===e.type){const n=this.clipboardManager.parseHtml(e.data);i=this.pasteClipboardContent(t,n)}else if("text"===e.type){const n=e.data;t.insertText(n),i=!0}else"image"===e.type&&(i=await this.pasteImage(t,e.data));return this.transactionManager.endCompoundOperation(),!!i&&(this.canvasManager.render(),this.emit("paste",{success:!0,type:e.type}),!0)}catch(t){return this.transactionManager.endCompoundOperation(),console.error("Paste failed:",t),!1}}selectAll(){const t=this.canvasManager.getEditingTextBox();if(t)return t.flowingContent.selectAll(),void this.canvasManager.render();const e=this.canvasManager.getFocusedControl();if(e instanceof W&&e.focusedCell){const t=e.getCell(e.focusedCell.row,e.focusedCell.col);if(t)return t.flowingContent.selectAll(),void this.canvasManager.render()}const i=this.getActiveFlowingContent();i&&(i.selectAll(),this.canvasManager.render(),this.emit("text-selection-changed",{selection:i.getSelection(),section:this._activeEditingSection}))}pasteProprietaryContent(t,e){const i=this.clipboardManager.generateNewIds(e.content);return this.pasteClipboardContent(t,i)}pasteClipboardContent(t,e){const i=t.getCursorPosition(),{text:n,formattingRuns:s,substitutionFields:o,embeddedObjects:r,hyperlinks:a}=e;if(t.insertText(n),s&&s.length>0){const e=t.getFormattingManager();for(let t=0;t<s.length;t++){const o=s[t],r=s[t+1],a=i+o.index,l=r?i+r.index:i+n.length;e.applyFormatting(a,l,{fontFamily:o.formatting.fontFamily,fontSize:o.formatting.fontSize,fontWeight:o.formatting.fontWeight,fontStyle:o.formatting.fontStyle,color:o.formatting.color,backgroundColor:o.formatting.backgroundColor})}}if(o&&o.length>0)for(const e of o){const n=i+e.textIndex;t.insertSubstitutionFieldAt(e.fieldName,n,{fieldType:e.fieldType,displayFormat:e.displayFormat,defaultValue:e.defaultValue,formatting:e.formatting})}if(r&&r.length>0)for(const e of r){const n=i+e.textIndex,s=this.createEmbeddedObjectFromData(e.object);s&&(t.insertEmbeddedObjectAt(s,n,s.position),this.observeEmbeddedObject(s))}if(a&&a.length>0)for(const e of a){const n=i+e.startIndex,s=i+e.endIndex;t.insertHyperlinkAt(e.url,n,s,{title:e.title,formatting:e.formatting})}return!0}createEmbeddedObjectFromData(t){const e=U.tryCreate(t);return e||O.warn("[pc-editor] Unknown object type:",t.objectType),e}async pasteImage(t,e){try{const{dataUrl:i,width:n,height:s}=await this.clipboardManager.createImageFromBlob(e),o=400,r=n>o?o/n:1,a=new I({id:`img_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,textIndex:t.getCursorPosition(),size:{width:n*r,height:s*r},src:i,alt:"Pasted image"});return t.insertEmbeddedObject(a,"inline"),this.observeEmbeddedObject(a),!0}catch(t){return console.error("Failed to paste image:",t),!1}}setLogging(t){O.setEnabled(t)}destroy(){this.disableTextInput(),this.canvasManager&&this.canvasManager.destroy(),this.layoutEngine&&this.layoutEngine.destroy(),this.document.clear(),this.removeAllListeners(),this._isReady=!1}},t.PDFImportError=zt,t.PDFImporter=Ht,t.PDFParser=Ot,t.Page=r,t.RegionManager=X,t.RepeatingSectionManager=y,t.RepeatingSectionPane=class extends Vt{constructor(t="repeating-section",e={}){super(t,{className:"pc-pane-repeating-section",...e}),this.fieldPathInput=null,this.positionHint=null,this.currentSection=null,this.onApplyCallback=e.onApply,this.onRemoveCallback=e.onRemove}attach(t){if(super.attach(t),this.editor){const t=t=>{if("repeating-section"===t.type&&t.sectionId){const e=this.editor?.getRepeatingSection(t.sectionId);e&&this.showSection(e)}},e=()=>{this.hideSection()};this.editor.on("selection-change",t),this.editor.on("repeating-section-removed",e),this.eventCleanup.push(()=>{this.editor?.off("selection-change",t),this.editor?.off("repeating-section-removed",e)})}}createContent(){const t=document.createElement("div");this.fieldPathInput=this.createTextInput({placeholder:"items"}),t.appendChild(this.createFormGroup("Array Field Path",this.fieldPathInput,{hint:'Path to array in merge data (e.g., "items" or "contact.addresses")'}));const e=this.createButton("Apply Changes",{variant:"primary"});this.addButtonListener(e,()=>this.applyChanges()),t.appendChild(e);const i=this.createButton("Remove Loop",{variant:"danger"});return i.style.marginTop="0.5rem",this.addButtonListener(i,()=>this.removeSection()),t.appendChild(i),this.positionHint=this.createHint(""),t.appendChild(this.positionHint),t}showSection(t){this.currentSection=t,this.fieldPathInput&&(this.fieldPathInput.value=t.fieldPath),this.positionHint&&(this.positionHint.textContent=`Loop from position ${t.startIndex} to ${t.endIndex}`),this.show()}hideSection(){this.currentSection=null,this.hide()}applyChanges(){if(!this.editor||!this.currentSection)return void this.onApplyCallback?.(!1,new Error("No section selected"));const t=this.fieldPathInput?.value.trim();if(t){if(t!==this.currentSection.fieldPath)try{this.editor.updateRepeatingSectionFieldPath(this.currentSection.id,t)?(this.currentSection=this.editor.getRepeatingSection(this.currentSection.id)||null,this.currentSection&&this.showSection(this.currentSection),this.onApplyCallback?.(!0)):this.onApplyCallback?.(!1,new Error("Failed to update section"))}catch(t){this.onApplyCallback?.(!1,t instanceof Error?t:new Error(String(t)))}}else this.onApplyCallback?.(!1,new Error("Field path cannot be empty"))}removeSection(){if(this.editor&&this.currentSection)try{this.editor.removeRepeatingSection(this.currentSection.id),this.hideSection(),this.onRemoveCallback?.(!0)}catch{this.onRemoveCallback?.(!1)}}getCurrentSection(){return this.currentSection}hasSection(){return null!==this.currentSection}update(){}},t.RulerControl=$t,t.SubstitutionFieldManager=b,t.SubstitutionFieldPane=class extends Vt{constructor(t="substitution-field",e={}){super(t,{className:"pc-pane-substitution-field",...e}),this.fieldNameInput=null,this.fieldDefaultInput=null,this.valueTypeSelect=null,this.numberFormatSelect=null,this.currencyFormatSelect=null,this.dateFormatSelect=null,this.positionHint=null,this.numberFormatGroup=null,this.currencyFormatGroup=null,this.dateFormatGroup=null,this.currentField=null,this.onApplyCallback=e.onApply}attach(t){if(super.attach(t),this.editor){const t=t=>{"field"===t.type&&t.field?this.showField(t.field):!t.type||t.type};this.editor.on("selection-change",t),this.eventCleanup.push(()=>{this.editor?.off("selection-change",t)})}}createContent(){const t=document.createElement("div");this.fieldNameInput=this.createTextInput({placeholder:"Field name"}),t.appendChild(this.createFormGroup("Field Name",this.fieldNameInput)),this.fieldDefaultInput=this.createTextInput({placeholder:"Default value (optional)"}),t.appendChild(this.createFormGroup("Default Value",this.fieldDefaultInput)),this.valueTypeSelect=this.createSelect([{value:"",label:"(None)"},{value:"number",label:"Number"},{value:"currency",label:"Currency"},{value:"date",label:"Date"}]),this.addImmediateApplyListener(this.valueTypeSelect,()=>this.updateFormatGroups()),t.appendChild(this.createFormGroup("Value Type",this.valueTypeSelect)),this.numberFormatGroup=this.createSection(),this.numberFormatGroup.style.display="none",this.numberFormatSelect=this.createSelect([{value:"0",label:"Integer (0)"},{value:"0.00",label:"Two decimals (0.00)"},{value:"0,0",label:"Thousands separator (0,0)"},{value:"0,0.00",label:"Thousands + decimals (0,0.00)"}]),this.numberFormatGroup.appendChild(this.createFormGroup("Number Format",this.numberFormatSelect)),t.appendChild(this.numberFormatGroup),this.currencyFormatGroup=this.createSection(),this.currencyFormatGroup.style.display="none",this.currencyFormatSelect=this.createSelect([{value:"USD",label:"USD ($)"},{value:"EUR",label:"EUR"},{value:"GBP",label:"GBP"},{value:"JPY",label:"JPY"}]),this.currencyFormatGroup.appendChild(this.createFormGroup("Currency",this.currencyFormatSelect)),t.appendChild(this.currencyFormatGroup),this.dateFormatGroup=this.createSection(),this.dateFormatGroup.style.display="none",this.dateFormatSelect=this.createSelect([{value:"MMMM D, YYYY",label:"January 1, 2026"},{value:"MM/DD/YYYY",label:"01/01/2026"},{value:"DD/MM/YYYY",label:"01/01/2026 (EU)"},{value:"YYYY-MM-DD",label:"2026-01-01 (ISO)"}]),this.dateFormatGroup.appendChild(this.createFormGroup("Date Format",this.dateFormatSelect)),t.appendChild(this.dateFormatGroup);const e=this.createButton("Apply Changes",{variant:"primary"});return this.addButtonListener(e,()=>this.applyChanges()),t.appendChild(e),this.positionHint=this.createHint(""),t.appendChild(this.positionHint),t}updateFormatGroups(){const t=this.valueTypeSelect?.value||"";this.numberFormatGroup&&(this.numberFormatGroup.style.display="number"===t?"block":"none"),this.currencyFormatGroup&&(this.currencyFormatGroup.style.display="currency"===t?"block":"none"),this.dateFormatGroup&&(this.dateFormatGroup.style.display="date"===t?"block":"none")}showField(t){this.currentField=t,this.fieldNameInput&&(this.fieldNameInput.value=t.fieldName),this.fieldDefaultInput&&(this.fieldDefaultInput.value=t.defaultValue||""),this.positionHint&&(this.positionHint.textContent=`Field at position ${t.textIndex}`),this.valueTypeSelect&&(this.valueTypeSelect.value=t.formatConfig?.valueType||""),this.numberFormatSelect&&t.formatConfig?.numberFormat&&(this.numberFormatSelect.value=t.formatConfig.numberFormat),this.currencyFormatSelect&&t.formatConfig?.currencyFormat&&(this.currencyFormatSelect.value=t.formatConfig.currencyFormat),this.dateFormatSelect&&t.formatConfig?.dateFormat&&(this.dateFormatSelect.value=t.formatConfig.dateFormat),this.updateFormatGroups(),this.show()}hideField(){this.currentField=null,this.hide()}applyChanges(){if(!this.editor||!this.currentField)return void this.onApplyCallback?.(!1,new Error("No field selected"));const t=this.fieldNameInput?.value.trim();if(!t)return void this.onApplyCallback?.(!1,new Error("Field name cannot be empty"));const e={};t!==this.currentField.fieldName&&(e.fieldName=t);const i=this.fieldDefaultInput?.value||void 0;i!==this.currentField.defaultValue&&(e.defaultValue=i);const n=this.valueTypeSelect?.value;if(n){const t={valueType:n};"number"===n&&this.numberFormatSelect?.value?t.numberFormat=this.numberFormatSelect.value:"currency"===n&&this.currencyFormatSelect?.value?t.currencyFormat=this.currencyFormatSelect.value:"date"===n&&this.dateFormatSelect?.value&&(t.dateFormat=this.dateFormatSelect.value),e.formatConfig=t}else this.currentField.formatConfig&&(e.formatConfig=void 0);if(0!==Object.keys(e).length)try{this.editor.updateField(this.currentField.textIndex,e)?(this.currentField=this.editor.getFieldAt(this.currentField.textIndex)||null,this.onApplyCallback?.(!0)):this.onApplyCallback?.(!1,new Error("Failed to update field"))}catch(t){this.onApplyCallback?.(!1,t instanceof Error?t:new Error(String(t)))}}getCurrentField(){return this.currentField}hasField(){return null!==this.currentField}update(){}},t.TableCell=j,t.TableObject=W,t.TablePane=class extends Vt{constructor(t="table",e={}){super(t,{className:"pc-pane-table",...e}),this.rowCountDisplay=null,this.colCountDisplay=null,this.cellSelectionDisplay=null,this.headerRowInput=null,this.headerColInput=null,this.defaultPaddingInput=null,this.defaultBorderColorInput=null,this.loopFieldInput=null,this.cellBgColorInput=null,this.borderTopCheck=null,this.borderRightCheck=null,this.borderBottomCheck=null,this.borderLeftCheck=null,this.borderWidthInput=null,this.borderColorInput=null,this.borderStyleSelect=null,this.currentTable=null,this._isUpdating=!1,this.onApplyCallback=e.onApply}attach(t){if(super.attach(t),this.editor){const t=()=>this.updateFromFocusedTable();this.editor.on("selection-change",t),this.editor.on("table-cell-focus",t),this.editor.on("table-cell-selection",t),this.eventCleanup.push(()=>{this.editor?.off("selection-change",t),this.editor?.off("table-cell-focus",t),this.editor?.off("table-cell-selection",t)}),this.updateFromFocusedTable()}}createContent(){const t=document.createElement("div"),e=this.createSection("Structure"),i=document.createElement("div");i.className="pc-pane-info-list",this.rowCountDisplay=document.createElement("span"),this.colCountDisplay=document.createElement("span");const n=document.createElement("div");n.className="pc-pane-info",n.innerHTML='<span class="pc-pane-info-label">Rows</span>',n.appendChild(this.rowCountDisplay);const s=document.createElement("div");s.className="pc-pane-info",s.innerHTML='<span class="pc-pane-info-label">Columns</span>',s.appendChild(this.colCountDisplay),i.appendChild(n),i.appendChild(s),e.appendChild(i);const o=this.createButtonGroup(),r=this.createButton("+ Row");this.addButtonListener(r,()=>this.insertRow());const a=this.createButton("- Row");this.addButtonListener(a,()=>this.removeRow());const l=this.createButton("+ Column");this.addButtonListener(l,()=>this.insertColumn());const h=this.createButton("- Column");this.addButtonListener(h,()=>this.removeColumn()),o.appendChild(r),o.appendChild(a),o.appendChild(l),o.appendChild(h),e.appendChild(o),t.appendChild(e);const d=this.createSection("Headers"),c=this.createRow();this.headerRowInput=this.createNumberInput({min:0,max:10,value:0}),this.headerColInput=this.createNumberInput({min:0,max:10,value:0}),c.appendChild(this.createFormGroup("Header Rows",this.headerRowInput,{inline:!0})),c.appendChild(this.createFormGroup("Header Cols",this.headerColInput,{inline:!0})),d.appendChild(c);const g=this.createButton("Apply Headers");this.addButtonListener(g,()=>this.applyHeaders()),d.appendChild(g),t.appendChild(d);const u=this.createSection("Row Loop");this.loopFieldInput=this.createTextInput({placeholder:"items"}),u.appendChild(this.createFormGroup("Array Field",this.loopFieldInput,{hint:"Creates a loop on the currently focused row"}));const f=this.createButton("Create Row Loop");this.addButtonListener(f,()=>this.createRowLoop()),u.appendChild(f),t.appendChild(u);const p=this.createSection("Defaults"),m=this.createRow();this.defaultPaddingInput=this.createNumberInput({min:0,max:20,value:8}),this.defaultBorderColorInput=this.createColorInput("#cccccc"),m.appendChild(this.createFormGroup("Padding",this.defaultPaddingInput,{inline:!0})),m.appendChild(this.createFormGroup("Border",this.defaultBorderColorInput,{inline:!0})),p.appendChild(m);const b=this.createButton("Apply Defaults");this.addButtonListener(b,()=>this.applyDefaults()),p.appendChild(b),t.appendChild(p);const x=this.createSection("Cell Formatting");this.cellSelectionDisplay=this.createHint("No cell selected"),x.appendChild(this.cellSelectionDisplay),this.cellBgColorInput=this.createColorInput("#ffffff"),x.appendChild(this.createFormGroup("Background",this.cellBgColorInput));const y=document.createElement("div");y.className="pc-pane-row",y.style.flexWrap="wrap",y.style.gap="4px",this.borderTopCheck=document.createElement("input"),this.borderTopCheck.type="checkbox",this.borderTopCheck.checked=!0,this.borderRightCheck=document.createElement("input"),this.borderRightCheck.type="checkbox",this.borderRightCheck.checked=!0,this.borderBottomCheck=document.createElement("input"),this.borderBottomCheck.type="checkbox",this.borderBottomCheck.checked=!0,this.borderLeftCheck=document.createElement("input"),this.borderLeftCheck.type="checkbox",this.borderLeftCheck.checked=!0,y.appendChild(this.createCheckbox("Top",!0)),y.appendChild(this.createCheckbox("Right",!0)),y.appendChild(this.createCheckbox("Bottom",!0)),y.appendChild(this.createCheckbox("Left",!0));const w=y.querySelectorAll("label");w[0]&&w[0].replaceChild(this.borderTopCheck,w[0].querySelector("input")),w[1]&&w[1].replaceChild(this.borderRightCheck,w[1].querySelector("input")),w[2]&&w[2].replaceChild(this.borderBottomCheck,w[2].querySelector("input")),w[3]&&w[3].replaceChild(this.borderLeftCheck,w[3].querySelector("input")),x.appendChild(this.createFormGroup("Borders",y));const C=this.createRow();this.borderWidthInput=this.createNumberInput({min:0,max:5,value:1}),this.borderColorInput=this.createColorInput("#cccccc"),C.appendChild(this.createFormGroup("Width",this.borderWidthInput,{inline:!0})),C.appendChild(this.createFormGroup("Color",this.borderColorInput,{inline:!0})),x.appendChild(C),this.borderStyleSelect=this.createSelect([{value:"solid",label:"Solid"},{value:"dashed",label:"Dashed"},{value:"dotted",label:"Dotted"},{value:"none",label:"None"}],"solid"),x.appendChild(this.createFormGroup("Style",this.borderStyleSelect));const S=this.createButton("Apply to Cell(s)",{variant:"primary"});return this.addButtonListener(S,()=>this.applyCellFormatting()),x.appendChild(S),t.appendChild(x),t}updateFromFocusedTable(){if(this.editor&&!this._isUpdating){this._isUpdating=!0;try{const t=this.editor.getFocusedTable();t?this.showTable(t):this.hideTable()}finally{this._isUpdating=!1}}}showTable(t){this.currentTable=t,this.rowCountDisplay&&(this.rowCountDisplay.textContent=String(t.rowCount),this.rowCountDisplay.className="pc-pane-info-value"),this.colCountDisplay&&(this.colCountDisplay.textContent=String(t.columnCount),this.colCountDisplay.className="pc-pane-info-value"),this.headerRowInput&&(this.headerRowInput.value=String(t.headerRowCount)),this.headerColInput&&(this.headerColInput.value=String(t.headerColumnCount)),this.defaultPaddingInput&&(this.defaultPaddingInput.value=String(t.defaultCellPadding)),this.defaultBorderColorInput&&(this.defaultBorderColorInput.value=t.defaultBorderColor),this.updateCellSelectionInfo(t),this.show()}hideTable(){this.currentTable=null,this.hide()}updateCellSelectionInfo(t){if(!this.cellSelectionDisplay)return;const e=t.focusedCell,i=t.selectedRange;if(i){const t=(i.end.row-i.start.row+1)*(i.end.col-i.start.col+1);this.cellSelectionDisplay.textContent=`${t} cells selected`}else if(e){this.cellSelectionDisplay.textContent=`Cell [${e.row}, ${e.col}]`;const i=t.getCell(e.row,e.col);if(i){this.cellBgColorInput&&(this.cellBgColorInput.value=i.backgroundColor||"#ffffff");const t=i.border;this.borderTopCheck&&(this.borderTopCheck.checked="none"!==t.top.style),this.borderRightCheck&&(this.borderRightCheck.checked="none"!==t.right.style),this.borderBottomCheck&&(this.borderBottomCheck.checked="none"!==t.bottom.style),this.borderLeftCheck&&(this.borderLeftCheck.checked="none"!==t.left.style);const e="none"!==t.top.style?t.top:"none"!==t.right.style?t.right:"none"!==t.bottom.style?t.bottom:"none"!==t.left.style?t.left:t.top;this.borderWidthInput&&(this.borderWidthInput.value=String(e.width)),this.borderColorInput&&(this.borderColorInput.value=e.color),this.borderStyleSelect&&(this.borderStyleSelect.value=e.style)}}else this.cellSelectionDisplay.textContent="No cell selected"}insertRow(){if(!this.editor||!this.currentTable)return;const t=this.currentTable.focusedCell,e=t?t.row+1:this.currentTable.rowCount;this.editor.tableInsertRow(this.currentTable,e),this.updateFromFocusedTable()}removeRow(){if(!this.editor||!this.currentTable)return;const t=this.currentTable.focusedCell;t&&this.currentTable.rowCount>1&&(this.editor.tableRemoveRow(this.currentTable,t.row),this.updateFromFocusedTable())}insertColumn(){if(!this.editor||!this.currentTable)return;const t=this.currentTable.focusedCell,e=t?t.col+1:this.currentTable.columnCount;this.editor.tableInsertColumn(this.currentTable,e),this.updateFromFocusedTable()}removeColumn(){if(!this.editor||!this.currentTable)return;const t=this.currentTable.focusedCell;t&&this.currentTable.columnCount>1&&(this.editor.tableRemoveColumn(this.currentTable,t.col),this.updateFromFocusedTable())}applyHeaders(){if(this.currentTable){if(this.headerRowInput){const t=parseInt(this.headerRowInput.value,10);this.currentTable.setHeaderRowCount(t)}if(this.headerColInput){const t=parseInt(this.headerColInput.value,10);this.currentTable.setHeaderColumnCount(t)}this.editor?.render(),this.onApplyCallback?.(!0)}}applyDefaults(){this.currentTable&&(this.defaultPaddingInput&&(this.currentTable.defaultCellPadding=parseInt(this.defaultPaddingInput.value,10)),this.defaultBorderColorInput&&(this.currentTable.defaultBorderColor=this.defaultBorderColorInput.value),this.editor?.render(),this.onApplyCallback?.(!0))}applyCellFormatting(){if(!this.currentTable)return;const t=this.currentTable.focusedCell,e=this.currentTable.selectedRange,i=[];if(e)for(let t=e.start.row;t<=e.end.row;t++)for(let n=e.start.col;n<=e.end.col;n++)i.push({row:t,col:n});else t&&i.push(t);if(0===i.length)return;const n={width:parseInt(this.borderWidthInput?.value||"1",10),color:this.borderColorInput?.value||"#cccccc",style:this.borderStyleSelect?.value||"solid"},s={width:0,color:"#000000",style:"none"},o={top:this.borderTopCheck?.checked?{...n}:{...s},right:this.borderRightCheck?.checked?{...n}:{...s},bottom:this.borderBottomCheck?.checked?{...n}:{...s},left:this.borderLeftCheck?.checked?{...n}:{...s}},r=this.cellBgColorInput?.value;for(const{row:t,col:e}of i){const i=this.currentTable.getCell(t,e);i&&(r&&(i.backgroundColor=r),i.border=o)}this.editor?.render(),this.onApplyCallback?.(!0)}getCurrentTable(){return this.currentTable}hasTable(){return null!==this.currentTable}createRowLoop(){if(!this.editor||!this.currentTable)return void this.onApplyCallback?.(!1,new Error("No table focused"));const t=this.loopFieldInput?.value.trim()||"";t?(this.editor.createRepeatingSection(0,0,t),this.onApplyCallback?.(!0)):this.onApplyCallback?.(!1,new Error("Array field path is required"))}update(){this.updateFromFocusedTable()}},t.TableRow=D,t.TableRowLoopPane=class extends Vt{constructor(t="table-row-loop",e={}){super(t,{className:"pc-pane-table-row-loop",...e}),this.fieldPathInput=null,this.rangeHint=null,this.currentLoop=null,this.currentTable=null,this.onApplyCallback=e.onApply,this.onRemoveCallback=e.onRemove}attach(t){super.attach(t)}createContent(){const t=document.createElement("div");this.fieldPathInput=this.createTextInput({placeholder:"items"}),t.appendChild(this.createFormGroup("Array Field Path",this.fieldPathInput,{hint:'Path to array in merge data (e.g., "items" or "orders")'}));const e=this.createButton("Apply Changes",{variant:"primary"});this.addButtonListener(e,()=>this.applyChanges()),t.appendChild(e);const i=this.createButton("Remove Loop",{variant:"danger"});return i.style.marginTop="0.5rem",this.addButtonListener(i,()=>this.removeLoop()),t.appendChild(i),this.rangeHint=this.createHint(""),t.appendChild(this.rangeHint),t}showLoop(t,e){this.currentTable=t,this.currentLoop=e,this.fieldPathInput&&(this.fieldPathInput.value=e.fieldPath),this.rangeHint&&(this.rangeHint.textContent=`Rows ${e.startRowIndex} - ${e.endRowIndex}`),this.show()}hideLoop(){this.currentTable=null,this.currentLoop=null,this.hide()}applyChanges(){if(!this.currentTable||!this.currentLoop)return void this.onApplyCallback?.(!1,new Error("No loop selected"));const t=this.fieldPathInput?.value.trim();if(t){if(t!==this.currentLoop.fieldPath)try{this.currentTable.updateRowLoopFieldPath(this.currentLoop.id,t)?(this.currentLoop=this.currentTable.getRowLoop(this.currentLoop.id)||null,this.currentLoop&&this.showLoop(this.currentTable,this.currentLoop),this.onApplyCallback?.(!0)):this.onApplyCallback?.(!1,new Error("Failed to update loop"))}catch(t){this.onApplyCallback?.(!1,t instanceof Error?t:new Error(String(t)))}}else this.onApplyCallback?.(!1,new Error("Field path cannot be empty"))}removeLoop(){if(this.currentTable&&this.currentLoop)try{this.currentTable.removeRowLoop(this.currentLoop.id)?(this.hideLoop(),this.onRemoveCallback?.(!0)):this.onRemoveCallback?.(!1)}catch{this.onRemoveCallback?.(!1)}}getCurrentLoop(){return this.currentLoop}getCurrentTable(){return this.currentTable}hasLoop(){return null!==this.currentLoop}update(){}},t.TextBoxObject=E,t.TextBoxPane=class extends Vt{constructor(t="textbox",e={}){super(t,{className:"pc-pane-textbox",...e}),this.positionSelect=null,this.offsetGroup=null,this.offsetXInput=null,this.offsetYInput=null,this.bgColorInput=null,this.borderWidthInput=null,this.borderColorInput=null,this.borderStyleSelect=null,this.paddingInput=null,this._isUpdating=!1,this.currentTextBox=null,this.onApplyCallback=e.onApply}attach(t){if(super.attach(t),this.editor){const t=()=>this.updateFromSelection();this.editor.on("selection-change",t),this.editor.on("textbox-updated",t),this.eventCleanup.push(()=>{this.editor?.off("selection-change",t),this.editor?.off("textbox-updated",t)}),this.updateFromSelection()}}createContent(){const t=document.createElement("div"),e=this.createSection("Position");this.positionSelect=this.createSelect([{value:"inline",label:"Inline"},{value:"block",label:"Block"},{value:"relative",label:"Relative"}],"inline"),this.addImmediateApplyListener(this.positionSelect,()=>this.updateOffsetVisibility()),e.appendChild(this.createFormGroup("Type",this.positionSelect)),this.offsetGroup=document.createElement("div"),this.offsetGroup.style.display="none";const i=this.createRow();this.offsetXInput=this.createNumberInput({value:0}),this.offsetYInput=this.createNumberInput({value:0}),i.appendChild(this.createFormGroup("X",this.offsetXInput,{inline:!0})),i.appendChild(this.createFormGroup("Y",this.offsetYInput,{inline:!0})),this.offsetGroup.appendChild(i),e.appendChild(this.offsetGroup),t.appendChild(e);const n=this.createSection("Background");this.bgColorInput=this.createColorInput("#ffffff"),n.appendChild(this.createFormGroup("Color",this.bgColorInput)),t.appendChild(n);const s=this.createSection("Border"),o=this.createRow();this.borderWidthInput=this.createNumberInput({min:0,max:10,value:1}),this.borderColorInput=this.createColorInput("#cccccc"),o.appendChild(this.createFormGroup("Width",this.borderWidthInput,{inline:!0})),o.appendChild(this.createFormGroup("Color",this.borderColorInput,{inline:!0})),s.appendChild(o),this.borderStyleSelect=this.createSelect([{value:"solid",label:"Solid"},{value:"dashed",label:"Dashed"},{value:"dotted",label:"Dotted"},{value:"none",label:"None"}],"solid"),s.appendChild(this.createFormGroup("Style",this.borderStyleSelect)),t.appendChild(s);const r=this.createSection("Padding");this.paddingInput=this.createNumberInput({min:0,max:50,value:8}),r.appendChild(this.createFormGroup("All sides (px)",this.paddingInput)),t.appendChild(r);const a=this.createButton("Apply Changes",{variant:"primary"});return this.addButtonListener(a,()=>this.applyChanges()),t.appendChild(a),t}updateFromSelection(){if(this.editor&&!this._isUpdating){this._isUpdating=!0;try{const t=this.editor.getSelectedTextBox?.();t&&!t.editing?this.showTextBox(t):this.hideTextBox()}finally{this._isUpdating=!1}}}showTextBox(t){this.currentTextBox=t,this.positionSelect&&(this.positionSelect.value=t.position||"inline"),this.updateOffsetVisibility(),this.offsetXInput&&(this.offsetXInput.value=String(t.relativeOffset?.x??0)),this.offsetYInput&&(this.offsetYInput.value=String(t.relativeOffset?.y??0)),this.bgColorInput&&(this.bgColorInput.value=t.backgroundColor||"#ffffff");const e=t.border,i="none"!==e.top.style?e.top:"none"!==e.right.style?e.right:"none"!==e.bottom.style?e.bottom:"none"!==e.left.style?e.left:e.top;this.borderWidthInput&&(this.borderWidthInput.value=String(i.width)),this.borderColorInput&&(this.borderColorInput.value=i.color),this.borderStyleSelect&&(this.borderStyleSelect.value=i.style),this.paddingInput&&(this.paddingInput.value=String(t.padding??8)),this.show()}hideTextBox(){this.currentTextBox=null,this.hide()}updateOffsetVisibility(){this.offsetGroup&&this.positionSelect&&(this.offsetGroup.style.display="relative"===this.positionSelect.value?"block":"none")}applyChanges(){if(!this.editor||!this.currentTextBox)return void this.onApplyCallback?.(!1,new Error("No text box selected"));const t={};this.positionSelect&&(t.position=this.positionSelect.value),"relative"===this.positionSelect?.value&&(t.relativeOffset={x:parseInt(this.offsetXInput?.value||"0",10),y:parseInt(this.offsetYInput?.value||"0",10)}),this.bgColorInput&&(t.backgroundColor=this.bgColorInput.value);const e={width:parseInt(this.borderWidthInput?.value||"1",10),color:this.borderColorInput?.value||"#cccccc",style:this.borderStyleSelect?.value||"solid"};t.border={top:{...e},right:{...e},bottom:{...e},left:{...e}},this.paddingInput&&(t.padding=parseInt(this.paddingInput.value,10));try{this.editor.updateTextBox(this.currentTextBox.id,t)?this.onApplyCallback?.(!0):this.onApplyCallback?.(!1,new Error("Failed to update text box"))}catch(t){this.onApplyCallback?.(!1,t instanceof Error?t:new Error(String(t)))}}getCurrentTextBox(){return this.currentTextBox}hasTextBox(){return null!==this.currentTextBox}update(){this.updateFromSelection()}},t.TextFormattingManager=u,t.TextLayout=C,t.TextMeasurer=S,t.TextPositionCalculator=_,t.TextState=g,t.VerticalRuler=class extends $t{constructor(t={}){super("vertical-ruler",t),this.orientation="vertical",this.contentOffsetY=0,this.pageHeightPx=0,this.pageGap=40,this.totalPages=1}updateScrollOffset(){if(!this.editor)return;const t=this.editor.getScrollPosition();this.scrollOffset=t.y}getContentOffset(){return this.contentOffsetY}updateFromMetrics(t){if(!t||!this.editor)return;const e=Ut("mm");this.pageHeightPx=t.pageHeight*e*this.zoomLevel,this.totalPages=t.totalPages,this.documentSize=(this.pageHeightPx+this.pageGap)*this.totalPages-this.pageGap,this.marginStart=t.margins.top*e*this.zoomLevel,this.marginEnd=(t.pageHeight-t.margins.bottom)*e*this.zoomLevel;const i=this.editor.getContentOffset(),n=this.editor.getScrollPosition();this.contentOffsetY=i.y-n.y}renderMargins(t,e){if(!this.ctx)return;const i=this.contentOffsetY,n=i+this.documentSize;i>0&&(this.ctx.fillStyle=this.options.marginColor,this.ctx.fillRect(0,0,t,i)),n<e&&(this.ctx.fillStyle=this.options.marginColor,this.ctx.fillRect(0,n,t,e-n));for(let n=0;n<this.totalPages-1;n++){const s=i+(n+1)*this.pageHeightPx+n*this.pageGap,o=s,r=s+this.pageGap;r>0&&o<e&&(this.ctx.fillStyle=this.options.marginColor,this.ctx.fillRect(0,Math.max(0,o),t,Math.min(r,e)-Math.max(0,o)))}this.ctx.strokeStyle=this.options.tickColor,this.ctx.lineWidth=1;for(let n=0;n<this.totalPages;n++){const s=i+n*(this.pageHeightPx+this.pageGap),o=s+this.marginStart,r=s+this.marginEnd;o>=0&&o<=e&&(this.ctx.beginPath(),this.ctx.moveTo(0,o),this.ctx.lineTo(t,o),this.ctx.stroke()),r>=0&&r<=e&&(this.ctx.beginPath(),this.ctx.moveTo(0,r),this.ctx.lineTo(t,r),this.ctx.stroke())}}calculateTickMarks(){const t=[],e=Ut(this.options.units)*this.zoomLevel,i=this.options.majorTickInterval,n=i/this.options.minorTicksPerMajor,s=this.getVisibleLength();for(let o=0;o<this.totalPages;o++){const r=o*(this.pageHeightPx+this.pageGap),a=Math.max(0,-this.contentOffsetY-r),l=Math.min(this.pageHeightPx,s-this.contentOffsetY-r);if(l<0||a>this.pageHeightPx)continue;const h=Math.floor(a/e/n)*n-n,d=Math.ceil(l/e/n)*n+n;for(let s=Math.max(0,h);s*e<=this.pageHeightPx&&s<=d;s+=n){const n=r+s*e,o=Math.abs(s%i)<.001,a={position:n,isMajor:o};o&&this.options.showLabels&&(a.label=String(Math.round(s))),t.push(a)}}return t}renderTicks(t,e,i){if(!this.ctx)return;const n=.6*e,s=.3*e;this.ctx.strokeStyle=this.options.tickColor,this.ctx.lineWidth=1,this.ctx.font=`${this.options.labelFontSize}px sans-serif`,this.ctx.fillStyle=this.options.labelColor,this.ctx.textAlign="right",this.ctx.textBaseline="middle";const o=this.contentOffsetY;for(const r of t){const t=r.position+o;if(t<-10||t>i+10)continue;if(this.isInPageGap(r.position))continue;const a=r.isMajor?n:s;this.ctx.beginPath(),this.ctx.moveTo(e,t),this.ctx.lineTo(e-a,t),this.ctx.stroke(),r.label&&(this.ctx.save(),this.ctx.translate(e-n-2,t),this.ctx.rotate(-Math.PI/2),this.ctx.textAlign="center",this.ctx.fillText(r.label,0,0),this.ctx.restore())}}isInPageGap(t){for(let e=0;e<this.totalPages-1;e++){const i=(e+1)*this.pageHeightPx+e*this.pageGap,n=i+this.pageGap;if(t>=i&&t<n)return!0}return!1}renderCursorIndicator(t,e){this.ctx&&null!==this.currentMousePosition&&(this.ctx.fillStyle=this.options.activeColor,this.ctx.fillRect(0,this.currentMousePosition-1,t,2),this.ctx.beginPath(),this.ctx.moveTo(t,this.currentMousePosition-4),this.ctx.lineTo(t,this.currentMousePosition+4),this.ctx.lineTo(t-6,this.currentMousePosition),this.ctx.closePath(),this.ctx.fill())}},t.ViewSettingsPane=class extends Vt{constructor(t="view-settings",e={}){super(t,{className:"pc-pane-view-settings",...e}),this.rulersBtn=null,this.controlCharsBtn=null,this.marginLinesBtn=null,this.gridBtn=null,this.onToggleRulers=e.onToggleRulers,this.rulersVisible=e.rulersVisible??!0}attach(t){if(super.attach(t),this.editor){const t=()=>this.updateButtonStates();this.editor.on("grid-changed",t),this.editor.on("margin-lines-changed",t),this.editor.on("control-characters-changed",t),this.eventCleanup.push(()=>{this.editor?.off("grid-changed",t),this.editor?.off("margin-lines-changed",t),this.editor?.off("control-characters-changed",t)}),this.updateButtonStates()}}createContent(){const t=document.createElement("div");return t.className="pc-pane-button-group pc-pane-view-toggles",this.onToggleRulers&&(this.rulersBtn=this.createToggleButton("Rulers",this.rulersVisible),this.addButtonListener(this.rulersBtn,()=>this.toggleRulers()),t.appendChild(this.rulersBtn)),this.controlCharsBtn=this.createToggleButton("Control Chars",!1),this.addButtonListener(this.controlCharsBtn,()=>this.toggleControlChars()),t.appendChild(this.controlCharsBtn),this.marginLinesBtn=this.createToggleButton("Margin Lines",!0),this.addButtonListener(this.marginLinesBtn,()=>this.toggleMarginLines()),t.appendChild(this.marginLinesBtn),this.gridBtn=this.createToggleButton("Grid",!0),this.addButtonListener(this.gridBtn,()=>this.toggleGrid()),t.appendChild(this.gridBtn),t}createToggleButton(t,e){const i=document.createElement("button");return i.type="button",i.className="pc-pane-toggle",e&&i.classList.add("pc-pane-toggle--active"),i.textContent=t,i.title=`Toggle ${t}`,i}toggleRulers(){this.onToggleRulers&&(this.onToggleRulers(),this.rulersVisible=!this.rulersVisible,this.rulersBtn?.classList.toggle("pc-pane-toggle--active",this.rulersVisible))}toggleControlChars(){if(!this.editor)return;const t=this.editor.getShowControlCharacters();this.editor.setShowControlCharacters(!t)}toggleMarginLines(){if(!this.editor)return;const t=this.editor.getShowMarginLines();this.editor.setShowMarginLines(!t)}toggleGrid(){if(!this.editor)return;const t=this.editor.getShowGrid();this.editor.setShowGrid(!t)}updateButtonStates(){this.editor&&(this.controlCharsBtn&&this.controlCharsBtn.classList.toggle("pc-pane-toggle--active",this.editor.getShowControlCharacters()),this.marginLinesBtn&&this.marginLinesBtn.classList.toggle("pc-pane-toggle--active",this.editor.getShowMarginLines()),this.gridBtn&&this.gridBtn.classList.toggle("pc-pane-toggle--active",this.editor.getShowGrid()))}setRulersVisible(t){this.rulersVisible=t,this.rulersBtn?.classList.toggle("pc-pane-toggle--active",t)}update(){this.updateButtonStates()}}});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("pdf-lib"),require("@pdf-lib/fontkit"),require("pdfjs-dist")):"function"==typeof define&&define.amd?define(["exports","pdf-lib","@pdf-lib/fontkit","pdfjs-dist"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).PCEditor={},t.PDFLib,t.fontkit,t.pdfjsLib)}(this,function(t,e,i,n){"use strict";function o(t){var e=Object.create(null);return t&&Object.keys(t).forEach(function(i){if("default"!==i){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}}),e.default=t,Object.freeze(e)}var s=o(n);class r{constructor(){this.events=new Map}on(t,e){this.events.has(t)||this.events.set(t,new Set),this.events.get(t).add(e)}off(t,e){const i=this.events.get(t);i&&(i.delete(e),0===i.size&&this.events.delete(t))}emit(t,...e){const i=this.events.get(t);i&&i.forEach(i=>{try{i(...e)}catch(e){console.error(`Error in event handler for ${t}:`,e)}})}once(t,e){const i=(...n)=>{this.off(t,i),e(...n)};this.on(t,i)}removeAllListeners(t){t?this.events.delete(t):this.events.clear()}listenerCount(t){const e=this.events.get(t);return e?e.size:0}}class a extends r{constructor(t,e){super(),this._id=t.id,this._settings=e}get id(){return this._id}get settings(){return{...this._settings}}getPageDimensions(){const t={A4:{width:210,height:297},Letter:{width:215.9,height:279.4},Legal:{width:215.9,height:355.6},A3:{width:297,height:420}};let e;return e="Custom"===this._settings.pageSize&&this._settings.customPageSize?{width:this._settings.customPageSize.width,height:this._settings.customPageSize.height}:"Custom"!==this._settings.pageSize&&t[this._settings.pageSize]||t.A4,"landscape"===this._settings.pageOrientation&&(e={width:e.height,height:e.width}),this.convertToPixels(e)}convertToPixels(t){const e={px:1,mm:96/25.4,in:96,pt:96/72}[this._settings.units]||1;return{width:t.width*e,height:t.height*e}}getContentBounds(){const t=this.getPageDimensions(),e=this._settings.margins,i=this.convertToPixels({width:1,height:1}).width,n=e.top*i,o=e.bottom*i,s=e.left*i,r=e.right*i;return{position:{x:s,y:n},size:{width:t.width-s-r,height:t.height-n-o}}}getHeaderBounds(){const t=this.getPageDimensions(),e=this._settings.margins,i=this.convertToPixels({width:1,height:1}).width,n=e.top*i,o=e.left*i,s=e.right*i;return{position:{x:o,y:0},size:{width:t.width-o-s,height:n}}}getFooterBounds(){const t=this.getPageDimensions(),e=this._settings.margins,i=this.convertToPixels({width:1,height:1}).width,n=e.bottom*i,o=e.left*i,s=e.right*i;return{position:{x:o,y:t.height-n},size:{width:t.width-o-s,height:n}}}updateSettings(t){this._settings=t,this.emit("settings-changed",{settings:t}),this.emit("change")}toData(){return{id:this._id}}}const l={listType:"bullet",bulletStyle:"disc",nestingLevel:0},d={fontFamily:"Arial",fontSize:14,fontWeight:"normal",fontStyle:"normal",color:"#000000"},h={alignment:"left"},c="",g="\f";class u extends r{constructor(t){super(),this.content="",this.cursorPosition=0,this.fieldCheckCallback=null,this.selectionAnchor=null,t&&(this.content=t)}setFieldCheckCallback(t){this.fieldCheckCallback=t}isReplacementChar(t){return this.content.charAt(t)===c}isFieldAt(t){return!!this.fieldCheckCallback&&(this.isReplacementChar(t)&&this.fieldCheckCallback(t))}getText(){return this.content}setText(t){const e=this.content;this.content=t,this.cursorPosition=Math.min(this.cursorPosition,t.length),this.emit("text-changed",{text:t,previousContent:e,cursorPosition:this.cursorPosition})}insertText(t,e){const i=e??this.cursorPosition,n=this.content;return this.content=this.content.slice(0,i)+t+this.content.slice(i),this.cursorPosition=i+t.length,this.emit("text-inserted",{text:t,position:i,newCursorPosition:this.cursorPosition,previousContent:n}),this.cursorPosition}deleteText(t,e){const i=t+e,n=this.content,o=this.content.slice(t,i);return this.content=this.content.slice(0,t)+this.content.slice(i),this.cursorPosition=Math.min(this.cursorPosition,t),this.emit("text-deleted",{start:t,length:e,deletedText:o,newCursorPosition:this.cursorPosition,previousContent:n}),o}backspace(){if(0===this.cursorPosition)return!1;const t=this.cursorPosition-1;return this.isFieldAt(t),this.deleteText(t,1),!0}deleteForward(){return!(this.cursorPosition>=this.content.length)&&(this.isFieldAt(this.cursorPosition),this.deleteText(this.cursorPosition,1),!0)}getCursorPosition(){return this.cursorPosition}setCursorPosition(t){const e=this.cursorPosition,i=Math.max(0,Math.min(t,this.content.length));this.cursorPosition=i,this.cursorPosition!==e&&(this.emit("cursor-moved",{position:this.cursorPosition,previousPosition:e}),null!==this.selectionAnchor&&this.emitSelectionChange())}moveCursor(t){if(0!==t)if(t<0)for(let e=0;e<Math.abs(t);e++)this.moveCursorLeft();else for(let e=0;e<t;e++)this.moveCursorRight()}moveCursorLeft(){if(0===this.cursorPosition)return;const t=this.cursorPosition-1;this.setCursorPosition(t)}moveCursorRight(){if(this.cursorPosition>=this.content.length)return;const t=this.cursorPosition+1;this.isFieldAt(this.cursorPosition),this.setCursorPosition(t)}get length(){return this.content.length}get isEmpty(){return 0===this.content.length}charAt(t){return this.content.charAt(t)}substring(t,e){return this.content.substring(t,e)}indexOf(t,e){return this.content.indexOf(t,e)}clear(){this.setText("")}setSelectionAnchor(t){this.selectionAnchor=t??this.cursorPosition}getSelection(){if(null===this.selectionAnchor)return null;const t=Math.min(this.selectionAnchor,this.cursorPosition),e=Math.max(this.selectionAnchor,this.cursorPosition);return t===e?null:{start:t,end:e}}hasSelection(){return null!==this.getSelection()}hasSelectionAnchor(){return null!==this.selectionAnchor}clearSelection(){null!==this.selectionAnchor&&(this.selectionAnchor=null,this.emit("selection-changed",{selection:null}))}getSelectedText(){const t=this.getSelection();return t?this.content.substring(t.start,t.end):""}deleteSelection(){const t=this.getSelection();return!!t&&(this.deleteText(t.start,t.end-t.start),this.selectionAnchor=null,!0)}selectLeft(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorLeft(),this.emitSelectionChange()}selectRight(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorRight(),this.emitSelectionChange()}emitSelectionChange(){this.emit("selection-changed",{selection:this.getSelection()})}isWordChar(t){return/[\w\u00C0-\u024F]/.test(t)}getWordBoundaries(t){if(0===this.content.length)return{start:0,end:0};const e=Math.max(0,Math.min(t,this.content.length));if(e>=this.content.length){let t=e;for(;t>0&&this.isWordChar(this.content.charAt(t-1));)t--;return{start:t,end:this.content.length}}const i=this.content.charAt(e);if(!this.isWordChar(i)){if(e>0&&this.isWordChar(this.content.charAt(e-1))){let t=e-1;for(;t>0&&this.isWordChar(this.content.charAt(t-1));)t--;return{start:t,end:e}}return{start:e,end:e}}let n=e;for(;n>0&&this.isWordChar(this.content.charAt(n-1));)n--;let o=e;for(;o<this.content.length&&this.isWordChar(this.content.charAt(o));)o++;return{start:n,end:o}}getParagraphBoundaries(t){if(0===this.content.length)return{start:0,end:0};const e=Math.max(0,Math.min(t,this.content.length));let i=e;for(;i>0&&"\n"!==this.content.charAt(i-1);)i--;let n=e;for(;n<this.content.length&&"\n"!==this.content.charAt(n);)n++;return{start:i,end:n}}selectWord(){const{start:t,end:e}=this.getWordBoundaries(this.cursorPosition);t!==e&&(this.selectionAnchor=t,this.cursorPosition=e,this.emitSelectionChange())}selectParagraph(){const{start:t,end:e}=this.getParagraphBoundaries(this.cursorPosition);this.selectionAnchor=t,this.cursorPosition=e,this.emitSelectionChange()}selectAll(){0!==this.content.length&&(this.selectionAnchor=0,this.cursorPosition=this.content.length,this.emitSelectionChange())}moveCursorToLineStart(){let t=this.cursorPosition;for(;t>0&&"\n"!==this.content.charAt(t-1);)t--;this.setCursorPosition(t)}moveCursorToLineEnd(){let t=this.cursorPosition;for(;t<this.content.length&&"\n"!==this.content.charAt(t);)t++;this.setCursorPosition(t)}moveCursorToDocumentStart(){this.setCursorPosition(0)}moveCursorToDocumentEnd(){this.setCursorPosition(this.content.length)}selectToLineStart(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorToLineStart(),this.emitSelectionChange()}selectToLineEnd(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorToLineEnd(),this.emitSelectionChange()}selectToDocumentStart(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorToDocumentStart(),this.emitSelectionChange()}selectToDocumentEnd(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorToDocumentEnd(),this.emitSelectionChange()}moveCursorWordLeft(){if(0===this.cursorPosition)return;let t=this.cursorPosition-1;for(;t>0&&!this.isWordChar(this.content.charAt(t));)t--;for(;t>0&&this.isWordChar(this.content.charAt(t-1));)t--;this.setCursorPosition(t)}moveCursorWordRight(){if(this.cursorPosition>=this.content.length)return;let t=this.cursorPosition;for(;t<this.content.length&&this.isWordChar(this.content.charAt(t));)t++;for(;t<this.content.length&&!this.isWordChar(this.content.charAt(t));)t++;this.setCursorPosition(t)}selectWordLeft(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorWordLeft(),this.emitSelectionChange()}selectWordRight(){null===this.selectionAnchor&&(this.selectionAnchor=this.cursorPosition),this.moveCursorWordRight(),this.emitSelectionChange()}}class f extends r{constructor(t){super(),this.formatting=new Map,this._pendingFormatting=null,this._defaultFormatting={...d,...t}}get defaultFormatting(){return{...this._defaultFormatting}}setDefaultFormatting(t){this._defaultFormatting={...this._defaultFormatting,...t},this.emit("default-formatting-changed",{formatting:this._defaultFormatting})}getFormattingAt(t){const e=this.formatting.get(t);return e?{...this._defaultFormatting,...e}:{...this._defaultFormatting}}applyFormatting(t,e,i,n=!1){for(let n=t;n<e;n++){const t=this.formatting.get(n)||{...this._defaultFormatting};this.formatting.set(n,{...t,...i})}n||this.emit("formatting-changed",{start:t,end:e,formatting:i})}setFormattingAt(t,e,i=!1){this.formatting.set(t,{...e}),i||this.emit("formatting-changed",{start:t,end:t+1,formatting:e})}clearFormatting(t,e){for(let i=t;i<e;i++)this.formatting.delete(i);this.emit("formatting-cleared",{start:t,end:e})}shiftFormatting(t,e){if(0===e)return;const i=new Map;for(const[n,o]of this.formatting.entries())if(n>=t){this.formatting.delete(n);const t=n+e;t>=0&&i.set(t,o)}for(const[t,e]of i.entries())this.formatting.set(t,e)}handleDeletion(t,e){for(let i=t;i<t+e;i++)this.formatting.delete(i);this.shiftFormatting(t+e,-e)}getAllFormatting(){return new Map(this.formatting)}getCompressedRuns(t){const e=[],i=this._defaultFormatting;let n=null;for(let o=0;o<t;o++){const t=this.getFormattingAt(o);if(null===n||t.fontFamily!==n.fontFamily||t.fontSize!==n.fontSize||t.fontWeight!==n.fontWeight||t.fontStyle!==n.fontStyle||t.color!==n.color||t.backgroundColor!==n.backgroundColor){(!(t.fontFamily===i.fontFamily&&t.fontSize===i.fontSize&&t.fontWeight===i.fontWeight&&t.fontStyle===i.fontStyle&&t.color===i.color&&t.backgroundColor===i.backgroundColor)||e.length>0)&&e.push({index:o,formatting:{...t}}),n=t}}return e}setAllFormatting(t){this.formatting=new Map(t),this.emit("formatting-restored")}clear(){this.formatting.clear(),this._pendingFormatting=null,this.emit("formatting-cleared",{start:0,end:1/0})}setPendingFormatting(t){this._pendingFormatting={...this._pendingFormatting,...t},this.emit("pending-formatting-changed",{formatting:this._pendingFormatting})}getPendingFormatting(){return this._pendingFormatting?{...this._pendingFormatting}:null}hasPendingFormatting(){return null!==this._pendingFormatting}clearPendingFormatting(){null!==this._pendingFormatting&&(this._pendingFormatting=null,this.emit("pending-formatting-cleared"))}applyPendingFormatting(t,e){this._pendingFormatting&&e>0&&this.applyFormatting(t,t+e,this._pendingFormatting)}}const p=["disc","circle","square"],m=["decimal","lower-alpha","lower-roman"];class b extends r{constructor(t){super(),this.formatting=new Map,this._defaultFormatting={...h,...t}}get defaultFormatting(){return{...this._defaultFormatting}}setDefaultFormatting(t){this._defaultFormatting={...this._defaultFormatting,...t},this.emit("default-formatting-changed",{formatting:this._defaultFormatting})}getParagraphStart(t,e){if(t<=0)return 0;for(let i=Math.min(t-1,e.length-1);i>=0;i--)if("\n"===e[i])return i+1;return 0}getFormattingAt(t,e){const i=this.getParagraphStart(t,e);return this.getFormattingForParagraph(i)}getFormattingForParagraph(t){const e=this.formatting.get(t);return e?{...e}:{...this._defaultFormatting}}setAlignment(t,e){const i=this.formatting.get(t)||{...this._defaultFormatting};this.formatting.set(t,{...i,alignment:e}),this.emit("paragraph-formatting-changed",{paragraphStart:t,alignment:e})}setListFormatting(t,e){const i=this.formatting.get(t)||{...this._defaultFormatting};if(void 0===e){const{listFormatting:e,...n}=i;this.formatting.set(t,n)}else this.formatting.set(t,{...i,listFormatting:e});this.emit("paragraph-formatting-changed",{paragraphStart:t,listFormatting:e})}clearListFormatting(t){this.setListFormatting(t,void 0)}toggleList(t,e){const i=this.formatting.get(t),n=i?.listFormatting;if(n?.listType===e)this.clearListFormatting(t);else{const i=n?.nestingLevel??0,o="bullet"===e?{listType:"bullet",bulletStyle:this.getBulletStyleForLevel(i),nestingLevel:i}:{listType:"number",numberStyle:this.getNumberStyleForLevel(i),nestingLevel:i};this.setListFormatting(t,o)}}indentParagraph(t){const e=this.formatting.get(t),i=e?.listFormatting;if(!i)return void this.setListFormatting(t,{...l});if(i.nestingLevel>=8)return;const n=i.nestingLevel+1,o="bullet"===i.listType?{...i,nestingLevel:n,bulletStyle:this.getBulletStyleForLevel(n)}:{...i,nestingLevel:n,numberStyle:this.getNumberStyleForLevel(n)};this.setListFormatting(t,o)}outdentParagraph(t){const e=this.formatting.get(t),i=e?.listFormatting;if(!i)return;if(0===i.nestingLevel)return void this.clearListFormatting(t);const n=i.nestingLevel-1,o="bullet"===i.listType?{...i,nestingLevel:n,bulletStyle:this.getBulletStyleForLevel(n)}:{...i,nestingLevel:n,numberStyle:this.getNumberStyleForLevel(n)};this.setListFormatting(t,o)}getBulletStyleForLevel(t){return p[t%p.length]}getNumberStyleForLevel(t){return m[t%m.length]}getListNumber(t,e){const i=this.getFormattingForParagraph(t).listFormatting;if(!i||"number"!==i.listType)return;const n=i.nestingLevel,o=[0];for(let t=0;t<e.length;t++)"\n"===e[t]&&o.push(t+1);const s=o.indexOf(t);if(-1===s)return i.startNumber??1;let r=0,a=1;for(let t=s;t>=0;t--){const e=o[t],i=this.getFormattingForParagraph(e).listFormatting;if(!(i&&i.nestingLevel>n)){if(!i||"number"!==i.listType||i.nestingLevel!==n)break;if(r++,void 0!==i.startNumber){a=i.startNumber;break}}}return a+r-1}applyToRange(t,e,i,n){const o=this.getParagraphBoundariesInRange(t,e,i);for(const t of o){const e=this.formatting.get(t)||{...this._defaultFormatting};this.formatting.set(t,{...e,...n})}this.emit("paragraph-formatting-changed",{start:t,end:e,formatting:n})}getParagraphBoundariesInRange(t,e,i){const n=[],o=this.getParagraphStart(t,i);n.push(o);for(let o=t;o<e&&o<i.length;o++)"\n"===i[o]&&o+1<=e&&n.push(o+1);return[...new Set(n)]}shiftParagraphs(t,e,i){if(0===e)return;const n=new Map;for(const[i,o]of this.formatting.entries())if(i>t){this.formatting.delete(i);const t=i+e;t>=0&&n.set(t,o)}for(const[t,e]of n.entries())this.formatting.set(t,e);const o=i.slice(t,t+e);if(o.includes("\n")){const e=this.getParagraphStart(t,i),n=this.formatting.get(e);if(n)for(let e=0;e<o.length;e++)if("\n"===o[e]){const i=t+e+1;this.formatting.has(i)||this.formatting.set(i,{...n})}}}handleDeletion(t,e){const i=t+e;for(const e of this.formatting.keys())e>t&&e<i&&this.formatting.delete(e);const n=new Map;for(const[t,o]of this.formatting.entries())if(t>=i){this.formatting.delete(t);const i=t-e;i>=0&&n.set(i,o)}for(const[t,e]of n.entries())this.formatting.set(t,e)}clear(){this.formatting.clear(),this.emit("paragraph-formatting-cleared")}toJSON(){return Array.from(this.formatting.entries()).map(([t,e])=>({paragraphStart:t,formatting:e}))}fromJSON(t){this.formatting.clear();for(const e of t)this.formatting.set(e.paragraphStart,e.formatting);this.emit("paragraph-formatting-loaded")}getAllFormatting(){return new Map(this.formatting)}}class x extends r{constructor(){super(),this.fields=new Map,this.nextId=1}insert(t,e,i){const n={id:"field-"+this.nextId++,textIndex:e,fieldName:t,fieldType:i?.fieldType,displayFormat:i?.displayFormat,defaultValue:i?.defaultValue,formatting:i?.formatting};return this.fields.set(e,n),this.emit("field-added",{field:n}),n}remove(t){const e=this.fields.get(t);return e&&(this.fields.delete(t),this.emit("field-removed",{field:e})),e}getFieldAt(t){return this.fields.get(t)}hasFieldAt(t){return this.fields.has(t)}getFieldsInRange(t,e){const i=[];for(const[n,o]of this.fields)n>=t&&n<e&&i.push({textIndex:n,field:o});return i.sort((t,e)=>t.textIndex-e.textIndex)}insertAt(t,e){e.textIndex=t,this.fields.set(t,e),this.emit("field-added",{field:e})}getFields(){return new Map(this.fields)}getFieldsArray(){return Array.from(this.fields.values()).sort((t,e)=>t.textIndex-e.textIndex)}findById(t){for(const e of this.fields.values())if(e.id===t)return e}findByFieldName(t){for(const e of this.fields.values())if(e.fieldName===t)return e}findAllByFieldName(t){return Array.from(this.fields.values()).filter(e=>e.fieldName===t)}isPageNumberField(t){return"pageNumber"===t.fieldType}isPageCountField(t){return"pageCount"===t.fieldType}isSpecialField(t){return"pageNumber"===t.fieldType||"pageCount"===t.fieldType}getPageNumberFields(){return Array.from(this.fields.values()).filter(t=>"pageNumber"===t.fieldType)}getPageCountFields(){return Array.from(this.fields.values()).filter(t=>"pageCount"===t.fieldType)}getDataFields(){return Array.from(this.fields.values()).filter(t=>!t.fieldType||"data"===t.fieldType)}shiftFields(t,e){const i=[];for(const[e,n]of this.fields)e>=t&&i.push({oldIndex:e,field:n});for(const{oldIndex:t,field:n}of i)this.fields.delete(t),n.textIndex=t+e,this.fields.set(n.textIndex,n);i.length>0&&this.emit("fields-shifted",{fromIndex:t,delta:e})}handleDeletion(t,e){const i=t+e,n=[],o=[];for(const[e,s]of this.fields)e>=t&&e<i?n.push(s):e>=i&&o.push({oldIndex:e,field:s});for(const t of n)this.fields.delete(t.textIndex),this.emit("field-removed",{field:t});for(const{oldIndex:t,field:i}of o)this.fields.delete(t),i.textIndex=t-e,this.fields.set(i.textIndex,i);return(n.length>0||o.length>0)&&this.emit("fields-changed"),n}updateFieldConfig(t,e){const i=this.fields.get(t);return!!i&&(void 0!==e.fieldName&&(i.fieldName=e.fieldName),void 0!==e.displayFormat&&(i.displayFormat=e.displayFormat),void 0!==e.defaultValue&&(i.defaultValue=e.defaultValue),void 0!==e.formatConfig&&(i.formatConfig=e.formatConfig?{...e.formatConfig}:void 0),this.emit("field-updated",{field:i}),!0)}setFieldFormatting(t,e){const i=this.fields.get(t);return!!i&&(i.formatting={...e},this.emit("field-formatting-changed",{field:i}),!0)}getFieldFormatting(t){const e=this.fields.get(t);return e?.formatting||d}getDisplayText(t,e,i){return"pageNumber"===t.fieldType?void 0!==e?t.displayFormat?t.displayFormat.replace(/%d/g,String(e)):String(e):"{{page}}":"pageCount"===t.fieldType?void 0!==i?t.displayFormat?t.displayFormat.replace(/%d/g,String(i)):String(i):"{{pages}}":`{{field: ${t.fieldName}}}`}getDisplayTextAt(t){const e=this.fields.get(t);if(e)return this.getDisplayText(e)}get count(){return this.fields.size}get isEmpty(){return 0===this.fields.size}clear(){const t=this.fields.size>0;this.fields.clear(),t&&this.emit("fields-cleared")}toJSON(){return this.getFieldsArray()}fromJSON(t){this.clear();for(const e of t){const t={id:e.id,textIndex:e.textIndex,fieldName:e.fieldName,fieldType:e.fieldType,displayFormat:e.displayFormat,defaultValue:e.defaultValue,formatting:e.formatting?{...e.formatting}:void 0,formatConfig:e.formatConfig?{...e.formatConfig}:void 0};this.fields.set(t.textIndex,t);const i=parseInt(e.id.replace("field-",""),10);!isNaN(i)&&i>=this.nextId&&(this.nextId=i+1)}this.emit("fields-loaded",{count:this.fields.size})}}class y extends r{constructor(){super(),this.objects=new Map}getObjects(){return new Map(this.objects)}getObjectsArray(){return Array.from(this.objects.entries()).sort((t,e)=>t[0]-e[0]).map(([t,e])=>({object:e,textIndex:t}))}getObjectAt(t){return this.objects.get(t)}getObjectsInRange(t,e){const i=[];for(const[n,o]of this.objects.entries())n>=t&&n<e&&i.push({object:o,textIndex:n});return i.sort((t,e)=>t.textIndex-e.textIndex)}hasObjectAt(t){return this.objects.has(t)}insert(t,e){t.textIndex=e,this.objects.set(e,t),t.on("position-changed",()=>{this.emit("object-updated",{object:t,textIndex:t.textIndex})}),t.on("offset-changed",()=>{this.emit("object-updated",{object:t,textIndex:t.textIndex})}),t.on("size-changed",()=>{this.emit("object-updated",{object:t,textIndex:t.textIndex})}),this.emit("object-added",{object:t,textIndex:e})}remove(t){const e=this.objects.get(t);if(e)return this.objects.delete(t),this.emit("object-removed",{object:e,textIndex:t}),e}shiftObjects(t,e){if(0===e)return;const i=[];for(const[e,n]of this.objects.entries())e>=t&&i.push({oldIndex:e,object:n});for(const{oldIndex:t}of i)this.objects.delete(t);for(const{oldIndex:t,object:n}of i){const i=t+e;i>=0&&(n.textIndex=i,this.objects.set(i,n))}i.length>0&&this.emit("objects-shifted",{fromIndex:t,delta:e})}handleDeletion(t,e){const i=t+e,n=[],o=[];for(const[e,s]of this.objects)e>=t&&e<i?n.push(s):e>=i&&o.push({oldIndex:e,object:s});for(const t of n)this.objects.delete(t.textIndex),this.emit("object-removed",{object:t,textIndex:t.textIndex});for(const{oldIndex:t}of o)this.objects.delete(t);for(const{oldIndex:t,object:i}of o){const n=t-e;i.textIndex=n,this.objects.set(n,i)}return(n.length>0||o.length>0)&&this.emit("objects-changed"),n}get count(){return this.objects.size}get isEmpty(){return 0===this.objects.size}clear(){const t=this.objects.size>0;this.objects.clear(),t&&this.emit("objects-cleared")}getObjectIds(){return Array.from(this.objects.values()).map(t=>t.id)}findById(t){for(const[e,i]of this.objects.entries())if(i.id===t)return{object:i,textIndex:e}}findByType(t){const e=[];for(const[i,n]of this.objects.entries())n.objectType===t&&e.push({object:n,textIndex:i});return e.sort((t,e)=>t.textIndex-e.textIndex)}updatePosition(t,e){const i=this.objects.get(t);return!!i&&(i.position=e,this.emit("object-updated",{object:i,textIndex:t}),!0)}deselectAll(){for(const t of this.objects.values())t.selected&&(t.selected=!1)}getSelectedObject(){for(const[t,e]of this.objects.entries())if(e.selected)return{object:e,textIndex:t}}}class w extends r{constructor(){super(),this.sections=new Map,this.nextId=1}create(t,e,i){const n="section-"+this.nextId++,o={id:n,fieldPath:i,startIndex:t,endIndex:e};return this.sections.set(n,o),this.emit("section-added",{section:o}),o}remove(t){const e=this.sections.get(t);return e&&(this.sections.delete(t),this.emit("section-removed",{section:e})),e}getSection(t){return this.sections.get(t)}getSections(){return Array.from(this.sections.values())}getSectionsSorted(){return this.getSections().sort((t,e)=>t.startIndex-e.startIndex)}getSectionsDescending(){return this.getSections().sort((t,e)=>e.startIndex-t.startIndex)}getSectionContaining(t){for(const e of this.sections.values())if(t>=e.startIndex&&t<e.endIndex)return e}getSectionAtBoundary(t){for(const e of this.sections.values())if(e.startIndex===t||e.endIndex===t)return e}updateFieldPath(t,e){const i=this.sections.get(t);return!!i&&(i.fieldPath=e,this.emit("section-updated",{section:i}),!0)}updateVisualState(t,e){const i=this.sections.get(t);return!!i&&(i.visualState=e,!0)}shiftSections(t,e){let i=!1;for(const n of this.sections.values())t<=n.startIndex?(n.startIndex+=e,n.endIndex+=e,i=!0):t<n.endIndex&&(n.endIndex+=e,i=!0);i&&this.emit("sections-shifted",{fromIndex:t,delta:e})}handleDeletion(t,e){const i=t+e,n=[],o=[];for(const s of this.sections.values())if(s.startIndex>=t&&s.endIndex<=i)n.push(s);else{if(s.startIndex<i&&s.endIndex>t){if(t<=s.startIndex){n.push(s);continue}if(t<s.endIndex){if(i>=s.endIndex){const e=t;if(e<=s.startIndex){n.push(s);continue}o.push({id:s.id,newStart:s.startIndex,newEnd:e})}else{const t=s.endIndex-e;o.push({id:s.id,newStart:s.startIndex,newEnd:t})}continue}}s.startIndex>=i&&o.push({id:s.id,newStart:s.startIndex-e,newEnd:s.endIndex-e})}for(const t of n)this.sections.delete(t.id),this.emit("section-removed",{section:t});for(const t of o){const e=this.sections.get(t.id);e&&(e.startIndex=t.newStart,e.endIndex=t.newEnd)}return(n.length>0||o.length>0)&&this.emit("sections-changed"),n}validateBoundaries(t,e,i){if(0!==t&&"\n"!==i[t-1])return!1;if(0!==e&&e<i.length&&"\n"!==i[e-1])return!1;if(e<=t)return!1;for(const i of this.sections.values())if(t>=i.startIndex&&t<i.endIndex||e>i.startIndex&&e<=i.endIndex||t<=i.startIndex&&e>=i.endIndex)return!1;return!0}get count(){return this.sections.size}get isEmpty(){return 0===this.sections.size}clear(){const t=this.sections.size>0;this.sections.clear(),t&&this.emit("sections-cleared")}toJSON(){return this.getSectionsSorted().map(t=>({id:t.id,fieldPath:t.fieldPath,startIndex:t.startIndex,endIndex:t.endIndex}))}fromJSON(t){this.clear();for(const e of t){const t={id:e.id,fieldPath:e.fieldPath,startIndex:e.startIndex,endIndex:e.endIndex};this.sections.set(t.id,t);const i=parseInt(e.id.replace("section-",""),10);!isNaN(i)&&i>=this.nextId&&(this.nextId=i+1)}this.emit("sections-loaded",{count:this.sections.size})}}class C extends r{constructor(){super(),this.sections=new Map,this.nextId=1}create(t,e,i){const n="cond-"+this.nextId++,o={id:n,predicate:i,startIndex:t,endIndex:e};return this.sections.set(n,o),this.emit("section-added",{section:o}),o}remove(t){const e=this.sections.get(t);return e&&(this.sections.delete(t),this.emit("section-removed",{section:e})),e}getSection(t){return this.sections.get(t)}getSections(){return Array.from(this.sections.values())}getSectionsSorted(){return this.getSections().sort((t,e)=>t.startIndex-e.startIndex)}getSectionsDescending(){return this.getSections().sort((t,e)=>e.startIndex-t.startIndex)}getSectionContaining(t){for(const e of this.sections.values())if(t>=e.startIndex&&t<e.endIndex)return e}getSectionAtBoundary(t){for(const e of this.sections.values())if(e.startIndex===t||e.endIndex===t)return e}updatePredicate(t,e){const i=this.sections.get(t);return!!i&&(i.predicate=e,this.emit("section-updated",{section:i}),!0)}updateVisualState(t,e){const i=this.sections.get(t);return!!i&&(i.visualState=e,!0)}shiftSections(t,e){let i=!1;for(const n of this.sections.values())t<=n.startIndex?(n.startIndex+=e,n.endIndex+=e,i=!0):t<n.endIndex&&(n.endIndex+=e,i=!0);i&&this.emit("sections-shifted",{fromIndex:t,delta:e})}handleDeletion(t,e){const i=t+e,n=[],o=[];for(const s of this.sections.values())if(s.startIndex>=t&&s.endIndex<=i)n.push(s);else{if(s.startIndex<i&&s.endIndex>t){if(t<=s.startIndex){n.push(s);continue}if(t<s.endIndex){if(i>=s.endIndex){const e=t;if(e<=s.startIndex){n.push(s);continue}o.push({id:s.id,newStart:s.startIndex,newEnd:e})}else{const t=s.endIndex-e;o.push({id:s.id,newStart:s.startIndex,newEnd:t})}continue}}s.startIndex>=i&&o.push({id:s.id,newStart:s.startIndex-e,newEnd:s.endIndex-e})}for(const t of n)this.sections.delete(t.id),this.emit("section-removed",{section:t});for(const t of o){const e=this.sections.get(t.id);e&&(e.startIndex=t.newStart,e.endIndex=t.newEnd)}return(n.length>0||o.length>0)&&this.emit("sections-changed"),n}validateBoundaries(t,e,i){if(0!==t&&"\n"!==i[t-1])return!1;if(0!==e&&e<i.length&&"\n"!==i[e-1])return!1;if(e<=t)return!1;for(const i of this.sections.values())if(t>=i.startIndex&&t<i.endIndex||e>i.startIndex&&e<=i.endIndex||t<=i.startIndex&&e>=i.endIndex)return!1;return!0}get count(){return this.sections.size}get isEmpty(){return 0===this.sections.size}clear(){const t=this.sections.size>0;this.sections.clear(),t&&this.emit("sections-cleared")}toJSON(){return this.getSectionsSorted().map(t=>({id:t.id,predicate:t.predicate,startIndex:t.startIndex,endIndex:t.endIndex}))}fromJSON(t){this.clear();for(const e of t){const t={id:e.id,predicate:e.predicate,startIndex:e.startIndex,endIndex:e.endIndex};this.sections.set(t.id,t);const i=parseInt(e.id.replace("cond-",""),10);!isNaN(i)&&i>=this.nextId&&(this.nextId=i+1)}this.emit("sections-loaded",{count:this.sections.size})}}class S extends r{constructor(){super(...arguments),this.hyperlinks=new Map,this.nextId=1}insert(t,e,i,n){const o=this.generateId(),s={id:o,url:t,startIndex:e,endIndex:i,title:n?.title,formatting:n?.formatting};return this.hyperlinks.set(o,s),this.emit("hyperlink-added",{hyperlink:s}),s}remove(t){this.hyperlinks.has(t)&&(this.hyperlinks.delete(t),this.emit("hyperlink-removed",{id:t}))}update(t,e){const i=this.hyperlinks.get(t);i&&(void 0!==e.url&&(i.url=e.url),void 0!==e.title&&(i.title=e.title),void 0!==e.startIndex&&(i.startIndex=e.startIndex),void 0!==e.endIndex&&(i.endIndex=e.endIndex),void 0!==e.formatting&&(i.formatting=e.formatting),this.emit("hyperlink-updated",{id:t,updates:e}))}getHyperlinkById(t){return this.hyperlinks.get(t)}getHyperlinkAt(t){for(const e of this.hyperlinks.values())if(t>=e.startIndex&&t<e.endIndex)return e}getHyperlinksInRange(t,e){const i=[];for(const n of this.hyperlinks.values())n.startIndex<e&&n.endIndex>t&&i.push(n);return i}getAll(){return Array.from(this.hyperlinks.values())}shiftHyperlinks(t,e){for(const i of this.hyperlinks.values())t<=i.startIndex?(i.startIndex+=e,i.endIndex+=e):t<i.endIndex&&(i.endIndex+=e)}handleDeletion(t,e){const i=t+e,n=[];for(const o of this.hyperlinks.values()){const s=o.startIndex,r=o.endIndex;t>=r||(i<=s?(o.startIndex-=e,o.endIndex-=e):t<=s&&i>=r?n.push(o.id):t>s&&i<r?o.endIndex-=e:t<=s&&i>s&&i<r?(o.startIndex=t,o.endIndex=r-i+t):t>s&&t<r&&i>=r&&(o.endIndex=t))}for(const t of n)this.hyperlinks.delete(t),this.emit("hyperlink-removed",{id:t})}clear(){this.hyperlinks.clear(),this.emit("hyperlinks-cleared")}toJSON(){return this.getAll().map(t=>({id:t.id,url:t.url,startIndex:t.startIndex,endIndex:t.endIndex,title:t.title,formatting:t.formatting}))}fromJSON(t){this.hyperlinks.clear();for(const e of t){const t={id:e.id,url:e.url,startIndex:e.startIndex,endIndex:e.endIndex,title:e.title,formatting:e.formatting};this.hyperlinks.set(e.id,t)}this.emit("hyperlinks-loaded")}generateId(){return"hyperlink-"+this.nextId++}}class v{flowText(t,e){if(!t)return[this.createEmptyPage(e)];const i=this.splitIntoLogicalLines(t),n=[];let o=0;for(let t=0;t<i.length;t++){const s=i[t],{text:r,delimiter:a}=s,l=o+r.length,d=e.paragraphFormatting.getFormattingForParagraph(o),h=d.alignment,c=d.listFormatting,g=c?e.paragraphFormatting.getListNumber(o,e.content):void 0,u=this.wrapLogicalLine(r,o,e,h,"end"===a,c,g);if("end"!==a&&u.length>0){const t=u[u.length-1];"newline"===a?t.endsWithNewline=!0:"pagebreak"===a&&(t.endsWithPageBreak=!0)}n.push(...u),o=l+("end"!==a?1:0)}return this.paginateLines(n,e.availableHeight)}splitIntoLogicalLines(t){const e=[];let i=0;for(let n=0;n<t.length;n++){const o=t[n];"\n"!==o&&o!==g||(e.push({text:t.substring(i,n),delimiter:"\n"===o?"newline":"pagebreak"}),i=n+1)}return e.push({text:t.substring(i),delimiter:"end"}),e}wrapLogicalLine(t,e,i,n,o,s,r){const{availableWidth:a,formatting:l,measurer:d}=i,h=[],c=s?this.calculateListIndent(s.nestingLevel):0;let g="",u=0;if(s){g=this.getListMarkerText(s,r);const t=l.getFormattingAt(e);u=d.measureText(g,t)}const f=a-c;if(0===t.length){const t=this.createEmptyLine(e,l,n);if(s){const i=l.getFormattingAt(e>0?e-1:e);t.listMarker={text:g,width:u,indent:c,isFirstLineOfListItem:!0,formatting:i}}return h.push(t),h}const p=this.splitIntoSegments(t,e,i);let m=this.createLineBuilder(e,l),b=0;const x=(t,e)=>{s&&(t.listMarker={text:e?g:"",width:u,indent:c,isFirstLineOfListItem:e}),h.push(t)};for(let t=0;t<p.length;t++){const e=p[t],i=e.text.length>0&&/^\s+$/.test(e.text),o=e.embeddedObjects.find(t=>t.isBlock);if(o){if(m.text.length>0){x(this.finalizeLineBuilder(m,n,!0,f),0===h.length)}x(this.createBlockObjectLine(o,e,n),0===h.length),m=this.createLineBuilder(e.startIndex+1,l),b=0;continue}if(m.width+e.width>f&&m.text.length>0){if(i){if(this.addSegmentToLine(m,e,b),b+=e.width,t+1<p.length){x(this.finalizeLineBuilder(m,n,!1,f),0===h.length);const e=p[t+1];m=this.createLineBuilder(e.startIndex,l),b=0}continue}x(this.finalizeLineBuilder(m,n,!1,f),0===h.length),m=this.createLineBuilder(e.startIndex,l),b=0}this.addSegmentToLine(m,e,b),b+=e.width}if(m.text.length>0||0===h.length){x(this.finalizeLineBuilder(m,n,!0,f),0===h.length)}return h}createBlockObjectLine(t,e,i){const n=t.object;return{text:e.text,width:n.width,height:n.height,baseline:n.height,runs:e.runs,substitutionFields:e.substitutionFields,embeddedObjects:[t],startIndex:e.startIndex,endIndex:e.startIndex+e.text.length,alignment:i,isBlockObjectLine:!0,allowPageBreakBefore:!0}}splitIntoSegments(t,e,i){const n=[];let o=0;for(;o<t.length;){const s=t[o],r=/\s/.test(s);if(s===c){const t=this.measureSegment(s,e+o,i);n.push(t),o++;continue}let a=o+1;for(;a<t.length;){const e=t[a];if(/\s/.test(e)!==r||e===c)break;a++}const l=this.measureSegment(t.substring(o,a),e+o,i);n.push(l),o=a}return n}measureSegment(t,e,i){const{formatting:n,substitutionFields:o,embeddedObjects:s,measurer:r}=i;let a=0,l=0,d=0;const h=[],c=[],g=[];let u=null;for(let i=0;i<t.length;i++){const f=e+i,p=t[i],m=n.getFormattingAt(f),b=o.getFieldAt(f),x=s.getObjectAt(f);if(b){u&&u.text.length>0&&(h.push({text:u.text,formatting:u.formatting,startIndex:u.startIndex,endIndex:u.startIndex+u.text.length}),u=null);const t=r.measureSubstitutionField(b,m);c.push({field:b,textIndex:f,x:a,width:t.width}),h.push({text:p,formatting:m,startIndex:f,endIndex:f+1}),a+=t.width,l=Math.max(l,t.height),d=Math.max(d,.8*m.fontSize)}else if(x)if(u&&u.text.length>0&&(h.push({text:u.text,formatting:u.formatting,startIndex:u.startIndex,endIndex:u.startIndex+u.text.length}),u=null),"block"===x.position)g.push({object:x,textIndex:f,x:0,isBlock:!0}),h.push({text:p,formatting:m,startIndex:f,endIndex:f+1}),d=Math.max(d,.8*m.fontSize);else if("relative"===x.position)g.push({object:x,textIndex:f,x:a,isAnchor:!0}),h.push({text:p,formatting:m,startIndex:f,endIndex:f+1}),d=Math.max(d,.8*m.fontSize);else{const t=x.width+2;g.push({object:x,textIndex:f,x:a}),h.push({text:p,formatting:m,startIndex:f,endIndex:f+1}),a+=t,l=Math.max(l,x.height),d=Math.max(d,.8*m.fontSize)}else{if(""===p)continue;{const t=r.measureCharacter(p,m),e=r.getLineHeight(m);u&&this.formattingEquals(u.formatting,m)||(u&&u.text.length>0&&h.push({text:u.text,formatting:u.formatting,startIndex:u.startIndex,endIndex:u.startIndex+u.text.length}),u={text:"",formatting:m,startIndex:f}),u.text+=p,a+=t,l=Math.max(l,e),d=Math.max(d,.8*m.fontSize)}}}if(u&&u.text.length>0&&h.push({text:u.text,formatting:u.formatting,startIndex:u.startIndex,endIndex:u.startIndex+u.text.length}),0===l){const t=n.getFormattingAt(e);l=1.2*t.fontSize,d=.8*t.fontSize}return{text:t,startIndex:e,width:a,height:l,baseline:d,runs:h,substitutionFields:c,embeddedObjects:g}}addSegmentToLine(t,e,i){t.text+=e.text,t.width+=e.width,t.height=Math.max(t.height,e.height),t.baseline=Math.max(t.baseline,e.baseline),t.endIndex=e.startIndex+e.text.length;for(const i of e.runs)t.runs.push(i);for(const n of e.substitutionFields)t.substitutionFields.push({...n,x:i+n.x});for(const n of e.embeddedObjects)t.embeddedObjects.push({...n,x:i+n.x})}formattingEquals(t,e){return t.fontFamily===e.fontFamily&&t.fontSize===e.fontSize&&t.fontWeight===e.fontWeight&&t.fontStyle===e.fontStyle&&t.color===e.color&&t.backgroundColor===e.backgroundColor}createLineBuilder(t,e){const i=e.getFormattingAt(t);return{text:"",width:0,height:1.2*i.fontSize,baseline:.8*i.fontSize,runs:[],substitutionFields:[],embeddedObjects:[],startIndex:t,endIndex:t}}finalizeLineBuilder(t,e,i,n){const o={text:t.text,width:t.width,height:t.height,baseline:t.baseline,runs:t.runs,substitutionFields:t.substitutionFields,embeddedObjects:t.embeddedObjects,startIndex:t.startIndex,endIndex:t.endIndex,alignment:e};if("justify"===e&&!i&&o.text.length>0){const e=this.countWordGaps(o.text);if(e>0){const i=n-this.getTrimmedLineWidth(t);i>0&&(o.extraWordSpacing=i/e)}}return o}countWordGaps(t){const e=t.trimEnd();let i=0,n=!1;for(const t of e){const e=/\s/.test(t);e||n?e&&n&&(i++,n=!1):n=!0}return i}getTrimmedLineWidth(t){const e=t.text.trimEnd(),i=t.text.length-e.length;if(0===i)return t.width;let n=0,o=i;for(let e=t.runs.length-1;e>=0&&o>0;e--){const i=t.runs[e],s=Math.min(o,i.text.length);n+=s*i.formatting.fontSize*.3,o-=s}return Math.max(0,t.width-n)}createEmptyLine(t,e,i){const n=e.getFormattingAt(t);return{text:"",width:0,height:1.2*n.fontSize,baseline:.8*n.fontSize,runs:[],substitutionFields:[],embeddedObjects:[],startIndex:t,endIndex:t,alignment:i}}createEmptyPage(t){const e=t.paragraphFormatting.getFormattingForParagraph(0).alignment,i={text:"",width:0,height:1.2*t.formatting.defaultFormatting.fontSize,baseline:.8*t.formatting.defaultFormatting.fontSize,runs:[],substitutionFields:[],embeddedObjects:[],startIndex:0,endIndex:0,alignment:e};return{lines:[i],height:i.height,startIndex:0,endIndex:0}}paginateLines(t,e){const i=[];let n={lines:[],height:0,startIndex:t.length>0?t[0].startIndex:0,endIndex:0};for(const o of t){const t=!0===o.isBlockObjectLine;if(n.height+o.height>e&&n.lines.length>0){const t=e-n.height,s=o.embeddedObjects?.some(e=>{if("table"!==e.object.objectType||e.object.height<=t)return!1;const i=e.object;if(i.getHeaderHeight&&i.getFirstDataRowHeight){return i.getHeaderHeight()+i.getFirstDataRowHeight()<=t}return!0});s||(n.endIndex=n.lines[n.lines.length-1].endIndex,i.push(n),n={lines:[],height:0,startIndex:o.startIndex,endIndex:0})}else t&&n.lines.length;n.lines.push(o),n.height+=o.height,o.endsWithPageBreak&&n.lines.length>0&&(n.endIndex=o.endIndex,i.push(n),n={lines:[],height:0,startIndex:o.endIndex+1,endIndex:0})}return n.lines.length>0&&(n.endIndex=n.lines[n.lines.length-1].endIndex,i.push(n)),0===i.length&&i.push({lines:[],height:0,startIndex:0,endIndex:0}),i}findPositionForIndex(t,e){for(let i=0;i<t.length;i++){const n=t[i];for(let t=0;t<n.lines.length;t++){const o=n.lines[t];if(e>=o.startIndex&&e<=o.endIndex)return{pageIndex:i,lineIndex:t}}}if(t.length>0){const e=t[t.length-1];return{pageIndex:t.length-1,lineIndex:Math.max(0,e.lines.length-1)}}return null}getParagraphBoundaries(t){const e=[0];for(let i=0;i<t.length;i++)"\n"===t[i]&&e.push(i+1);return e}calculateListIndent(t){return 24*(t+1)}getListMarkerText(t,e){return"bullet"===t.listType?this.getBulletCharacter(t.bulletStyle,t.nestingLevel)+" ":"number"===t.listType&&void 0!==e?this.formatNumber(e,t.numberStyle)+" ":""}getBulletCharacter(t,e){switch(t||["disc","circle","square"][(e||0)%3]){case"disc":default:return"•";case"circle":return"◦";case"square":return"▪";case"dash":return"–";case"none":return""}}formatNumber(t,e){switch(e){case"lower-alpha":return this.toAlpha(t,!1)+".";case"upper-alpha":return this.toAlpha(t,!0)+".";case"lower-roman":return this.toRoman(t,!1)+".";case"upper-roman":return this.toRoman(t,!0)+".";default:return t+"."}}toAlpha(t,e){let i="";for(;t>0;)t--,i=String.fromCharCode(t%26+(e?65:97))+i,t=Math.floor(t/26);return i}toRoman(t,e){const i=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]];let n="";for(const[e,o]of i)for(;t>=e;)n+=o,t-=e;return e?n:n.toLowerCase()}}class F{constructor(t){this.fontCache=new Map,this.ctx=t}toFontString(t){const e=`${t.fontStyle}-${t.fontWeight}-${t.fontSize}-${t.fontFamily}`;let i=this.fontCache.get(e);return i||(i=`${t.fontStyle||""} ${t.fontWeight||""} ${t.fontSize}px ${t.fontFamily}`.trim(),this.fontCache.set(e,i)),i}measureText(t,e){return this.ctx.font=this.toFontString(e),this.ctx.measureText(t).width}measureCharacter(t,e){return"\t"===t?this.measureText(" ",e):this.measureText(t,e)}getLineHeight(t){return 1.2*t.fontSize}getBaseline(t){return.8*t.fontSize}getCharacterIndexAtX(t,e,i,n=0){if(e<=0)return n;this.ctx.font=this.toFontString(i);let o=0;for(let i=0;i<t.length;i++){const s=this.ctx.measureText(t[i]).width;if(e<o+s/2)return n+i;o+=s}return n+t.length}getXPositionForIndex(t,e,i,n=0){const o=e-n;return o<=0?0:o>=t.length?this.measureText(t,i):this.measureText(t.substring(0,o),i)}setContext(t){this.ctx=t}getFieldDisplayText(t,e,i){return"pageNumber"===t.fieldType?void 0!==e?t.displayFormat?t.displayFormat.replace(/%d/g,String(e)):String(e):t.displayFormat?t.displayFormat.replace(/%d/g,"00"):"00":"pageCount"===t.fieldType?void 0!==i?t.displayFormat?t.displayFormat.replace(/%d/g,String(i)):String(i):t.displayFormat?t.displayFormat.replace(/%d/g,"00"):"00":`{{field: ${t.fieldName}}}`}measureSubstitutionField(t,e,i,n){const o=this.getFieldDisplayText(t,i,n),s=t.formatting||e||d;return{width:this.measureText(o,s),height:this.getLineHeight(s)}}measureEmbeddedObject(t){return{width:t.width,height:t.height}}measureEmbeddedAt(t,e,i,n){const o=e.get(t);if(o){return{...this.measureSubstitutionField(o,n),type:"field",field:o}}const s=i.get(t);if(s){return{...this.measureEmbeddedObject(s),type:"object",object:s}}return{width:0,height:0,type:"none"}}measureWordWithEmbedded(t,e,i,n,o){let s=0,r=this.getLineHeight(e);const a=[],l=[];for(let d=0;d<t.length;d++){const h=t[d],g=o+d;if(h===c){const t=this.measureEmbeddedAt(g,i,n,e);"field"===t.type&&t.field?(a.push({field:t.field,textIndex:g,width:t.width,xOffset:s}),s+=t.width,r=Math.max(r,t.height)):"object"===t.type&&t.object&&(l.push({object:t.object,textIndex:g,xOffset:s}),s+=t.width,"inline"===t.object.position&&(r=Math.max(r,t.height)))}else s+=this.measureCharacter(h,e)}return{width:s,height:r,fields:a,objects:l}}}const I={width:1,color:"#cccccc",style:"solid"};class _ extends r{constructor(t){super(),this._relativeOffset={x:0,y:0},this._selected=!1,this._locked=!1,this._renderedPosition=null,this._renderedPageIndex=-1,this._id=t.id,this._textIndex=t.textIndex,this._position=t.position||"inline",this._size={...t.size},t.relativeOffset&&(this._relativeOffset={...t.relativeOffset})}get id(){return this._id}get textIndex(){return this._textIndex}set textIndex(t){this._textIndex=t,this.emit("text-index-changed",{textIndex:t})}get position(){return this._position}set position(t){this._position=t,this.emit("position-changed",{position:t})}get relativeOffset(){return{...this._relativeOffset}}set relativeOffset(t){this._relativeOffset={...t},this.emit("offset-changed",{offset:{...t}})}get size(){return{...this._size}}set size(t){this._size={...t},this.emit("size-changed",{size:{...t}})}get width(){return this._size.width}set width(t){this._size.width=t,this.emit("size-changed",{size:{...this._size}})}get height(){return this._size.height}set height(t){this._size.height=t,this.emit("size-changed",{size:{...this._size}})}get selected(){return this._selected}set selected(t){this._selected!==t&&(this._selected=t,this.emit("selection-changed",{selected:t}))}get locked(){return this._locked}set locked(t){this._locked=t,this.emit("locked-changed",{locked:t})}get renderedPosition(){return this._renderedPosition}set renderedPosition(t){this._renderedPosition=t?{...t}:null}get renderedPageIndex(){return this._renderedPageIndex}set renderedPageIndex(t){this._renderedPageIndex=t}getBounds(){return{x:0,y:0,width:this._size.width,height:this._size.height}}containsPoint(t,e){return t.x>=e.x&&t.x<=e.x+this._size.width&&t.y>=e.y&&t.y<=e.y+this._size.height}resize(t){const e=this.getMinSize(),i=this.getMaxSize();let n=Math.max(t.width,e.width),o=Math.max(t.height,e.height);i&&(n=Math.min(n,i.width),o=Math.min(o,i.height)),this.size={width:n,height:o}}handleClick(t){this._locked||(this.selected=!0)}handleDoubleClick(t){}getMinSize(){return{width:20,height:20}}getMaxSize(){return null}get resizable(){return!this._locked}getResizeHandles(){return this._locked?[]:["nw","n","ne","e","se","s","sw","w"]}renderSelectionBorder(t){const{width:e,height:i}=this._size;if(t.strokeStyle="#0066ff",t.lineWidth=2,t.setLineDash([4,4]),t.strokeRect(0,0,e,i),t.setLineDash([]),this.resizable){const e=8,i=this.getResizeHandles();t.fillStyle="#ffffff",t.strokeStyle="#0066ff",t.lineWidth=1;for(const n of i){const i=this.getHandlePosition(n,e);t.fillRect(i.x,i.y,e,e),t.strokeRect(i.x,i.y,e,e)}}}getHandlePosition(t,e){const{width:i,height:n}=this._size,o=e/2;switch(t){case"nw":return{x:-o,y:-o};case"n":return{x:i/2-o,y:-o};case"ne":return{x:i-o,y:-o};case"e":return{x:i-o,y:n/2-o};case"se":return{x:i-o,y:n-o};case"s":return{x:i/2-o,y:n-o};case"sw":return{x:-o,y:n-o};case"w":return{x:-o,y:n/2-o}}}getResizeHandleAtPoint(t,e=12){if(!this.resizable)return null;const i=this.getResizeHandles(),n=e/2;for(const o of i){const i=this.getHandlePosition(o,e);if(t.x>=i.x-n&&t.x<=i.x+e+n&&t.y>=i.y-n&&t.y<=i.y+e+n)return o}return null}}class T extends _{constructor(t){super(t),this._image=null,this._loaded=!1,this._error=!1,this._src=t.src,this._fit=t.fit||"contain",this._resizeMode=t.resizeMode||"locked-aspect-ratio",this._alt=t.alt||"",this.loadImage()}get objectType(){return"image"}get src(){return this._src}set src(t){this._src!==t&&(this._src=t,this._loaded=!1,this._error=!1,this.loadImage())}get fit(){return this._fit}set fit(t){this._fit=t,this.emit("fit-changed",{fit:t})}get resizeMode(){return this._resizeMode}set resizeMode(t){this._resizeMode=t,this.emit("resize-mode-changed",{resizeMode:t})}get alt(){return this._alt}set alt(t){this._alt=t}get loaded(){return this._loaded}get hasError(){return this._error}get imageElement(){return this._loaded?this._image:null}toPngDataUrl(){if(!this._loaded||!this._image)return null;try{const t=document.createElement("canvas");t.width=this._image.naturalWidth||this._size.width,t.height=this._image.naturalHeight||this._size.height;const e=t.getContext("2d");return e?(e.drawImage(this._image,0,0,t.width,t.height),t.toDataURL("image/png")):null}catch{return null}}loadImage(){this._src?(this._image=new Image,this._image.onload=()=>{this._loaded=!0,this._error=!1,this.emit("image-loaded",{src:this._src})},this._image.onerror=()=>{this._loaded=!1,this._error=!0,this.emit("image-error",{src:this._src})},this._image.src=this._src):this._error=!0}render(t){this._loaded&&this._image?this.drawImage(t):this._error?this.drawErrorPlaceholder(t):this.drawLoadingPlaceholder(t),this._selected&&this.renderSelectionBorder(t)}drawImage(t){if(!this._image)return;const{width:e,height:i}=this._size,n=this._image.naturalWidth,o=this._image.naturalHeight;let s=0,r=0,a=n,l=o,d=0,h=0,c=e,g=i,u=!1;switch(this._fit){case"fill":break;case"contain":{const t=Math.min(e/n,i/o);c=n*t,g=o*t,d=(e-c)/2,h=(i-g)/2;break}case"cover":{const t=Math.max(e/n,i/o);a=e/t,l=i/t,s=(n-a)/2,r=(o-l)/2;break}case"none":c=n,g=o,d=(e-n)/2,h=(i-o)/2,(n>e||o>i)&&(u=!0);break;case"tile":return void this.drawTiledImage(t,e,i)}u&&(t.save(),t.beginPath(),t.rect(0,0,e,i),t.clip()),t.drawImage(this._image,s,r,a,l,d,h,c,g),u&&t.restore()}drawTiledImage(t,e,i){if(!this._image)return;const n=this._image.naturalWidth,o=this._image.naturalHeight;for(let s=0;s<i;s+=o)for(let r=0;r<e;r+=n){const a=Math.min(n,e-r),l=Math.min(o,i-s);t.drawImage(this._image,0,0,a,l,r,s,a,l)}}drawLoadingPlaceholder(t){const{width:e,height:i}=this._size;t.fillStyle="#f0f0f0",t.fillRect(0,0,e,i),t.strokeStyle="#cccccc",t.lineWidth=1,t.strokeRect(0,0,e,i),t.fillStyle="#888888",t.font="12px Arial",t.textAlign="center",t.textBaseline="middle",t.fillText("Loading...",e/2,i/2)}drawErrorPlaceholder(t){const{width:e,height:i}=this._size;t.fillStyle="#fff0f0",t.fillRect(0,0,e,i),t.strokeStyle="#ffcccc",t.lineWidth=1,t.strokeRect(0,0,e,i),t.strokeStyle="#ff6666",t.lineWidth=2,t.beginPath(),t.moveTo(.3*e,.3*i),t.lineTo(.7*e,.7*i),t.moveTo(.7*e,.3*i),t.lineTo(.3*e,.7*i),t.stroke(),i>40&&(t.fillStyle="#cc0000",t.font="10px Arial",t.textAlign="center",t.textBaseline="bottom",t.fillText("Image failed",e/2,i-5))}toData(){return{id:this._id,objectType:"image",textIndex:this._textIndex,position:this._position,size:{...this._size},relativeOffset:"relative"===this._position?{...this._relativeOffset}:void 0,data:{src:this._src,fit:this._fit,resizeMode:this._resizeMode,alt:this._alt,naturalWidth:this._image?.naturalWidth,naturalHeight:this._image?.naturalHeight}}}restoreFromData(t){this._size={...t.size},t.position&&(this._position=t.position),t.relativeOffset&&(this._relativeOffset={...t.relativeOffset});const e=t.data;if(e){const t=void 0!==e.src&&e.src!==this._src;void 0!==e.fit&&(this._fit=e.fit),void 0!==e.resizeMode&&(this._resizeMode=e.resizeMode),void 0!==e.alt&&(this._alt=e.alt),t&&this.setSource(e.src)}this.emit("state-restored",{data:t})}clone(){return new T({id:`${this._id}-clone-${Date.now()}`,textIndex:this._textIndex,position:this._position,size:{...this._size},relativeOffset:"relative"===this._position?{...this._relativeOffset}:void 0,src:this._src,fit:this._fit,resizeMode:this._resizeMode,alt:this._alt})}setSource(t,e){this._src=t,this._loaded=!1,this._error=!1,this._image=new Image,this._image.onload=()=>{if(this._loaded=!0,this._error=!1,void 0!==e?.maxWidth||void 0!==e?.maxHeight){const t=this.getNaturalSize();if(t){const i=e.maxWidth??t.width,n=e.maxHeight??t.height,o=Math.min(i/t.width,n/t.height,1);this.size={width:t.width*o,height:t.height*o}}}this.emit("image-loaded",{src:this._src})},this._image.onerror=()=>{this._loaded=!1,this._error=!0,this.emit("image-error",{src:this._src})},this._image.src=t}getNaturalSize(){return this._loaded&&this._image?{width:this._image.naturalWidth,height:this._image.naturalHeight}:null}resizeToNatural(){const t=this.getNaturalSize();t&&(this.size=t)}resizeToFit(t,e){const i=this.getNaturalSize();if(!i)return;const n=Math.min(t/i.width,e/i.height,1);this.size={width:i.width*n,height:i.height*n}}}class P{static getFontString(t){return`${t.fontStyle||""} ${t.fontWeight||""} ${t.fontSize}px ${t.fontFamily}`.trim()}static getAlignmentOffset(t,e){switch(t.alignment){case"center":return(e-t.width)/2;case"right":return e-t.width;default:return 0}}static findLineAtY(t,e){if(0===t.length)return null;let i=0;for(let n=0;n<t.length;n++){const o=t[n];if(e>=i&&e<i+o.height)return{line:o,lineIndex:n,lineY:i};i+=o.height}if(e>=i&&t.length>0){const e=t.length-1,n=t[e];return{line:n,lineIndex:e,lineY:i-n.height}}return null}static getXPositionForTextIndex(t,e,i){if(e<=t.startIndex)return 0;if(e>=t.endIndex)return"justify"===t.alignment&&t.extraWordSpacing?t.width+this.countWordGapsUpTo(t,t.endIndex)*t.extraWordSpacing:t.width;const n=this.buildSubstitutionFieldMap(t),o=this.buildEmbeddedObjectMap(t);let s=0;for(const r of t.runs){i.font=this.getFontString(r.formatting);for(let a=0;a<r.text.length;a++){const l=r.startIndex+a;if(l>=e)return s;const d=r.text[a];s+=this.getCharWidth(d,l,i,n,o),"justify"===t.alignment&&t.extraWordSpacing&&/\s/.test(d)&&(s+=t.extraWordSpacing)}}return s}static getTextIndexAtX(t,e,i){if(e<=0)return t.startIndex;const n=this.buildSubstitutionFieldMap(t),o=this.buildEmbeddedObjectMap(t);let s=0;const r=t.extraWordSpacing||0;for(const a of t.runs){i.font=this.getFontString(a.formatting);for(let t=0;t<a.text.length;t++){const l=a.startIndex+t,d=a.text[t],h=n.get(l);if(h){const t=h.width;if(e>=s&&e<s+t)return l+1;s+=t,r>0&&/\s/.test(d)&&(s+=r);continue}const c=this.getCharWidth(d,l,i,n,o);if(e>=s&&e<s+c)return e<s+c/2?l:l+1;s+=c,r>0&&/\s/.test(d)&&(s+=r)}}return t.endIndex}static getCharWidth(t,e,i,n,o){const s=n.get(e);if(s)return s.width;const r=o.get(e);return r?r.object.width+2:""!==t?"\t"===t?i.measureText(" ").width:i.measureText(t).width:0}static buildSubstitutionFieldMap(t){const e=new Map;return t.substitutionFields&&t.substitutionFields.forEach(t=>e.set(t.textIndex,t)),e}static buildEmbeddedObjectMap(t){const e=new Map;return t.embeddedObjects&&t.embeddedObjects.forEach(t=>e.set(t.textIndex,t)),e}static countWordGapsUpTo(t,e){let i=0,n=!1;for(let o=t.startIndex;o<Math.min(e,t.endIndex);o++){const e=o-t.startIndex;if(e>=t.text.length)break;const s=t.text[e],r=/\s/.test(s);r||n?r&&n&&(i++,n=!1):n=!0}return i}}const R="Arial",k=14,A="#000000",M="#ffffff",E=4;class L extends _{constructor(t){super(t),this._editing=!1,this._flowedLines=[],this._flowedPage=null,this.type="textbox",this._content=t.content||"",this._fontFamily=t.fontFamily||R,this._fontSize=t.fontSize||k,this._color=t.color||A,this._backgroundColor=t.backgroundColor||M,this._border=function(t,e){const i=e?{...I,color:e}:{...I};return{top:t?.top?{...i,...t.top}:{...i},right:t?.right?{...i,...t.right}:{...i},bottom:t?.bottom?{...i,...t.bottom}:{...i},left:t?.left?{...i,...t.left}:{...i}}}(t.border,t.borderColor),this._padding=t.padding??E,this._flowingContent=new X(this._content),this._flowingContent.setDefaultFormatting({fontFamily:this._fontFamily,fontSize:this._fontSize,color:this._color}),this._flowingContent.on("content-changed",()=>{this._content=this._flowingContent.getText(),this.emit("content-changed",{content:this._content})})}get objectType(){return"textbox"}get content(){return this._content}set content(t){this._content=t,this._flowingContent.setText(t),this.emit("content-changed",{content:t})}get fontFamily(){return this._fontFamily}set fontFamily(t){this._fontFamily=t,this._flowingContent.setDefaultFormatting({fontFamily:t}),this.emit("style-changed",{fontFamily:t})}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize=t,this._flowingContent.setDefaultFormatting({fontSize:t}),this.emit("style-changed",{fontSize:t})}get color(){return this._color}set color(t){this._color=t,this._flowingContent.setDefaultFormatting({color:t}),this.emit("style-changed",{color:t})}get backgroundColor(){return this._backgroundColor}set backgroundColor(t){this._backgroundColor=t,this.emit("style-changed",{backgroundColor:t})}get border(){return this._border}set border(t){this._border=t,this.emit("style-changed",{border:t})}get borderColor(){return this._border.top.color}set borderColor(t){this._border={top:{...this._border.top,color:t},right:{...this._border.right,color:t},bottom:{...this._border.bottom,color:t},left:{...this._border.left,color:t}},this.emit("style-changed",{borderColor:t})}get padding(){return this._padding}set padding(t){this._padding=t,this.emit("style-changed",{padding:t})}get editing(){return this._editing}set editing(t){this._editing!==t&&(this._editing=t,t?this._flowingContent.focus():this._flowingContent.blur(),this.emit("editing-changed",{editing:t}))}get flowingContent(){return this._flowingContent}getTextBounds(){const t="none"!==this._border.left.style?this._border.left.width:0,e="none"!==this._border.right.style?this._border.right.width:0,i="none"!==this._border.top.style?this._border.top.width:0,n="none"!==this._border.bottom.style?this._border.bottom.width:0;return{width:this._size.width-2*this._padding-t-e,height:this._size.height-2*this._padding-i-n}}getTextOffset(){const t="none"!==this._border.left.style?this._border.left.width:0,e="none"!==this._border.top.style?this._border.top.width:0;return{x:this._padding+t,y:this._padding+e}}getTextAreaBounds(){if(!this._renderedPosition)return null;const t=this.getTextOffset(),e=this.getTextBounds();return{x:this._renderedPosition.x+t.x,y:this._renderedPosition.y+t.y,width:e.width,height:e.height}}render(t){this.renderBackground(t),this.renderBorder(t),this._selected&&this.renderSelectionBorder(t),this._editing&&this.renderEditingBorder(t)}renderBackground(t){const{width:e,height:i}=this._size;t.fillStyle=this._backgroundColor,t.fillRect(0,0,e,i)}renderBorder(t){const{width:e,height:i}=this._size;this.drawBorderSide(t,"top",0,0,e,0),this.drawBorderSide(t,"right",e,0,e,i),this.drawBorderSide(t,"bottom",e,i,0,i),this.drawBorderSide(t,"left",0,i,0,0)}drawBorderSide(t,e,i,n,o,s){const r=this._border[e];if(!("none"===r.style||r.width<=0)){switch(t.strokeStyle=r.color,t.lineWidth=r.width,r.style){case"dashed":t.setLineDash([3*r.width,2*r.width]);break;case"dotted":t.setLineDash([r.width,r.width]);break;default:t.setLineDash([])}t.beginPath(),t.moveTo(i,n),t.lineTo(o,s),t.stroke(),t.setLineDash([])}}getXPositionInLine(t,e,i){const n=this.getTextBounds();return P.getAlignmentOffset(e,n.width)+P.getXPositionForTextIndex(e,i,t)}renderEditingBorder(t){const{width:e,height:i}=this._size;t.strokeStyle="#0099ff",t.lineWidth=2,t.setLineDash([]),t.strokeRect(1,1,e-2,i-2)}moveCursorVertical(t,e){if(0===this._flowedLines.length)return!1;const i=this._flowingContent.getCursorPosition();let n=-1;for(let t=0;t<this._flowedLines.length;t++){const e=this._flowedLines[t];if(i>=e.startIndex&&i<=e.endIndex){n=t;break}}-1===n&&(n=this._flowedLines.length-1);const o=n+t;if(o<0||o>=this._flowedLines.length)return!1;const s=this._flowedLines[n],r=this._flowedLines[o],a=this.getXPositionInLine(e,s,i),l=this.getTextIndexAtX(e,r,a);return this._flowingContent.setCursorPosition(l),this._flowingContent.resetCursorBlink(),!0}getTextIndexAtX(t,e,i){const n=this.getTextBounds(),o=i-P.getAlignmentOffset(e,n.width);return P.getTextIndexAtX(e,o,t)}focus(){this.editing=!0}blur(){this.editing=!1}hasFocus(){return this._editing&&this._flowingContent.hasFocus()}handleKeyDown(t){return!!this._editing&&("Escape"===t.key?(t.preventDefault(),this.finishEditing(),!0):this._flowingContent.handleKeyDown(t))}onCursorBlink(t){this._flowingContent.onCursorBlink(t)}offCursorBlink(t){this._flowingContent.offCursorBlink(t)}handleDoubleClick(t){this._locked||(this.editing=!0,this.emit("edit-requested",{object:this}))}finishEditing(){this.editing=!1}toData(){const t=this._flowingContent.getText(),e=this._flowingContent.getFormattingManager().getCompressedRuns(t.length).map(t=>[t.index,{...t.formatting}]),i=this._flowingContent.getSubstitutionFieldManager().getFieldsArray();return{id:this._id,objectType:"textbox",textIndex:this._textIndex,position:this._position,size:{...this._size},relativeOffset:"relative"===this._position?{...this._relativeOffset}:void 0,data:{content:this._content,fontFamily:this._fontFamily,fontSize:this._fontSize,color:this._color,backgroundColor:this._backgroundColor,border:this._border,padding:this._padding,formattingRuns:e,substitutionFields:i}}}restoreFromData(t){this._size={...t.size},t.position&&(this._position=t.position),t.relativeOffset&&(this._relativeOffset={...t.relativeOffset});const e=t.data;if(e){if(void 0!==e.content&&(this._content=e.content,this._flowingContent.setText(e.content)),void 0!==e.fontFamily&&(this._fontFamily=e.fontFamily),void 0!==e.fontSize&&(this._fontSize=e.fontSize),void 0!==e.color&&(this._color=e.color),void 0!==e.backgroundColor&&(this._backgroundColor=e.backgroundColor),void 0!==e.border&&(this._border={...e.border}),void 0!==e.padding&&(this._padding=e.padding),e.formattingRuns&&e.formattingRuns.length>0){const t=this._flowingContent.getFormattingManager();t.clear();const i=this._flowingContent.getText().length;for(let n=0;n<e.formattingRuns.length;n++){const[o,s]=e.formattingRuns[n],r=n+1<e.formattingRuns.length?e.formattingRuns[n+1][0]:i;o<r&&t.applyFormatting(o,r,s)}}if(e.substitutionFields){const t=this._flowingContent.getSubstitutionFieldManager();t.clear();for(const i of e.substitutionFields)t.insertAt(i.textIndex,i)}}this._flowedLines=[],this._flowedPage=null,this.emit("state-restored",{data:t})}clone(){return new L({id:`${this._id}-clone-${Date.now()}`,textIndex:this._textIndex,position:this._position,size:{...this._size},relativeOffset:"relative"===this._position?{...this._relativeOffset}:void 0,content:this._content,fontFamily:this._fontFamily,fontSize:this._fontSize,color:this._color,backgroundColor:this._backgroundColor,border:this._border,padding:this._padding})}getContentSize(t){if(!this._content)return{width:50,height:1.2*this._fontSize+2*this._padding};t.font=`${this._fontSize}px ${this._fontFamily}`;const e=this._content.split("\n");let i=0;for(const n of e){const e=t.measureText(n);i=Math.max(i,e.width)}const n=e.length*this._fontSize*1.2,o=("none"!==this._border.top.style?this._border.top.width:0)+("none"!==this._border.bottom.style?this._border.bottom.width:0),s=("none"!==this._border.left.style?this._border.left.width:0)+("none"!==this._border.right.style?this._border.right.width:0);return{width:i+2*this._padding+s,height:n+2*this._padding+o}}resizeToContent(t){const e=this.getContentSize(t),i=this.getMinSize();this.size={width:Math.max(e.width,i.width),height:Math.max(e.height,i.height)}}getRegionBounds(t){return this.getTextAreaBounds()}globalToLocal(t,e){const i=this.getRegionBounds(e);return i?t.x<i.x||t.x>i.x+i.width||t.y<i.y||t.y>i.y+i.height?null:{x:t.x-i.x,y:t.y-i.y}:null}localToGlobal(t,e){const i=this.getRegionBounds(e);return i?{x:t.x+i.x,y:t.y+i.y}:t}getFlowedLines(t){return this._flowedLines}getFlowedPages(){return this._flowedPage?[this._flowedPage]:[]}getAvailableWidth(){return this.getTextBounds().width}spansMultiplePages(){return!1}getPageCount(){return 1}containsPointInRegion(t,e){return!!this._renderedPosition&&(t.x>=this._renderedPosition.x&&t.x<=this._renderedPosition.x+this._size.width&&t.y>=this._renderedPosition.y&&t.y<=this._renderedPosition.y+this._size.height)}reflow(t){const e=this.getTextBounds();if(e.width<=0||e.height<=0)return this._flowedLines=[],void(this._flowedPage=null);const i=this._flowingContent.flowText(e.width,1e4,t);this._flowedLines=i.length>0?i[0].lines:[],this._flowedPage=i.length>0?i[0]:null}}const B={cellPadding:4,borderColor:"#000000",borderWidth:1,fontFamily:"Arial",fontSize:12,color:"#000000",backgroundColor:"#ffffff",minColumnWidth:20,minRowHeight:20,defaultColumnWidth:100},O={width:1,color:"#000000",style:"solid"};function z(t){return t.top+t.bottom}let D=!1;const j={setEnabled(t){D=t},isEnabled:()=>D,log(...t){D&&console.log(...t)},warn(...t){D&&console.warn(...t)},error(...t){console.error(...t)}};class H extends r{constructor(t){super(),this.type="tablecell",this._flowedLines=[],this._flowedPage=null,this._bounds=null,this._renderedPosition=null,this._renderedPageIndex=0,this._editing=!1,this._reflowDirty=!0,this._lastReflowWidth=0,this._cachedContentHeight=null,this._id=t.id||`cell_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,this._rowSpan=t.rowSpan??1,this._colSpan=t.colSpan??1,this._backgroundColor=t.backgroundColor??B.backgroundColor,this._border=function(t){const e=O;return{top:t?.top||{...e},right:t?.right||{...e},bottom:t?.bottom||{...e},left:t?.left||{...e}}}(t.border),this._padding=function(t,e){const i=e??B.cellPadding;return"number"==typeof t?{top:t,right:t,bottom:t,left:t}:{top:t?.top??i,right:t?.right??i,bottom:t?.bottom??i,left:t?.left??i}}(t.padding,B.cellPadding),this._verticalAlign=t.verticalAlign??"top",this._fontFamily=t.fontFamily??B.fontFamily,this._fontSize=t.fontSize??B.fontSize,this._color=t.color??B.color,this._flowingContent=new X,this._flowingContent.setDefaultFormatting({fontFamily:this._fontFamily,fontSize:this._fontSize,color:this._color}),this._flowingContent.insertEmbeddedObject=()=>{j.warn("[pc-editor:TableCell] Embedded objects are not allowed in table cells. Use insertSubstitutionField instead.")},t.content&&this._flowingContent.setText(t.content),this._flowingContent.on("content-changed",()=>{this._reflowDirty=!0,this._cachedContentHeight=null,this.emit("content-changed",{cellId:this._id})}),this._flowingContent.on("cursor-moved",()=>{this.emit("cursor-moved",{cellId:this._id})})}get id(){return this._id}get rowSpan(){return this._rowSpan}set rowSpan(t){t>=1&&t!==this._rowSpan&&(this._rowSpan=t,this.emit("span-changed",{cellId:this._id,rowSpan:t,colSpan:this._colSpan}))}get colSpan(){return this._colSpan}set colSpan(t){t>=1&&t!==this._colSpan&&(this._colSpan=t,this.emit("span-changed",{cellId:this._id,rowSpan:this._rowSpan,colSpan:t}))}get backgroundColor(){return this._backgroundColor}set backgroundColor(t){this._backgroundColor!==t&&(this._backgroundColor=t,this.emit("style-changed",{cellId:this._id,backgroundColor:t}))}get border(){return this._border}set border(t){this._border=t,this.emit("style-changed",{cellId:this._id,border:t})}get padding(){return this._padding}set padding(t){this._padding=t,this.emit("style-changed",{cellId:this._id,padding:t})}get verticalAlign(){return this._verticalAlign}set verticalAlign(t){this._verticalAlign!==t&&(this._verticalAlign=t,this.emit("style-changed",{cellId:this._id,verticalAlign:t}))}get fontFamily(){return this._fontFamily}set fontFamily(t){this._fontFamily=t,this._flowingContent.setDefaultFormatting({fontFamily:t}),this.emit("style-changed",{cellId:this._id,fontFamily:t})}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize=t,this._flowingContent.setDefaultFormatting({fontSize:t}),this.emit("style-changed",{cellId:this._id,fontSize:t})}get color(){return this._color}set color(t){this._color=t,this._flowingContent.setDefaultFormatting({color:t}),this.emit("style-changed",{cellId:this._id,color:t})}get flowingContent(){return this._flowingContent}get content(){return this._flowingContent.getText()}set content(t){this._flowingContent.setText(t)}insertSubstitutionField(t,e){this._flowingContent.insertSubstitutionField(t,e)}setBounds(t){this._bounds=t}getBounds(){return this._bounds}setRenderedPosition(t){this._renderedPosition=t}getRenderedPosition(){return this._renderedPosition}set renderedPageIndex(t){this._renderedPageIndex=t}get renderedPageIndex(){return this._renderedPageIndex}getContentBounds(){if(!this._bounds)return null;const t="none"!==this._border.left.style?this._border.left.width:0,e="none"!==this._border.top.style?this._border.top.width:0;return{x:this._bounds.x+t+this._padding.left,y:this._bounds.y+e+this._padding.top,width:this._bounds.width-(i=this._padding,i.left+i.right)-("none"!==this._border.left.style?this._border.left.width:0)-("none"!==this._border.right.style?this._border.right.width:0),height:this._bounds.height-z(this._padding)-("none"!==this._border.top.style?this._border.top.width:0)-("none"!==this._border.bottom.style?this._border.bottom.width:0)};var i}getContentHeight(t){if(null!==this._cachedContentHeight&&!this._reflowDirty)return this._cachedContentHeight;(this._reflowDirty||0===this._flowedLines.length&&this._flowingContent.getText().length>0)&&this.reflow(t);let e=0;for(const t of this._flowedLines)e+=t.height;return e+=z(this._padding),e+="none"!==this._border.top.style?this._border.top.width:0,e+="none"!==this._border.bottom.style?this._border.bottom.width:0,this._cachedContentHeight=Math.max(e,B.minRowHeight),this._cachedContentHeight}getRegionBounds(t){if(!this._renderedPosition||!this._bounds)return null;const e="none"!==this._border.left.style?this._border.left.width:0,i="none"!==this._border.top.style?this._border.top.width:0,n="none"!==this._border.right.style?this._border.right.width:0,o="none"!==this._border.bottom.style?this._border.bottom.width:0;return{x:this._renderedPosition.x+e+this._padding.left,y:this._renderedPosition.y+i+this._padding.top,width:this._bounds.width-this._padding.left-this._padding.right-e-n,height:this._bounds.height-this._padding.top-this._padding.bottom-i-o}}globalToLocal(t,e){const i=this.getRegionBounds(e);return i?t.x<i.x||t.x>i.x+i.width||t.y<i.y||t.y>i.y+i.height?null:{x:t.x-i.x,y:t.y-i.y}:null}localToGlobal(t,e){const i=this.getRegionBounds(e);return i?{x:t.x+i.x,y:t.y+i.y}:t}getFlowedLines(t){return this._flowedLines}getFlowedPages(){return this._flowedPage?[this._flowedPage]:[]}getAvailableWidth(){if(!this._bounds)return 0;const t="none"!==this._border.left.style?this._border.left.width:0,e="none"!==this._border.right.style?this._border.right.width:0;return this._bounds.width-this._padding.left-this._padding.right-t-e}spansMultiplePages(){return!1}getPageCount(){return 1}containsPointInRegion(t,e){const i=this.getRegionBounds(e);return!!i&&(t.x>=i.x&&t.x<=i.x+i.width&&t.y>=i.y&&t.y<=i.y+i.height)}reflow(t){const e=this.getAvailableWidth();if(e<=0)return this._flowedLines=[],this._flowedPage=null,void(this._reflowDirty=!1);if(!this._reflowDirty&&this._lastReflowWidth===e&&this._flowedLines.length>0)return;const i=this._flowingContent.flowText(e,1e4,t);this._flowedLines=i.length>0?i[0].lines:[],this._flowedPage=i.length>0?i[0]:null,this._reflowDirty=!1,this._lastReflowWidth=e,this._cachedContentHeight=null,j.log("[pc-editor:TableCell.reflow] cellId:",this._id,"text:",JSON.stringify(this._flowingContent.getText()),"lines:",this._flowedLines.length)}markReflowDirty(){this._reflowDirty=!0,this._cachedContentHeight=null}get editing(){return this._editing}set editing(t){this._editing!==t&&(this._editing=t,t?this._flowingContent.focus():this._flowingContent.blur(),this.emit("editing-changed",{cellId:this._id,editing:t}))}focus(){this.editing=!0}blur(){this.editing=!1}hasFocus(){return this._editing&&this._flowingContent.hasFocus()}handleKeyDown(t){if(j.log("[pc-editor:TableCell.handleKeyDown] Key:",t.key,"_editing:",this._editing,"flowingContent.hasFocus:",this._flowingContent.hasFocus()),!this._editing)return!1;if("Tab"===t.key)return!1;j.log("[pc-editor:TableCell.handleKeyDown] Delegating to FlowingTextContent.handleKeyDown");const e=this._flowingContent.handleKeyDown(t);return j.log("[pc-editor:TableCell.handleKeyDown] FlowingTextContent handled:",e),e}onCursorBlink(t){this._flowingContent.onCursorBlink(t)}offCursorBlink(t){this._flowingContent.offCursorBlink(t)}render(t){this._bounds&&(this.renderBackground(t),this.renderBorder(t))}renderBackground(t){this._bounds&&(t.fillStyle=this._backgroundColor,t.fillRect(0,0,this._bounds.width,this._bounds.height))}renderBorder(t){if(!this._bounds)return;const{width:e,height:i}=this._bounds;"none"!==this._border.top.style&&this.renderBorderSide(t,this._border.top,0,0,e,0),"none"!==this._border.right.style&&this.renderBorderSide(t,this._border.right,e,0,e,i),"none"!==this._border.bottom.style&&this.renderBorderSide(t,this._border.bottom,0,i,e,i),"none"!==this._border.left.style&&this.renderBorderSide(t,this._border.left,0,0,0,i)}renderBorderSide(t,e,i,n,o,s){switch(t.strokeStyle=e.color,t.lineWidth=e.width,e.style){case"dashed":t.setLineDash([4,4]);break;case"dotted":t.setLineDash([2,2]);break;default:t.setLineDash([])}t.beginPath(),t.moveTo(i,n),t.lineTo(o,s),t.stroke(),t.setLineDash([])}toData(){const t=this._flowingContent.getText(),e=this._flowingContent.getFormattingManager().getCompressedRuns(t.length).map(t=>[t.index,t.formatting]),i=this._flowingContent.getSubstitutionFieldManager().getFieldsArray(),n=B,o=O,s=t=>t.width===o.width&&t.color===o.color&&t.style===o.style,r=s(this._border.top)&&s(this._border.right)&&s(this._border.bottom)&&s(this._border.left),a=this._padding.top===n.cellPadding&&this._padding.right===n.cellPadding&&this._padding.bottom===n.cellPadding&&this._padding.left===n.cellPadding,l={};return 1!==this._rowSpan&&(l.rowSpan=this._rowSpan),1!==this._colSpan&&(l.colSpan=this._colSpan),this._backgroundColor!==n.backgroundColor&&(l.backgroundColor=this._backgroundColor),r||(l.border=this._border),a||(l.padding=this._padding),"top"!==this._verticalAlign&&(l.verticalAlign=this._verticalAlign),t&&(l.content=t),this._fontFamily!==n.fontFamily&&(l.fontFamily=this._fontFamily),this._fontSize!==n.fontSize&&(l.fontSize=this._fontSize),this._color!==n.color&&(l.color=this._color),e.length>0&&(l.formattingRuns=e),i.length>0&&(l.substitutionFields=i),l}static fromData(t){const e=new H({id:t.id,rowSpan:t.rowSpan,colSpan:t.colSpan,backgroundColor:t.backgroundColor,border:t.border,padding:t.padding,verticalAlign:t.verticalAlign,content:t.content,fontFamily:t.fontFamily,fontSize:t.fontSize,color:t.color});if(t.formattingRuns&&t.formattingRuns.length>0){const i=e._flowingContent.getFormattingManager(),n=(t.content||"").length;for(let e=0;e<t.formattingRuns.length;e++){const[o,s]=t.formattingRuns[e],r=e+1<t.formattingRuns.length?t.formattingRuns[e+1][0]:n;o<r&&i.applyFormatting(o,r,s)}}if(t.substitutionFields&&Array.isArray(t.substitutionFields)){const i=e._flowingContent.getSubstitutionFieldManager();for(const e of t.substitutionFields)void 0!==e.textIndex&&e.fieldName&&(i.insert(e.fieldName,e.textIndex,{defaultValue:e.defaultValue,displayFormat:e.displayFormat}),e.formatting&&i.setFieldFormatting(e.textIndex,e.formatting))}return e}clone(){return H.fromData(this.toData())}}class N extends r{constructor(t,e,i){if(super(),this._calculatedHeight=0,this._id=t.id||`row_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,this._height=t.height??null,this._minHeight=t.minHeight??B.minRowHeight,this._isHeader=t.isHeader??!1,this._cells=[],t.cells&&t.cells.length>0)for(let n=0;n<e;n++){const e=t.cells[n]||{},o={...i,...e},s=new H(o);this.setupCellListeners(s),this._cells.push(s)}else for(let t=0;t<e;t++){const t=new H(i||{});this.setupCellListeners(t),this._cells.push(t)}}setupCellListeners(t){t.on("content-changed",t=>{this.emit("cell-content-changed",{rowId:this._id,...t})}),t.on("style-changed",t=>{this.emit("cell-style-changed",{rowId:this._id,...t})}),t.on("span-changed",t=>{this.emit("cell-span-changed",{rowId:this._id,...t})}),t.on("editing-changed",t=>{this.emit("cell-editing-changed",{rowId:this._id,...t})})}get id(){return this._id}get cells(){return this._cells}get cellCount(){return this._cells.length}get height(){return this._height}set height(t){this._height!==t&&(this._height=t,this.emit("height-changed",{rowId:this._id,height:t}))}get minHeight(){return this._minHeight}set minHeight(t){this._minHeight!==t&&(this._minHeight=t,this.emit("min-height-changed",{rowId:this._id,minHeight:t}))}get isHeader(){return this._isHeader}set isHeader(t){this._isHeader!==t&&(this._isHeader=t,this.emit("header-changed",{rowId:this._id,isHeader:t}))}get calculatedHeight(){return this._calculatedHeight}getCell(t){return t<0||t>=this._cells.length?null:this._cells[t]}addCell(t,e){this.setupCellListeners(t),void 0!==e&&e>=0&&e<=this._cells.length?this._cells.splice(e,0,t):this._cells.push(t),this.emit("cell-added",{rowId:this._id,cellId:t.id,index:e??this._cells.length-1})}removeCell(t){if(t<0||t>=this._cells.length)return null;const[e]=this._cells.splice(t,1);return this.emit("cell-removed",{rowId:this._id,cellId:e.id,index:t}),e}insertCell(t,e){const i=new H(e||{});return this.setupCellListeners(i),t<0?t=0:t>this._cells.length&&(t=this._cells.length),this._cells.splice(t,0,i),this.emit("cell-added",{rowId:this._id,cellId:i.id,index:t}),i}calculateHeight(t,e){if(null!==this._height)return this._calculatedHeight=Math.max(this._height,this._minHeight),this._calculatedHeight;let i=this._minHeight;for(let n=0;n<this._cells.length;n++){const o=this._cells[n];let s=0;for(let t=n;t<n+o.colSpan&&t<e.length;t++)s+=e[t]||B.defaultColumnWidth;o.setBounds({x:0,y:0,width:s,height:1e3});const r=o.getContentHeight(t);r>i&&(i=r)}return this._calculatedHeight=i,this._calculatedHeight}setCellBounds(t,e,i,n){for(let o=0;o<this._cells.length;o++){const s=this._cells[o],r=e[o]||0,a=i[o]||B.defaultColumnWidth;s.setBounds({x:r,y:t,width:a,height:n})}}toData(){const t={cells:this._cells.map(t=>t.toData())};return null!==this._height&&(t.height=this._height),this._minHeight!==B.minRowHeight&&(t.minHeight=this._minHeight),this._isHeader&&(t.isHeader=this._isHeader),t}static fromData(t){const e=new N({id:t.id,height:t.height,minHeight:t.minHeight,isHeader:t.isHeader},t.cells.length);return e._cells=t.cells.map(t=>{const i=H.fromData(t);return e.setupCellListeners(i),i}),e}clone(){return N.fromData(this.toData())}}class W{static normalizeRange(t){return{start:{row:Math.min(t.start.row,t.end.row),col:Math.min(t.start.col,t.end.col)},end:{row:Math.max(t.start.row,t.end.row),col:Math.max(t.start.col,t.end.col)}}}static isValidRange(t,e){const i=this.normalizeRange(e);return i.start.row>=0&&i.start.col>=0&&i.end.row<t.rowCount&&i.end.col<t.columnCount}static canMerge(t,e){const i=this.normalizeRange(e);if(!this.isValidRange(t,i))return"Range is out of table bounds";const n=i.end.row-i.start.row+1,o=i.end.col-i.start.col+1;if(1===n&&1===o)return"Selection must include at least 2 cells to merge";for(let e=i.start.row;e<=i.end.row;e++)for(let n=i.start.col;n<=i.end.col;n++){const o=t.resolveCell(e,n);if(!o)continue;if(o.isSpanned){const t=o.rowIndex,e=o.colIndex;if(t<i.start.row||t>i.end.row||e<i.start.col||e>i.end.col)return"Cannot merge: selection overlaps with existing merged cells"}const s=t.getCell(e,n);if(s){const t=e+s.rowSpan-1,o=n+s.colSpan-1;if(t>i.end.row||o>i.end.col)return"Cannot merge: selection overlaps with existing merged cells"}}return null}static mergeCells(t,e){const i=this.normalizeRange(e),n=this.canMerge(t,i);if(n)return{success:!1,error:n};const o=i.end.row-i.start.row+1,s=i.end.col-i.start.col+1,r=t.getCell(i.start.row,i.start.col);if(!r)return{success:!1,error:"Could not find origin cell"};for(let e=i.start.row;e<=i.end.row;e++)for(let n=i.start.col;n<=i.end.col;n++){if(e===i.start.row&&n===i.start.col)continue;const o=t.getCell(e,n);o&&(o.content="",o.rowSpan=1,o.colSpan=1)}return r.rowSpan=o,r.colSpan=s,{success:!0,mergedCell:r}}static canSplit(t,e,i){const n=t.getCell(e,i);return n?1===n.rowSpan&&1===n.colSpan?"Cell is not merged":null:"Cell not found"}static splitCell(t,e,i){const n=this.canSplit(t,e,i);if(n)return{success:!1,error:n};const o=t.getCell(e,i);if(!o)return{success:!1,error:"Cell not found"};const s=o.rowSpan,r=o.colSpan;o.rowSpan=1,o.colSpan=1;const a=[o];for(let n=e;n<e+s&&n<t.rowCount;n++)for(let o=i;o<i+r&&o<t.columnCount;o++){if(n===e&&o===i)continue;const s=t.getCell(n,o);s&&(s.rowSpan=1,s.colSpan=1,a.push(s))}return{success:!0,newCells:a}}static getCellsInRange(t,e){const i=this.normalizeRange(e),n=[],o=new Set;for(let e=i.start.row;e<=i.end.row;e++)for(let s=i.start.col;s<=i.end.col;s++){const i=t.resolveCell(e,s);if(!i)continue;const r=`${i.rowIndex},${i.colIndex}`;o.has(r)||(o.add(r),n.push(i.cell))}return n}static rangesOverlap(t,e){const i=this.normalizeRange(t),n=this.normalizeRange(e);return!(i.end.row<n.start.row||i.start.row>n.end.row||i.end.col<n.start.col||i.start.col>n.end.col)}static getMergedCellRange(t,e,i){return{start:{row:e,col:i},end:{row:e+t.rowSpan-1,col:i+t.colSpan-1}}}}function G(){return`col_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}class U extends _{constructor(t){super(t),this._rows=[],this._columns=[],this._focusedCell=null,this._editing=!1,this._selectedRange=null,this._coveredCells=new Map,this._rowLoops=new Map,this._rowConditionals=new Map,this._layoutDirty=!0,this._cachedRowHeights=[],this._cachedRowPositions=[],this._renderedSlices=new Map,this._nextCondId=1,this._selectedRowLoopId=null,this._selectedRowConditionalId=null,this._position="block",this._defaultCellPadding=t.defaultCellPadding??B.cellPadding,this._defaultBorderColor=t.defaultBorderColor??B.borderColor,this._defaultBorderWidth=t.defaultBorderWidth??B.borderWidth,this._defaultFontFamily=t.defaultFontFamily??B.fontFamily,this._defaultFontSize=t.defaultFontSize??B.fontSize,this._defaultColor=t.defaultColor??B.color;const e=t.columns??2;if(t.columnConfig&&t.columnConfig.length>0)this._columns=t.columnConfig.map(t=>({id:t.id||G(),width:t.width,minWidth:t.minWidth??B.minColumnWidth}));else if(t.columnWidths&&t.columnWidths.length>0)this._columns=t.columnWidths.map(t=>({id:G(),width:t,minWidth:B.minColumnWidth}));else for(let t=0;t<e;t++)this._columns.push({id:G(),width:B.defaultColumnWidth,minWidth:B.minColumnWidth});const i=t.rows??2,n={fontFamily:this._defaultFontFamily,fontSize:this._defaultFontSize,color:this._defaultColor,padding:this._defaultCellPadding};if(t.rowData&&t.rowData.length>0)for(const e of t.rowData){const t=new N(e,this._columns.length,n);this.setupRowListeners(t),this._rows.push(t)}else for(let t=0;t<i;t++){const t=new N({},this._columns.length,n);this.setupRowListeners(t),this._rows.push(t)}this.updateSizeFromLayout()}get objectType(){return"table"}set position(t){"block"!==t&&j.warn(`[pc-editor:TableObject] Tables only support 'block' positioning. Ignoring attempt to set '${t}'.`),super.position="block"}get position(){return super.position}get rows(){return this._rows}get rowCount(){return this._rows.length}get columns(){return this._columns}get columnCount(){return this._columns.length}get headerRows(){return this._rows.filter(t=>t.isHeader)}get headerRowCount(){return this._rows.filter(t=>t.isHeader).length}setHeaderRow(t,e=!0){const i=this._rows[t];i&&(i.isHeader=e,this.emit("header-changed",{rowIndex:t,isHeader:e}))}setHeaderRowCount(t){for(let e=0;e<this._rows.length;e++)this._rows[e].isHeader=e<t;this.emit("headers-changed",{count:t})}getHeaderHeight(){let t=0;for(const e of this._rows)e.isHeader&&(t+=e.calculatedHeight);return t}getFirstDataRowHeight(){for(const t of this._rows)if(!t.isHeader)return t.calculatedHeight;return 0}getHeaderRowIndices(){const t=[];for(let e=0;e<this._rows.length;e++)this._rows[e].isHeader&&t.push(e);return t}get headerColumns(){return this._columns.filter(t=>t.isHeader)}get headerColumnCount(){return this._columns.filter(t=>t.isHeader).length}setHeaderColumn(t,e=!0){const i=this._columns[t];i&&(i.isHeader=e,this.emit("header-column-changed",{colIndex:t,isHeader:e}))}setHeaderColumnCount(t){for(let e=0;e<this._columns.length;e++)this._columns[e].isHeader=e<t;this.emit("header-columns-changed",{count:t})}getHeaderColumnIndices(){const t=[];for(let e=0;e<this._columns.length;e++)this._columns[e].isHeader&&t.push(e);return t}isHeaderCell(t,e){const i=this._rows[t],n=this._columns[e];return!0===i?.isHeader||!0===n?.isHeader}get defaultCellPadding(){return this._defaultCellPadding}set defaultCellPadding(t){this._defaultCellPadding=t,this.emit("style-changed",{defaultCellPadding:t})}get defaultBorderColor(){return this._defaultBorderColor}set defaultBorderColor(t){this._defaultBorderColor=t,this.emit("style-changed",{defaultBorderColor:t})}get defaultBorderWidth(){return this._defaultBorderWidth}set defaultBorderWidth(t){this._defaultBorderWidth=t,this.emit("style-changed",{defaultBorderWidth:t})}get defaultFontFamily(){return this._defaultFontFamily}set defaultFontFamily(t){this._defaultFontFamily=t,this.emit("style-changed",{defaultFontFamily:t})}get defaultFontSize(){return this._defaultFontSize}set defaultFontSize(t){this._defaultFontSize=t,this.emit("style-changed",{defaultFontSize:t})}get defaultColor(){return this._defaultColor}set defaultColor(t){this._defaultColor=t,this.emit("style-changed",{defaultColor:t})}set size(t){const e=this._columns.reduce((t,e)=>t+e.width,0),i=this._rows.reduce((t,e)=>t+(e.calculatedHeight||e.minHeight),0);if(e>0&&i>0&&this._columns.length>0&&this._rows.length>0){const n=t.width-e,o=this._columns.length-1,s=this._columns[o],r=Math.max(s.minWidth||20,s.width+n);s.width=r;const a=t.height-i,l=this._rows[this._rows.length-1],d=l.calculatedHeight||l.minHeight,h=Math.max(l.minHeight,d+a);l.height=h}this._size={...t},this.markLayoutDirty(),this.emit("size-changed",{size:{...t}})}get size(){return{...this._size}}getCell(t,e){const i=this._rows[t];return i?i.getCell(e):null}resolveCell(t,e){const i=`${t},${e}`,n=this._coveredCells.get(i);if(n){const t=this.getCell(n.row,n.col);return t?{cell:t,rowIndex:n.row,colIndex:n.col,isSpanned:!0}:null}const o=this.getCell(t,e);return o?{cell:o,rowIndex:t,colIndex:e,isSpanned:!1}:null}getCellAtPoint(t){let e=0,i=-1;for(let n=0;n<this._columns.length;n++){const o=this._columns[n].width;if(t.x>=e&&t.x<e+o){i=n;break}e+=o}if(-1===i)return null;let n=0,o=-1;for(let e=0;e<this._rows.length;e++){const i=this._rows[e].calculatedHeight;if(t.y>=n&&t.y<n+i){o=e;break}n+=i}return-1===o?null:{row:o,col:i}}setupRowListeners(t){t.on("cell-content-changed",t=>{this._layoutDirty=!0,this.emit("cell-content-changed",t),this.emit("content-changed",{})}),t.on("cell-style-changed",t=>{this.emit("cell-style-changed",t)}),t.on("cell-span-changed",t=>{this._layoutDirty=!0,this.updateCoveredCells(),this.emit("cell-span-changed",t)}),t.on("cell-editing-changed",t=>{this.emit("cell-editing-changed",t)}),t.on("height-changed",()=>{this._layoutDirty=!0,this.updateSizeFromLayout(),this.emit("layout-changed",{})})}setColumnWidth(t,e){if(t<0||t>=this._columns.length)return;const i=this._columns[t].minWidth??B.minColumnWidth;this._columns[t].width=Math.max(e,i),this._layoutDirty=!0;for(const e of this._rows){const i=e.getCell(t);i&&i.markReflowDirty()}this.updateSizeFromLayout(),this.emit("column-width-changed",{colIndex:t,width:this._columns[t].width})}getColumnPositions(){const t=[];let e=0;for(const i of this._columns)t.push(e),e+=i.width;return t}getColumnWidths(){return this._columns.map(t=>t.width)}insertColumn(t,e){const i=e??B.defaultColumnWidth,n={id:G(),width:i,minWidth:B.minColumnWidth};t<0&&(t=0),t>this._columns.length&&(t=this._columns.length);for(let e=0;e<this._rows.length;e++){const i=this._rows[e];for(let e=0;e<t;e++){const n=i.getCell(e);n&&n.colSpan>1&&e+n.colSpan>t&&n.colSpan++}}this._columns.splice(t,0,n);const o={fontFamily:this._defaultFontFamily,fontSize:this._defaultFontSize,color:this._defaultColor,padding:this._defaultCellPadding};for(const e of this._rows)e.insertCell(t,o);this._layoutDirty=!0,this.updateCoveredCells(),this.updateSizeFromLayout(),this.emit("column-inserted",{colIndex:t})}removeColumn(t){if(!(t<0||t>=this._columns.length||this._columns.length<=1)){this._columns.splice(t,1);for(const e of this._rows)e.removeCell(t);if(this._selectedRange){const{start:e,end:i}=this._selectedRange;(e.col>=this._columns.length||i.col>=this._columns.length||t>=e.col&&t<=i.col)&&(this._selectedRange=null)}this._focusedCell&&this._focusedCell.col>=this._columns.length&&(this._focusedCell=null),this._layoutDirty=!0,this.updateCoveredCells(),this.updateSizeFromLayout(),this.emit("column-removed",{colIndex:t})}}insertRow(t,e){const i={fontFamily:this._defaultFontFamily,fontSize:this._defaultFontSize,color:this._defaultColor,padding:this._defaultCellPadding},n=new N(e||{},this._columns.length,i);this.setupRowListeners(n),t<0&&(t=0),t>this._rows.length&&(t=this._rows.length);for(let e=0;e<t;e++){const i=this._rows[e];for(let n=0;n<i.cellCount;n++){const o=i.getCell(n);o&&o.rowSpan>1&&e+o.rowSpan>t&&o.rowSpan++}}return this._rows.splice(t,0,n),this.shiftRowLoopIndices(t,1),this._layoutDirty=!0,this.updateCoveredCells(),this.updateSizeFromLayout(),this.emit("row-inserted",{rowIndex:t,rowId:n.id}),n}removeRow(t){if(t<0||t>=this._rows.length)return null;if(this._rows.length<=1)return null;const[e]=this._rows.splice(t,1);if(this.shiftRowLoopIndices(t,-1),this._selectedRange){const{start:e,end:i}=this._selectedRange;(e.row>=this._rows.length||i.row>=this._rows.length||t>=e.row&&t<=i.row)&&(this._selectedRange=null)}return this._focusedCell&&this._focusedCell.row>=this._rows.length&&(this._focusedCell=null),this._layoutDirty=!0,this.updateCoveredCells(),this.updateSizeFromLayout(),this.emit("row-removed",{rowIndex:t,rowId:e.id}),e}generateRowLoopId(){return`rowloop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}createRowLoop(t,e,i){if(t<0||e>=this._rows.length)return j.warn("[pc-editor:TableObject.createRowLoop] Invalid row range"),null;if(t>e)return j.warn("[pc-editor:TableObject.createRowLoop] Start index must be <= end index"),null;for(const i of this._rowLoops.values())if(this.loopRangesOverlap(t,e,i.startRowIndex,i.endRowIndex))return j.warn("[pc-editor:TableObject.createRowLoop] Loop range overlaps with existing loop"),null;for(let i=t;i<=e;i++)if(this._rows[i]?.isHeader)return j.warn("[pc-editor:TableObject.createRowLoop] Loop rows cannot be header rows"),null;const n={id:this.generateRowLoopId(),fieldPath:i,startRowIndex:t,endRowIndex:e};return this._rowLoops.set(n.id,n),this.emit("row-loop-created",{loop:n}),this.emit("content-changed",{}),n}removeRowLoop(t){return!!this._rowLoops.get(t)&&(this._rowLoops.delete(t),this.emit("row-loop-removed",{loopId:t}),this.emit("content-changed",{}),!0)}getRowLoop(t){return this._rowLoops.get(t)}getAllRowLoops(){return Array.from(this._rowLoops.values())}getRowLoopAtRow(t){for(const e of this._rowLoops.values())if(t>=e.startRowIndex&&t<=e.endRowIndex)return e}updateRowLoopFieldPath(t,e){const i=this._rowLoops.get(t);return!!i&&(i.fieldPath=e,this.emit("row-loop-updated",{loop:i}),this.emit("content-changed",{}),!0)}loopRangesOverlap(t,e,i,n){return t<=n&&i<=e}generateRowConditionalId(){return"row-cond-"+this._nextCondId++}createRowConditional(t,e,i){if(t<0||e>=this._rows.length)return j.warn("[pc-editor:TableObject.createRowConditional] Invalid row range"),null;if(t>e)return j.warn("[pc-editor:TableObject.createRowConditional] Start index must be <= end index"),null;for(const i of this._rowConditionals.values())if(this.loopRangesOverlap(t,e,i.startRowIndex,i.endRowIndex))return j.warn("[pc-editor:TableObject.createRowConditional] Range overlaps with existing conditional"),null;const n={id:this.generateRowConditionalId(),predicate:i,startRowIndex:t,endRowIndex:e};return this._rowConditionals.set(n.id,n),this.emit("row-conditional-created",{conditional:n}),this.emit("content-changed",{}),n}removeRowConditional(t){return!!this._rowConditionals.get(t)&&(this._rowConditionals.delete(t),this.emit("row-conditional-removed",{conditionalId:t}),!0)}getRowConditional(t){return this._rowConditionals.get(t)}getAllRowConditionals(){return Array.from(this._rowConditionals.values())}getRowConditionalAtRow(t){for(const e of this._rowConditionals.values())if(t>=e.startRowIndex&&t<=e.endRowIndex)return e}updateRowConditionalPredicate(t,e){const i=this._rowConditionals.get(t);return!!i&&(i.predicate=e,this.emit("row-conditional-updated",{conditional:i}),this.emit("content-changed",{}),!0)}shiftRowLoopIndices(t,e){const i=[];for(const n of this._rowLoops.values())if(e<0){const o=t+Math.abs(e)-1;if(t<=n.endRowIndex&&o>=n.startRowIndex){i.push(n.id);continue}t<n.startRowIndex&&(n.startRowIndex+=e,n.endRowIndex+=e)}else t<=n.startRowIndex?(n.startRowIndex+=e,n.endRowIndex+=e):t<=n.endRowIndex&&(n.endRowIndex+=e);for(const t of i)this._rowLoops.delete(t),this.emit("row-loop-removed",{loopId:t,reason:"row-deleted"});this.shiftRowConditionalIndices(t,e)}shiftRowConditionalIndices(t,e){const i=[];for(const n of this._rowConditionals.values())if(e<0){const o=t+Math.abs(e)-1;if(t<=n.endRowIndex&&o>=n.startRowIndex){i.push(n.id);continue}t<n.startRowIndex&&(n.startRowIndex+=e,n.endRowIndex+=e)}else t<=n.startRowIndex?(n.startRowIndex+=e,n.endRowIndex+=e):t<=n.endRowIndex&&(n.endRowIndex+=e);for(const t of i)this._rowConditionals.delete(t),this.emit("row-conditional-removed",{conditionalId:t,reason:"row-deleted"})}getRowsInRange(t,e){const i=[];for(let n=t;n<=e&&n<this._rows.length;n++)i.push(this._rows[n]);return i}removeRowsInRange(t,e){const i=e-t+1,n=this._rows.splice(t,i);if(this._selectedRange){const{start:i,end:n}=this._selectedRange;(i.row>=this._rows.length||n.row>=this._rows.length||i.row<=e&&n.row>=t)&&(this._selectedRange=null)}return this._focusedCell&&this._focusedCell.row>=this._rows.length&&(this._focusedCell=null),this._layoutDirty=!0,this.updateCoveredCells(),n}insertRowsAt(t,e){for(const t of e)this.setupRowListeners(t);this._rows.splice(t,0,...e),this._layoutDirty=!0,this.updateCoveredCells(),this.updateSizeFromLayout()}calculateLayout(t,e=!1){if(!e&&!this._layoutDirty&&this._cachedRowHeights.length===this._rows.length)return;const i=this.getColumnWidths(),n=this.getColumnPositions(),o=[];let s=0;for(const e of this._rows){const n=e.calculateHeight(t,i);o.push(n),s+=n}const r=[];let a=0;for(const t of o)r.push(a),a+=t;this._cachedRowHeights=o,this._cachedRowPositions=r,this._layoutDirty=!1;for(let t=0;t<this._rows.length;t++){const e=this._rows[t];for(let s=0;s<e.cellCount;s++){const a=e.getCell(s);if(!a)continue;let l=0;const d=a.colSpan;for(let t=s;t<s+d&&t<this._columns.length;t++)l+=i[t];let h=0;const c=a.rowSpan;for(let e=t;e<t+c&&e<this._rows.length;e++)h+=o[e];a.setBounds({x:n[s],y:r[t],width:l,height:h})}}const l=i.reduce((t,e)=>t+e,0);this._size={width:l,height:s}}markLayoutDirty(){this._layoutDirty=!0}get layoutDirty(){return this._layoutDirty}get cachedRowHeights(){return this._cachedRowHeights}get cachedRowPositions(){return this._cachedRowPositions}updateSizeFromLayout(){const t=this._columns.reduce((t,e)=>t+e.width,0);let e=0;for(const t of this._rows)e+=t.calculatedHeight||t.minHeight;this._size={width:t,height:e}}updateCoveredCells(){this._coveredCells.clear();for(let t=0;t<this._rows.length;t++){const e=this._rows[t];for(let i=0;i<e.cellCount;i++){const n=e.getCell(i);if(!n)continue;const o=n.rowSpan,s=n.colSpan;if(o>1||s>1)for(let e=t;e<t+o&&e<this._rows.length;e++)for(let n=i;n<i+s&&n<this._columns.length;n++)e===t&&n===i||this._coveredCells.set(`${e},${n}`,{row:t,col:i})}}}updateCellRenderedPositions(){if(!this._renderedPosition)return;const t=this.getColumnPositions();let e=0;for(const i of this._rows){for(let n=0;n<i.cellCount;n++){const o=i.getCell(n);o&&o.setRenderedPosition({x:this._renderedPosition.x+t[n],y:this._renderedPosition.y+e})}e+=i.calculatedHeight}}calculatePageLayout(t,e){const i=this.getHeaderHeight(),n=this.getHeaderRowIndices(),o=this._size.height;if(o<=t)return{slices:[{startRow:0,endRow:this._rows.length,isContinuation:!1,height:o,yOffset:0}],totalHeight:o,headerHeight:i,headerRowIndices:n};let s=0;for(;s<this._rows.length&&this._rows[s].isHeader;)s++;const r=i+(s<this._rows.length?this._rows[s].calculatedHeight:0)<=t?t:e,a=[];let l=0,d=0,h=!0;for(;l<this._rows.length;){const t=h?r:e,n=!h;let o=n?i:0,c=l;const g=d;for(n&&l<s&&(l=s,c=l);c<this._rows.length;){const e=this._rows[c];if(n&&e.isHeader){c++;continue}const i=e.calculatedHeight;if(o+i>t)break;o+=i,d+=i,c++}if(c=this.adjustSliceEndForMergedCells(l,c),c<this._rows.length){o=n?i:0,d=g;for(let t=l;t<c;t++)n&&this._rows[t].isHeader||(o+=this._rows[t].calculatedHeight,d+=this._rows[t].calculatedHeight)}if(c===l&&l<this._rows.length){for(;c<this._rows.length&&this._rows[c].isHeader;)c++;c<this._rows.length&&(o+=this._rows[c].calculatedHeight,d+=this._rows[c].calculatedHeight,c++)}((h?c>s:c>l)||c===this._rows.length)&&(a.push({startRow:l,endRow:c,isContinuation:n,height:o,yOffset:g}),h=!1),l=c}return{slices:a,totalHeight:o,headerHeight:i,headerRowIndices:n}}adjustSliceEndForMergedCells(t,e){for(let i=t;i<e;i++){const n=this._rows[i];for(let o=0;o<n.cellCount;o++){const s=n.getCell(o);if(s&&s.rowSpan>1){const n=i+s.rowSpan;if(n>e&&n<=this._rows.length&&i>t)return i}}}return e}renderSlice(t,e,i){const n=this.getColumnPositions(),o=this.getColumnWidths();let s=0;if(e.isContinuation&&i.headerRowIndices.length>0)for(const e of i.headerRowIndices){const i=this._rows[e];if(i){for(let r=0;r<i.cellCount;r++){const a=`${e},${r}`;if(this._coveredCells.has(a))continue;const l=i.getCell(r);if(!l)continue;let d=0;for(let t=r;t<r+l.colSpan&&t<this._columns.length;t++)d+=o[t];t.save(),t.translate(n[r],s);const h=l.getBounds();l.setBounds({x:n[r],y:s,width:d,height:i.calculatedHeight}),l.render(t),h&&l.setBounds(h),t.restore()}s+=i.calculatedHeight}}for(let i=e.startRow;i<e.endRow;i++){const r=this._rows[i];if(r&&(!e.isContinuation||!r.isHeader)){for(let e=0;e<r.cellCount;e++){const a=`${i},${e}`;if(this._coveredCells.has(a))continue;const l=r.getCell(e);if(!l)continue;let d=0;for(let t=e;t<e+l.colSpan&&t<this._columns.length;t++)d+=o[t];let h=0;for(let t=i;t<i+l.rowSpan&&t<this._rows.length;t++)h+=this._rows[t].calculatedHeight;t.save(),t.translate(n[e],s);const c=l.getBounds();l.setBounds({x:n[e],y:s,width:d,height:h}),l.render(t),c&&l.setBounds(c),t.restore()}s+=r.calculatedHeight}}this._selectedRange&&this.renderRangeSelectionForSlice(t,e,i)}renderRangeSelectionForSlice(t,e,i){if(!this._selectedRange)return;const{start:n,end:o}=this._selectedRange,s=this.getColumnPositions(),r=this.getColumnWidths(),a=s[n.col],l=s[o.col]+r[o.col],d=new Map;let h=0;if(e.isContinuation&&i.headerRowIndices.length>0)for(const t of i.headerRowIndices){const e=this._rows[t];e&&(d.set(t,h),h+=e.calculatedHeight)}for(let t=e.startRow;t<e.endRow;t++){const i=this._rows[t];i&&(e.isContinuation&&i.isHeader||(d.set(t,h),h+=i.calculatedHeight))}let c=null,g=null;for(let t=n.row;t<=o.row;t++){const e=d.get(t);if(void 0!==e){const i=this._rows[t];i&&(null===c&&(c=e),g=e+i.calculatedHeight)}}null!==c&&null!==g&&(t.fillStyle="rgba(0, 120, 215, 0.2)",t.fillRect(a,c,l-a,g-c),t.strokeStyle="rgba(0, 120, 215, 0.8)",t.lineWidth=2,t.setLineDash([]),t.strokeRect(a+1,c+1,l-a-2,g-c-2))}getRowsForSlice(t,e){const i=[];if(t.isContinuation)for(const t of e.headerRowIndices)this._rows[t]&&i.push(this._rows[t]);for(let e=t.startRow;e<t.endRow;e++){const n=this._rows[e];!n||t.isContinuation&&n.isHeader||i.push(n)}return i}needsPageSplit(t){return this._size.height>t}setRenderedSlice(t,e,i,n,o=0,s=0,r=0){this._renderedSlices.set(t,{position:e,height:i,slicePosition:n,sliceIndex:o,yOffset:s,headerHeight:r})}getRenderedSlice(t){return this._renderedSlices.get(t)}clearRenderedSlices(){this._renderedSlices.clear()}getRenderedPageIndices(){return Array.from(this._renderedSlices.keys())}get editing(){return this._editing}set editing(t){if(this._editing!==t){if(this._editing=t,!t&&this._focusedCell){const t=this.getCell(this._focusedCell.row,this._focusedCell.col);t&&t.blur(),this._focusedCell=null}this.emit("editing-changed",{editing:t})}}get focusedCell(){return this._focusedCell}focusCell(t,e){if(this._focusedCell){const t=this.getCell(this._focusedCell.row,this._focusedCell.col);t&&(t.flowingContent.clearSelection(),t.blur())}const i=this.resolveCell(t,e);i&&(this._focusedCell={row:i.rowIndex,col:i.colIndex},i.cell.focus(),this._editing=!0,this.emit("cell-focused",{rowIndex:i.rowIndex,colIndex:i.colIndex,cellId:i.cell.id}))}moveFocus(t){if(!this._focusedCell)return this._rows.length>0&&this._columns.length>0&&(this.focusCell(0,0),!0);let{row:e,col:i}=this._focusedCell;switch(t){case"next":case"right":if(i++,i>=this._columns.length&&(i=0,e++,e>=this._rows.length))return!1;break;case"previous":case"left":if(i--,i<0&&(i=this._columns.length-1,e--,e<0))return!1;break;case"up":if(e--,e<0)return!1;break;case"down":if(e++,e>=this._rows.length)return!1}return this.focusCell(e,i),!0}focus(){this._editing=!0,!this._focusedCell&&this._rows.length>0&&this._columns.length>0&&this.focusCell(0,0),this.emit("focus",{})}blur(){this.editing=!1,this.clearSelection(),this.emit("blur",{})}hasFocus(){return this._editing}handleKeyDown(t){if(j.log("[pc-editor:TableObject.handleKeyDown] Key:",t.key,"_editing:",this._editing,"_focusedCell:",this._focusedCell),!this._editing)return!1;if("Tab"===t.key)return t.preventDefault(),this.moveFocus(t.shiftKey?"previous":"next"),!0;if("Escape"===t.key)return t.preventDefault(),this.blur(),!0;if(this._focusedCell){const e=this.getCell(this._focusedCell.row,this._focusedCell.col);if(e){const i=e.flowingContent,n=i.getCursorPosition(),o=i.getText().length;return"ArrowLeft"===t.key&&0===n&&!t.shiftKey&&this.moveFocus("left")||"ArrowRight"===t.key&&n>=o&&!t.shiftKey&&this.moveFocus("right")?(t.preventDefault(),!0):e.handleKeyDown(t)}}return!1}onCursorBlink(t){for(const e of this._rows)for(const i of e.cells)i.onCursorBlink(t)}offCursorBlink(t){for(const e of this._rows)for(const i of e.cells)i.offCursorBlink(t)}handleDoubleClick(t){if(this._locked)return;const e=this.getCellAtPoint(t);e&&this.focusCell(e.row,e.col)}get selectedRange(){return this._selectedRange}selectRange(t){this._selectedRange=W.normalizeRange(t),this.emit("selection-changed",{range:this._selectedRange})}clearSelection(){this._selectedRange=null,this.emit("selection-changed",{range:null})}mergeCells(t){const e=t||this._selectedRange;if(!e)return{success:!1,error:"No range specified for merge"};const i=W.mergeCells(this,e);if(i.success){this.updateCoveredCells(),this.markLayoutDirty(),i.mergedCell&&i.mergedCell.markReflowDirty(),this.clearSelection();const t=W.normalizeRange(e);this.focusCell(t.start.row,t.start.col),this.emit("cells-merged",{range:e}),this.emit("content-changed",{})}return i}splitCell(t,e){const i=W.splitCell(this,t,e);if(i.success){if(this.updateCoveredCells(),this.markLayoutDirty(),i.newCells)for(const t of i.newCells)t.markReflowDirty();this.emit("cell-split",{row:t,col:e}),this.emit("content-changed",{})}return i}canMergeRange(t){const e=t||this._selectedRange;if(!e)return{canMerge:!1,error:"No range specified"};const i=W.canMerge(this,e);return{canMerge:null===i,error:i||void 0}}canSplitCell(t,e){const i=W.canSplit(this,t,e);return{canSplit:null===i,error:i||void 0}}render(t,e){let i=0,n=this._rows.length;e&&this._cachedRowPositions.length>0&&(i=this.findFirstVisibleRow(e.y),n=this.findLastVisibleRow(e.y+e.height)+1);for(let e=i;e<n&&e<this._rows.length;e++){const i=this._rows[e];for(let n=0;n<i.cellCount;n++){const o=`${e},${n}`;if(this._coveredCells.has(o))continue;const s=i.getCell(n);if(!s)continue;const r=s.getBounds();r&&(t.save(),t.translate(r.x,r.y),s.render(t),t.restore())}}this._rowLoops.size>0&&this.renderRowLoopIndicators(t),this._rowConditionals.size>0&&this.renderRowConditionalIndicators(t),this._selectedRange&&this.renderRangeSelection(t),this._selected&&this.renderSelectionBorder(t),this._editing&&this.renderEditingIndicator(t)}selectRowLoop(t){this._selectedRowLoopId=t}get selectedRowLoopId(){return this._selectedRowLoopId}getRowLoopAtPoint(t){let e=this._cachedRowPositions;if(0===e.length){e=[];let t=0;for(const i of this._rows)e.push(t),t+=i.calculatedHeight}for(const i of this._rowLoops.values()){const n=e[i.startRowIndex]||0;let o=n;for(let t=i.startRowIndex;t<=i.endRowIndex&&t<this._rows.length;t++)o+=this._rows[t].calculatedHeight;const s=30,r=10+2*U.LOOP_LABEL_PADDING,a=-6-s-4,l=n-r-2;if(t.x>=a&&t.x<=a+s+4&&t.y>=l&&t.y<=l+r+4)return i}return null}renderRowLoopIndicators(t){const e=U.LOOP_COLOR,i=U.LOOP_LABEL_PADDING,n=U.LOOP_LABEL_RADIUS;let o=this._cachedRowPositions;if(0===o.length){o=[];let t=0;for(const e of this._rows)o.push(t),t+=e.calculatedHeight}for(const s of this._rowLoops.values()){const r=this._selectedRowLoopId===s.id,a=o[s.startRowIndex]||0;let l=a;for(let t=s.startRowIndex;t<=s.endRowIndex&&t<this._rows.length;t++)l+=this._rows[t].calculatedHeight;const d=l-a;t.fillStyle=e,t.fillRect(-6,a,4,d),t.strokeStyle=e,t.lineWidth=1,t.beginPath(),t.moveTo(-4,a),t.lineTo(-4,l),t.stroke(),t.save(),t.font="10px Arial";const h="Loop",c=t.measureText(h).width+2*i,g=10+2*i,u=-6-c-4,f=a-g-2;t.beginPath(),t.roundRect(u,f,c,g,n),r?(t.fillStyle=e,t.fill(),t.fillStyle="#ffffff"):(t.fillStyle="#ffffff",t.fill(),t.strokeStyle=e,t.lineWidth=1.5,t.stroke(),t.fillStyle=e),t.textBaseline="middle",t.fillText(h,u+i,f+g/2),t.restore()}}selectRowConditional(t){this._selectedRowConditionalId=t}get selectedRowConditionalId(){return this._selectedRowConditionalId}getRowConditionalAtPoint(t){let e=this._cachedRowPositions;if(0===e.length){e=[];let t=0;for(const i of this._rows)e.push(t),t+=i.calculatedHeight}for(const i of this._rowConditionals.values()){const n=e[i.startRowIndex]||0;let o=n;for(let t=i.startRowIndex;t<=i.endRowIndex&&t<this._rows.length;t++)o+=this._rows[t].calculatedHeight;const s=this._columns.reduce((t,e)=>t+e.width,0),r=22,a=10+2*U.LOOP_LABEL_PADDING,l=s+10,d=n-a-2;if(t.x>=l&&t.x<=l+r+4&&t.y>=d&&t.y<=d+a+4)return i}return null}renderRowConditionalIndicators(t){const e=U.COND_COLOR,i=U.LOOP_LABEL_PADDING,n=U.LOOP_LABEL_RADIUS;let o=this._cachedRowPositions;if(0===o.length){o=[];let t=0;for(const e of this._rows)o.push(t),t+=e.calculatedHeight}const s=this._columns.reduce((t,e)=>t+e.width,0);for(const r of this._rowConditionals.values()){const a=this._selectedRowConditionalId===r.id,l=o[r.startRowIndex]||0;let d=l;for(let t=r.startRowIndex;t<=r.endRowIndex&&t<this._rows.length;t++)d+=this._rows[t].calculatedHeight;const h=d-l;t.fillStyle=e,t.fillRect(s+2,l,4,h),t.strokeStyle=e,t.lineWidth=1,t.beginPath(),t.moveTo(s+4,l),t.lineTo(s+4,d),t.stroke(),t.save(),t.font="10px Arial";const c="If",g=t.measureText(c).width+2*i,u=10+2*i,f=s+10,p=l-u-2;t.beginPath(),t.roundRect(f,p,g,u,n),a?(t.fillStyle=e,t.fill(),t.fillStyle="#ffffff"):(t.fillStyle="#ffffff",t.fill(),t.strokeStyle=e,t.lineWidth=1.5,t.stroke(),t.fillStyle=e),t.textBaseline="middle",t.fillText(c,f+i,p+u/2),t.restore()}}findFirstVisibleRow(t){const e=this._cachedRowPositions,i=this._cachedRowHeights;if(0===e.length)return 0;let n=0,o=e.length-1;for(;n<o;){const s=Math.floor((n+o)/2);e[s]+(i[s]||0)<=t?n=s+1:o=s}return n}findLastVisibleRow(t){const e=this._cachedRowPositions;if(0===e.length)return 0;let i=0,n=e.length-1;for(;i<n;){const o=Math.ceil((i+n)/2);e[o]>t?n=o-1:i=o}return i}getVisibleRowRange(t,e){if(0===this._cachedRowPositions.length)return{startRow:0,endRow:this._rows.length};return{startRow:this.findFirstVisibleRow(t),endRow:Math.min(this.findLastVisibleRow(t+e)+1,this._rows.length)}}renderRangeSelection(t){if(!this._selectedRange)return;const{start:e,end:i}=this._selectedRange,n=this.getColumnPositions(),o=this.getColumnWidths(),s=[];let r=0;for(const t of this._rows)s.push(r),r+=t.calculatedHeight;const a=n[e.col],l=n[i.col]+o[i.col],d=s[e.row],h=s[i.row]+this._rows[i.row].calculatedHeight;t.fillStyle="rgba(0, 120, 215, 0.2)",t.fillRect(a,d,l-a,h-d),t.strokeStyle="rgba(0, 120, 215, 0.8)",t.lineWidth=2,t.setLineDash([]),t.strokeRect(a+1,d+1,l-a-2,h-d-2)}renderEditingIndicator(t){const{width:e,height:i}=this._size;t.strokeStyle="#0099ff",t.lineWidth=2,t.setLineDash([]),t.strokeRect(1,1,e-2,i-2)}toData(){const t=this._rowLoops.size>0?Array.from(this._rowLoops.values()).map(t=>({id:t.id,fieldPath:t.fieldPath,startRowIndex:t.startRowIndex,endRowIndex:t.endRowIndex})):void 0;return{id:this._id,objectType:"table",textIndex:this._textIndex,position:this._position,size:{...this._size},data:{columns:this._columns.map(t=>({...t})),rows:this._rows.map(t=>t.toData()),rowLoops:t,rowConditionals:this._rowConditionals.size>0?Array.from(this._rowConditionals.values()).map(t=>({id:t.id,predicate:t.predicate,startRowIndex:t.startRowIndex,endRowIndex:t.endRowIndex})):void 0,defaultCellPadding:this._defaultCellPadding,defaultBorderColor:this._defaultBorderColor,defaultBorderWidth:this._defaultBorderWidth,defaultFontFamily:this._defaultFontFamily,defaultFontSize:this._defaultFontSize,defaultColor:this._defaultColor}}}static fromData(t){const e={id:t.id,textIndex:t.textIndex,position:t.position,size:t.size,columnConfig:t.data.columns,defaultCellPadding:t.data.defaultCellPadding,defaultBorderColor:t.data.defaultBorderColor,defaultBorderWidth:t.data.defaultBorderWidth,defaultFontFamily:t.data.defaultFontFamily,defaultFontSize:t.data.defaultFontSize,defaultColor:t.data.defaultColor},i=new U(e);i._rows=[];for(const e of t.data.rows){const t=N.fromData(e);i.setupRowListeners(t),i._rows.push(t)}if(t.data.rowLoops)for(const e of t.data.rowLoops)i._rowLoops.set(e.id,{id:e.id,fieldPath:e.fieldPath,startRowIndex:e.startRowIndex,endRowIndex:e.endRowIndex});if(t.data.rowConditionals)for(const e of t.data.rowConditionals)i._rowConditionals.set(e.id,{id:e.id,predicate:e.predicate,startRowIndex:e.startRowIndex,endRowIndex:e.endRowIndex});return i.updateCoveredCells(),i}restoreFromSnapshot(t){this._columns=t.data.columns.map(t=>({...t})),this._rows=[];for(const e of t.data.rows){const t=N.fromData(e);this.setupRowListeners(t),this._rows.push(t)}if(this._rowLoops.clear(),t.data.rowLoops)for(const e of t.data.rowLoops)this._rowLoops.set(e.id,{id:e.id,fieldPath:e.fieldPath,startRowIndex:e.startRowIndex,endRowIndex:e.endRowIndex});if(this._rowConditionals.clear(),t.data.rowConditionals)for(const e of t.data.rowConditionals)this._rowConditionals.set(e.id,{id:e.id,predicate:e.predicate,startRowIndex:e.startRowIndex,endRowIndex:e.endRowIndex});void 0!==t.data.defaultCellPadding&&(this._defaultCellPadding=t.data.defaultCellPadding),void 0!==t.data.defaultBorderColor&&(this._defaultBorderColor=t.data.defaultBorderColor),void 0!==t.data.defaultBorderWidth&&(this._defaultBorderWidth=t.data.defaultBorderWidth),this._layoutDirty=!0,this.updateCoveredCells(),this.updateSizeFromLayout(),this.emit("structure-restored",{})}clone(){return U.fromData(this.toData())}}U.LOOP_COLOR="#6B46C1",U.LOOP_LABEL_PADDING=4,U.LOOP_LABEL_RADIUS=4,U.COND_COLOR="#D97706";class ${constructor(){this._resizeState=null}get resizeState(){return this._resizeState}get isResizing(){return null!==this._resizeState}detectResizeHandle(t,e,i,n){const o=e.x-i.x,s=e.y-i.y,r=void 0!==n?n:t.size.height;if(o<0||s<0||o>t.size.width||s>r)return null;const a=t.getColumnPositions(),l=t.getColumnWidths();for(let t=0;t<a.length;t++){const e=a[t]+l[t];if(Math.abs(o-e)<=4)return{type:"column",index:t,position:e}}let d=0;const h=t.rows;for(let t=0;t<h.length;t++)if(d+=h[t].calculatedHeight,Math.abs(s-d)<=4)return{type:"row",index:t,position:d};return null}startResize(t,e,i){if(!e.type)return;let n,o;if("column"===e.type)n=t.columns[e.index].width,e.index<t.columns.length-1&&(o=t.columns[e.index+1].width);else{if(n=t.rows[e.index].calculatedHeight,e.index<t.rows.length-1){const i=t.rows[e.index+1];o=i.calculatedHeight||i.minHeight}}this._resizeState={table:t,handleType:e.type,index:e.index,startPosition:e.position,startSize:n,nextStartSize:o,tablePosition:i}}updateResize(t){if(!this._resizeState)return!1;const{table:e,handleType:i,index:n,startPosition:o,startSize:s,nextStartSize:r,tablePosition:a}=this._resizeState;if("column"===i){const i=n===e.columns.length-1,l=t.x-a.x-o;if(i){const t=Math.max(s+l,e.columns[n].minWidth||20);e.setColumnWidth(n,t)}else if(void 0!==r){const t=e.columns[n+1],i=e.columns[n].minWidth||20,o=r-(t.minWidth||20),a=-(s-i),d=Math.max(a,Math.min(o,l)),h=s+d,c=r-d;e.setColumnWidth(n,h),e.setColumnWidth(n+1,c)}return!0}if("row"===i){const i=n===e.rows.length-1,l=t.y-a.y-o,d=e.rows[n];if(i){const t=Math.max(s+l,d.minHeight);d.height=t}else if(void 0!==r){const t=e.rows[n+1],i=r-t.minHeight,o=-(s-d.minHeight),a=Math.max(o,Math.min(i,l)),h=s+a,c=r-a;d.height=h,t.height=c}return!0}return!1}endResize(){this._resizeState=null}cancelResize(){if(!this._resizeState)return;const{table:t,handleType:e,index:i,startSize:n,nextStartSize:o}=this._resizeState;"column"===e?(t.setColumnWidth(i,n),void 0!==o&&i<t.columns.length-1&&t.setColumnWidth(i+1,o)):"row"===e&&(t.rows[i].height=n,void 0!==o&&i<t.rows.length-1&&(t.rows[i+1].height=o)),this._resizeState=null}static getCursorForHandle(t){switch(t){case"column":return"col-resize";case"row":return"row-resize";default:return"default"}}}class V{static register(t,e){this.registry.set(t,e)}static unregister(t){return this.registry.delete(t)}static isRegistered(t){return this.ensureInitialized(),this.registry.has(t)}static getRegisteredTypes(){return this.ensureInitialized(),Array.from(this.registry.keys())}static create(t){this.ensureInitialized();const e=this.registry.get(t.objectType);if(!e)throw new Error(`Unknown object type: ${t.objectType}. Registered types: ${this.getRegisteredTypes().join(", ")}`);return e(t)}static tryCreate(t){try{return this.create(t)}catch{return null}}static initialize(){this.initialized||(this.register("image",t=>new T({id:t.id,textIndex:t.textIndex,position:t.position,size:t.size,relativeOffset:t.relativeOffset,src:t.data.src,fit:t.data.fit,resizeMode:t.data.resizeMode,alt:t.data.alt})),this.register("textbox",t=>{const e=new L({id:t.id,textIndex:t.textIndex,position:t.position,size:t.size,relativeOffset:t.relativeOffset,content:t.data.content,fontFamily:t.data.fontFamily,fontSize:t.data.fontSize,color:t.data.color,backgroundColor:t.data.backgroundColor,borderColor:t.data.borderColor,border:t.data.border,padding:t.data.padding});if(t.data.formattingRuns&&Array.isArray(t.data.formattingRuns)){const i=t.data.formattingRuns;if(i.length>0){const t=e.flowingContent.getFormattingManager(),n=e.flowingContent.getText().length;for(let e=0;e<i.length;e++){const[o,s]=i[e],r=e+1<i.length?i[e+1][0]:n;o<r&&t.applyFormatting(o,r,s)}}}if(t.data.substitutionFields&&Array.isArray(t.data.substitutionFields)){const i=e.flowingContent.getSubstitutionFieldManager();for(const e of t.data.substitutionFields)void 0!==e.textIndex&&e.fieldName&&i.insert(e.fieldName,e.textIndex,{defaultValue:e.defaultValue,displayFormat:e.displayFormat})}return e}),this.register("table",t=>U.fromData(t)),this.initialized=!0)}static ensureInitialized(){this.initialized||this.initialize()}static reset(){this.registry.clear(),this.initialized=!1}}V.registry=new Map,V.initialized=!1;class X extends r{constructor(t){super(),this._hasFocus=!1,this._cursorBlinkTimer=null,this._cursorVisible=!0,this._cursorBlinkHandlers=new Set,this.textState=new u(t),this.formatting=new f,this.paragraphFormatting=new b,this.substitutionFields=new x,this.embeddedObjects=new y,this.repeatingSections=new w,this.conditionalSections=new C,this.hyperlinks=new S,this.layout=new v,this.setupEventForwarding(),this.setupFieldCheckCallback()}setupFieldCheckCallback(){this.textState.setFieldCheckCallback(t=>this.substitutionFields.hasFieldAt(t))}setupEventForwarding(){this.textState.on("text-changed",t=>{this.emit("content-changed",{text:t.text,cursorPosition:t.cursorPosition})}),this.textState.on("text-inserted",t=>{this.emit("content-changed",{text:this.textState.getText(),cursorPosition:t.newCursorPosition})}),this.textState.on("text-deleted",t=>{this.formatting.handleDeletion(t.start,t.length),this.substitutionFields.handleDeletion(t.start,t.length),this.embeddedObjects.handleDeletion(t.start,t.length),this.repeatingSections.handleDeletion(t.start,t.length),this.conditionalSections.handleDeletion(t.start,t.length),this.paragraphFormatting.handleDeletion(t.start,t.length),this.hyperlinks.handleDeletion(t.start,t.length),this.emit("content-changed",{text:this.textState.getText(),cursorPosition:t.newCursorPosition})}),this.textState.on("cursor-moved",t=>{this.emit("cursor-moved",{position:t.position})}),this.textState.on("selection-changed",t=>{this.emit("selection-changed",t)}),this.formatting.on("formatting-changed",t=>{this.emit("formatting-changed",t)}),this.substitutionFields.on("field-added",t=>{this.emit("substitution-field-added",t)}),this.substitutionFields.on("field-removed",t=>{this.emit("substitution-field-removed",t)}),this.substitutionFields.on("field-updated",t=>{this.emit("substitution-field-updated",t)}),this.embeddedObjects.on("object-added",t=>{this.emit("embedded-object-added",t)}),this.embeddedObjects.on("object-removed",t=>{this.emit("embedded-object-removed",t)}),this.embeddedObjects.on("object-updated",t=>{this.emit("embedded-object-updated",t),this.emit("content-changed",{type:"object-updated",...t})}),this.repeatingSections.on("section-added",t=>{this.emit("repeating-section-added",t)}),this.repeatingSections.on("section-removed",t=>{this.emit("repeating-section-removed",t)}),this.repeatingSections.on("section-updated",t=>{this.emit("repeating-section-updated",t)}),this.conditionalSections.on("section-added",t=>{this.emit("conditional-section-added",t)}),this.conditionalSections.on("section-removed",t=>{this.emit("conditional-section-removed",t)}),this.conditionalSections.on("section-updated",t=>{this.emit("conditional-section-updated",t)}),this.hyperlinks.on("hyperlink-added",t=>{this.emit("hyperlink-added",t)}),this.hyperlinks.on("hyperlink-removed",t=>{this.emit("hyperlink-removed",t)}),this.hyperlinks.on("hyperlink-updated",t=>{this.emit("hyperlink-updated",t)})}getText(){return this.textState.getText()}setText(t){this.textState.setText(t)}insertText(t,e){const i=e??this.textState.getCursorPosition(),n=this.formatting.getPendingFormatting();let o=null;if(n)o=n;else{const t=this.textState.getText();i>0?o=this.formatting.getFormattingAt(i-1):t.length>0&&(o=this.formatting.getFormattingAt(0))}this.formatting.shiftFormatting(i,t.length),this.substitutionFields.shiftFields(i,t.length),this.embeddedObjects.shiftObjects(i,t.length),this.repeatingSections.shiftSections(i,t.length),this.conditionalSections.shiftSections(i,t.length),this.hyperlinks.shiftHyperlinks(i,t.length),this.textState.insertText(t,i),this.paragraphFormatting.shiftParagraphs(i,t.length,this.textState.getText()),o&&t.length>0&&this.formatting.applyFormatting(i,i+t.length,o,!0),this.emit("text-inserted",{position:i,text:t,formatting:o})}insertPageBreak(){this.insertText(g)}deleteText(t,e,i=!0){const n=this.textState.substring(t,t+e),o=new Map;for(let i=0;i<e;i++){const e=this.formatting.getFormattingAt(t+i);e&&o.set(i,e)}const s=this.embeddedObjects.getObjectsInRange(t,t+e).map(e=>({offset:e.textIndex-t,object:e.object})),r=this.substitutionFields.getFieldsInRange(t,t+e).map(e=>({offset:e.textIndex-t,field:e.field}));this.textState.deleteText(t,e),this.emit("text-deleted",{position:t,deletedText:n,deletedFormatting:o,deletedObjects:s,deletedFields:r,isBackspace:i})}insertTextAt(t,e){this.formatting.shiftFormatting(t,e.length),this.substitutionFields.shiftFields(t,e.length),this.embeddedObjects.shiftObjects(t,e.length),this.repeatingSections.shiftSections(t,e.length),this.conditionalSections.shiftSections(t,e.length),this.hyperlinks.shiftHyperlinks(t,e.length);const i=this.textState.getText();this.textState.setText(i.slice(0,t)+e+i.slice(t)),this.paragraphFormatting.shiftParagraphs(t,e.length,this.textState.getText())}deleteTextAt(t,e){this.formatting.handleDeletion(t,e),this.substitutionFields.handleDeletion(t,e),this.embeddedObjects.handleDeletion(t,e),this.repeatingSections.handleDeletion(t,e),this.conditionalSections.handleDeletion(t,e),this.paragraphFormatting.handleDeletion(t,e),this.hyperlinks.handleDeletion(t,e);const i=this.textState.getText();this.textState.setText(i.slice(0,t)+i.slice(t+e))}getCursorPosition(){return this.textState.getCursorPosition()}setCursorPosition(t){this.formatting.clearPendingFormatting(),this.textState.setCursorPosition(t)}moveCursorLeft(){this.formatting.clearPendingFormatting(),this.textState.moveCursorLeft()}moveCursorRight(){this.formatting.clearPendingFormatting(),this.textState.moveCursorRight()}getSelection(){return this.textState.getSelection()}setSelectionAnchor(t){this.textState.setSelectionAnchor(t)}hasSelection(){return this.textState.hasSelection()}hasSelectionAnchor(){return this.textState.hasSelectionAnchor()}clearSelection(){this.textState.clearSelection()}setSelection(t,e){this.textState.setSelectionAnchor(t),this.textState.setCursorPosition(e)}getSelectedText(){return this.textState.getSelectedText()}deleteSelection(){const t=this.getSelection();return!!t&&(this.deleteText(t.start,t.end-t.start),this.clearSelection(),!0)}replaceSelection(t){const e=this.hasSelection();e&&(this.emit("compound-operation-start",{}),this.deleteSelection()),this.insertText(t),e&&this.emit("compound-operation-end",{description:"Replace"})}beginCompoundOperation(t){this.emit("compound-operation-start",{description:t})}endCompoundOperation(){this.emit("compound-operation-end",{})}selectLeft(){this.textState.selectLeft()}selectRight(){this.textState.selectRight()}selectWord(){this.textState.selectWord()}selectParagraph(){this.textState.selectParagraph()}selectAll(){this.textState.selectAll()}getWordBoundaries(t){return this.textState.getWordBoundaries(t)}getParagraphBoundariesAt(t){return this.textState.getParagraphBoundaries(t)}moveCursorToLineStart(){this.textState.moveCursorToLineStart()}moveCursorToLineEnd(){this.textState.moveCursorToLineEnd()}moveCursorToDocumentStart(){this.textState.moveCursorToDocumentStart()}moveCursorToDocumentEnd(){this.textState.moveCursorToDocumentEnd()}selectToLineStart(){this.textState.selectToLineStart()}selectToLineEnd(){this.textState.selectToLineEnd()}selectToDocumentStart(){this.textState.selectToDocumentStart()}selectToDocumentEnd(){this.textState.selectToDocumentEnd()}moveCursorWordLeft(){this.textState.moveCursorWordLeft()}moveCursorWordRight(){this.textState.moveCursorWordRight()}selectWordLeft(){this.textState.selectWordLeft()}selectWordRight(){this.textState.selectWordRight()}getFormattingAt(t){return this.formatting.getFormattingAt(t)}applyFormatting(t,e,i){const n=new Map;for(let i=t;i<e;i++){const e=this.formatting.getFormattingAt(i);e&&n.set(i-t,e)}this.formatting.applyFormatting(t,e,i);for(const n of this.substitutionFields.getFieldsArray())if(n.textIndex>=t&&n.textIndex<e){const t={...n.formatting||this.formatting.defaultFormatting,...i};this.substitutionFields.setFieldFormatting(n.textIndex,t)}this.emit("formatting-changed",{start:t,end:e,newFormatting:i,previousFormatting:n}),this.emit("content-changed",{type:"formatting",start:t,end:e})}getDefaultFormatting(){return this.formatting.defaultFormatting}setDefaultFormatting(t){this.formatting.setDefaultFormatting(t)}setPendingFormatting(t){this.formatting.setPendingFormatting(t)}getPendingFormatting(){return this.formatting.getPendingFormatting()}hasPendingFormatting(){return this.formatting.hasPendingFormatting()}clearPendingFormatting(){this.formatting.clearPendingFormatting()}getEffectiveFormattingAtCursor(){const t=this.getCursorPosition(),e=this.getPendingFormatting();let i;if(t>0)i=this.formatting.getFormattingAt(t-1);else{i=this.getText().length>0?this.formatting.getFormattingAt(0):this.formatting.defaultFormatting}return e?{...i,...e}:i}getSubstitutionFields(){return this.substitutionFields.getFields()}insertSubstitutionField(t,e){const i=this.textState.getCursorPosition(),n=e?.formatting||this.formatting.getFormattingAt(i);this.formatting.shiftFormatting(i,1),this.substitutionFields.shiftFields(i,1),this.embeddedObjects.shiftObjects(i,1),this.repeatingSections.shiftSections(i,1),this.conditionalSections.shiftSections(i,1),this.textState.insertText(c,i),this.paragraphFormatting.shiftParagraphs(i,1,this.textState.getText());const o=this.substitutionFields.insert(t,i,{...e,formatting:n});return n&&this.formatting.applyFormatting(i,i+1,n,!0),this.emit("substitution-field-inserted",{position:i,field:o}),this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()}),o}insertPageNumberField(t){return this.insertSubstitutionField("page",{fieldType:"pageNumber",displayFormat:t})}insertPageCountField(t){return this.insertSubstitutionField("pages",{fieldType:"pageCount",displayFormat:t})}insertSubstitutionFieldAt(t,e,i){const n=this.substitutionFields.insert(t,e,i);return i?.formatting&&this.formatting.applyFormatting(e,e+1,i.formatting),this.emit("substitution-field-inserted",{position:e,field:n}),n}removeSubstitutionField(t){return!!this.substitutionFields.remove(t)&&(this.textState.deleteText(t,1),!0)}getSubstitutionFieldAt(t){return this.substitutionFields.getFieldAt(t)}updateSubstitutionFieldConfig(t,e){return this.substitutionFields.updateFieldConfig(t,e)}getEmbeddedObjects(){return this.embeddedObjects.getObjects()}getEmbeddedObjectsInRange(t,e){return this.embeddedObjects.getObjectsInRange(t,e)}getSubstitutionFieldsInRange(t,e){return this.substitutionFields.getFieldsInRange(t,e).map(t=>({...t.field,textIndex:t.textIndex,field:t.field}))}insertEmbeddedObject(t,e="inline"){const i=this.textState.getCursorPosition();this.substitutionFields.shiftFields(i,1),this.embeddedObjects.shiftObjects(i,1),this.textState.insertText(c,i);const n="table"===t.objectType?"block":e;t.position=n,this.embeddedObjects.insert(t,i),this.emit("embedded-object-inserted",{position:i,object:t,objectPosition:n}),this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()})}insertEmbeddedObjectAt(t,e,i="inline"){this.substitutionFields.shiftFields(e,1),this.embeddedObjects.shiftObjects(e,1);const n=this.textState.getText();this.textState.setText(n.slice(0,e)+c+n.slice(e)),t.position=i,this.embeddedObjects.insert(t,e),this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()})}removeEmbeddedObject(t){return!!this.embeddedObjects.remove(t)&&(this.textState.deleteText(t,1),!0)}getEmbeddedObjectAt(t){return this.embeddedObjects.getObjectAt(t)}findEmbeddedObjectById(t){return this.embeddedObjects.findById(t)}getSelectedEmbeddedObject(){return this.embeddedObjects.getSelectedObject()}deselectAllEmbeddedObjects(){this.embeddedObjects.deselectAll()}flowText(t,e,i){const n=new F(i),o=this.textState.getText(),s={availableWidth:t,availableHeight:e,measurer:n,formatting:this.formatting,paragraphFormatting:this.paragraphFormatting,substitutionFields:this.substitutionFields,embeddedObjects:this.embeddedObjects,content:o};return this.layout.flowText(o,s)}findPositionForIndex(t,e){return this.layout.findPositionForIndex(t,e)}get length(){return this.textState.length}get isEmpty(){return this.textState.isEmpty}clear(){this.textState.clear(),this.formatting.clear(),this.paragraphFormatting.clear(),this.substitutionFields.clear(),this.embeddedObjects.clear(),this.repeatingSections.clear(),this.conditionalSections.clear(),this.hyperlinks.clear()}focus(){this._hasFocus||(this._hasFocus=!0,this._cursorVisible=!0,this.startCursorBlink(),this.emit("focus"))}blur(){this._hasFocus&&(this._hasFocus=!1,this._cursorVisible=!1,this.stopCursorBlink(),this.emit("blur"))}hasFocus(){return this._hasFocus}isCursorVisible(){return this._hasFocus&&this._cursorVisible}handleKeyDown(t){if(j.log("[pc-editor:FlowingTextContent.handleKeyDown] Key:",t.key,"_hasFocus:",this._hasFocus),!this._hasFocus)return j.log("[pc-editor:FlowingTextContent.handleKeyDown] No focus, returning false"),!1;switch(t.key){case"Backspace":if(t.preventDefault(),!this.deleteSelection()){const t=this.getCursorPosition();t>0&&this.deleteText(t-1,1)}return!0;case"Delete":if(t.preventDefault(),!this.deleteSelection()){const t=this.getCursorPosition();t<this.getText().length&&this.deleteText(t,1,!1)}return!0;case"ArrowLeft":return t.preventDefault(),t.ctrlKey||t.metaKey?t.shiftKey?this.selectWordLeft():(this.clearSelection(),this.moveCursorWordLeft()):t.shiftKey?this.selectLeft():(this.clearSelection(),this.moveCursorLeft()),this.resetCursorBlink(),!0;case"ArrowRight":return t.preventDefault(),t.ctrlKey||t.metaKey?t.shiftKey?this.selectWordRight():(this.clearSelection(),this.moveCursorWordRight()):t.shiftKey?this.selectRight():(this.clearSelection(),this.moveCursorRight()),this.resetCursorBlink(),!0;case"Home":return t.preventDefault(),t.ctrlKey||t.metaKey?t.shiftKey?this.selectToDocumentStart():(this.clearSelection(),this.moveCursorToDocumentStart()):t.shiftKey?this.selectToLineStart():(this.clearSelection(),this.moveCursorToLineStart()),this.resetCursorBlink(),!0;case"End":return t.preventDefault(),t.ctrlKey||t.metaKey?t.shiftKey?this.selectToDocumentEnd():(this.clearSelection(),this.moveCursorToDocumentEnd()):t.shiftKey?this.selectToLineEnd():(this.clearSelection(),this.moveCursorToLineEnd()),this.resetCursorBlink(),!0;case"ArrowUp":case"ArrowDown":return t.shiftKey&&!this.hasSelectionAnchor()?this.setSelectionAnchor():t.shiftKey||this.clearSelection(),!1;case"Enter":return t.preventDefault(),t.ctrlKey||t.metaKey?this.replaceSelection(g):this.replaceSelection("\n"),!0;case"Tab":{t.preventDefault();const e=this.textState.getCursorPosition(),i=this.textState.getText(),n=this.paragraphFormatting.getParagraphStart(e,i);return this.paragraphFormatting.getFormattingForParagraph(n).listFormatting?t.shiftKey?this.outdentParagraph():this.indentParagraph():t.shiftKey||this.replaceSelection("\t"),!0}default:return!(1!==t.key.length||t.ctrlKey||t.altKey||t.metaKey)&&(t.preventDefault(),this.replaceSelection(t.key),!0)}}onCursorBlink(t){this._cursorBlinkHandlers.add(t)}offCursorBlink(t){this._cursorBlinkHandlers.delete(t)}startCursorBlink(){this.stopCursorBlink(),this._cursorVisible=!0,this._cursorBlinkTimer=setInterval(()=>{this._cursorVisible=!this._cursorVisible;for(const t of this._cursorBlinkHandlers)t();this.emit("cursor-blink",{visible:this._cursorVisible})},530)}stopCursorBlink(){this._cursorBlinkTimer&&(clearInterval(this._cursorBlinkTimer),this._cursorBlinkTimer=null)}resetCursorBlink(){this._hasFocus&&(this._cursorVisible=!0,this.startCursorBlink())}getAlignmentAt(t){return this.paragraphFormatting.getFormattingAt(t,this.textState.getText()).alignment}setAlignment(t){const e=this.textState.getCursorPosition(),i=this.textState.getText(),n=this.paragraphFormatting.getParagraphStart(e,i),o=this.paragraphFormatting.getFormattingAt(e,i).alignment;this.paragraphFormatting.setAlignment(n,t),this.emit("alignment-changed",{paragraphIndex:n,newAlignment:t,previousAlignment:o}),this.emit("content-changed",{text:i,cursorPosition:e})}setAlignmentForRange(t,e,i){const n=this.textState.getText();this.paragraphFormatting.applyToRange(t,e,n,{alignment:i}),this.emit("content-changed",{text:n,cursorPosition:this.textState.getCursorPosition()})}getTextState(){return this.textState}getFormattingManager(){return this.formatting}getParagraphFormattingManager(){return this.paragraphFormatting}getSubstitutionFieldManager(){return this.substitutionFields}getEmbeddedObjectManager(){return this.embeddedObjects}getRepeatingSectionManager(){return this.repeatingSections}getLayoutEngine(){return this.layout}getHyperlinkManager(){return this.hyperlinks}getAffectedParagraphStarts(){const t=this.textState.getText(),e=this.getSelection();if(e&&e.start!==e.end)return this.paragraphFormatting.getParagraphBoundariesInRange(e.start,e.end,t);const i=this.textState.getCursorPosition();return[this.paragraphFormatting.getParagraphStart(i,t)]}toggleBulletList(){const t=this.textState.getText(),e=this.getAffectedParagraphStarts();for(const t of e)this.paragraphFormatting.toggleList(t,"bullet");this.emit("content-changed",{text:t,cursorPosition:this.textState.getCursorPosition()})}toggleNumberedList(){const t=this.textState.getText(),e=this.getAffectedParagraphStarts();for(const t of e)this.paragraphFormatting.toggleList(t,"number");this.emit("content-changed",{text:t,cursorPosition:this.textState.getCursorPosition()})}indentParagraph(){const t=this.textState.getText(),e=this.getAffectedParagraphStarts();for(const t of e)this.paragraphFormatting.indentParagraph(t);this.emit("content-changed",{text:t,cursorPosition:this.textState.getCursorPosition()})}outdentParagraph(){const t=this.textState.getText(),e=this.getAffectedParagraphStarts();for(const t of e)this.paragraphFormatting.outdentParagraph(t);this.emit("content-changed",{text:t,cursorPosition:this.textState.getCursorPosition()})}getListFormatting(){const t=this.textState.getCursorPosition(),e=this.textState.getText(),i=this.paragraphFormatting.getParagraphStart(t,e);return this.paragraphFormatting.getFormattingForParagraph(i).listFormatting}insertHyperlink(t,e){const i=this.getSelection();if(!i||i.start===i.end)return null;const n=this.hyperlinks.insert(t,i.start,i.end,e);return this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()}),n}insertHyperlinkAt(t,e,i,n){const o=this.hyperlinks.insert(t,e,i,n);return this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()}),o}removeHyperlink(t){this.hyperlinks.remove(t),this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()})}updateHyperlink(t,e){this.hyperlinks.update(t,e),this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()})}getHyperlinkAt(t){return this.hyperlinks.getHyperlinkAt(t)}getHyperlinkById(t){return this.hyperlinks.getHyperlinkById(t)}getHyperlinksInRange(t,e){return this.hyperlinks.getHyperlinksInRange(t,e)}getAllHyperlinks(){return this.hyperlinks.getAll()}getParagraphBoundaries(){return this.layout.getParagraphBoundaries(this.textState.getText())}getRepeatingSections(){return this.repeatingSections.getSections()}createRepeatingSection(t,e,i){const n=this.textState.getText();if(!this.repeatingSections.validateBoundaries(t,e,n))return null;const o=this.repeatingSections.create(t,e,i);return this.emit("content-changed",{text:n,cursorPosition:this.textState.getCursorPosition()}),o}removeRepeatingSection(t){return!!this.repeatingSections.remove(t)&&(this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()}),!0)}getRepeatingSection(t){return this.repeatingSections.getSection(t)}getRepeatingSectionAtBoundary(t){return this.repeatingSections.getSectionAtBoundary(t)}updateRepeatingSectionFieldPath(t,e){const i=this.repeatingSections.updateFieldPath(t,e);return i&&this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()}),i}getConditionalSectionManager(){return this.conditionalSections}getConditionalSections(){return this.conditionalSections.getSections()}createConditionalSection(t,e,i){const n=this.textState.getText();if(!this.conditionalSections.validateBoundaries(t,e,n))return null;const o=this.conditionalSections.create(t,e,i);return this.emit("content-changed",{text:n,cursorPosition:this.textState.getCursorPosition()}),o}removeConditionalSection(t){return!!this.conditionalSections.remove(t)&&(this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()}),!0)}getConditionalSection(t){return this.conditionalSections.getSection(t)}getConditionalSectionAtBoundary(t){return this.conditionalSections.getSectionAtBoundary(t)}updateConditionalSectionPredicate(t,e){const i=this.conditionalSections.updatePredicate(t,e);return i&&this.emit("content-changed",{text:this.textState.getText(),cursorPosition:this.textState.getCursorPosition()}),i}toData(){const t=this.textState.getText(),e=this.formatting.getCompressedRuns(t.length).map(t=>({index:t.index,formatting:{fontFamily:t.formatting.fontFamily,fontSize:t.formatting.fontSize,fontWeight:t.formatting.fontWeight,fontStyle:t.formatting.fontStyle,color:t.formatting.color,backgroundColor:t.formatting.backgroundColor}})),i=this.paragraphFormatting.toJSON(),n=this.substitutionFields.toJSON().map(t=>({id:t.id,textIndex:t.textIndex,fieldName:t.fieldName,fieldType:t.fieldType,displayFormat:t.displayFormat,defaultValue:t.defaultValue,formatting:t.formatting?{fontFamily:t.formatting.fontFamily,fontSize:t.formatting.fontSize,fontWeight:t.formatting.fontWeight,fontStyle:t.formatting.fontStyle,color:t.formatting.color,backgroundColor:t.formatting.backgroundColor}:void 0,formatConfig:t.formatConfig?{valueType:t.formatConfig.valueType,numberFormat:t.formatConfig.numberFormat,decimalPlaces:t.formatConfig.decimalPlaces,useGrouping:t.formatConfig.useGrouping,currencyFormat:t.formatConfig.currencyFormat,currencySymbol:t.formatConfig.currencySymbol,currencyPosition:t.formatConfig.currencyPosition,dateFormat:t.formatConfig.dateFormat,locale:t.formatConfig.locale}:void 0})),o=this.repeatingSections.toJSON(),s=this.conditionalSections.toJSON(),r=[];this.embeddedObjects.getObjects().forEach((t,e)=>{r.push({textIndex:e,object:t.toData()})});const a=this.hyperlinks.toJSON();return{text:t,formattingRuns:e.length>0?e:void 0,paragraphFormatting:i.length>0?i:void 0,substitutionFields:n.length>0?n:void 0,repeatingSections:o.length>0?o:void 0,conditionalSections:s.length>0?s:void 0,embeddedObjects:r.length>0?r:void 0,hyperlinks:a.length>0?a:void 0}}static fromData(t){const e=new X(t.text);if(t.formattingRuns&&t.formattingRuns.length>0){const i=t.text.length,n=e.getFormattingManager();for(let e=0;e<t.formattingRuns.length;e++){const o=t.formattingRuns[e],s=t.formattingRuns[e+1],r=o.index,a=s?s.index:i;r<a&&n.applyFormatting(r,a,o.formatting)}}if(t.paragraphFormatting&&t.paragraphFormatting.length>0&&e.getParagraphFormattingManager().fromJSON(t.paragraphFormatting),t.substitutionFields&&t.substitutionFields.length>0&&e.getSubstitutionFieldManager().fromJSON(t.substitutionFields),t.repeatingSections&&t.repeatingSections.length>0&&e.getRepeatingSectionManager().fromJSON(t.repeatingSections),t.conditionalSections&&t.conditionalSections.length>0&&e.getConditionalSectionManager().fromJSON(t.conditionalSections),t.embeddedObjects&&t.embeddedObjects.length>0)for(const i of t.embeddedObjects){const t=V.tryCreate(i.object);t?e.getEmbeddedObjectManager().insert(t,i.textIndex):j.warn(`[pc-editor:FlowingTextContent] Failed to create embedded object of type: ${i.object.objectType}`)}return t.hyperlinks&&t.hyperlinks.length>0&&e.getHyperlinkManager().fromJSON(t.hyperlinks),e}loadFromData(t){if(this.clear(),this.textState.setText(t.text),t.formattingRuns&&t.formattingRuns.length>0){const e=t.text.length;for(let i=0;i<t.formattingRuns.length;i++){const n=t.formattingRuns[i],o=t.formattingRuns[i+1],s=n.index,r=o?o.index:e;s<r&&this.formatting.applyFormatting(s,r,n.formatting)}}if(t.paragraphFormatting&&t.paragraphFormatting.length>0&&this.paragraphFormatting.fromJSON(t.paragraphFormatting),t.substitutionFields&&t.substitutionFields.length>0&&this.substitutionFields.fromJSON(t.substitutionFields),t.repeatingSections&&t.repeatingSections.length>0&&this.repeatingSections.fromJSON(t.repeatingSections),t.conditionalSections&&t.conditionalSections.length>0&&this.conditionalSections.fromJSON(t.conditionalSections),t.embeddedObjects&&t.embeddedObjects.length>0)for(const e of t.embeddedObjects){const t=V.tryCreate(e.object);t?this.embeddedObjects.insert(t,e.textIndex):j.warn(`[pc-editor:FlowingTextContent] Failed to create embedded object of type: ${e.object.objectType}`)}t.hyperlinks&&t.hyperlinks.length>0&&this.hyperlinks.fromJSON(t.hyperlinks)}}class K{constructor(t,e){this.pos=0,this.tokens=t,this.data=e}peek(){return this.tokens[this.pos]}advance(){const t=this.tokens[this.pos];return this.pos++,t}parse(){return this.parseOr()}parseOr(){let t=this.parseAnd();for(;"operator"===this.peek().type&&"||"===this.peek().value;){this.advance();const e=this.parseAnd();t=this.isTruthy(t)||this.isTruthy(e)}return t}parseAnd(){let t=this.parseComparison();for(;"operator"===this.peek().type&&"&&"===this.peek().value;){this.advance();const e=this.parseComparison();t=this.isTruthy(t)&&this.isTruthy(e)}return t}parseComparison(){const t=this.parseUnary(),e=this.peek();if("operator"===e.type){const i=e.value;if("=="===i||"!="===i||">"===i||"<"===i||">="===i||"<="===i||"=~"===i||"!~"===i){this.advance();const e=this.parseUnary();return this.compare(t,i,e)}}return t}parseUnary(){if("not"===this.peek().type){this.advance();const t=this.parseUnary();return!this.isTruthy(t)}return this.parsePrimary()}parsePrimary(){const t=this.peek();if("paren"===t.type&&"("===t.value){this.advance();const t=this.parseOr();return"paren"===this.peek().type&&")"===this.peek().value&&this.advance(),t}return"string"===t.type||"number"===t.type||"boolean"===t.type?(this.advance(),t.value):"identifier"===t.type?(this.advance(),this.resolveIdentifier(t.value)):void this.advance()}resolveIdentifier(t){const e=t.split(".");let i=this.data;for(const t of e){if(null==i)return;if("object"!=typeof i)return;i=i[t]}return i}compare(t,e,i){if("=~"===e||"!~"===e){const n=this.toString(t),o=this.toString(i);try{const t=new RegExp(o).test(n);return"=~"===e?t:!t}catch{return"!~"===e}}if(">"===e||"<"===e||">="===e||"<="===e){const n=this.toNumber(t),o=this.toNumber(i);switch(e){case">":return n>o;case"<":return n<o;case">=":return n>=o;case"<=":return n<=o}}const n=this.toNumberIfNumeric(t),o=this.toNumberIfNumeric(i);switch(e){case"==":return n==o;case"!=":return n!=o;default:return!1}}toString(t){return null==t?"":"string"==typeof t?t:String(t)}toNumber(t){if("number"==typeof t)return t;if("string"==typeof t){const e=Number(t);return isNaN(e)?NaN:e}return"boolean"==typeof t?t?1:0:NaN}toNumberIfNumeric(t){if("string"==typeof t&&t.length>0){const e=Number(t);if(!isNaN(e))return e}return t}isTruthy(t){return null!=t&&("boolean"==typeof t?t:"number"==typeof t?0!==t:"string"==typeof t?t.length>0:!Array.isArray(t)||t.length>0)}}class Y{static evaluate(t,e){if(!t||0===t.trim().length)return!1;try{const i=function(t){const e=[];let i=0;for(;i<t.length;){const n=t[i];if(" "!==n&&"\t"!==n&&"\n"!==n&&"\r"!==n)if("("!==n&&")"!==n){if(i+1<t.length){const n=t[i]+t[i+1];if("=="===n||"!="===n||">="===n||"<="===n||"&&"===n||"||"===n||"=~"===n||"!~"===n){e.push({type:"operator",value:n}),i+=2;continue}}if(">"!==n&&"<"!==n)if("!"!==n){if('"'===n||"'"===n){const o=n;i++;let s="";for(;i<t.length&&t[i]!==o;)"\\"===t[i]&&i+1<t.length?(i++,s+=t[i]):s+=t[i],i++;i++,e.push({type:"string",value:s});continue}if(n>="0"&&n<="9"){let n="";for(;i<t.length&&(t[i]>="0"&&t[i]<="9"||"."===t[i]);)n+=t[i],i++;e.push({type:"number",value:parseFloat(n)});continue}if(n>="a"&&n<="z"||n>="A"&&n<="Z"||"_"===n||"$"===n){let n="";for(;i<t.length&&(t[i]>="a"&&t[i]<="z"||t[i]>="A"&&t[i]<="Z"||t[i]>="0"&&t[i]<="9"||"_"===t[i]||"$"===t[i]||"."===t[i]);)n+=t[i],i++;"true"===n?e.push({type:"boolean",value:!0}):"false"===n?e.push({type:"boolean",value:!1}):e.push({type:"identifier",value:n});continue}i++}else e.push({type:"not"}),i++;else e.push({type:"operator",value:n}),i++}else e.push({type:"paren",value:n}),i++;else i++}return e.push({type:"eof"}),e}(t.trim()),n=new K(i,e).parse();return null!=n&&("boolean"==typeof n?n:"number"==typeof n?0!==n:"string"==typeof n?n.length>0:!Array.isArray(n)||n.length>0)}catch{return!1}}}class q{globalToLocal(t,e){const i=this.getRegionBounds(e);return i?t.x<i.x||t.x>i.x+i.width||t.y<i.y||t.y>i.y+i.height?null:{x:t.x-i.x,y:t.y-i.y}:null}localToGlobal(t,e){const i=this.getRegionBounds(e);return i?{x:t.x+i.x,y:t.y+i.y}:t}getPageCount(){return this.getFlowedPages().length||1}containsPointInRegion(t,e){const i=this.getRegionBounds(e);return!!i&&(t.x>=i.x&&t.x<=i.x+i.width&&t.y>=i.y&&t.y<=i.y+i.height)}}class J{constructor(){this._bodyRegion=null,this._headerRegion=null,this._footerRegion=null,this._textBoxRegions=new Map}setBodyRegion(t){this._bodyRegion=t}getBodyRegion(){return this._bodyRegion}setHeaderRegion(t){this._headerRegion=t}getHeaderRegion(){return this._headerRegion}setFooterRegion(t){this._footerRegion=t}getFooterRegion(){return this._footerRegion}registerTextBox(t){this._textBoxRegions.set(t.id,t)}unregisterTextBox(t){this._textBoxRegions.delete(t)}getTextBoxRegion(t){return this._textBoxRegions.get(t)||null}getAllTextBoxRegions(){return Array.from(this._textBoxRegions.values())}getAllRegions(){const t=[];this._bodyRegion&&t.push(this._bodyRegion),this._headerRegion&&t.push(this._headerRegion),this._footerRegion&&t.push(this._footerRegion);for(const e of this._textBoxRegions.values())t.push(e);return t}getRegionAtPoint(t,e){for(const i of this._textBoxRegions.values())if(i.containsPointInRegion(t,e))return i;return this._headerRegion&&this._headerRegion.containsPointInRegion(t,e)?this._headerRegion:this._footerRegion&&this._footerRegion.containsPointInRegion(t,e)?this._footerRegion:this._bodyRegion&&this._bodyRegion.containsPointInRegion(t,e)?this._bodyRegion:null}findRegionByFlowingContent(t){if(this._bodyRegion&&this._bodyRegion.flowingContent===t)return this._bodyRegion;if(this._headerRegion&&this._headerRegion.flowingContent===t)return this._headerRegion;if(this._footerRegion&&this._footerRegion.flowingContent===t)return this._footerRegion;for(const e of this._textBoxRegions.values())if(e.flowingContent===t)return e;return null}clear(){this._bodyRegion=null,this._headerRegion=null,this._footerRegion=null,this._textBoxRegions.clear()}}class Z extends q{constructor(t,e){super(),this.id="body",this.type="body",this._flowedPages=[],this._availableWidth=0,this._flowingContent=t,this._getPage=e}get flowingContent(){return this._flowingContent}getRegionBounds(t){const e=this._getPage(t);if(!e)return null;const i=e.getContentBounds();return{x:i.position.x,y:i.position.y,width:i.size.width,height:i.size.height}}getFlowedLines(t){return t<0||t>=this._flowedPages.length?[]:this._flowedPages[t].lines}getFlowedPages(){return this._flowedPages}getAvailableWidth(){return this._availableWidth}spansMultiplePages(){return!0}reflow(t){const e=this.getRegionBounds(0);if(!e)return this._flowedPages=[],void(this._availableWidth=0);this._availableWidth=e.width,this._flowedPages=this._flowingContent.flowText(e.width,100*e.height,t)}setFlowedPages(t,e){this._flowedPages=t,this._availableWidth=e}}class Q extends q{constructor(t,e){super(),this.id="header",this.type="header",this._flowedPage=null,this._availableWidth=0,this._flowingContent=t,this._getPage=e}get flowingContent(){return this._flowingContent}getRegionBounds(t){const e=this._getPage(t);if(!e)return null;const i=e.getHeaderBounds();return{x:i.position.x,y:i.position.y,width:i.size.width,height:i.size.height}}getFlowedLines(t){return this._flowedPage?.lines||[]}getFlowedPages(){return this._flowedPage?[this._flowedPage]:[]}getAvailableWidth(){return this._availableWidth}spansMultiplePages(){return!1}reflow(t){const e=this.getRegionBounds(0);if(!e)return this._flowedPage=null,void(this._availableWidth=0);this._availableWidth=e.width;const i=this._flowingContent.flowText(e.width,e.height,t);this._flowedPage=i.length>0?i[0]:null}setFlowedPage(t,e){this._flowedPage=t,this._availableWidth=e}}class tt extends q{constructor(t,e){super(),this.id="footer",this.type="footer",this._flowedPage=null,this._availableWidth=0,this._flowingContent=t,this._getPage=e}get flowingContent(){return this._flowingContent}getRegionBounds(t){const e=this._getPage(t);if(!e)return null;const i=e.getFooterBounds();return{x:i.position.x,y:i.position.y,width:i.size.width,height:i.size.height}}getFlowedLines(t){return this._flowedPage?.lines||[]}getFlowedPages(){return this._flowedPage?[this._flowedPage]:[]}getAvailableWidth(){return this._availableWidth}spansMultiplePages(){return!1}reflow(t){const e=this.getRegionBounds(0);if(!e)return this._flowedPage=null,void(this._availableWidth=0);this._availableWidth=e.width;const i=this._flowingContent.flowText(e.width,e.height,t);this._flowedPage=i.length>0?i[0]:null}setFlowedPage(t,e){this._flowedPage=t,this._availableWidth=e}}const et={USD:"USD",EUR:"EUR",GBP:"GBP",JPY:"JPY"};function it(t,e){if(null==t)return"";if(!e||!e.valueType)return String(t);const i=e.locale||"en-US";switch(e.valueType){case"number":return nt(t,e,i);case"currency":return function(t,e,i){const n=ot(t);if(isNaN(n))return String(t);const o=e.currencyFormat||"USD";if("custom"===o){const t=e.currencySymbol||"$",o=e.currencyPosition||"before",s=nt(n,{decimalPlaces:e.decimalPlaces??2,useGrouping:e.useGrouping??!0},i);return"before"===o?`${t}${s}`:`${s}${t}`}const s={style:"currency",currency:et[o],minimumFractionDigits:e.decimalPlaces,maximumFractionDigits:e.decimalPlaces};"JPY"===o&&void 0===e.decimalPlaces&&(s.minimumFractionDigits=0,s.maximumFractionDigits=0);try{return new Intl.NumberFormat(i,s).format(n)}catch{return String(n)}}(t,e,i);case"date":return function(t,e,i){const n=function(t){if(t instanceof Date)return t;if("string"==typeof t||"number"==typeof t){const e=new Date(t);return isNaN(e.getTime())?null:e}return null}(t);if(!n||isNaN(n.getTime()))return String(t);const o=e.dateFormat;if("iso"===o)return n.toISOString().split("T")[0];const s=function(t){switch(t){case"short":return{dateStyle:"short"};case"medium":default:return{dateStyle:"medium"};case"long":return{dateStyle:"long"};case"full":return{dateStyle:"full"};case"time-short":return{timeStyle:"short"};case"time-long":return{timeStyle:"medium"};case"datetime-short":return{dateStyle:"short",timeStyle:"short"};case"datetime-long":return{dateStyle:"long",timeStyle:"short"}}}(o);try{return new Intl.DateTimeFormat(i,s).format(n)}catch{return n.toLocaleDateString()}}(t,e,i);default:return String(t)}}function nt(t,e,i){const n=ot(t);if(isNaN(n))return String(t);const o={};switch(e.numberFormat){case"integer":o.maximumFractionDigits=0,o.useGrouping=e.useGrouping??!1;break;case"decimal":o.minimumFractionDigits=e.decimalPlaces??2,o.maximumFractionDigits=e.decimalPlaces??2,o.useGrouping=e.useGrouping??!1;break;case"decimal-1":o.minimumFractionDigits=1,o.maximumFractionDigits=1,o.useGrouping=e.useGrouping??!1;break;case"decimal-3":o.minimumFractionDigits=3,o.maximumFractionDigits=3,o.useGrouping=e.useGrouping??!1;break;case"thousands":o.maximumFractionDigits=0,o.useGrouping=!0;break;case"percent":o.style="percent",o.minimumFractionDigits=e.decimalPlaces??2,o.maximumFractionDigits=e.decimalPlaces??2;break;case"scientific":o.notation="scientific",o.minimumFractionDigits=e.decimalPlaces??2,o.maximumFractionDigits=e.decimalPlaces??2;break;default:void 0!==e.decimalPlaces&&(o.minimumFractionDigits=e.decimalPlaces,o.maximumFractionDigits=e.decimalPlaces),void 0!==e.useGrouping&&(o.useGrouping=e.useGrouping)}try{return new Intl.NumberFormat(i,o).format(n)}catch{return String(n)}}function ot(t){if("number"==typeof t)return t;if("string"==typeof t){const e=t.replace(/[^0-9.-]/g,"");return parseFloat(e)}return NaN}class st extends r{constructor(t){super(),this._pages=[],this._version="1.0.0",this._bodyFlowingContent=new X,this._headerFlowingContent=new X,this._footerFlowingContent=new X,this.setupFlowingContentListeners(),t?(this._version=t.version||this._version,this._settings=t.settings||this.getDefaultSettings(),t.pages.forEach(t=>{this.addPage(new a(t,this._settings))}),t.bodyContent&&this._bodyFlowingContent.loadFromData(t.bodyContent),t.headerContent&&this._headerFlowingContent.loadFromData(t.headerContent),t.footerContent&&this._footerFlowingContent.loadFromData(t.footerContent)):(this._settings=this.getDefaultSettings(),this.addPage(new a(this.createEmptyPageData(),this._settings)))}setupFlowingContentListeners(){this._bodyFlowingContent.on("content-changed",()=>{this.emit("body-content-changed"),this.emit("change")}),this._bodyFlowingContent.on("cursor-moved",t=>{this.emit("cursor-moved",t)}),this._bodyFlowingContent.on("formatting-changed",t=>{this.emit("formatting-changed",t),this.emit("change")}),this._bodyFlowingContent.on("inline-element-added",t=>{this.emit("inline-element-added",t),this.emit("change")}),this._headerFlowingContent.on("content-changed",()=>{this.emit("header-content-changed"),this.emit("change")}),this._footerFlowingContent.on("content-changed",()=>{this.emit("footer-content-changed"),this.emit("change")})}getDefaultSettings(){return{pageSize:"A4",pageOrientation:"portrait",margins:{top:20,right:20,bottom:20,left:20},units:"mm"}}createEmptyPageData(){return{id:this.generateId()}}generateId(){return`page_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}get pages(){return this._pages}get pageCount(){return this._pages.length}get settings(){return{...this._settings}}get version(){return this._version}get bodyFlowingContent(){return this._bodyFlowingContent}get headerFlowingContent(){return this._headerFlowingContent}get footerFlowingContent(){return this._footerFlowingContent}addPage(t,e){void 0!==e&&e>=0&&e<=this._pages.length?this._pages.splice(e,0,t):this._pages.push(t),t.on("change",()=>this.handlePageChange()),this.emit("page-added",{page:t,index:e}),this.emit("change")}removePage(t){const e=this._pages.findIndex(e=>e.id===t);if(-1===e)return null;const[i]=this._pages.splice(e,1);return i.removeAllListeners(),this.emit("page-removed",{page:i,index:e}),this.emit("change"),i}getPage(t){return this._pages.find(e=>e.id===t)}getPageByIndex(t){return this._pages[t]}movePage(t,e){const i=this._pages.findIndex(e=>e.id===t);if(-1===i||e<0||e>=this._pages.length)return!1;const[n]=this._pages.splice(i,1);return this._pages.splice(e,0,n),this.emit("page-moved",{page:n,fromIndex:i,toIndex:e}),this.emit("change"),!0}updateSettings(t){this._settings={...this._settings,...t},this._pages.forEach(t=>{t.updateSettings(this._settings)}),this.emit("settings-changed",{settings:this._settings}),this.emit("change")}handlePageChange(){this.emit("change")}toData(){return{version:this._version,settings:{...this._settings},pages:this._pages.map(t=>t.toData()),bodyContent:this._bodyFlowingContent.toData(),headerContent:this._headerFlowingContent.toData(),footerContent:this._footerFlowingContent.toData(),metadata:{modifiedAt:(new Date).toISOString()}}}clear(){this._pages.forEach(t=>t.removeAllListeners()),this._pages=[],this._bodyFlowingContent.setText(""),this._headerFlowingContent.setText(""),this._footerFlowingContent.setText(""),this.emit("cleared"),this.emit("change")}}class rt{constructor(){this.targets=new Map}clear(){this.targets.clear()}clearCategory(t){for(const[e,i]of this.targets){const n=i.filter(e=>e.category!==t);0===n.length?this.targets.delete(e):this.targets.set(e,n)}}register(t,e){let i=this.targets.get(t);i||(i=[],this.targets.set(t,i)),i.push(e)}queryAtPoint(t,e){const i=this.targets.get(t);if(!i)return null;const n=[];for(const t of i)this.containsPoint(t.bounds,e)&&n.push(t);return 0===n.length?null:(n.sort((t,e)=>e.priority-t.priority),n[0])}queryAllAtPoint(t,e){const i=this.targets.get(t);if(!i)return[];const n=[];for(const t of i)this.containsPoint(t.bounds,e)&&n.push(t);return n.sort((t,e)=>e.priority-t.priority),n}queryByType(t,e,i){const n=this.targets.get(t);if(!n)return null;let o=null;for(const t of n)t.type===i&&this.containsPoint(t.bounds,e)&&(!o||t.priority>o.priority)&&(o=t);return o}getTargetsForPage(t){return this.targets.get(t)||[]}getPageIndices(){return Array.from(this.targets.keys()).sort((t,e)=>t-e)}getTotalTargetCount(){let t=0;for(const e of this.targets.values())t+=e.length;return t}containsPoint(t,e){return e.x>=t.x&&e.x<=t.x+t.width&&e.y>=t.y&&e.y<=t.y+t.height}}const at=100,lt=90,dt=80,ht="#87CEEB",ct="#888888",gt="Page Break",ut="#6B46C1",ft=[4,4],pt="#D97706",mt=[4,4];class bt extends r{constructor(t){super(),this.flowedPages=new Map,this.headerFlowedPage=null,this.footerFlowedPage=null,this._focusedRegion=null,this.selectedText=null,this.showControlCharacters=!1,this.tableContinuations=new Map,this.pageTextOffsets=new Map,this._hitTestManager=new rt,this.document=t,this.setupFlowingContentListeners()}get hitTestManager(){return this._hitTestManager}setShowControlCharacters(t){this.showControlCharacters=t}findCursorLocationInBody(t){const e=this.document.pages[0];if(!e)return null;const i=this.flowedPages.get(e.id);if(!i||0===i.length)return null;for(let e=0;e<i.length;e++){const n=i[e];for(let i=0;i<n.lines.length;i++){const o=n.lines[i];if(t>=o.startIndex&&t<=o.endIndex)return{pageIndex:e,lineIndex:i,line:o,flowedPage:n}}}if(i.length>0){const t=i.length-1,e=i[t];if(e.lines.length>0){const i=e.lines.length-1;return{pageIndex:t,lineIndex:i,line:e.lines[i],flowedPage:e}}}return null}findCursorLocationInSection(t,e){const i="header"===e?this.headerFlowedPage:this.footerFlowedPage;if(!i||0===i.lines.length)return null;for(let e=0;e<i.lines.length;e++){const n=i.lines[e];if(t>=n.startIndex&&t<=n.endIndex)return{lineIndex:e,line:n,flowedPage:i}}const n=i.lines.length-1;return{lineIndex:n,line:i.lines[n],flowedPage:i}}calculateCursorPosition(t){const e=this.getActiveFlowingContent();if(!e)return null;const i=e.getCursorPosition(),n=this.document.pages[0];if(!n)return null;if("body"===this.getActiveSection()){const e=this.findCursorLocationInBody(i);if(!e)return null;const o=n.getContentBounds(),s=o.size.width,r=P.getAlignmentOffset(e.line,s),a=P.getXPositionForTextIndex(e.line,i,t),l=e.line.listMarker?.indent??0;let d=o.position.y;d+=this.getPageTextOffset(e.pageIndex);for(let t=0;t<e.lineIndex;t++)d+=e.flowedPage.lines[t].height;return{x:o.position.x+r+l+a,y:d,height:e.line.height,pageIndex:e.pageIndex}}{const e=this.getActiveSection(),o=this.findCursorLocationInSection(i,e);if(!o)return null;const s="header"===e?n.getHeaderBounds():n.getFooterBounds(),r=s.size.width,a=P.getAlignmentOffset(o.line,r),l=P.getXPositionForTextIndex(o.line,i,t),d=o.line.listMarker?.indent??0;let h=s.position.y;for(let t=0;t<o.lineIndex;t++)h+=o.flowedPage.lines[t].height;return{x:s.position.x+a+d+l,y:h,height:o.line.height,pageIndex:0}}}setFocusedRegion(t){this._focusedRegion=t}getFocusedRegion(){return this._focusedRegion}getActiveSection(){if(this._focusedRegion){const t=this._focusedRegion.type;return"textbox"===t||"tablecell"===t?"body":t}return"body"}getActiveFlowingContent(){return this._focusedRegion?this._focusedRegion.flowingContent:this.document.bodyFlowingContent}setupFlowingContentListeners(){const t=this.document.bodyFlowingContent;t.on("content-changed",()=>{this.emit("content-changed")}),t.on("selection-changed",t=>{"body"===this.getActiveSection()&&(t.selection?this.setTextSelection(t.selection.start,t.selection.end):this.clearTextSelection(),this.emit("selection-changed",t))}),this.document.headerFlowingContent.on("content-changed",()=>{this.emit("header-content-changed"),this.emit("content-changed")}),this.document.headerFlowingContent.on("selection-changed",t=>{"header"===this.getActiveSection()&&(t.selection?this.setTextSelection(t.selection.start,t.selection.end):this.clearTextSelection(),this.emit("selection-changed",t))}),this.document.footerFlowingContent.on("content-changed",()=>{this.emit("footer-content-changed"),this.emit("content-changed")}),this.document.footerFlowingContent.on("selection-changed",t=>{"footer"===this.getActiveSection()&&(t.selection?this.setTextSelection(t.selection.start,t.selection.end):this.clearTextSelection(),this.emit("selection-changed",t))})}renderPageFlowingText(t,e,i){const n=this.document.pages.findIndex(e=>e.id===t.id);if(0===n){this.clearTableContinuations();const n=this.flowTextForPage(t,e,i);this.flowedPages.set(t.id,n),n.length>1&&this.emit("text-overflow",{pageId:t.id,overflowPages:n.slice(1),totalPages:n.length}),n.length>0&&this.renderFlowedPage(n[0],e,i,0,this.document.bodyFlowingContent)}else{const t=this.flowedPages.get(this.document.pages[0].id);t&&t.length>n?this.renderFlowedPage(t[n],e,i,n,this.document.bodyFlowingContent):this.renderTableContinuationsForPage(e,n,i)}const o=this.document.bodyFlowingContent;if(o&&"body"===this.getActiveSection()&&o.isCursorVisible()&&this.renderCursor(e,n),"body"===this.getActiveSection()&&this.selectedText){const o=0===n?this.flowedPages.get(t.id):this.flowedPages.get(this.document.pages[0].id);if(o&&o.length>n){const t=this.getPageTextOffset(n),s=t>0?{...i,y:i.y+t}:i;this.renderTextSelection(o[n],e,s)}}}renderHeaderText(t,e,i,n,o=0){const s=t.getHeaderBounds(),r={x:s.position.x,y:s.position.y,width:s.size.width,height:s.size.height},a=this.document.headerFlowingContent.flowText(r.width,r.height,e);a.length>0?(this.headerFlowedPage=a[0],n?this.renderRegion(n,e,o,{renderCursor:i,renderSelection:i}):(this.renderFlowedPage(a[0],e,r,o,this.document.headerFlowingContent),i&&this.document.headerFlowingContent.isCursorVisible()&&this.renderCursor(e,0),i&&this.selectedText&&this.renderTextSelection(a[0],e,r))):this.headerFlowedPage=null}renderFooterText(t,e,i,n,o=0){const s=t.getFooterBounds(),r={x:s.position.x,y:s.position.y,width:s.size.width,height:s.size.height},a=this.document.footerFlowingContent.flowText(r.width,r.height,e);a.length>0?(this.footerFlowedPage=a[0],n?this.renderRegion(n,e,o,{renderCursor:i,renderSelection:i}):(this.renderFlowedPage(a[0],e,r,o,this.document.footerFlowingContent),i&&this.document.footerFlowingContent.isCursorVisible()&&this.renderCursor(e,0),i&&this.selectedText&&this.renderTextSelection(a[0],e,r))):this.footerFlowedPage=null}handleRegionClick(t,e,i,n){const o=t.globalToLocal(e,i);if(!o)return null;if("body"===t.type){const t=this.getPageTextOffset(i);t>0&&(o.y-=t)}const s=this.getFlowedLinesForRegion(t,i),r=this.getAvailableWidthForRegion(t,i);if(0===s.length)return t.flowingContent.setCursorPosition(0),t.flowingContent.resetCursorBlink(),this.emit("text-clicked",{textIndex:0,line:0,section:t.type}),this.emit("cursor-changed",{textIndex:0,section:t.type}),{textIndex:0,lineIndex:0};const a=P.findLineAtY(s,o.y);if(a){const{line:s,lineIndex:l}=a,d=P.getAlignmentOffset(s,r),h=t.getRegionBounds(i);if(h){const i=h.y+a.lineY,n=h.x+d,o=this.getInlineElementAtPoint(s,e,i,n);if(o)return this.emit("inline-element-clicked",{element:o,point:e,section:t.type}),null;const r=this.getSubstitutionFieldAtPoint(s,e,i,n);r&&this.emit("substitution-field-clicked",{field:r,point:e,section:t.type})}const c=o.x-d,g=P.getTextIndexAtX(s,c,n);return t.flowingContent.setCursorPosition(g),t.flowingContent.resetCursorBlink(),this.emit("text-clicked",{textIndex:g,line:l,section:t.type}),this.emit("cursor-changed",{textIndex:g,section:t.type}),{textIndex:g,lineIndex:l}}const l=s.length-1,d=s[l].endIndex;return t.flowingContent.setCursorPosition(d),t.flowingContent.resetCursorBlink(),this.emit("text-clicked",{textIndex:d,line:l,section:t.type}),this.emit("cursor-changed",{textIndex:d,section:t.type}),{textIndex:d,lineIndex:l}}getFlowedLinesForRegion(t,e){switch(t.type){case"header":return this.headerFlowedPage?.lines||[];case"footer":return this.footerFlowedPage?.lines||[];case"body":{const t=this.document.pages[0];if(!t)return[];const i=this.flowedPages.get(t.id);return i&&i.length>e&&i[e]?.lines||[]}case"textbox":case"tablecell":return t.getFlowedLines(e);default:return[]}}getAvailableWidthForRegion(t,e){const i=t.getRegionBounds(e);return i?.width||0}renderRegion(t,e,i,n={}){const{renderCursor:o=!0,renderSelection:s=!0,clipToBounds:r=!1}=n,a=t.getRegionBounds(i);if(!a)return;const l=this.getFlowedLinesForRegion(t,i),d=this.getAvailableWidthForRegion(t,i),h=t.flowingContent,c=h.hasFocus()?h.getCursorPosition():void 0;if(r&&(e.save(),e.beginPath(),e.rect(a.x,a.y,a.width,a.height),e.clip()),s&&h.hasFocus()){const t=h.getSelection();t&&t.start!==t.end&&this.renderRegionSelection(l,e,a,d,t)}const g=this.document.pages[0],u=g&&this.flowedPages.get(g.id)?.length||1,f=h.getAllHyperlinks(),p=[];let m=a.y;for(let t=0;t<l.length;t++){const n=l[t];if(r&&m+n.height<a.y)m+=n.height;else{if(r&&m>a.y+a.height)break;if(n.embeddedObjects)for(const t of n.embeddedObjects)t.isAnchor&&"relative"===t.object.position&&p.push({object:t.object,anchorX:a.x,anchorY:m});this.renderFlowedLine(n,e,{x:a.x,y:m},d,i,c,u,f),m+=n.height}}o&&h.hasFocus()&&h.isCursorVisible()&&this.renderRegionCursor(l,e,a,d,h.getCursorPosition()),r&&e.restore(),p.length>0&&this.renderRelativeObjects(p,e,i)}renderRegionSelection(t,e,i,n,o){const s=Math.min(o.start,o.end),r=Math.max(o.start,o.end);e.save(),e.fillStyle="rgba(0, 102, 204, 0.3)";let a=i.y;for(const o of t){if(r>o.startIndex&&s<o.endIndex){const t=Math.max(s,o.startIndex),l=Math.min(r,o.endIndex),d=P.getAlignmentOffset(o,n),h=o.listMarker?.indent??0,c=i.x+d+h+P.getXPositionForTextIndex(o,t,e),g=i.x+d+h+P.getXPositionForTextIndex(o,l,e);e.fillRect(c,a,g-c,o.height)}a+=o.height}e.restore()}renderRegionCursor(t,e,i,n,o){let s=i.y;for(const r of t){if(o>=r.startIndex&&o<=r.endIndex){const t=P.getAlignmentOffset(r,n),a=r.listMarker?.indent??0,l=i.x+t+a+P.getXPositionForTextIndex(r,o,e);return e.save(),e.strokeStyle="#000000",e.lineWidth=1,e.beginPath(),e.moveTo(l,s),e.lineTo(l,s+r.height),e.stroke(),void e.restore()}s+=r.height}if(t.length>0){const r=t[t.length-1],a=P.getAlignmentOffset(r,n),l=r.listMarker?.indent??0,d=i.x+a+l+P.getXPositionForTextIndex(r,o,e);s=i.y;for(let e=0;e<t.length-1;e++)s+=t[e].height;e.save(),e.strokeStyle="#000000",e.lineWidth=1,e.beginPath(),e.moveTo(d,s),e.lineTo(d,s+r.height),e.stroke(),e.restore()}else e.save(),e.strokeStyle="#000000",e.lineWidth=1,e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(i.x,i.y+14),e.stroke(),e.restore()}flowTextForPage(t,e,i){return this.document.bodyFlowingContent.flowText(i.width,i.height,e)}renderFlowedPage(t,e,i,n,o){let s=i.y;if(n>0&&this.tableContinuations.size>0){const t=this.renderTableContinuationsAtPosition(e,n,i,s);s+=t,this.pageTextOffsets.set(n,t)}else this.pageTextOffsets.set(n,0);const r=o||this.document.bodyFlowingContent,a=(r?.hasFocus()??!1)&&r?r.getCursorPosition():void 0,l=this.document.pages[0],d=l&&this.flowedPages.get(l.id)?.length||1,h=r?r.getAllHyperlinks():[],c=[];for(let o=0;o<t.lines.length;o++){const r=t.lines[o];if(r.embeddedObjects)for(const t of r.embeddedObjects)t.isAnchor&&"relative"===t.object.position&&c.push({object:t.object,anchorX:i.x,anchorY:s});this.renderFlowedLine(r,e,{x:i.x,y:s},i.width,n,a,d,h),s+=r.height}this.renderRelativeObjects(c,e,n)}renderRelativeObjects(t,e,i){for(const{object:n,anchorX:o,anchorY:s}of t){const t=n.relativeOffset,r=o+t.x,a=s+t.y;if(n.renderedPosition={x:r,y:a},n.renderedPageIndex=i,n instanceof U||this._hitTestManager.register(i,{type:"embedded-object",category:"content",bounds:{x:r,y:a,width:n.width,height:n.height},priority:dt,data:{type:"embedded-object",object:n}}),e.save(),e.translate(r,a),n instanceof L){const t=n;t.reflow(e),t.render(e),e.restore(),this.renderRegion(t,e,i,{renderCursor:!0,renderSelection:!0,clipToBounds:!0})}else n.render(e),e.restore()}}renderFlowedLine(t,e,i,n,o,s,r,a){const l=t.listMarker?.indent||0,h=n-l;let c=i.x+l+this.getAlignmentOffset(t,h);e.save(),e.textBaseline="alphabetic",t.listMarker?.isFirstLineOfListItem&&t.listMarker.text&&this.renderListMarker(t.listMarker,e,i,t.baseline,t.runs[0]?.formatting||t.listMarker.formatting);const g=new Map;t.substitutionFields&&t.substitutionFields.forEach(t=>{g.set(t.textIndex,t)});const u=new Map;t.embeddedObjects&&t.embeddedObjects.forEach(t=>{u.set(t.textIndex,t)});for(const l of t.runs){e.font=this.getFontString(l.formatting),e.fillStyle=l.formatting.color;for(let d=0;d<l.text.length;d++){const h=l.startIndex+d,f=l.text[d],p=g.get(h);if(p){const n=s===h+1,a=o+1;c=this.renderSubstitutionField(p,e,{x:c,y:i.y},t,n,a,r);continue}const m=u.get(h);if(m)c=this.renderEmbeddedObject(m,e,{x:c,y:i.y},t,n,i.x,o);else if(""!==f){const n="\t"===f?e.measureText(" ").width:e.measureText(f).width;let o;if(a)for(const t of a)if(h>=t.startIndex&&h<t.endIndex){o=t;break}if(l.formatting.backgroundColor){const o=.8*l.formatting.fontSize,s=1.2*l.formatting.fontSize,r=i.y+t.baseline-o;e.fillStyle=l.formatting.backgroundColor,e.fillRect(c,r,n,s),e.fillStyle=l.formatting.color}if(this.showControlCharacters){if(" "===f){e.fillStyle=ht,e.fillText("·",c,i.y+t.baseline),e.fillStyle=l.formatting.color,c+=n,"justify"===t.alignment&&t.extraWordSpacing&&(c+=t.extraWordSpacing);continue}if("\t"===f){e.fillStyle=ht,e.fillText("→",c,i.y+t.baseline),e.fillStyle=l.formatting.color,c+=n,"justify"===t.alignment&&t.extraWordSpacing&&(c+=t.extraWordSpacing);continue}if("\n"===f){e.fillStyle=ht,e.fillText("¶",c,i.y+t.baseline),e.fillStyle=l.formatting.color,c+=n;continue}}else if("\t"===f){c+=n,"justify"===t.alignment&&t.extraWordSpacing&&(c+=t.extraWordSpacing);continue}if(o){const s=o.formatting?.color||"#0066CC";if(e.fillStyle=s,e.fillText(f,c,i.y+t.baseline),!1!==o.formatting?.underline){const o=i.y+t.baseline+2;e.beginPath(),e.strokeStyle=s,e.lineWidth=1,e.moveTo(c,o),e.lineTo(c+n,o),e.stroke()}e.fillStyle=l.formatting.color}else e.fillText(f,c,i.y+t.baseline);c+=n,"justify"===t.alignment&&t.extraWordSpacing&&/\s/.test(f)&&(c+=t.extraWordSpacing)}}}if(this.showControlCharacters&&t.endsWithNewline){e.fillStyle=ht;const o=t.runs[t.runs.length-1]?.formatting||d;e.font=this.getFontString(o);const s=e.measureText("¶").width,r=i.x+n-s,a=Math.min(c,r);e.fillText("¶",a,i.y+t.baseline)}t.endsWithPageBreak&&this.renderPageBreakIndicator(e,i,t,n),e.restore()}renderListMarker(t,e,i,n,o){const s=o||d;e.save(),e.font=this.getFontString(s),e.fillStyle=s.color,e.textBaseline="alphabetic";const r=e.measureText(t.text).width,a=i.x+t.indent-r-6,l=i.y+n;e.fillText(t.text,a,l),e.restore()}renderPageBreakIndicator(t,e,i,n){const o=e.y+i.height+8;if(t.save(),this.showControlCharacters){t.strokeStyle=ct,t.lineWidth=1,t.setLineDash([4,4]),t.beginPath(),t.moveTo(e.x,o),t.lineTo(e.x+n,o),t.stroke(),t.setLineDash([]),t.font="11px Arial";const i=t.measureText(gt).width+8,s=14,r=e.x+(n-i)/2,a=o-s/2;t.fillStyle="#FFFFFF",t.fillRect(r,a,i,s),t.strokeStyle=ct,t.lineWidth=1,t.strokeRect(r,a,i,s),t.fillStyle=ct,t.textAlign="center",t.textBaseline="middle",t.fillText(gt,e.x+n/2,o)}else t.strokeStyle="#CCCCCC",t.lineWidth=1,t.setLineDash([]),t.beginPath(),t.moveTo(e.x,o),t.lineTo(e.x+n,o),t.stroke();t.restore()}renderSubstitutionField(t,e,i,n,o=!1,s,r){let a;const l=t.field.fieldType;a="pageNumber"===l?void 0!==s?t.field.displayFormat?t.field.displayFormat.replace(/%d/g,String(s)):String(s):"{{page}}":"pageCount"===l?void 0!==r?t.field.displayFormat?t.field.displayFormat.replace(/%d/g,String(r)):String(r):"{{pages}}":`{{field: ${t.field.fieldName}}}`;const h=t.field.formatting||d;e.save(),e.font=this.getFontString(h);const c=.8*h.fontSize,g=1.2*h.fontSize,u=e.measureText(a).width,f=i.y+n.baseline,p=f-c,m="pageNumber"===l||"pageCount"===l,b=m?"#d4ebff":"#e8e8e8",x=m?"#87CEEB":"#cccccc";return e.fillStyle=h.backgroundColor||b,e.fillRect(i.x,p,u,g),h.backgroundColor||(e.strokeStyle=x,e.lineWidth=1,e.strokeRect(i.x,p,u,g)),o&&(e.strokeStyle="#0066ff",e.lineWidth=2,e.setLineDash([4,2]),e.strokeRect(i.x-1,p-1,u+2,g+2),e.setLineDash([])),e.fillStyle=h.color,e.fillText(a,i.x,f),e.restore(),i.x+u}renderEmbeddedObject(t,e,i,n,o,s,r){const a=t.object;let l=i.x,d=i.y+(n.height-a.height)/2;if(t.isAnchor){if(this.showControlCharacters){e.save(),e.fillStyle=ht,e.font="12px Arial";const t=e.measureText("⚓").width||12,o=s-t-4;e.fillText("⚓",o,i.y+n.baseline),e.restore(),this._hitTestManager.register(r,{type:"embedded-object",category:"content",bounds:{x:o,y:i.y,width:t,height:n.height},priority:dt,data:{type:"embedded-object",object:a}})}return i.x}switch(a.position){case"block":l="right"===n.alignment?s+o-a.width:"center"===n.alignment?s+(o-a.width)/2:s,d=i.y;break;case"relative":{const t=a.relativeOffset;l=s+t.x,d=i.y+t.y;break}default:l=i.x}if(a.renderedPosition={x:l,y:d},a.renderedPageIndex=r,a instanceof U||this._hitTestManager.register(r,{type:"embedded-object",category:"content",bounds:{x:l,y:d,width:a.width,height:a.height},priority:dt,data:{type:"embedded-object",object:a}}),a instanceof L){const t=a;t.reflow(e),e.save(),e.translate(l,d),t.render(e),e.restore(),this.renderRegion(t,e,r,{renderCursor:!0,renderSelection:!0,clipToBounds:!0})}else if(a instanceof U){const t=a;t.calculateLayout(e,!0);for(const i of t.rows)for(const t of i.cells)t.reflow(e);t.calculateLayout(e,!0);const i=this.document.pages[r],n=i?.getContentBounds(),o=t.id,s=this.tableContinuations.get(o);if(s&&s.sliceIndex<s.pageLayout.slices.length){const i=s.pageLayout.slices[s.sliceIndex];t.renderedPosition={x:l,y:d},t.renderedPageIndex=r,e.save(),e.translate(l,d),t.renderSlice(e,i,s.pageLayout),e.restore();const n=t.getRowsForSlice(i,s.pageLayout);this.renderTableCellText(t,n,e,r,l,d,i,s.pageLayout);let a=0;for(const t of n)a+=t.calculatedHeight;const h=s.sliceIndex===s.pageLayout.slices.length-1?"last":"middle",c=s.pageLayout.slices[s.sliceIndex].yOffset,g=s.pageLayout.headerHeight;t.setRenderedSlice(r,{x:l,y:d},a,h,s.sliceIndex,c,g),this.registerTableSliceHitTarget(t,r,{x:l,y:d},a),t.selected&&this.drawEmbeddedObjectHandles(e,t,{x:l,y:d},{width:t.width,height:a},h),s.sliceIndex+1<s.pageLayout.slices.length?this.tableContinuations.set(o,{...s,sliceIndex:s.sliceIndex+1}):this.tableContinuations.delete(o)}else if(n){const i=n.position.y+n.size.height-d;if(t.needsPageSplit(i)){const s=n.size.height,a=t.calculatePageLayout(i,s);t.renderedPosition={x:l,y:d},t.renderedPageIndex=r;const h=a.slices[0];e.save(),e.translate(l,d),t.renderSlice(e,h,a),e.restore();const c=t.getRowsForSlice(h,a);this.renderTableCellText(t,c,e,r,l,d,h,a);let g=0;for(const t of c)g+=t.calculatedHeight;const u=1===a.slices.length?"only":"first";if(t.setRenderedSlice(r,{x:l,y:d},g,u,0,0,0),this.registerTableSliceHitTarget(t,r,{x:l,y:d},g),t.selected&&this.drawEmbeddedObjectHandles(e,t,{x:l,y:d},{width:t.width,height:g},u),a.slices.length>1){this.tableContinuations.set(o,{table:t,sliceIndex:1,pageLayout:a});const e=this.document.pages[0];e&&this.emit("text-overflow",{pageId:e.id,overflowPages:[],totalPages:r+a.slices.length})}}else{t.renderedPosition={x:l,y:d},t.renderedPageIndex=r,t.updateCellRenderedPositions(),t.setRenderedSlice(r,{x:l,y:d},t.height,"only",0,0,0),this.registerTableSliceHitTarget(t,r,{x:l,y:d},t.height),e.save(),e.translate(l,d),t.render(e),e.restore();for(const i of t.rows)for(const t of i.cells)this.renderRegion(t,e,r,{renderCursor:t.editing,renderSelection:t.editing,clipToBounds:!0});t.selected&&this.drawEmbeddedObjectHandles(e,t,{x:l,y:d}),this.tableContinuations.delete(o)}}else{t.renderedPosition={x:l,y:d},t.renderedPageIndex=r,t.updateCellRenderedPositions(),t.setRenderedSlice(r,{x:l,y:d},t.height,"only",0,0,0),this.registerTableSliceHitTarget(t,r,{x:l,y:d},t.height),e.save(),e.translate(l,d),t.render(e),e.restore();for(const i of t.rows)for(const t of i.cells)this.renderRegion(t,e,r,{renderCursor:t.editing,renderSelection:t.editing,clipToBounds:!0});t.selected&&this.drawEmbeddedObjectHandles(e,t,{x:l,y:d})}}else e.save(),e.translate(l,d),a.render(e),e.restore();return!a.selected||a instanceof U||this.drawEmbeddedObjectHandles(e,a,{x:l,y:d}),"inline"===a.position?i.x+a.width+2:i.x}renderTableCellText(t,e,i,n,o,s,r,a){const l=t.getColumnPositions(),d=t.getColumnWidths();let h=0;const c=new Set;if(r.isContinuation&&a.headerRowIndices.length>0)for(const e of a.headerRowIndices){const r=t.rows[e];if(r){c.add(r.id);for(let e=0;e<r.cellCount;e++){const a=r.getCell(e);if(!a)continue;let c=0;for(let i=e;i<e+a.colSpan&&i<t.columnCount;i++)c+=d[i];a.setRenderedPosition({x:o+l[e],y:s+h}),a.renderedPageIndex=n,a.setBounds({x:l[e],y:h,width:c,height:r.calculatedHeight}),this.renderRegion(a,i,n,{renderCursor:a.editing,renderSelection:a.editing,clipToBounds:!0})}h+=r.calculatedHeight}}for(const r of e)if(!c.has(r.id)){for(let e=0;e<r.cellCount;e++){const a=r.getCell(e);if(!a)continue;let c=0;for(let i=e;i<e+a.colSpan&&i<t.columnCount;i++)c+=d[i];a.setRenderedPosition({x:o+l[e],y:s+h}),a.renderedPageIndex=n,a.setBounds({x:l[e],y:h,width:c,height:r.calculatedHeight}),this.renderRegion(a,i,n,{renderCursor:a.editing,renderSelection:a.editing,clipToBounds:!0})}h+=r.calculatedHeight}}clearTableContinuations(){this.tableContinuations.clear(),this.pageTextOffsets.clear()}hasTableContinuations(){return this.tableContinuations.size>0}getPageTextOffset(t){return this.pageTextOffsets.get(t)||0}registerTableSliceHitTarget(t,e,i,n){this._hitTestManager.register(e,{type:"embedded-object",category:"content",bounds:{x:i.x,y:i.y,width:t.width,height:n},priority:dt,data:{type:"embedded-object",object:t}})}updateResizeHandleTargets(t){this._hitTestManager.clearCategory("resize-handles"),j.log("[pc-editor:FlowingTextRenderer] updateResizeHandleTargets selectedObjects:",t.length);for(const e of t)if(e.resizable)if(e instanceof U)this.registerTableResizeHandles(e);else{const t=e.renderedPosition,i=e.renderedPageIndex;j.log("[pc-editor:FlowingTextRenderer] updateResizeHandleTargets object:",e.id,"pageIndex:",i,"pos:",t),t&&i>=0&&this.registerObjectResizeHandles(e,i,t)}}registerObjectResizeHandles(t,e,i){const n=t.getResizeHandles();for(const o of n){const n=this.getHandlePosition(o,i,t.width,t.height,12);this._hitTestManager.register(e,{type:"resize-handle",category:"resize-handles",bounds:{x:n.x,y:n.y,width:12,height:12},priority:at,data:{type:"resize-handle",handle:o,element:t}})}}registerTableResizeHandles(t){for(const e of this._hitTestManager.getPageIndices()){const i=t.getRenderedSlice(e);if(!i)continue;let n;switch(i.slicePosition){case"first":n=["nw","n","ne","w","e"];break;case"middle":n=["w","e"];break;case"last":n=["w","e","sw","s","se"];break;default:n=t.getResizeHandles().map(t=>t)}for(const o of n){const n=this.getHandlePosition(o,i.position,t.width,i.height,12);this._hitTestManager.register(e,{type:"resize-handle",category:"resize-handles",bounds:{x:n.x,y:n.y,width:12,height:12},priority:at,data:{type:"resize-handle",handle:o,element:t}})}}}updateTableDividerTargets(t){if(this._hitTestManager.clearCategory("table-dividers"),!t)return;const e=t.getRenderedPageIndices();for(const i of e){const e=t.getRenderedSlice(i);if(!e)continue;const{position:n,height:o}=e,s=t.getColumnPositions(),r=t.getColumnWidths();for(let e=0;e<s.length;e++){const a=n.x+s[e]+r[e];this._hitTestManager.register(i,{type:"table-divider",category:"table-dividers",bounds:{x:a-4,y:n.y,width:8,height:o},priority:lt,data:{type:"table-divider",table:t,dividerType:"column",index:e}})}let a=0;const l=t.rows,d="only"===e.slicePosition||"first"===e.slicePosition,h=t.headerRowCount;for(let s=0;s<l.length;s++){if(a+=l[s].calculatedHeight,d){if(a>o)continue;this._hitTestManager.register(i,{type:"table-divider",category:"table-dividers",bounds:{x:n.x,y:n.y+a-4,width:t.width,height:8},priority:lt,data:{type:"table-divider",table:t,dividerType:"row",index:s}})}else{const r=e.yOffset,d=r+o-(h>0?e.headerHeight:0);if(s<h){let o=0;for(let t=0;t<=s;t++)o+=l[t].calculatedHeight;o<=e.headerHeight&&this._hitTestManager.register(i,{type:"table-divider",category:"table-dividers",bounds:{x:n.x,y:n.y+o-4,width:t.width,height:8},priority:lt,data:{type:"table-divider",table:t,dividerType:"row",index:s}});continue}if(a<r||a>d+r)continue;const c=e.headerHeight+(a-r);if(c>o)continue;this._hitTestManager.register(i,{type:"table-divider",category:"table-dividers",bounds:{x:n.x,y:n.y+c-4,width:t.width,height:8},priority:lt,data:{type:"table-divider",table:t,dividerType:"row",index:s}})}}}}renderTableContinuationsForPage(t,e,i){for(const[n,o]of this.tableContinuations.entries()){if(o.sliceIndex>=o.pageLayout.slices.length)continue;const s=o.table,r=o.pageLayout.slices[o.sliceIndex],a=i.x,l=i.y;s.renderedPosition={x:a,y:l},s.renderedPageIndex=e,t.save(),t.translate(a,l),s.renderSlice(t,r,o.pageLayout),t.restore();const d=s.getRowsForSlice(r,o.pageLayout);this.renderTableCellText(s,d,t,e,a,l,r,o.pageLayout);let h=0;for(const t of d)h+=t.calculatedHeight;const c=o.sliceIndex===o.pageLayout.slices.length-1?"last":"middle",g=o.pageLayout.slices[o.sliceIndex].yOffset,u=o.pageLayout.headerHeight;if(s.setRenderedSlice(e,{x:a,y:l},h,c,o.sliceIndex,g,u),this.registerTableSliceHitTarget(s,e,{x:a,y:l},h),s.selected&&this.drawEmbeddedObjectHandles(t,s,{x:a,y:l},{width:s.width,height:h},c),o.sliceIndex+1<o.pageLayout.slices.length){this.tableContinuations.set(n,{...o,sliceIndex:o.sliceIndex+1});const t=this.document.pages[0];t&&this.emit("text-overflow",{pageId:t.id,overflowPages:[],totalPages:e+o.pageLayout.slices.length-o.sliceIndex})}else this.tableContinuations.delete(n)}}renderTableContinuationsAtPosition(t,e,i,n){let o=0;for(const[s,r]of this.tableContinuations.entries()){if(r.sliceIndex>=r.pageLayout.slices.length)continue;const a=r.table,l=r.pageLayout.slices[r.sliceIndex],d=i.x,h=n+o;a.renderedPosition={x:d,y:h},a.renderedPageIndex=e,t.save(),t.translate(d,h),a.renderSlice(t,l,r.pageLayout),t.restore();const c=a.getRowsForSlice(l,r.pageLayout);this.renderTableCellText(a,c,t,e,d,h,l,r.pageLayout);let g=0;for(const t of c)g+=t.calculatedHeight;o+=g;const u=r.sliceIndex===r.pageLayout.slices.length-1?"last":"middle",f=r.pageLayout.slices[r.sliceIndex].yOffset,p=r.pageLayout.headerHeight;if(a.setRenderedSlice(e,{x:d,y:h},g,u,r.sliceIndex,f,p),this.registerTableSliceHitTarget(a,e,{x:d,y:h},g),a.selected&&this.drawEmbeddedObjectHandles(t,a,{x:d,y:h},{width:a.width,height:g},u),r.sliceIndex+1<r.pageLayout.slices.length){this.tableContinuations.set(s,{...r,sliceIndex:r.sliceIndex+1});const t=this.document.pages[0];t&&this.emit("text-overflow",{pageId:t.id,overflowPages:[],totalPages:e+r.pageLayout.slices.length-r.sliceIndex})}else this.tableContinuations.delete(s)}return o}drawEmbeddedObjectHandles(t,e,i,n,o="only"){const s=n?.width??e.size.width,r=n?.height??e.size.height;if(t.save(),t.setTransform(1,0,0,1,0,0),t.strokeStyle="#0066ff",t.lineWidth=2,t.setLineDash([4,4]),t.strokeRect(i.x,i.y,s,r),t.setLineDash([]),e.resizable){let n;switch(o){case"first":n=["nw","n","ne","w","e"];break;case"middle":n=["w","e"];break;case"last":n=["w","e","sw","s","se"];break;default:n=e.getResizeHandles()}t.fillStyle="#0066ff",t.strokeStyle="#ffffff",t.lineWidth=1;for(const e of n){const n=this.getHandlePosition(e,i,s,r,8);t.fillRect(n.x,n.y,8,8),t.strokeRect(n.x,n.y,8,8)}}t.restore()}getHandlePosition(t,e,i,n,o){const s=o/2;switch(t){case"nw":return{x:e.x-s,y:e.y-s};case"n":return{x:e.x+i/2-s,y:e.y-s};case"ne":return{x:e.x+i-s,y:e.y-s};case"e":return{x:e.x+i-s,y:e.y+n/2-s};case"se":return{x:e.x+i-s,y:e.y+n-s};case"s":return{x:e.x+i/2-s,y:e.y+n-s};case"sw":return{x:e.x-s,y:e.y+n-s};case"w":return{x:e.x-s,y:e.y+n/2-s};default:return e}}getFontString(t){return`${t.fontStyle||""} ${t.fontWeight||""} ${t.fontSize}px ${t.fontFamily}`.trim()}getAlignmentOffset(t,e){switch(t.alignment){case"center":return(e-t.width)/2;case"right":return e-t.width;default:return 0}}isCursorAfterFieldOrObject(){let t;if("body"===this.getActiveSection()?t=this.document.bodyFlowingContent:"header"===this.getActiveSection()?t=this.document.headerFlowingContent:"footer"===this.getActiveSection()&&(t=this.document.footerFlowingContent),!t)return!1;const e=t.getCursorPosition();if(e<=0)return!1;if(void 0!==t.getSubstitutionFieldManager().getFieldAt(e-1))return!0;const i=t.getEmbeddedObjects();for(const[,t]of i.entries())if(t.textIndex===e-1&&t.selected)return!0;return!1}renderCursor(t,e){const i=this.getActiveFlowingContent();if(!i||!i.isCursorVisible())return;if(this.isCursorAfterFieldOrObject())return;const n=this.calculateCursorPosition(t);n&&n.pageIndex===e&&(t.save(),t.strokeStyle="#000000",t.lineWidth=1,t.beginPath(),t.moveTo(n.x,n.y),t.lineTo(n.x,n.y+n.height),t.stroke(),t.restore())}renderTextSelection(t,e,i){if(!this.selectedText)return;e.save(),e.fillStyle="rgba(0, 100, 255, 0.3)";let n=i.y;for(const o of t.lines){if(this.lineContainsSelection(o,this.selectedText)){const t=this.getSelectionBoundsInLine(o,this.selectedText),s=o.listMarker?.indent??0,r=i.width-s,a=this.getAlignmentOffset(o,r),l=i.x+s;e.fillRect(l+a+t.x,n,t.width,o.height)}n+=o.height}e.restore()}lineContainsSelection(t,e){return!(t.endIndex<=e.start||t.startIndex>=e.end)}getSelectionBoundsInLine(t,e){const i=Math.max(e.start,t.startIndex),n=Math.min(e.end,t.endIndex),o=this.getXPositionForTextIndex(t,i);return{x:o,width:this.getXPositionForTextIndex(t,n)-o}}getTextIndexAtPoint(t,e){const i=this.document.pages[0];if(!i)return null;const n=this.flowedPages.get(i.id);if(!n||0===n.length)return null;const o=this.document.getPage(e);if(!o)return null;const s=this.document.pages.findIndex(t=>t.id===e);if(s<0||s>=n.length)return null;const r=n[s];if(!r||0===r.lines.length)return null;const a=o.getContentBounds(),l=t.y-a.position.y,d=t.x-a.position.x,h=a.size.width;if(l<0&&r.lines.length>0)return r.lines[0].startIndex;let c=0;for(let t=0;t<r.lines.length;t++){const e=r.lines[t];if(l>=c&&l<c+e.height){const t=this.getAlignmentOffset(e,h);return this.getTextIndexInLine(e,d-t)}c+=e.height}if(r.lines.length>0){return r.lines[r.lines.length-1].endIndex}return null}getTextIndexInLine(t,e){const i=document.createElement("canvas").getContext("2d");if(!i)return t.startIndex;const n=new Map;t.substitutionFields&&t.substitutionFields.forEach(t=>n.set(t.textIndex,t));const o=new Map;t.embeddedObjects&&t.embeddedObjects.forEach(t=>o.set(t.textIndex,t));let s=0;const r=t.extraWordSpacing||0;for(const a of t.runs){i.font=this.getFontString(a.formatting);for(let t=0;t<a.text.length;t++){const l=a.startIndex+t,d=a.text[t];let h;const c=n.get(l);if(c){if(h=c.width,e>=s&&e<s+h)return l+1;s+=h,r>0&&/\s/.test(d)&&(s+=r)}else{if(o.has(l)){h=o.get(l).object.width+2}else h=""!==d?"\t"===d?i.measureText(" ").width:i.measureText(d).width:0;if(e>=s&&e<s+h)return e<s+h/2?l:l+1;s+=h,r>0&&/\s/.test(d)&&(s+=r)}}}return t.endIndex}getInlineElementAtPoint(t,e,i,n){if(t.embeddedObjects&&void 0!==i&&void 0!==n)for(const o of t.embeddedObjects){const s=o.object,r=o.x+n,a=i+(t.height-s.height)/2;if(s.containsPoint(e,{x:r,y:a}))return{type:"embedded-object",object:s,textIndex:o.textIndex}}return null}getEmbeddedObjectAtPoint(t,e,i,n){if(!t.embeddedObjects)return null;for(const o of t.embeddedObjects){const s=o.object,r=o.x+n,a=i+(t.height-s.height)/2;if(s.containsPoint(e,{x:r,y:a}))return s}return null}getSubstitutionFieldAtPoint(t,e,i,n){if(!t.substitutionFields)return null;for(const o of t.substitutionFields)if(e.x>=o.x+n&&e.x<=o.x+n+o.width&&e.y>=i&&e.y<=i+t.height)return o;return null}getXPositionForTextIndex(t,e){if(e<=t.startIndex)return 0;if(e>=t.endIndex)return"justify"===t.alignment&&t.extraWordSpacing?t.width+this.countWordGapsUpTo(t,t.endIndex)*t.extraWordSpacing:t.width;const i=document.createElement("canvas").getContext("2d");if(!i)return 0;const n=new Map;t.substitutionFields&&t.substitutionFields.forEach(t=>n.set(t.textIndex,t));const o=new Map;t.embeddedObjects&&t.embeddedObjects.forEach(t=>o.set(t.textIndex,t));let s=0;for(const r of t.runs){i.font=this.getFontString(r.formatting);for(let a=0;a<r.text.length;a++){const l=r.startIndex+a;if(l>=e)return s;const d=r.text[a];let h;const c=n.get(l);if(c)h=c.width;else if(o.has(l)){h=o.get(l).object.width+2}else h=""!==d?"\t"===d?i.measureText(" ").width:i.measureText(d).width:0;s+=h,"justify"===t.alignment&&t.extraWordSpacing&&/\s/.test(d)&&(s+=t.extraWordSpacing)}}return s}countWordGapsUpTo(t,e){let i=0,n=!1;for(let o=t.startIndex;o<Math.min(e,t.endIndex);o++){const e=o-t.startIndex;if(e>=t.text.length)break;const s=t.text[e],r=/\s/.test(s);r||n?r&&n&&(i++,n=!1):n=!0}return i}moveCursorVertical(t,e){if("header"===this.getActiveSection())return this.moveCursorVerticalInSection(t,this.headerFlowedPage,e,"header");if("footer"===this.getActiveSection())return this.moveCursorVerticalInSection(t,this.footerFlowedPage,e,"footer");const i=this.flowedPages.get(e);if(!i||0===i.length)return null;const n=this.document.getPage(e);if(!n)return null;const o=this.document.bodyFlowingContent.getCursorPosition(),s=this.findCursorLocationInBody(o);if(!s)return null;const r=s.lineIndex,a=s.pageIndex,l=i[a];if(!l)return null;const d=r+t,h=n.getContentBounds().size.width,c=this.calculateCursorRelativeX();if(d<0){if(a>0){const t=i[a-1];if(t&&t.lines.length>0){const e=t.lines.length-1,i=t.lines[e];return this.getTextIndexAtVisualX(i,c,h)}}return i[0].lines.length>0?i[0].lines[0].startIndex:null}if(d>=l.lines.length){if(a<i.length-1){const t=i[a+1];if(t&&t.lines.length>0){const e=t.lines[0];return this.getTextIndexAtVisualX(e,c,h)}}const t=i[i.length-1];if(t&&t.lines.length>0){return t.lines[t.lines.length-1].endIndex}return null}const g=l.lines[d];return this.getTextIndexAtVisualX(g,c,h)}moveCursorVerticalInSection(t,e,i,n){if(!e||0===e.lines.length)return null;const o=this.document.pages[0];if(!o)return null;const s=("header"===n?o.getHeaderBounds():o.getFooterBounds()).size.width,r=("header"===n?this.document.headerFlowingContent:this.document.footerFlowingContent).getCursorPosition(),a=this.findCursorLocationInSection(r,n),l=(a?a.lineIndex:0)+t;if(l<0)return e.lines[0].startIndex;if(l>=e.lines.length){return e.lines[e.lines.length-1].endIndex}const d=e.lines[l],h=this.calculateCursorRelativeXForSection(n);return this.getTextIndexAtVisualX(d,h,s)}calculateCursorRelativeXForSection(t){const e=("header"===t?this.document.headerFlowingContent:this.document.footerFlowingContent).getCursorPosition(),i=this.findCursorLocationInSection(e,t);if(!i)return 0;const n=document.createElement("canvas").getContext("2d");if(!n)return 0;const o=this.document.pages[0];if(!o)return 0;const s=("header"===t?o.getHeaderBounds():o.getFooterBounds()).size.width;return P.getAlignmentOffset(i.line,s)+P.getXPositionForTextIndex(i.line,e,n)}calculateCursorRelativeX(){const t=this.document.pages[0];if(!t)return 0;const e=this.document.bodyFlowingContent.getCursorPosition(),i=this.findCursorLocationInBody(e);if(!i)return 0;const n=document.createElement("canvas").getContext("2d");if(!n)return 0;const o=t.getContentBounds().size.width;return P.getAlignmentOffset(i.line,o)+P.getXPositionForTextIndex(i.line,e,n)}getTextIndexAtVisualX(t,e,i){const n=e-this.getAlignmentOffset(t,i);return this.getTextIndexInLine(t,n)}setTextSelection(t,e){this.selectedText={start:Math.min(t,e),end:Math.max(t,e)},this.emit("selection-changed",this.selectedText)}clearTextSelection(){this.selectedText=null,this.emit("selection-cleared")}getFlowedPagesForPage(t){return this.flowedPages.get(t)||[]}getFlowedPagesSnapshot(){const t=this.document.pages[0],e=t&&this.flowedPages.get(t.id)||[],i=this.document.bodyFlowingContent?.getAllHyperlinks().map(t=>({url:t.url,startIndex:t.startIndex,endIndex:t.endIndex})),n=this.document.headerFlowingContent?.getAllHyperlinks().map(t=>({url:t.url,startIndex:t.startIndex,endIndex:t.endIndex})),o=this.document.footerFlowingContent?.getAllHyperlinks().map(t=>({url:t.url,startIndex:t.startIndex,endIndex:t.endIndex}));return{body:e,header:this.headerFlowedPage,footer:this.footerFlowedPage,bodyHyperlinks:i?.length?i:void 0,headerHyperlinks:n?.length?n:void 0,footerHyperlinks:o?.length?o:void 0}}renderRepeatingSectionIndicators(t,e,i,n,o,s,r=null){for(const a of t)this.renderSectionIndicator(a,e,i,n,o,s,a.id===r)}renderSectionIndicator(t,e,i,n,o,s,r=!1){const a=this.findLineYForTextIndex(o,t.startIndex,n),l=this.findLineYForTextIndex(o,t.endIndex,n);if(!(t.startIndex<o.endIndex&&t.endIndex>o.startIndex))return;const d=null!==a,h=null!==l,c=t.startIndex<o.startIndex,g=t.endIndex>o.endIndex;i.save(),i.strokeStyle=ut,i.fillStyle=ut,i.lineWidth=1;const u=s.x+5,f=u+16;if(d){const t=a.y;i.setLineDash(ft),i.beginPath(),i.moveTo(n.x,t),i.lineTo(n.x+n.width,t),i.stroke(),i.setLineDash([]),i.beginPath(),i.moveTo(u+32,t),i.lineTo(n.x,t),i.stroke()}else if(c){const t=n.y;i.setLineDash(ft),i.beginPath(),i.moveTo(n.x,t),i.lineTo(n.x+n.width,t),i.stroke(),i.setLineDash([]),i.beginPath(),i.moveTo(f,t),i.lineTo(n.x,t),i.stroke()}if(h){const t=l.y;i.setLineDash(ft),i.beginPath(),i.moveTo(n.x,t),i.lineTo(n.x+n.width,t),i.stroke(),i.setLineDash([]),i.beginPath(),i.moveTo(f,t),i.lineTo(n.x,t),i.stroke()}else if(g){const t=n.y+n.height;i.setLineDash(ft),i.beginPath(),i.moveTo(n.x,t),i.lineTo(n.x+n.width,t),i.stroke(),i.setLineDash([]),i.beginPath(),i.moveTo(f,t),i.lineTo(n.x,t),i.stroke()}let p,m;if(p=d?a.y:n.y,m=h?l.y:g?n.y+n.height:p,m>p&&(i.beginPath(),i.moveTo(f,p),i.lineTo(f,m),i.stroke()),d){const t=a.y;this.drawLoopLabel(i,u,t-10,"Loop",r)}t.visualState={startPageIndex:d?e:-1,startY:d?a.y:0,endPageIndex:h?e:-1,endY:h?l.y:0,spansMultiplePages:!d||!h},i.restore()}drawLoopLabel(t,e,i,n,o=!1){t.save(),t.font="10px Arial";const s=t.measureText(n).width+8;t.beginPath(),this.roundRect(t,e,i,s,18,4),o?(t.fillStyle=ut,t.fill(),t.fillStyle="#ffffff"):(t.fillStyle="#ffffff",t.fill(),t.strokeStyle=ut,t.lineWidth=1.5,t.stroke(),t.fillStyle=ut),t.textBaseline="middle",t.fillText(n,e+4,i+9),t.restore()}roundRect(t,e,i,n,o,s){t.moveTo(e+s,i),t.lineTo(e+n-s,i),t.quadraticCurveTo(e+n,i,e+n,i+s),t.lineTo(e+n,i+o-s),t.quadraticCurveTo(e+n,i+o,e+n-s,i+o),t.lineTo(e+s,i+o),t.quadraticCurveTo(e,i+o,e,i+o-s),t.lineTo(e,i+s),t.quadraticCurveTo(e,i,e+s,i),t.closePath()}findLineYForTextIndex(t,e,i){let n=i.y;for(let i=0;i<t.lines.length;i++){const o=t.lines[i];if(e>=o.startIndex&&e<=o.endIndex)return{y:n,lineIndex:i};if(e===o.startIndex)return{y:n,lineIndex:i};n+=o.height}if(t.lines.length>0){if(e===t.lines[t.lines.length-1].endIndex+1)return{y:n,lineIndex:t.lines.length-1}}return null}sectionSpansPage(t,e){if(0===e.lines.length)return!1;const i=e.startIndex,n=e.endIndex;return t.startIndex<i&&t.endIndex>n}getRepeatingSectionAtPoint(t,e,i,n,o,s){const r=n.x+5,a=r+16;for(const i of e){const e=this.findLineYForTextIndex(s,i.startIndex,o),n=this.findLineYForTextIndex(s,i.endIndex,o),l=this.sectionSpansPage(i,s);if(!e&&!n&&!l)continue;if(e){const n=e.y-10,o=18;if(t.x>=r&&t.x<=r+32&&t.y>=n&&t.y<=n+o)return i}let d,h;if(d=e?e.y:o.y,n)h=n.y;else{if(!l)continue;h=o.y+s.height}if(Math.abs(t.x-a)<=10&&t.y>=d&&t.y<=h)return i}return null}renderConditionalSectionIndicators(t,e,i,n,o,s,r=null){for(const a of t)this.renderConditionalIndicator(a,e,i,n,o,s,a.id===r)}renderConditionalIndicator(t,e,i,n,o,s,r=!1){const a=this.findLineYForTextIndex(o,t.startIndex,n),l=this.findLineYForTextIndex(o,t.endIndex,n);if(!(t.startIndex<o.endIndex&&t.endIndex>o.startIndex))return;const d=null!==a,h=null!==l,c=t.startIndex<o.startIndex,g=t.endIndex>o.endIndex;i.save(),i.strokeStyle=pt,i.fillStyle=pt,i.lineWidth=1;const u=n.x+n.width+5,f=u+11;if(d){const t=a.y;i.setLineDash(mt),i.beginPath(),i.moveTo(n.x,t),i.lineTo(n.x+n.width,t),i.stroke(),i.setLineDash([]),i.beginPath(),i.moveTo(n.x+n.width,t),i.lineTo(u,t),i.stroke()}else if(c){const t=n.y;i.setLineDash(mt),i.beginPath(),i.moveTo(n.x,t),i.lineTo(n.x+n.width,t),i.stroke(),i.setLineDash([]),i.beginPath(),i.moveTo(f,t),i.lineTo(n.x+n.width,t),i.stroke()}if(h){const t=l.y;i.setLineDash(mt),i.beginPath(),i.moveTo(n.x,t),i.lineTo(n.x+n.width,t),i.stroke(),i.setLineDash([]),i.beginPath(),i.moveTo(f,t),i.lineTo(n.x+n.width,t),i.stroke()}else if(g){const t=n.y+n.height;i.setLineDash(mt),i.beginPath(),i.moveTo(n.x,t),i.lineTo(n.x+n.width,t),i.stroke(),i.setLineDash([]),i.beginPath(),i.moveTo(f,t),i.lineTo(n.x+n.width,t),i.stroke()}let p,m;if(p=d?a.y:n.y,m=h?l.y:g?n.y+n.height:p,m>p&&(i.beginPath(),i.moveTo(f,p),i.lineTo(f,m),i.stroke()),d){const t=a.y;this.drawCondLabel(i,u,t-10,"If",r)}t.visualState={startPageIndex:d?e:-1,startY:d?a.y:0,endPageIndex:h?e:-1,endY:h?l.y:0,spansMultiplePages:!d||!h},i.restore()}drawCondLabel(t,e,i,n,o=!1){t.save(),t.font="10px Arial";const s=t.measureText(n).width+8;t.beginPath(),this.roundRect(t,e,i,s,18,4),o?(t.fillStyle=pt,t.fill(),t.fillStyle="#ffffff"):(t.fillStyle="#ffffff",t.fill(),t.strokeStyle=pt,t.lineWidth=1.5,t.stroke(),t.fillStyle=pt),t.textBaseline="middle",t.fillText(n,e+4,i+9),t.restore()}getConditionalSectionAtPoint(t,e,i,n,o,s){const r=o.x+o.width+5,a=r+11;for(const i of e){const e=this.findLineYForTextIndex(s,i.startIndex,o),n=this.findLineYForTextIndex(s,i.endIndex,o),l=i.startIndex<s.startIndex&&i.endIndex>s.endIndex;if(!e&&!n&&!l)continue;if(e){const n=e.y-10,o=18;if(t.x>=r&&t.x<=r+22&&t.y>=n&&t.y<=n+o)return i}let d,h;if(d=e?e.y:o.y,n)h=n.y;else{if(!l)continue;h=o.y+s.height}if(Math.abs(t.x-a)<=10&&t.y>=d&&t.y<=h)return i}return null}destroy(){this.removeAllListeners()}}class xt extends r{constructor(t,e,i){super(),this.canvases=new Map,this.contexts=new Map,this.zoomLevel=1,this.selectedElements=new Set,this.isDragging=!1,this.dragStart=null,this.isResizing=!1,this.wasResizing=!1,this.resizeHandle=null,this.resizeStartSize=null,this.resizeStartPos=null,this.resizingElementId=null,this.showMargins=!0,this.isHandlingOverflow=!1,this.isSelectingText=!1,this.textSelectionStartPageId=null,this.selectedSectionId=null,this.selectedConditionalSectionId=null,this._activeSection="body",this.lastClickTime=0,this.lastClickPosition=null,this.clickCount=0,this.editingTextBox=null,this._editingTextBoxPageId=null,this._focusedControl=null,this._cursorSuspended=!1,this.isSelectingTextInTextBox=!1,this.tableResizeHandler=new $,this.isSelectingTableCells=!1,this.tableCellSelectionPending=!1,this.tableCellSelectionStart=null,this.tableCellSelectionStartPoint=null,this.tableCellSelectionTable=null,this.isSelectingTextInTableCell=!1,this.isDraggingRelativeObject=!1,this.relativeObjectDragPending=!1,this.relativeObjectDragStart=null,this.relativeObjectBeingDragged=null,this.relativeObjectDragStartOffset=null,this.handleFocusedCursorBlink=()=>{this.render()},this.container=t,this.document=e,this.options=i,this.flowingTextRenderer=new bt(e),this.regionManager=new J,this.setupFlowingTextListeners(),this.initializeRegions()}initializeRegions(){const t=new Z(this.document.bodyFlowingContent,t=>this.document.pages[t]||null);this.regionManager.setBodyRegion(t);const e=new Q(this.document.headerFlowingContent,t=>this.document.pages[t]||null);this.regionManager.setHeaderRegion(e);const i=new tt(this.document.footerFlowingContent,t=>this.document.pages[t]||null);this.regionManager.setFooterRegion(i)}initialize(){this.createCanvases(),this.setupEventListeners(),this.setupScrollListener(),this.updateCanvasScale(),this.setFocus(this.document.bodyFlowingContent),this.render()}createCanvases(){this.document.pages.forEach(t=>{const e=document.createElement("canvas");e.id=`canvas-${t.id}`,e.style.display="block",e.style.margin="20px auto",e.style.boxShadow="0 2px 8px rgba(0,0,0,0.1)";const i=t.getPageDimensions();e.width=i.width,e.height=i.height,this.container.appendChild(e),this.canvases.set(t.id,e);const n=e.getContext("2d");n&&this.contexts.set(t.id,n)})}setDocument(t){this.clearCanvases(),this.document=t,this.flowingTextRenderer.destroy(),this.flowingTextRenderer=new bt(t),this.setupFlowingTextListeners(),this.initializeRegions(),this.createCanvases(),this.setupEventListeners(),this.updateCanvasScale(),this._activeSection="body",this.selectedElements.clear(),this.editingTextBox=null,this._editingTextBoxPageId=null,this._focusedControl=null,this.setFocus(this.document.bodyFlowingContent),this.render()}clearCanvases(){this.canvases.forEach(t=>t.remove()),this.canvases.clear(),this.contexts.clear()}updateCanvasSizes(){this.document.pages.forEach(t=>{const e=this.canvases.get(t.id);if(!e)return;const i=t.getPageDimensions();e.width===i.width&&e.height===i.height||(e.width=i.width,e.height=i.height)}),this.updateCanvasScale()}render(){this.document.pages.forEach(t=>{const e=this.contexts.get(t.id);if(!e)return;const i=this.canvases.get(t.id);if(!i)return;e.clearRect(0,0,i.width,i.height),e.fillStyle="white",e.fillRect(0,0,i.width,i.height),this.options.showGrid&&this.drawGrid(e,i.width,i.height);const n=this.document.pages.findIndex(e=>e.id===t.id);0===n&&this.flowingTextRenderer.hitTestManager.clearCategory("content");const o=this.regionManager.getHeaderRegion();this.flowingTextRenderer.renderHeaderText(t,e,"header"===this._activeSection,o??void 0,n);const s=t.getContentBounds(),r={x:s.position.x,y:s.position.y,width:s.size.width,height:s.size.height};this.flowingTextRenderer.renderPageFlowingText(t,e,r);const a=this.regionManager.getFooterRegion();this.flowingTextRenderer.renderFooterText(t,e,"footer"===this._activeSection,a??void 0,n);const l=this.document.bodyFlowingContent,d=l?.getRepeatingSections()??[];if(d.length>0){const i=this.flowingTextRenderer.getFlowedPagesForPage(this.document.pages[0].id);if(i&&i[n]){const o=t.getPageDimensions(),s={x:0,y:0,width:o.width,height:o.height};this.flowingTextRenderer.renderRepeatingSectionIndicators(d,n,e,r,i[n],s,this.selectedSectionId)}}const h=l?.getConditionalSections()??[];if(h.length>0){const i=this.flowingTextRenderer.getFlowedPagesForPage(this.document.pages[0].id);if(i&&i[n]){const o=t.getPageDimensions(),s={x:0,y:0,width:o.width,height:o.height};this.flowingTextRenderer.renderConditionalSectionIndicators(h,n,e,r,i[n],s,this.selectedConditionalSectionId)}}this.renderPageElements(t,e),this.drawInactiveSectionOverlays(e,t),this.drawMarginLines(e,t),this.renderSelectionMarks(t,e)})}drawInactiveSectionOverlays(t,e){t.save(),t.fillStyle="rgba(255, 255, 255, 0.6)";const i=e.getPageDimensions(),n=e.getContentBounds(),o=n.position.y,s=n.position.y+n.size.height,r=i.height-s;"header"!==this._activeSection&&t.fillRect(0,0,i.width,o),"body"!==this._activeSection&&t.fillRect(0,o,i.width,n.size.height),"footer"!==this._activeSection&&t.fillRect(0,s,i.width,r),t.restore()}drawGrid(t,e,i){t.save(),t.strokeStyle="#e0e0e0",t.lineWidth=.5;const n=this.options.gridSize*this.zoomLevel;for(let o=0;o<=e;o+=n)t.beginPath(),t.moveTo(o,0),t.lineTo(o,i),t.stroke();for(let o=0;o<=i;o+=n)t.beginPath(),t.moveTo(0,o),t.lineTo(e,o),t.stroke();t.restore()}renderPageElements(t,e){}renderSelectionMarks(t,e){const i=this.document.pages.indexOf(t),n=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const t of n){const n=t.getEmbeddedObjects();for(const[,t]of n.entries())t instanceof U||t.selected&&!t.locked&&t.renderedPosition&&t.renderedPageIndex===i&&this.drawBaseEmbeddedObjectResizeHandles(e,t)}}drawBaseEmbeddedObjectResizeHandles(t,e){if(!e.renderedPosition)return;const i={x:e.renderedPosition.x,y:e.renderedPosition.y,width:e.width,height:e.height},n=this.getResizeHandles(i);t.save(),t.fillStyle="#0066ff",t.strokeStyle="#ffffff",t.lineWidth=1,Object.entries(n).forEach(([e,i])=>{t.fillRect(i.x-4,i.y-4,8,8),t.strokeRect(i.x-4,i.y-4,8,8)}),t.restore()}getResizeHandles(t){return{nw:{x:t.x,y:t.y},n:{x:t.x+t.width/2,y:t.y},ne:{x:t.x+t.width,y:t.y},e:{x:t.x+t.width,y:t.y+t.height/2},se:{x:t.x+t.width,y:t.y+t.height},s:{x:t.x+t.width/2,y:t.y+t.height},sw:{x:t.x,y:t.y+t.height},w:{x:t.x,y:t.y+t.height/2}}}setupEventListeners(){this.canvases.forEach((t,e)=>{t.addEventListener("mousedown",t=>this.handleMouseDown(t,e)),t.addEventListener("mousemove",t=>this.handleMouseMove(t,e)),t.addEventListener("mouseup",t=>this.handleMouseUp(t,e)),t.addEventListener("mouseleave",t=>this.handleMouseLeave(t,e)),t.addEventListener("click",t=>this.handleClick(t,e))})}handleMouseDown(t,e){const i=this.getMousePosition(t),n=this.getResizeHandleAt(i,e);if(n){this.isResizing=!0,this.resizeHandle=n.handle,this.dragStart=i;const o=this.getSelectedElementAt(e);return o&&o.renderedPosition&&(this.resizeStartSize={width:o.width,height:o.height},this.resizeStartPos={...o.renderedPosition},this.resizingElementId=o.id),void t.preventDefault()}const o=this.getTableResizeHandleAt(i,e);if(o&&o.handleInfo){const{table:e,handleInfo:i,tablePosition:n}=o;return this.tableResizeHandler.startResize(e,i,n),void t.preventDefault()}if(this._focusedControl instanceof U){const n=this._focusedControl,o=this.document.pages.findIndex(t=>t.id===e),s=n.getRenderedSlice(o),r=s?.position||(n.renderedPageIndex===o?n.renderedPosition:null),a=s?.height||n.height;if(r&&i.x>=r.x&&i.x<=r.x+n.width&&i.y>=r.y&&i.y<=r.y+a&&r){const a={x:i.x-r.x,y:i.y-r.y};if(s&&("middle"===s.slicePosition||"last"===s.slicePosition)){const t=s.headerHeight;a.y>=t&&(a.y=s.yOffset+(a.y-t))}const l=n.getCellAtPoint(a);if(l){const s=this.contexts.get(e);if(t.shiftKey&&n.focusedCell)return n.selectRange({start:n.focusedCell,end:l}),this.render(),this.emit("table-cell-selection-changed",{table:n}),void t.preventDefault();if(n.focusedCell&&n.focusedCell.row===l.row&&n.focusedCell.col===l.col){const e=n.getCell(l.row,l.col);if(e&&s&&o>=0){const r=e.flowingContent;t.shiftKey?(r.hasSelectionAnchor()||r.setSelectionAnchor(),this.flowingTextRenderer.handleRegionClick(e,i,o,s)):(r.clearSelection(),this.flowingTextRenderer.handleRegionClick(e,i,o,s),r.setSelectionAnchor()),this.isSelectingTextInTableCell=!0,this.tableCellSelectionTable=n,this.emit("tablecell-cursor-changed",{table:n,cell:e,cursorPosition:r.getCursorPosition()})}}else{this.tableCellSelectionPending=!0,this.tableCellSelectionStart=l,this.tableCellSelectionStartPoint={...i},this.tableCellSelectionTable=n,n.clearSelection(),n.focusCell(l.row,l.col);const t=n.getCell(l.row,l.col);t&&s&&o>=0&&(this.flowingTextRenderer.handleRegionClick(t,i,o,s),this.emit("tablecell-cursor-changed",{table:n,cell:t,cursorPosition:t.flowingContent.getCursorPosition()}))}return this.render(),void t.preventDefault()}}}if(this.editingTextBox&&this._editingTextBoxPageId===e){const n=this.editingTextBox,o=this.document.pages.findIndex(t=>t.id===e),s=this.contexts.get(e);if(s&&o>=0&&n.containsPointInRegion(i,o)){const e=n.flowingContent;return t.shiftKey?(e.hasSelectionAnchor()||e.setSelectionAnchor(),this.flowingTextRenderer.handleRegionClick(n,i,o,s)):(e.clearSelection(),this.flowingTextRenderer.handleRegionClick(n,i,o,s),e.setSelectionAnchor()),this.isSelectingTextInTextBox=!0,this.render(),void t.preventDefault()}}const s=this.document.pages.findIndex(t=>t.id===e),r=this.flowingTextRenderer.hitTestManager.queryByType(s,i,"embedded-object");if(r&&"embedded-object"===r.data.type){const t=r.data.object,e=this.getSectionForEmbeddedObject(t);return e&&e!==this._activeSection&&this.setActiveSection(e),void("relative"===t.position&&(this.relativeObjectDragPending=!0,this.relativeObjectDragStart={...i},this.relativeObjectBeingDragged=t,this.relativeObjectDragStartOffset={...t.relativeOffset}))}const a=this.getFlowingContentForActiveSection();if(a){const n=this.getRegionForActiveSection(),o=this.contexts.get(e),s=this.document.pages.findIndex(t=>t.id===e);if(n&&o&&s>=0)if(t.shiftKey){a.hasSelectionAnchor()||a.setSelectionAnchor();if(this.flowingTextRenderer.handleRegionClick(n,i,s,o))return this.clearSelection(),this.emit("text-selection-changed",{selection:a.getSelection(),section:this._activeSection}),this.isSelectingText=!0,this.textSelectionStartPageId=e,this.render(),void t.preventDefault()}else{const r=this.flowingTextRenderer.handleRegionClick(n,i,s,o);if(r)return this.clearSelection(),a.clearSelection(),a.setSelectionAnchor(r.textIndex),this.isSelectingText=!0,this.textSelectionStartPageId=e,this.render(),void t.preventDefault()}}this.isDragging=!0,this.dragStart=i}handleMouseMove(t,e){const i=this.getMousePosition(t),n=this.getViewportMousePosition(t);if(this.emit("mouse-move",{x:n.x,y:n.y}),this.relativeObjectDragPending&&this.relativeObjectDragStart&&this.relativeObjectBeingDragged){Math.sqrt(Math.pow(i.x-this.relativeObjectDragStart.x,2)+Math.pow(i.y-this.relativeObjectDragStart.y,2))>=xt.RELATIVE_DRAG_THRESHOLD&&(this.relativeObjectDragPending=!1,this.isDraggingRelativeObject=!0)}if(this.isDraggingRelativeObject&&this.relativeObjectBeingDragged&&this.relativeObjectDragStart&&this.relativeObjectDragStartOffset){const e=i.x-this.relativeObjectDragStart.x,n=i.y-this.relativeObjectDragStart.y;return this.relativeObjectBeingDragged.relativeOffset={x:this.relativeObjectDragStartOffset.x+e,y:this.relativeObjectDragStartOffset.y+n},this.render(),void t.preventDefault()}if(this.isSelectingTextInTextBox&&this.editingTextBox&&this._editingTextBoxPageId===e){const n=this.editingTextBox,o=this.document.pages.findIndex(t=>t.id===e),s=this.contexts.get(e);return s&&o>=0&&(this.flowingTextRenderer.handleRegionClick(n,i,o,s),this.render()),void t.preventDefault()}if(this.isSelectingTextInTableCell&&this.tableCellSelectionTable){const n=this.tableCellSelectionTable;if(n.focusedCell){const t=n.getCell(n.focusedCell.row,n.focusedCell.col);if(t){const n=this.document.pages.findIndex(t=>t.id===e),o=this.contexts.get(e);o&&n>=0&&(this.flowingTextRenderer.handleRegionClick(t,i,n,o),this.render())}}return void t.preventDefault()}if(this.isSelectingText&&this.textSelectionStartPageId){const n=this.getRegionForActiveSection(),o=this.contexts.get(e),s=this.document.pages.findIndex(t=>t.id===e);if(n&&o&&s>=0){this.flowingTextRenderer.handleRegionClick(n,i,s,o)&&this.render()}return void t.preventDefault()}if(this.tableResizeHandler.isResizing)return this.tableResizeHandler.updateResize(i)&&this.render(),void t.preventDefault();if(this.tableCellSelectionPending&&this.tableCellSelectionStartPoint&&this.tableCellSelectionTable){const e=i.x-this.tableCellSelectionStartPoint.x,n=i.y-this.tableCellSelectionStartPoint.y;if(!(Math.sqrt(e*e+n*n)>=xt.CELL_SELECTION_THRESHOLD))return void t.preventDefault();this.tableCellSelectionPending=!1,this.isSelectingTableCells=!0}if(this.isSelectingTableCells&&this.tableCellSelectionStart&&this.tableCellSelectionTable){const n=this.tableCellSelectionTable,o=this.document.pages.findIndex(t=>t.id===e),s=n.getRenderedSlice(o),r=s?.position||(n.renderedPageIndex===o?n.renderedPosition:null),a=s?.height||n.height;if(r){if(i.x>=r.x&&i.x<=r.x+n.width&&i.y>=r.y&&i.y<=r.y+a){const t={x:i.x-r.x,y:i.y-r.y};if(s&&("middle"===s.slicePosition||"last"===s.slicePosition)){const e=s.headerHeight;t.y>=e&&(t.y=s.yOffset+(t.y-e))}const e=n.getCellAtPoint(t);e&&(n.selectRange({start:this.tableCellSelectionStart,end:e}),this.render(),this.emit("table-cell-selection-changed",{table:n}))}}return void t.preventDefault()}if(this.isResizing&&this.dragStart&&this.resizeHandle){const t=i.x-this.dragStart.x,n=i.y-this.dragStart.y,o=this.getSelectedElementAt(e);if(o&&this.resizeStartSize&&this.resizeStartPos){const e=this.calculateNewSize(this.resizeHandle,this.resizeStartSize,this.resizeStartPos,t,n);if(e.size.width>20&&e.size.height>20){const t=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent];for(const i of t)if(i){const t=i.getEmbeddedObjectManager().findById(o.id);if(t){t.object.size={width:e.size.width,height:e.size.height};break}}}}return void this.render()}this.isDragging&&this.dragStart&&(this.dragStart=i,this.render()),this.updateCursor(i,e)}handleMouseUp(t,e){if(this.isSelectingTextInTextBox&&(this.isSelectingTextInTextBox=!1),this.isSelectingTextInTableCell&&(this.isSelectingTextInTableCell=!1),this.isSelectingText&&(this.isSelectingText=!1,this.textSelectionStartPageId=null),this.tableResizeHandler.isResizing&&this.tableResizeHandler.endResize(),(this.isSelectingTableCells||this.tableCellSelectionPending)&&(this.isSelectingTableCells=!1,this.tableCellSelectionPending=!1,this.tableCellSelectionStart=null,this.tableCellSelectionStartPoint=null,this.tableCellSelectionTable=null),(this.isDraggingRelativeObject||this.relativeObjectDragPending)&&(this.isDraggingRelativeObject&&(this.wasResizing=!0,this.emit("selection-change",{selectedElements:Array.from(this.selectedElements)})),this.isDraggingRelativeObject=!1,this.relativeObjectDragPending=!1,this.relativeObjectDragStart=null,this.relativeObjectBeingDragged=null,this.relativeObjectDragStartOffset=null),this.isDragging=!1,this.isResizing&&this.resizingElementId&&this.resizeStartSize){this.wasResizing=!0;const t=this.findEmbeddedObjectById(this.resizingElementId);if(t){const e={width:t.size.width,height:t.size.height};e.width===this.resizeStartSize.width&&e.height===this.resizeStartSize.height||this.emit("object-resized",{object:t,previousSize:this.resizeStartSize,newSize:e})}this.render(),this.updateResizeHandleHitTargets()}this.isResizing=!1,this.dragStart=null,this.resizeHandle=null,this.resizeStartSize=null,this.resizeStartPos=null,this.resizingElementId=null}handleMouseLeave(t,e){this.emit("mouse-leave"),this.isSelectingTextInTextBox&&(this.isSelectingTextInTextBox=!1),this.isSelectingTextInTableCell&&(this.isSelectingTextInTableCell=!1),this.isSelectingText&&(this.isSelectingText=!1,this.textSelectionStartPageId=null),this.tableResizeHandler.isResizing&&this.tableResizeHandler.cancelResize(),(this.isSelectingTableCells||this.tableCellSelectionPending)&&(this.isSelectingTableCells=!1,this.tableCellSelectionPending=!1,this.tableCellSelectionStart=null,this.tableCellSelectionStartPoint=null,this.tableCellSelectionTable=null),(this.isDraggingRelativeObject||this.relativeObjectDragPending)&&(this.isDraggingRelativeObject=!1,this.relativeObjectDragPending=!1,this.relativeObjectDragStart=null,this.relativeObjectBeingDragged=null,this.relativeObjectDragStartOffset=null),this.isDragging=!1,this.isResizing=!1,this.dragStart=null,this.resizeHandle=null,this.resizeStartSize=null,this.resizeStartPos=null;const i=this.canvases.get(e);i&&(i.style.cursor="default")}handleClick(t,e){if(this.wasResizing)return void(this.wasResizing=!1);if(this.isResizing)return;const i=this.getMousePosition(t),n=Date.now();let o=1;if(this.lastClickPosition){const t=n-this.lastClickTime,e=Math.sqrt(Math.pow(i.x-this.lastClickPosition.x,2)+Math.pow(i.y-this.lastClickPosition.y,2));t<300&&e<5&&(o=this.clickCount%3+1)}if(this.clickCount=o,this.lastClickTime=n,this.lastClickPosition={...i},2===o)return void this.handleDoubleClick(i,e);if(3===o)return void this.handleTripleClick(i,e);if(this._focusedControl instanceof U){const t=this._focusedControl,n=this.document.pages.findIndex(t=>t.id===e);let o=!1;const s=t.getRenderedSlice(n);if(s){const e=s.height;o=i.x>=s.position.x&&i.x<=s.position.x+t.width&&i.y>=s.position.y&&i.y<=s.position.y+e}else t.renderedPosition&&t.renderedPageIndex===n&&(o=t.containsPoint(i,t.renderedPosition));if(o)return;this.setFocus(null)}if(this.editingTextBox){const t=this.editingTextBox,e=t.renderedPosition;if(e){const n={x:e.x,y:e.y,width:t.width,height:t.height};if(i.x>=n.x&&i.x<=n.x+n.width&&i.y>=n.y&&i.y<=n.y+n.height){const e=t.flowingContent.getSelection();return void(e&&(e.start,e.end))}this.setEditingTextBox(null)}}const s=this.document.getPage(e),r=this.getFlowingContentForActiveSection();if(r){const t=r.getSelection();if(t&&t.start!==t.end)return}const a=this.document.pages.findIndex(t=>t.id===e),l=this.flowingTextRenderer.hitTestManager.queryByType(a,i,"embedded-object");if(l&&"embedded-object"===l.data.type){const t=l.data.object,e=this.getSectionForEmbeddedObject(t);e&&e!==this._activeSection&&this.setActiveSection(e);const i=this.getFlowingContentForActiveSection();return i&&i.clearSelection(),this.clearSelection(),void this.selectInlineElement(t)}const d=this.document.bodyFlowingContent;if(d){const t=d.getRepeatingSections();if(t.length>0&&s){const n=this.document.pages.findIndex(t=>t.id===e),o=this.flowingTextRenderer.getFlowedPagesForPage(this.document.pages[0].id);if(o&&o[n]){const e=s.getContentBounds(),r={x:e.position.x,y:e.position.y,width:e.size.width,height:e.size.height},a=s.getPageDimensions(),l={x:0,y:0,width:a.width,height:a.height},d=this.flowingTextRenderer.getRepeatingSectionAtPoint(i,t,n,l,r,o[n]);if(d)return this.clearSelection(),this.selectedSectionId=d.id,this.render(),void this.emit("repeating-section-clicked",{section:d})}}}if(d){const t=d.getConditionalSections();if(t.length>0&&s){const n=this.document.pages.findIndex(t=>t.id===e),o=this.flowingTextRenderer.getFlowedPagesForPage(this.document.pages[0].id);if(o&&o[n]){const e=s.getContentBounds(),r={x:e.position.x,y:e.position.y,width:e.size.width,height:e.size.height},a=s.getPageDimensions(),l={x:0,y:0,width:a.width,height:a.height},d=this.flowingTextRenderer.getConditionalSectionAtPoint(i,t,n,l,r,o[n]);if(d)return this.clearSelection(),this.selectedConditionalSectionId=d.id,this.render(),void this.emit("conditional-section-clicked",{section:d})}}}const h=this.document.pages.findIndex(t=>t.id===e),c=this.document.bodyFlowingContent;if(c){const t=c.getEmbeddedObjects();for(const[,e]of t.entries())if(e instanceof U&&e.renderedPosition&&e.renderedPageIndex===h){const t={x:i.x-e.renderedPosition.x,y:i.y-e.renderedPosition.y},n=e.getRowLoopAtPoint(t);if(n)return e.selectRowLoop(n.id),this.render(),void this.emit("table-row-loop-clicked",{table:e,loop:n});const o=e.getRowConditionalAtPoint(t);if(o)return e.selectRowConditional(o.id),this.render(),void this.emit("table-row-conditional-clicked",{table:e,conditional:o})}}const g=this.contexts.get(e),u=this.document.pages.findIndex(t=>t.id===e);if(g&&u>=0&&s){const t=this.getSectionAtPoint(i,s);t!==this._activeSection&&this.setActiveSection(t);const e=this.getRegionForActiveSection();if(e){if(this.flowingTextRenderer.handleRegionClick(e,i,u,g)){this.clearSelection();const t=this.getFlowingContentForActiveSection();return t&&t.clearSelection(),void this.render()}}const n=this.getRegionForActiveSection();if(n){if(n.globalToLocal(i,u))return}}this.clearSelection()}getRegionForActiveSection(){switch(this._activeSection){case"header":return this.regionManager.getHeaderRegion();case"footer":return this.regionManager.getFooterRegion();default:return this.regionManager.getBodyRegion()}}getFlowingContentForActiveSection(){switch(this._activeSection){case"header":return this.document.headerFlowingContent;case"footer":return this.document.footerFlowingContent;default:return this.document.bodyFlowingContent||null}}getMousePosition(t){const e=t.target.getBoundingClientRect();return{x:(t.clientX-e.left)/this.zoomLevel,y:(t.clientY-e.top)/this.zoomLevel}}getViewportMousePosition(t){const e=this.findScrollContainer();if(!e)return{x:t.clientX,y:t.clientY};const i=e.getBoundingClientRect();return{x:t.clientX-i.left,y:t.clientY-i.top}}getResizeHandleAt(t,e){const i=this.document.getPage(e);if(!i)return null;const n=this.document.pages.indexOf(i),o=this.flowingTextRenderer.hitTestManager.queryByType(n,t,"resize-handle");return o&&"resize-handle"===o.data.type?{handle:o.data.handle,element:o.data.element}:null}getSelectedElementAt(t){if(0===this.selectedElements.size)return null;if(!this.document.getPage(t))return null;const e=Array.from(this.selectedElements)[0],i=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent];for(const t of i)if(t){const i=t.getEmbeddedObjects();for(const[,t]of i.entries())if(t.id===e)return t}return null}calculateNewSize(t,e,i,n,o){const s={...e},r={...i};switch(t){case"nw":s.width=e.width-n,s.height=e.height-o,r.x=i.x+n,r.y=i.y+o;break;case"n":s.height=e.height-o,r.y=i.y+o;break;case"ne":s.width=e.width+n,s.height=e.height-o,r.y=i.y+o;break;case"e":s.width=e.width+n;break;case"se":s.width=e.width+n,s.height=e.height+o;break;case"s":s.height=e.height+o;break;case"sw":s.width=e.width-n,s.height=e.height+o,r.x=i.x+n;break;case"w":s.width=e.width-n,r.x=i.x+n}return{size:s,position:r}}updateCursor(t,e){const i=this.canvases.get(e);if(!i)return;const n=this.getResizeHandleAt(t,e);if(n){const t={nw:"nw-resize",n:"n-resize",ne:"ne-resize",e:"e-resize",se:"se-resize",s:"s-resize",sw:"sw-resize",w:"w-resize"};return void(i.style.cursor=t[n.handle]||"default")}const o=this.getTableResizeHandleAt(t,e);if(o&&o.handleInfo)return void(i.style.cursor=$.getCursorForHandle(o.handleInfo.type));const s=this.document.pages.findIndex(t=>t.id===e),r=this.flowingTextRenderer.hitTestManager,a=r.queryByType(s,t,"embedded-object");if(a&&"embedded-object"===a.data.type){const t=a.data.object;return"relative"===t.position?void(i.style.cursor="move"):void(t instanceof L&&this.editingTextBox===t||t instanceof U&&this._focusedControl===t?i.style.cursor=xt.TEXT_CURSOR:i.style.cursor="default")}const l=r.queryByType(s,t,"table-cell");if(l&&"table-cell"===l.data.type)return void(i.style.cursor=xt.TEXT_CURSOR);const d=r.queryByType(s,t,"text-region");if(d&&"text-region"===d.data.type)return void(i.style.cursor=xt.TEXT_CURSOR);const h=this.regionManager.getBodyRegion();if(h&&h.containsPointInRegion(t,s))return void(i.style.cursor=xt.TEXT_CURSOR);const c=this.regionManager.getHeaderRegion();if(c&&c.containsPointInRegion(t,s))return void(i.style.cursor=xt.TEXT_CURSOR);const g=this.regionManager.getFooterRegion();g&&g.containsPointInRegion(t,s)?i.style.cursor=xt.TEXT_CURSOR:i.style.cursor="default"}getTableResizeHandleAt(t,e){const i=this.document.pages.findIndex(t=>t.id===e),n=this.flowingTextRenderer.hitTestManager.queryByType(i,t,"table-divider");if(n&&"table-divider"===n.data.type){const{table:t,dividerType:e,index:o}=n.data,s=t.getRenderedSlice(i),r=s?.position||(t.renderedPageIndex===i?t.renderedPosition:null);if(r){let i;if("column"===e){const e=t.getColumnPositions(),n=t.getColumnWidths();i=e[o]+n[o]}else{let e=0;for(let i=0;i<=o;i++)e+=t.rows[i].calculatedHeight;i=e}return{table:t,handleInfo:{type:e,index:o,position:i},tablePosition:r}}}return null}removeEmbeddedObject(t){const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjectManager().findById(t);if(e){i.deleteTextAt(e.textIndex,1);break}}this.selectedElements.delete(t),this.render(),this.emit("element-removed",{elementId:t})}selectElement(t){j.log("[pc-editor:CanvasManager] Selecting element:",t),this.selectedElements.add(t);const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjects();for(const[,i]of e.entries())i.id===t&&(j.log("[pc-editor:CanvasManager] Found embedded object to select:",i.id),i.selected=!0)}j.log("[pc-editor:CanvasManager] Selected elements after selection:",Array.from(this.selectedElements)),this.render(),this.updateResizeHandleHitTargets(),this.emit("selection-change",{selectedElements:Array.from(this.selectedElements)})}findEmbeddedObjectById(t){const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjectManager().findById(t);if(e)return e.object}return null}updateResizeHandleHitTargets(){const t=[],e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of this.selectedElements)for(const n of e){const e=n.getEmbeddedObjects();for(const[,n]of e.entries())if(n.id===i){t.push(n);break}}this.flowingTextRenderer.updateResizeHandleTargets(t)}clearSelection(){j.log("[pc-editor:CanvasManager] clearSelection called, current selected elements:",Array.from(this.selectedElements)),this.selectedElements.forEach(t=>{j.log("[pc-editor:CanvasManager] Clearing selection for element:",t);const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjects();for(const[,i]of e.entries())i.id===t&&(j.log("[pc-editor:CanvasManager] Clearing selection on embedded object:",t),i.selected=!1)}}),this.selectedElements.clear(),this.selectedSectionId=null,this.selectedConditionalSectionId=null,j.log("[pc-editor:CanvasManager] About to render after clearing selection..."),this.render(),this.updateResizeHandleHitTargets(),this.emit("selection-change",{selectedElements:[]})}getSelectedElements(){return Array.from(this.selectedElements)}hasSelectedElements(){return this.selectedElements.size>0}selectBaseEmbeddedObject(t,e=!1){this.setFocus(null);const i=t.object||t;i.selected=!0,this.selectedElements.add(i.id);const n=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);let o=null;for(const t of n){const e=t.getEmbeddedObjects();for(const[,n]of e.entries())if(n.id===i.id){n.selected=!0,o=t;break}if(o)break}if(!e&&o){const e=t.textIndex??i.textIndex;void 0!==e&&(o.setCursorPosition(e+1),o.clearSelection())}this.render(),this.updateResizeHandleHitTargets(),this.emit("selection-change",{selectedElements:Array.from(this.selectedElements)})}selectInlineElement(t){this.selectBaseEmbeddedObject(t)}getBaseEmbeddedObjectAtPoint(t,e){const i=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const e of i){const i=e.getEmbeddedObjects();for(const[,e]of i.entries())if(e.renderedPosition){const i={x:e.renderedPosition.x,y:e.renderedPosition.y,width:e.width,height:e.height};if(t.x>=i.x&&t.x<=i.x+i.width&&t.y>=i.y&&t.y<=i.y+i.height)return e}}return null}getZoom(){return this.zoomLevel}getScrollPosition(){const t=this.findScrollContainer();return t?{x:t.scrollLeft,y:t.scrollTop}:{x:0,y:0}}getContentOffset(){const t=this.findScrollContainer(),e=this.canvases.values().next().value;if(!t||!e)return{x:0,y:0};const i=t.getBoundingClientRect(),n=e.getBoundingClientRect();return{x:n.left-i.left+t.scrollLeft,y:n.top-i.top+t.scrollTop}}findScrollContainer(){let t=this.container;for(;t;){const e=getComputedStyle(t),i=e.overflowY,n=e.overflowX;if("auto"===i||"scroll"===i||"auto"===n||"scroll"===n)return t;t=t.parentElement}return this.container.parentElement||this.container}setupScrollListener(){const t=this.findScrollContainer();t&&t.addEventListener("scroll",()=>{const t=this.getScrollPosition();this.emit("scroll",t)})}zoomIn(){this.setZoom(1.2*this.zoomLevel)}zoomOut(){this.setZoom(this.zoomLevel/1.2)}setZoom(t){this.zoomLevel=Math.max(.1,Math.min(5,t)),this.updateCanvasScale(),this.emit("zoom-change",{zoom:this.zoomLevel})}updateCanvasScale(){this.canvases.forEach(t=>{t.style.transform=`scale(${this.zoomLevel})`,t.style.transformOrigin="top center";const e=t.height*(this.zoomLevel-1);t.style.marginBottom=`${20+e}px`})}fitToWidth(){if(0===this.canvases.size)return;const t=this.canvases.values().next().value;if(!t)return;const e=this.container.clientWidth-40,i=t.width;this.setZoom(e/i)}fitToPage(){if(0===this.canvases.size)return;const t=this.canvases.values().next().value;if(!t)return;const e=this.container.clientWidth-40,i=this.container.clientHeight-40,n=e/t.width,o=i/t.height;this.setZoom(Math.min(n,o))}setupFlowingTextListeners(){this.flowingTextRenderer.on("text-clicked",t=>{this.emit("text-clicked",t)}),this.flowingTextRenderer.on("cursor-changed",t=>{this.emit("cursor-changed",t),this.render()}),this.flowingTextRenderer.on("cursor-blink",()=>{this.render()}),this.flowingTextRenderer.on("selection-changed",t=>{this.emit("text-selection-changed",t),this.render()}),this.flowingTextRenderer.on("text-overflow",t=>{this.handleTextOverflow(t)}),this.flowingTextRenderer.on("content-changed",()=>{this.checkForEmptyPages()}),this.flowingTextRenderer.on("inline-element-clicked",t=>{this.isSelectingText||this.isSelectingTextInTextBox||this.isSelectingTextInTableCell||this._focusedControl instanceof U&&this._focusedControl===t.element||this.editingTextBox!==t.element&&(this.clearSelection(),this.selectInlineElement(t.element))}),this.flowingTextRenderer.on("substitution-field-clicked",t=>{j.log("[pc-editor:CanvasManager] substitution-field-clicked Field:",t.field?.fieldName,"Section:",t.section),this.emit("substitution-field-clicked",t)})}handleTextOverflow(t){if(this.isHandlingOverflow)return;const{pageId:e,totalPages:i}=t,n=this.document.pages.findIndex(t=>t.id===e);if(-1===n)return;const o=this.document.pages.length,s=n+i;if(!(s<=o)){this.isHandlingOverflow=!0;try{for(let t=o;t<s;t++)this.createNewPage();this.clearCanvases(),this.createCanvases(),this.setupEventListeners(),this.updateCanvasScale(),setTimeout(()=>{this.isHandlingOverflow=!1,this.render()},0),this.emit("pages-added",{newPageCount:this.document.pages.length-o})}catch(t){throw this.isHandlingOverflow=!1,t}}}createNewPage(){if(!this.document.pages[0])return;const t={id:`page_${Date.now()}_${Math.random().toString(36).substr(2,9)}`},e=new a(t,this.document.settings);this.document.addPage(e)}showTextCursor(){const t=this.getFlowingContentForActiveSection();t&&this.setFocus(t),this.render()}hideTextCursor(){this.suspendCursor(),this.render()}suspendCursor(){this._focusedControl&&!this._cursorSuspended&&(this._focusedControl.offCursorBlink(this.handleFocusedCursorBlink),this._cursorSuspended=!0)}resumeCursor(){this._focusedControl&&this._cursorSuspended&&(this._focusedControl.onCursorBlink(this.handleFocusedCursorBlink),this._cursorSuspended=!1,this.render())}isCursorSuspended(){return this._cursorSuspended}moveCursorVertical(t){if(0===this.document.pages.length)return null;const e=this.document.pages[0].id;return this.flowingTextRenderer.moveCursorVertical(t,e)}drawMarginLines(t,e){if(!this.showMargins)return;const i=e.getContentBounds(),n=e.getPageDimensions();t.save(),t.setLineDash([5,5]),t.strokeStyle="#999999",t.lineWidth=1,t.beginPath(),t.moveTo(0,i.position.y),t.lineTo(n.width,i.position.y),t.stroke();const o=i.position.y+i.size.height;t.beginPath(),t.moveTo(0,o),t.lineTo(n.width,o),t.stroke(),t.beginPath(),t.moveTo(i.position.x,0),t.lineTo(i.position.x,n.height),t.stroke();const s=i.position.x+i.size.width;t.beginPath(),t.moveTo(s,0),t.lineTo(s,n.height),t.stroke(),t.restore()}checkForEmptyPages(){if(this.isHandlingOverflow)return;if(this.document.pages.length<=1)return;const t=this.flowingTextRenderer.getFlowedPagesForPage(this.document.pages[0].id);if(!t)return;const e=t.length,i=this.document.pages.length;if(i!==e&&i>e&&e>=1){for(let t=i-1;t>=e;t--)this.document.removePage(this.document.pages[t].id);this.clearCanvases(),this.createCanvases(),this.setupEventListeners(),this.updateCanvasScale(),setTimeout(()=>{this.render()},0),this.emit("pages-removed",{removedCount:i-e})}}setShowControlCharacters(t){this.options.showControlCharacters=t,this.flowingTextRenderer.setShowControlCharacters(t),this.render()}setShowGrid(t){this.options.showGrid=t,this.render()}getShowGrid(){return this.options.showGrid}setShowMarginLines(t){this.showMargins=t,this.render()}getShowMarginLines(){return this.showMargins}getActiveSection(){return this._activeSection}setActiveSection(t){if(this._activeSection!==t){const e=this._activeSection;this._activeSection=t;let i=null;"body"===t?i=this.regionManager.getBodyRegion():"header"===t?i=this.regionManager.getHeaderRegion():"footer"===t&&(i=this.regionManager.getFooterRegion()),this.flowingTextRenderer.setFocusedRegion(i);const n=i?.flowingContent;this.setFocus(n),this.render(),this.emit("section-focus-changed",{section:t,previousSection:e})}}getSectionForEmbeddedObject(t){const e=[{content:this.document.bodyFlowingContent,section:"body"},{content:this.document.headerFlowingContent,section:"header"},{content:this.document.footerFlowingContent,section:"footer"}];for(const{content:i,section:n}of e){if(!i)continue;const e=i.getEmbeddedObjects();for(const[,i]of e.entries())if(i.id===t.id)return n}return null}getSectionAtPoint(t,e){const i=e.getContentBounds();return t.y<i.position.y?"header":t.y>=i.position.y+i.size.height?"footer":"body"}handleDoubleClick(t,e){const i=this.document.getPage(e);if(!i)return;if(this.editingTextBox){const i=this.editingTextBox,n=this.document.pages.findIndex(t=>t.id===e),o=this.contexts.get(e);if(i.containsPointInRegion(t,n)&&o&&n>=0)return this.flowingTextRenderer.handleRegionClick(i,t,n,o),i.flowingContent.selectWord(),void this.render()}if(this._focusedControl instanceof U){const i=this._focusedControl,n=this.document.pages.findIndex(t=>t.id===e),o=this.contexts.get(e);if(i.focusedCell&&o&&n>=0){const e=i.getCell(i.focusedCell.row,i.focusedCell.col);if(e)return this.flowingTextRenderer.handleRegionClick(e,t,n,o),e.flowingContent.selectWord(),void this.render()}}const n=this.getFlowingContentForActiveSection();if(n){const i=n.getEmbeddedObjects(),o=this.document.pages.findIndex(t=>t.id===e);for(const[,n]of i.entries()){if(n instanceof L&&n.renderedPosition&&n.containsPointInRegion(t,o)){this.setEditingTextBox(n,e);const i=this.contexts.get(e);return i&&o>=0&&this.flowingTextRenderer.handleRegionClick(n,t,o,i),void this.render()}if(n instanceof U){const i=n.getRenderedSlice(o),s=i?.position||(n.renderedPageIndex===o?n.renderedPosition:null);if(s){const r=i?.height||n.height;if(t.x>=s.x&&t.x<=s.x+n.width&&t.y>=s.y&&t.y<=s.y+r){const r=this.contexts.get(e);if(r&&o>=0){const e={x:t.x-s.x,y:t.y-s.y};if(i&&("middle"===i.slicePosition||"last"===i.slicePosition)){const t=i.headerHeight;e.y>=t&&(e.y=i.yOffset+(e.y-t))}const a=n.getCellAtPoint(e);if(a){this.editingTextBox&&this.setEditingTextBox(null),n.focusCell(a.row,a.col);const e=n.getCell(a.row,a.col);return e&&(this.setFocus(n),this.flowingTextRenderer.handleRegionClick(e,t,o,r)),void this.render()}}}}}}}const o=this.getSectionAtPoint(t,i);if(o!==this._activeSection&&this.setActiveSection(o),"header"===o||"footer"===o){const i=this.contexts.get(e),n=this.document.pages.findIndex(t=>t.id===e),s="header"===o?this.regionManager.getHeaderRegion():this.regionManager.getFooterRegion();if(i&&n>=0&&s){this.flowingTextRenderer.handleRegionClick(s,t,n,i)&&this.render()}}const s=this.getFlowingContentForActiveSection();if(s){const i=this.contexts.get(e),n=this.document.pages.findIndex(t=>t.id===e),o=this.getRegionForActiveSection();i&&n>=0&&o&&this.flowingTextRenderer.handleRegionClick(o,t,n,i),s.selectWord(),this.emit("text-selection-changed",{selection:s.getSelection(),section:this._activeSection}),this.render()}}handleTripleClick(t,e){if(this.editingTextBox)return this.editingTextBox.flowingContent.selectParagraph(),void this.render();if(this._focusedControl instanceof U){const t=this._focusedControl;if(t.focusedCell){const e=t.getCell(t.focusedCell.row,t.focusedCell.col);if(e)return e.flowingContent.selectParagraph(),void this.render()}}const i=this.getFlowingContentForActiveSection();i&&(i.selectParagraph(),this.emit("text-selection-changed",{selection:i.getSelection(),section:this._activeSection}),this.render())}setEditingTextBox(t,e){if(this.editingTextBox!==t)if(this.editingTextBox=t,this._editingTextBoxPageId=e||null,t)this.document.bodyFlowingContent.clearSelection(),this.clearSelection(),this.selectInlineElement({type:"embedded-object",object:t,textIndex:t.textIndex}),this.setFocus(t),this.emit("textbox-editing-started",{textBox:t});else{const t=this.getFlowingContentForActiveSection();t?this.setFocus(t):this.setFocus(null),this.emit("textbox-editing-ended",{})}}getEditingTextBox(){return this.editingTextBox}isEditingTextBox(){return null!==this.editingTextBox}getEditingTextBoxPageId(){return this._editingTextBoxPageId}getContext(t){return this.contexts.get(t)||null}setFocus(t){this._focusedControl!==t&&(this._focusedControl instanceof U&&this.flowingTextRenderer.updateTableDividerTargets(null),this._focusedControl&&(this._focusedControl.offCursorBlink(this.handleFocusedCursorBlink),this._focusedControl.blur()),this._focusedControl=t,t instanceof U&&this.flowingTextRenderer.updateTableDividerTargets(t),t?(t.focus(),t.onCursorBlink(this.handleFocusedCursorBlink),this.emit("focus-changed",{control:t})):this.emit("focus-changed",{control:null}))}getFocusedControl(){return this._focusedControl}getFlowedPagesSnapshot(){return this.flowingTextRenderer.getFlowedPagesSnapshot()}destroy(){this.flowingTextRenderer.destroy(),this.clearCanvases(),this.removeAllListeners()}}xt.CELL_SELECTION_THRESHOLD=5,xt.RELATIVE_DRAG_THRESHOLD=3,xt.TEXT_CURSOR="url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='20' viewBox='0 0 16 20'%3E%3Cpath d='M5 1h2v1h2V1h2v2h-2v6h2v2h-2v6h2v2h-2v-1H7v1H5v-2h2v-6H5V9h2V3H5z' fill='%23000'/%3E%3C/svg%3E\") 8 10, text";class yt{bind(t,e){return{version:t.version,settings:t.settings,pages:t.pages.map(t=>({...t})),headerContent:t.headerContent,footerContent:t.footerContent}}}function wt(t,e){return e-t}function Ct(t,e,i,n,o){return{x:t,y:o-e-n,width:i,height:n}}const St={arial:{normal:e.StandardFonts.Helvetica,bold:e.StandardFonts.HelveticaBold,italic:e.StandardFonts.HelveticaOblique,boldItalic:e.StandardFonts.HelveticaBoldOblique},helvetica:{normal:e.StandardFonts.Helvetica,bold:e.StandardFonts.HelveticaBold,italic:e.StandardFonts.HelveticaOblique,boldItalic:e.StandardFonts.HelveticaBoldOblique},"sans-serif":{normal:e.StandardFonts.Helvetica,bold:e.StandardFonts.HelveticaBold,italic:e.StandardFonts.HelveticaOblique,boldItalic:e.StandardFonts.HelveticaBoldOblique},times:{normal:e.StandardFonts.TimesRoman,bold:e.StandardFonts.TimesRomanBold,italic:e.StandardFonts.TimesRomanItalic,boldItalic:e.StandardFonts.TimesRomanBoldItalic},"times new roman":{normal:e.StandardFonts.TimesRoman,bold:e.StandardFonts.TimesRomanBold,italic:e.StandardFonts.TimesRomanItalic,boldItalic:e.StandardFonts.TimesRomanBoldItalic},serif:{normal:e.StandardFonts.TimesRoman,bold:e.StandardFonts.TimesRomanBold,italic:e.StandardFonts.TimesRomanItalic,boldItalic:e.StandardFonts.TimesRomanBoldItalic},georgia:{normal:e.StandardFonts.TimesRoman,bold:e.StandardFonts.TimesRomanBold,italic:e.StandardFonts.TimesRomanItalic,boldItalic:e.StandardFonts.TimesRomanBoldItalic},courier:{normal:e.StandardFonts.Courier,bold:e.StandardFonts.CourierBold,italic:e.StandardFonts.CourierOblique,boldItalic:e.StandardFonts.CourierBoldOblique},"courier new":{normal:e.StandardFonts.Courier,bold:e.StandardFonts.CourierBold,italic:e.StandardFonts.CourierOblique,boldItalic:e.StandardFonts.CourierBoldOblique},monospace:{normal:e.StandardFonts.Courier,bold:e.StandardFonts.CourierBold,italic:e.StandardFonts.CourierOblique,boldItalic:e.StandardFonts.CourierBoldOblique}};function vt(t){if(!t)return e.rgb(0,0,0);const i=t.trim().toLowerCase();if(i.startsWith("#")){const t=i.slice(1);let n,o,s;if(3===t.length)n=parseInt(t[0]+t[0],16)/255,o=parseInt(t[1]+t[1],16)/255,s=parseInt(t[2]+t[2],16)/255;else{if(6!==t.length&&8!==t.length)return e.rgb(0,0,0);n=parseInt(t.slice(0,2),16)/255,o=parseInt(t.slice(2,4),16)/255,s=parseInt(t.slice(4,6),16)/255}return e.rgb(n,o,s)}const n=i.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(n)return e.rgb(parseInt(n[1])/255,parseInt(n[2])/255,parseInt(n[3])/255);const o={black:[0,0,0],white:[1,1,1],red:[1,0,0],green:[0,.5,0],blue:[0,0,1],yellow:[1,1,0],cyan:[0,1,1],magenta:[1,0,1],gray:[.5,.5,.5],grey:[.5,.5,.5],orange:[1,.65,0],purple:[.5,0,.5],pink:[1,.75,.8],brown:[.65,.16,.16],transparent:[0,0,0]};if(o[i]){const[t,n,s]=o[i];return e.rgb(t,n,s)}return e.rgb(0,0,0)}function Ft(t,e,i,n,o,s,r){const a=Ct(e,i,n,o,r);t.drawRectangle({x:a.x,y:a.y,width:a.width,height:a.height,color:s})}function It(t,e,i,n,o,s,r,a){t.drawLine({start:{x:e,y:wt(i,a)},end:{x:n,y:wt(o,a)},color:s,thickness:r})}class _t{constructor(t){this.fontCache=new Map,this.customFontCache=new Map,this.fontManager=t}async generate(t,n,o){const s=await e.PDFDocument.create();s.registerFontkit(i),this.fontCache.clear(),this.customFontCache.clear(),await this.embedStandardFonts(s),await this.embedCustomFonts(s);for(let i=0;i<t.pages.length;i++)try{const o=t.pages[i],r=o.getPageDimensions(),a=s.addPage([r.width,r.height]);a.drawRectangle({x:0,y:0,width:r.width,height:r.height,color:e.rgb(1,1,1)});const l=o.getContentBounds(),d={x:l.position.x,y:l.position.y,width:l.size.width,height:l.size.height};if(n?.header&&t.headerFlowingContent){const e=o.getHeaderBounds(),s={x:e.position.x,y:e.position.y,width:e.size.width,height:e.size.height};await this.renderFlowedPage(a,n.header,s,r.height,i,t.pages.length,n.headerHyperlinks)}if(n?.body&&n.body[i]&&await this.renderFlowedPage(a,n.body[i],d,r.height,i,t.pages.length,n.bodyHyperlinks),n?.footer&&t.footerFlowingContent){const e=o.getFooterBounds(),s={x:e.position.x,y:e.position.y,width:e.size.width,height:e.size.height};await this.renderFlowedPage(a,n.footer,s,r.height,i,t.pages.length,n.footerHyperlinks)}}catch(t){throw console.error(`[PDFGenerator] Error rendering page ${i+1}:`,t),t}return function(t,e){try{return new Blob([t],{type:e})}catch(i){const n=new ArrayBuffer(t.length),o=new Uint8Array(n);for(let e=0;e<t.length;e++)o[e]=t[e];return new Blob([n],{type:e})}}(await s.save(),"application/pdf")}async embedStandardFonts(t){const i=[e.StandardFonts.Helvetica,e.StandardFonts.HelveticaBold,e.StandardFonts.HelveticaOblique,e.StandardFonts.HelveticaBoldOblique,e.StandardFonts.TimesRoman,e.StandardFonts.TimesRomanBold,e.StandardFonts.TimesRomanItalic,e.StandardFonts.TimesRomanBoldItalic,e.StandardFonts.Courier,e.StandardFonts.CourierBold,e.StandardFonts.CourierOblique,e.StandardFonts.CourierBoldOblique];for(const e of i){const i=await t.embedFont(e);this.fontCache.set(e,i)}}filterToWinAnsi(t){let e="";for(let i=0;i<t.length;i++){const n=t.charCodeAt(i);if(n>=32&&n<=126)e+=t[i];else if(n>=160&&n<=255)e+=t[i];else if(9===n)e+=" ";else{if(10===n||13===n)continue;if(12===n)continue;e+=" "}}return e}async embedCustomFonts(t){const e=this.fontManager.getAvailableFonts();for(const i of e)if("custom"===i.source)for(const e of i.variants){if(!e.fontData)continue;const n=`custom:${i.family.toLowerCase()}:${e.weight}:${e.style}`;try{const o=e.fontData instanceof Uint8Array?e.fontData:new Uint8Array(e.fontData),s=await t.embedFont(o,{subset:!0});this.customFontCache.set(n,s),j.log("[pc-editor:PDFGenerator] Embedded custom font:",i.family,e.weight,e.style)}catch(t){j.warn("[pc-editor:PDFGenerator] Failed to embed custom font:",i.family,t)}}}isCustomFont(t){return!this.fontManager.isBuiltIn(t)&&this.fontManager.isRegistered(t)}getFont(t){const i=t.fontFamily||"Arial",n=t.fontWeight||"normal",o=t.fontStyle||"normal",s=`custom:${i.toLowerCase()}:${n}:${o}`,r=this.customFontCache.get(s);if(r)return r;const a=`custom:${i.toLowerCase()}:normal:normal`,l=this.customFontCache.get(a);if(l)return l;const d=function(t,e,i){const n=t.toLowerCase().trim(),o="bold"===e||"700"===e||"800"===e||"900"===e,s="italic"===i||"oblique"===i;let r="normal";o&&s?r="boldItalic":o?r="bold":s&&(r="italic");const a=St[n];return a?a[r]:St.helvetica[r]}(i,n,o);return this.fontCache.get(d)||this.fontCache.get(e.StandardFonts.Helvetica)}async renderFlowedPage(t,e,i,n,o,s,r){let a=i.y;const l=[],d=[];for(const h of e.lines){if(h.embeddedObjects)for(const t of h.embeddedObjects)t.isAnchor&&"relative"===t.object.position&&l.push({object:t.object,anchorX:i.x,anchorY:a});const e=this.getAlignmentOffset(h,i.width),c=i.x+e;let g=c;for(const e of h.runs){if(!e.text)continue;const i=e.formatting||{},o=this.isCustomFont(i.fontFamily||"Arial")?e.text:this.filterToWinAnsi(e.text);if(!o)continue;const s=this.getFont(i),l=i.fontSize||14,c=vt(i.color||"#000000"),u=s.widthOfTextAtSize(o,l);if(i.backgroundColor){const e=vt(i.backgroundColor);Ft(t,g,a,u,h.height,e,n)}const f=a+h.baseline;if(t.drawText(o,{x:g,y:wt(f,n),font:s,size:l,color:c}),r&&r.length>0&&d.push({x:g,y:a,width:u,height:h.height,startIndex:e.startIndex,endIndex:e.endIndex}),g+=u,h.extraWordSpacing&&o.includes(" ")){g+=(o.match(/ /g)||[]).length*h.extraWordSpacing}}for(const e of h.substitutionFields)this.renderSubstitutionField(t,e,c,a,h,n,o,s);for(const e of h.embeddedObjects){if(e.isAnchor)continue;let r=c+e.x;if(e.isBlock)switch(h.alignment){case"center":r=i.x+(i.width-e.object.width)/2;break;case"right":r=i.x+i.width-e.object.width;break;default:r=i.x}await this.renderEmbeddedObject(t,e.object,r,a,n,o,s)}a+=h.height}await this.renderRelativeObjects(t,l,n,o,s),r&&r.length>0&&d.length>0&&this.createHyperlinkAnnotations(t,d,r,n)}createHyperlinkAnnotations(t,e,i,n){for(const o of i){const i=e.filter(t=>t.startIndex<o.endIndex&&t.endIndex>o.startIndex);if(0===i.length)continue;const s=new Map;for(const t of i){const e=t.y;s.has(e)||s.set(e,[]),s.get(e).push(t)}for(const[e,i]of s){const s=Math.min(...i.map(t=>t.x)),r=Math.max(...i.map(t=>t.x+t.width)),a=i[0].height,l=n-e-a,d=t.doc.context.obj({Type:"Annot",Subtype:"Link",Rect:[s,l,r,l+a],Border:[0,0,0],A:{Type:"Action",S:"URI",URI:o.url}}),h=t.node.get(t.doc.context.obj("Annots"));h?h.push(d):t.node.set(t.doc.context.obj("Annots"),t.doc.context.obj([d]))}}}getAlignmentOffset(t,e){switch(t.alignment){case"center":return(e-t.width)/2;case"right":return e-t.width;default:return 0}}renderSubstitutionField(t,e,i,n,o,s,r,a){const l=e.field;let d="";if(d="pageNumber"===l.fieldType?String(r+1):"pageCount"===l.fieldType?String(a):l.defaultValue||"",!d)return;const h=this.filterToWinAnsi(d);if(!h)return;const c=l.formatting||{fontFamily:"Arial",fontSize:14,color:"#000000"},g=this.getFont(c),u=c.fontSize,f=vt(c.color),p=i+e.x,m=n+o.baseline;t.drawText(h,{x:p,y:wt(m,s),font:g,size:u,color:f})}async renderEmbeddedObject(t,e,i,n,o,s,r){e instanceof T?await this.renderImage(t,e,i,n,o):e instanceof L?await this.renderTextBox(t,e,i,n,o,s,r):e instanceof U&&await this.renderTable(t,e,i,n,o,s,r)}async renderRelativeObjects(t,e,i,n,o){for(const{object:s,anchorX:r,anchorY:a}of e){const e=s.relativeOffset,l=r+e.x,d=a+e.y;await this.renderEmbeddedObject(t,s,l,d,i,n,o)}}async renderImage(t,i,n,o,s){const r=t.doc,a=i.src;if(a.startsWith("data:"))try{let e=await this.embedImageFromDataUrl(r,a);if(!e){const t=i.toPngDataUrl();t&&(e=await this.embedImageFromDataUrl(r,t))}if(e){const r=this.calculateImageDrawParams(e.width,e.height,i.width,i.height,i.fit),a=n+r.dx,l=s-(o+r.dy+r.dh);return void("tile"===i.fit?this.drawTiledImage(t,e,n,o,i.width,i.height,s):t.drawImage(e,{x:a,y:l,width:r.dw,height:r.dh}))}}catch(t){j.warn("[pc-editor:PDFGenerator] Failed to embed image:",t)}const l=Ct(n,o,i.width,i.height,s);t.drawRectangle({x:l.x,y:l.y,width:l.width,height:l.height,borderColor:e.rgb(.8,.8,.8),borderWidth:1})}async embedImageFromDataUrl(t,e){const i=e.match(/^data:([^;,]+)?(?:;base64)?,(.*)$/);if(!i)return null;const n=i[1]||"",o=i[2],s=atob(o),r=new Uint8Array(s.length);for(let t=0;t<s.length;t++)r[t]=s.charCodeAt(t);return n.includes("jpeg")||n.includes("jpg")?await t.embedJpg(r):n.includes("png")?await t.embedPng(r):null}calculateImageDrawParams(t,e,i,n,o){let s=0,r=0,a=i,l=n;switch(o){case"fill":break;case"contain":{const o=Math.min(i/t,n/e);a=t*o,l=e*o,s=(i-a)/2,r=(n-l)/2;break}case"cover":{const o=Math.max(i/t,n/e);a=t*o,l=e*o,s=(i-a)/2,r=(n-l)/2;break}case"none":a=t,l=e,s=(i-t)/2,r=(n-e)/2;break;case"tile":a=t,l=e}return{dx:s,dy:r,dw:a,dh:l}}drawTiledImage(t,e,i,n,o,s,r){const a=e.width,l=e.height;for(let d=0;d<s;d+=l)for(let h=0;h<o;h+=a){const c=Math.min(a,o-h),g=Math.min(l,s-d),u=i+h,f=r-(n+d+g);t.drawImage(e,{x:u,y:f,width:c,height:g})}}async renderTextBox(t,e,i,n,o,s,r){if(e.backgroundColor){const s=vt(e.backgroundColor);Ft(t,i,n,e.width,e.height,s,o)}const a=e.border;a&&("none"!==a.top.style&&a.top.width>0&&It(t,i,n,i+e.width,n,vt(a.top.color),a.top.width,o),"none"!==a.right.style&&a.right.width>0&&It(t,i+e.width,n,i+e.width,n+e.height,vt(a.right.color),a.right.width,o),"none"!==a.bottom.style&&a.bottom.width>0&&It(t,i,n+e.height,i+e.width,n+e.height,vt(a.bottom.color),a.bottom.width,o),"none"!==a.left.style&&a.left.width>0&&It(t,i,n,i,n+e.height,vt(a.left.color),a.left.width,o));const l=e.flowingContent;if(l){const a="undefined"!=typeof document?document.createElement("canvas"):null,d=a?.getContext("2d");if(d){const a=e.padding||4,h=l.flowText(e.width-2*a,e.height-2*a,d);if(h.length>0){const l={x:i+a,y:n+a,width:e.width-2*a,height:e.height-2*a};await this.renderFlowedPage(t,h[0],l,o,s,r)}}}}async renderTable(t,e,i,n,o,s,r){const a=e.getColumnPositions(),l=e.getColumnWidths(),d=e.getRenderedSlice(s);let h;h=d&&"only"!==d.slicePosition?this.getTableRowsForSlice(e,{slicePosition:d.slicePosition,sliceIndex:d.sliceIndex,yOffset:d.yOffset,headerHeight:d.headerHeight}):e.rows.map((t,e)=>({row:t,originalIndex:e}));let c=n;const g=new Set;for(const{row:t,originalIndex:e}of h)for(let i=0;i<t.cells.length;i++){const n=t.cells[i];if(n&&(n.rowSpan>1||n.colSpan>1))for(let t=e;t<e+n.rowSpan;t++)for(let o=i;o<i+n.colSpan;o++)t===e&&o===i||g.add(`${t},${o}`)}for(const{row:n,originalIndex:d}of h){for(let u=0;u<n.cells.length;u++){const f=n.cells[u],p=`${d},${u}`;if(g.has(p))continue;if(!f)continue;let m=0;for(let t=u;t<u+f.colSpan;t++)m+=l[t]||0;let b=n.calculatedHeight;if(f.rowSpan>1){b=0;for(let t=d;t<d+f.rowSpan&&t<e.rows.length;t++){h.some(e=>e.originalIndex===t)&&(b+=e.rows[t].calculatedHeight)}}const x=i+a[u];if(f.backgroundColor){Ft(t,x,c,m,b,vt(f.backgroundColor),o)}this.renderCellBorders(t,f,x,c,m,b,o);const y=f.flowingContent;if(y){const e="undefined"!=typeof document?document.createElement("canvas"):null,i=e?.getContext("2d");if(i){const e=f.padding,n=e.left+e.right,a=e.top+e.bottom,l=y.flowText(m-n,b-a,i);if(l.length>0){const i={x:x+e.left,y:c+e.top,width:m-n,height:b-a};await this.renderFlowedPage(t,l[0],i,o,s,r)}}}}c+=n.calculatedHeight}}getTableRowsForSlice(t,e){const i=[];if("first"!==e.slicePosition&&"only"!==e.slicePosition)for(let e=0;e<t.rows.length;e++)t.rows[e].isHeader&&i.push({row:t.rows[e],originalIndex:e});let n=0;for(const e of t.rows)e.isHeader&&(n+=e.calculatedHeight);const o=e.yOffset;let s=t.height-n;const r=t.getRenderedPageIndices().sort((t,e)=>t-e),a=r.findIndex(i=>t.getRenderedSlice(i)?.sliceIndex===e.sliceIndex);if(a>=0&&a<r.length-1){const e=r[a+1],i=t.getRenderedSlice(e);i&&(s=i.yOffset)}let l=0;for(let e=0;e<t.rows.length;e++){const n=t.rows[e];if(n.isHeader)continue;const r=l,a=l+n.calculatedHeight;r<s&&a>o&&i.push({row:n,originalIndex:e}),l=a}return i}renderCellBorders(t,e,i,n,o,s,r){const a=e.border;"none"!==a.top.style&&a.top.width>0&&It(t,i,n,i+o,n,vt(a.top.color),a.top.width,r),"none"!==a.right.style&&a.right.width>0&&It(t,i+o,n,i+o,n+s,vt(a.right.color),a.right.width,r),"none"!==a.bottom.style&&a.bottom.width>0&&It(t,i,n+s,i+o,n+s,vt(a.bottom.color),a.bottom.width,r),"none"!==a.left.style&&a.left.width>0&&It(t,i,n,i,n+s,vt(a.left.color),a.left.width,r)}}class Tt extends r{constructor(t){super(),this.autoFlow=!0}setAutoFlow(t){this.autoFlow=t,this.emit("auto-flow-changed",{enabled:t})}getAutoFlow(){return this.autoFlow}checkContentOverflow(){return!1}insertPageBreak(t){}reflowDocument(){this.emit("document-reflowed")}getPageMetrics(t){return{contentHeight:0,availableHeight:t.getContentBounds().size.height,utilizationPercent:0,hasOverflow:!1}}}class Pt extends r{constructor(t,e){super(),this.isLayouting=!1,this.document=t,this.flowManager=new Tt(t),this.options={autoFlow:!0,snapToGrid:!1,gridSize:10,allowOrphans:!1,minimumContentHeight:50,...e},this.setupEventListeners()}setupEventListeners(){this.document.on("change",()=>{!this.isLayouting&&this.options.autoFlow&&this.requestLayout()}),this.flowManager.on("page-overflow-handled",t=>{this.emit("page-added",t)}),this.flowManager.on("page-break-inserted",t=>{this.emit("page-break-created",t)})}requestLayout(){this.isLayouting||setTimeout(()=>{this.performLayout()},100)}performLayout(){this.isLayouting=!0,this.emit("layout-start");try{this.emit("layout-complete",{hadOverflow:!1})}catch(t){this.emit("layout-error",{error:t})}finally{this.isLayouting=!1}}insertPageBreak(t){}setAutoFlow(t){this.options.autoFlow=t,this.flowManager.setAutoFlow(t),t&&this.performLayout()}setSnapToGrid(t,e){this.options.snapToGrid=t,e&&(this.options.gridSize=e)}getLayoutOptions(){return{...this.options}}updateLayoutOptions(t){this.options={...this.options,...t},this.emit("layout-options-changed",{options:this.options})}reflowDocument(){this.performLayout()}getDocumentMetrics(){return{totalPages:this.document.pages.length,totalContentHeight:0,averagePageUtilization:0,hasOverflow:!1}}destroy(){this.removeAllListeners(),this.flowManager.removeAllListeners()}}const Rt={maxTimeGap:500,maxCharacters:50};function kt(){return`${Date.now()}_${Math.random().toString(36).substr(2,9)}`}class At extends r{constructor(t,e,i,n=100){super(),this.undoStack=[],this.redoStack=[],this.maxHistory=100,this.isPerformingUndoRedo=!1,this.coalesceConfig=Rt,this.pendingTransaction=null,this.transactionStack=[],this.focusTracker=t,this._getContent=e,this._getObject=i,this.maxHistory=n}getContent(t){return this._getContent(t)}getObject(t){return this._getObject(t)}get isUndoRedoInProgress(){return this.isPerformingUndoRedo}recordMutation(t){if(!this.isPerformingUndoRedo){if(t.id||(t.id=kt()),this.transactionStack.length>0){const e=this.transactionStack[this.transactionStack.length-1];return e.mutations.push(t),e.endTime=t.timestamp,void(e.focusStateAfter=this.focusTracker.capture())}this.shouldCoalesce(t)?this.coalesceMutation(t):(this.flushPendingTransaction(),this.canStartCoalesce(t)?this.pendingTransaction=this.createTransactionFromMutation(t):this.commitTransaction(this.createTransactionFromMutation(t)),this.redoStack.length>0&&(this.redoStack=[],this.emitStateChange()))}}createTransactionFromMutation(t){const e=this.focusTracker.capture();return{id:kt(),startTime:t.timestamp,endTime:t.timestamp,mutations:[t],focusStateBefore:e,focusStateAfter:e,description:this.getDescriptionForMutation(t)}}shouldCoalesce(t){if(!this.pendingTransaction)return!1;const e=this.pendingTransaction,i=e.mutations[e.mutations.length-1];if(!this.sameSource(t.sourceId,i.sourceId))return!1;if(t.type!==i.type)return!1;if(t.timestamp-i.timestamp>this.coalesceConfig.maxTimeGap)return!1;if("insert"===t.type){const n=i.data,o=t.data;if(o.position!==n.position+n.text.length)return!1;if(e.mutations.reduce((t,e)=>"insert"===e.type?t+(e.data.text?.length||0):t,0)+o.text.length>this.coalesceConfig.maxCharacters)return!1}if("delete"===t.type){const e=i.data,n=t.data,o=n.position===e.position-1,s=n.position===e.position;if(!o&&!s)return!1}return!0}sameSource(t,e){if("type"in t&&"type"in e){const i=t,n=e;return i.type===n.type&&(i.objectId===n.objectId&&(i.cellAddress&&n.cellAddress?i.cellAddress.row===n.cellAddress.row&&i.cellAddress.col===n.cellAddress.col:i.cellAddress===n.cellAddress))}return!1}canStartCoalesce(t){return"insert"===t.type||"delete"===t.type}coalesceMutation(t){this.pendingTransaction&&(this.pendingTransaction.mutations.push(t),this.pendingTransaction.endTime=t.timestamp,this.pendingTransaction.focusStateAfter=this.focusTracker.capture())}flushPendingTransaction(){this.pendingTransaction&&(this.commitTransaction(this.pendingTransaction),this.pendingTransaction=null)}commitTransaction(t){if(0!==t.mutations.length){for(this.undoStack.push(t);this.undoStack.length>this.maxHistory;)this.undoStack.shift();this.emit("transaction-committed",{transaction:t}),this.emitStateChange()}}createBoundary(){this.flushPendingTransaction()}beginCompoundOperation(t){this.flushPendingTransaction();const e={id:kt(),startTime:Date.now(),endTime:0,mutations:[],focusStateBefore:this.focusTracker.capture(),focusStateAfter:this.focusTracker.capture(),description:t||"Multiple Changes"};this.transactionStack.push(e)}endCompoundOperation(t){if(0===this.transactionStack.length)return;const e=this.transactionStack.pop();if(e.endTime=Date.now(),e.focusStateAfter=this.focusTracker.capture(),t&&(e.description=t),this.transactionStack.length>0){this.transactionStack[this.transactionStack.length-1].mutations.push(...e.mutations)}else e.mutations.length>0&&(this.commitTransaction(e),this.redoStack.length>0&&(this.redoStack=[],this.emitStateChange()))}undo(){if(this.flushPendingTransaction(),0===this.undoStack.length)return!1;const t=this.undoStack.pop();this.isPerformingUndoRedo=!0;try{for(let e=t.mutations.length-1;e>=0;e--)this.undoMutation(t.mutations[e]);return this.focusTracker.restore(t.focusStateBefore),this.redoStack.push(t),this.emit("undo-performed",{transaction:t}),this.emitStateChange(),!0}finally{this.isPerformingUndoRedo=!1}}redo(){if(0===this.redoStack.length)return!1;const t=this.redoStack.pop();this.isPerformingUndoRedo=!0;try{for(const e of t.mutations)this.redoMutation(e);return this.focusTracker.restore(t.focusStateAfter),this.undoStack.push(t),this.emit("redo-performed",{transaction:t}),this.emitStateChange(),!0}finally{this.isPerformingUndoRedo=!1}}undoMutation(t){this.emit("undo-mutation",{mutation:t})}redoMutation(t){this.emit("redo-mutation",{mutation:t})}canUndo(){return this.undoStack.length>0||null!==this.pendingTransaction}canRedo(){return this.redoStack.length>0}getUndoDescription(){return this.pendingTransaction?this.pendingTransaction.description:0===this.undoStack.length?null:this.undoStack[this.undoStack.length-1].description}getRedoDescription(){return 0===this.redoStack.length?null:this.redoStack[this.redoStack.length-1].description}clear(){this.undoStack=[],this.redoStack=[],this.pendingTransaction=null,this.transactionStack=[],this.emit("history-cleared",void 0),this.emitStateChange()}getDescriptionForMutation(t){return{insert:"Typing",delete:"Delete",format:"Format",alignment:"Alignment","field-insert":"Insert Field","field-delete":"Delete Field","field-update":"Update Field","object-insert":"Insert Object","object-delete":"Delete Object","object-resize":"Resize","object-move":"Move","object-property":"Change Property","table-add-row":"Add Row","table-add-column":"Add Column","table-delete-row":"Delete Row","table-delete-column":"Delete Column","table-merge":"Merge Cells","table-split":"Split Cell"}[t.type]||"Change"}emitStateChange(){this.emit("state-changed",{canUndo:this.canUndo(),canRedo:this.canRedo()})}setCoalesceConfig(t){this.coalesceConfig={...this.coalesceConfig,...t}}setMaxHistory(t){for(this.maxHistory=t;this.undoStack.length>this.maxHistory;)this.undoStack.shift()}}class Mt{constructor(t,e){this.getActiveContent=t,this.restoreFocus=e}capture(){const t=this.getActiveContent();if(!t.content)return{activeSection:"body",focusedObjectId:null,tableCellAddress:null,cursorPosition:0,selection:null};const e=t.content.getSelection();return{activeSection:t.section,focusedObjectId:t.focusedObjectId,tableCellAddress:t.tableCellAddress,cursorPosition:t.content.getCursorPosition(),selection:e?{start:e.start,end:e.end}:null}}restore(t){this.restoreFocus(t)}captureFromContent(t,e,i=null,n=null){const o=t.getSelection();return{activeSection:e,focusedObjectId:i,tableCellAddress:n,cursorPosition:t.getCursorPosition(),selection:o?{start:o.start,end:o.end}:null}}}class Et{constructor(t){this.observedContents=new WeakMap,this.manager=t}observe(t,e){if(this.observedContents.has(t)){return void(this.observedContents.get(t).sourceId=e)}const i={insertText:t.insertText.bind(t),deleteText:t.deleteText.bind(t),insertTextAt:t.insertTextAt.bind(t),deleteTextAt:t.deleteTextAt.bind(t),applyFormatting:t.applyFormatting.bind(t),setAlignment:t.setAlignment.bind(t),setAlignmentForRange:t.setAlignmentForRange.bind(t),insertSubstitutionField:t.insertSubstitutionField.bind(t),removeSubstitutionField:t.removeSubstitutionField.bind(t),insertEmbeddedObject:t.insertEmbeddedObject.bind(t),removeEmbeddedObject:t.removeEmbeddedObject.bind(t)};this.observedContents.set(t,{sourceId:e,originalMethods:i}),t.insertText=(e,n)=>{if(this.manager.isUndoRedoInProgress)return i.insertText(e,n);const o=this.captureState(t),s=n??t.getCursorPosition();i.insertText(e,n);const r=this.captureState(t);this.recordMutation(t,{id:kt(),sourceId:this.getSourceId(t),type:"insert",timestamp:Date.now(),beforeState:o,afterState:r,data:{position:s,text:e,formatting:t.getFormattingManager().getFormattingAt(s)}})},t.deleteText=(e,n,o=!0)=>{if(this.manager.isUndoRedoInProgress)return i.deleteText(e,n,o);const s=this.captureState(t),r=t.getText().substring(e,e+n),a=this.captureFormattingInRange(t,e,n),l=this.captureFieldsInRange(t,e,n),d=this.captureObjectsInRange(t,e,n);i.deleteText(e,n,o);const h=this.captureState(t);this.recordMutation(t,{id:kt(),sourceId:this.getSourceId(t),type:"delete",timestamp:Date.now(),beforeState:s,afterState:h,data:{position:e,deletedText:r,deletedFormatting:a,deletedFields:l,deletedObjects:d}})},t.insertTextAt=(e,n)=>{if(this.manager.isUndoRedoInProgress)return i.insertTextAt(e,n);const o=this.captureState(t);i.insertTextAt(e,n);const s=this.captureState(t);this.recordMutation(t,{id:kt(),sourceId:this.getSourceId(t),type:"insert",timestamp:Date.now(),beforeState:o,afterState:s,data:{position:e,text:n}})},t.deleteTextAt=(e,n)=>{if(this.manager.isUndoRedoInProgress)return i.deleteTextAt(e,n);const o=this.captureState(t),s=t.getText().substring(e,e+n),r=this.captureFormattingInRange(t,e,n);i.deleteTextAt(e,n);const a=this.captureState(t);this.recordMutation(t,{id:kt(),sourceId:this.getSourceId(t),type:"delete",timestamp:Date.now(),beforeState:o,afterState:a,data:{position:e,deletedText:s,deletedFormatting:r}})},t.applyFormatting=(e,n,o)=>{if(this.manager.isUndoRedoInProgress)return i.applyFormatting(e,n,o);const s=this.captureState(t),r=this.captureFormattingInRange(t,e,n-e);this.manager.createBoundary(),i.applyFormatting(e,n,o);const a=this.captureState(t);this.recordMutation(t,{id:kt(),sourceId:this.getSourceId(t),type:"format",timestamp:Date.now(),beforeState:s,afterState:a,data:{start:e,end:n,newFormatting:o,previousFormatting:r}})},t.setAlignment=e=>{if(this.manager.isUndoRedoInProgress)return i.setAlignment(e);const n=this.captureState(t),o=t.getCursorPosition(),s=t.getParagraphBoundaries(),r=this.getParagraphIndexFromBoundaries(o,s),a=t.getAlignmentAt(o);this.manager.createBoundary(),i.setAlignment(e);const l=this.captureState(t);this.recordMutation(t,{id:kt(),sourceId:this.getSourceId(t),type:"alignment",timestamp:Date.now(),beforeState:n,afterState:l,data:{paragraphIndex:r,newAlignment:e,previousAlignment:a}})},t.insertSubstitutionField=(e,n)=>{if(this.manager.isUndoRedoInProgress)return i.insertSubstitutionField(e,n);const o=this.captureState(t),s=t.getCursorPosition();this.manager.createBoundary();const r=i.insertSubstitutionField(e,n),a=this.captureState(t),l=t.getSubstitutionFieldManager().getFieldAt(s);return l&&this.recordMutation(t,{id:kt(),sourceId:this.getSourceId(t),type:"field-insert",timestamp:Date.now(),beforeState:o,afterState:a,data:{position:s,field:{...l}}}),r},t.insertEmbeddedObject=(e,n="inline")=>{if(this.manager.isUndoRedoInProgress)return i.insertEmbeddedObject(e,n);const o=this.captureState(t),s=t.getCursorPosition();i.insertEmbeddedObject(e,n);const r=this.captureState(t),a=e.toData();this.recordMutation(t,{id:kt(),sourceId:this.getSourceId(t),type:"object-insert",timestamp:Date.now(),beforeState:o,afterState:r,data:{position:s,objectData:a}})},t.removeEmbeddedObject=e=>{if(this.manager.isUndoRedoInProgress)return i.removeEmbeddedObject(e);const n=t.getEmbeddedObjectAt(e);if(!n)return i.removeEmbeddedObject(e);const o=this.captureState(t),s=n.toData();this.manager.createBoundary();const r=i.removeEmbeddedObject(e),a=this.captureState(t);return this.recordMutation(t,{id:kt(),sourceId:this.getSourceId(t),type:"object-delete",timestamp:Date.now(),beforeState:o,afterState:a,data:{position:e,objectData:s}}),r}}unobserve(t){const e=this.observedContents.get(t);if(!e)return;const{originalMethods:i}=e;t.insertText=i.insertText,t.deleteText=i.deleteText,t.insertTextAt=i.insertTextAt,t.deleteTextAt=i.deleteTextAt,t.applyFormatting=i.applyFormatting,t.setAlignment=i.setAlignment,t.setAlignmentForRange=i.setAlignmentForRange,t.insertSubstitutionField=i.insertSubstitutionField,t.removeSubstitutionField=i.removeSubstitutionField,t.insertEmbeddedObject=i.insertEmbeddedObject,t.removeEmbeddedObject=i.removeEmbeddedObject,this.observedContents.delete(t)}isObserving(t){return this.observedContents.has(t)}getSourceId(t){const e=this.observedContents.get(t);return e?.sourceId??{type:"body"}}captureState(t){const e=t.getSelection();return{cursorPosition:t.getCursorPosition(),selection:e?{start:e.start,end:e.end}:null}}captureFormattingInRange(t,e,i){const n=new Map,o=t.getFormattingManager();for(let t=0;t<i;t++){const i=o.getFormattingAt(e+t);i&&n.set(t,{...i})}return n}captureFieldsInRange(t,e,i){return t.getSubstitutionFieldManager().getFieldsInRange(e,e+i).map(t=>({offset:t.textIndex-e,field:{...t.field}}))}captureObjectsInRange(t,e,i){const n=[],o=t.getEmbeddedObjects();for(const[t,s]of o)t>=e&&t<e+i&&n.push({offset:t-e,objectData:s.toData()});return n}getParagraphIndexFromBoundaries(t,e){for(let i=0;i<e.length;i++)if(t<e[i])return Math.max(0,i-1);return Math.max(0,e.length-1)}recordMutation(t,e){this.manager.recordMutation(e)}}class Lt{constructor(t){this.observedObjects=new WeakMap,this.manager=t}findPropertyDescriptor(t,e){let i=Object.getPrototypeOf(t);for(;i;){const t=Object.getOwnPropertyDescriptor(i,e);if(t)return t;i=Object.getPrototypeOf(i)}}observe(t){if(this.observedObjects.has(t))return;const e={type:this.getObjectType(t),objectId:t.id},i=this.findPropertyDescriptor(t,"size"),n=this.findPropertyDescriptor(t,"width"),o=this.findPropertyDescriptor(t,"height"),s=this.findPropertyDescriptor(t,"relativeOffset"),r={resize:t.resize.bind(t),sizeSetter:i?.set?.bind(t)||(()=>{}),widthSetter:n?.set?.bind(t)||(()=>{}),heightSetter:o?.set?.bind(t)||(()=>{}),relativeOffsetSetter:s?.set?.bind(t)||(()=>{})},a={sourceId:e,originalMethods:r};t instanceof U&&(a.originalTableMethods={insertRow:t.insertRow.bind(t),removeRow:t.removeRow.bind(t),insertColumn:t.insertColumn.bind(t),removeColumn:t.removeColumn.bind(t),mergeCells:t.mergeCells.bind(t),splitCell:t.splitCell.bind(t)},this.wrapTableMethods(t,a.originalTableMethods)),t instanceof T&&(a.originalImageProperties=this.wrapImageProperties(t)),t instanceof L&&(a.originalTextBoxProperties=this.wrapTextBoxProperties(t)),this.observedObjects.set(t,a),this.wrapCommonMethods(t,r,i,n,o,s)}wrapCommonMethods(t,e,i,n,o,s){t.resize=i=>{if(this.manager.isUndoRedoInProgress)return e.resize(i);const n={...t.size};e.resize(i);const o={...t.size};n.width===o.width&&n.height===o.height||this.recordResizeMutation(t,n,o)},Object.defineProperty(t,"size",{get:i?.get?.bind(t),set:i=>{if(this.manager.isUndoRedoInProgress)return void e.sizeSetter(i);const n={...t.size};e.sizeSetter(i),n.width===i.width&&n.height===i.height||this.recordResizeMutation(t,n,i)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"width",{get:n?.get?.bind(t),set:i=>{if(this.manager.isUndoRedoInProgress)return void e.widthSetter(i);const n={...t.size};e.widthSetter(i),n.width!==i&&this.recordResizeMutation(t,n,{width:i,height:t.height})},configurable:!0,enumerable:!0}),Object.defineProperty(t,"height",{get:o?.get?.bind(t),set:i=>{if(this.manager.isUndoRedoInProgress)return void e.heightSetter(i);const n={...t.size};e.heightSetter(i),n.height!==i&&this.recordResizeMutation(t,n,{width:t.width,height:i})},configurable:!0,enumerable:!0}),Object.defineProperty(t,"relativeOffset",{get:s?.get?.bind(t),set:i=>{if(this.manager.isUndoRedoInProgress)return void e.relativeOffsetSetter(i);const n={...t.relativeOffset};e.relativeOffsetSetter(i),n.x===i.x&&n.y===i.y||this.recordMoveMutation(t,n,i)},configurable:!0,enumerable:!0})}wrapImageProperties(t){const e=this.findPropertyDescriptor(t,"fit"),i=this.findPropertyDescriptor(t,"resizeMode"),n=this.findPropertyDescriptor(t,"alt"),o={fitSetter:e?.set?.bind(t)||(()=>{}),resizeModeSetter:i?.set?.bind(t)||(()=>{}),altSetter:n?.set?.bind(t)||(()=>{})};return Object.defineProperty(t,"fit",{get:e?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void o.fitSetter(e);const i=t.fit;o.fitSetter(e),i!==e&&this.recordPropertyMutation(t,"fit",i,e)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"resizeMode",{get:i?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void o.resizeModeSetter(e);const i=t.resizeMode;o.resizeModeSetter(e),i!==e&&this.recordPropertyMutation(t,"resizeMode",i,e)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"alt",{get:n?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void o.altSetter(e);const i=t.alt;o.altSetter(e),i!==e&&this.recordPropertyMutation(t,"alt",i,e)},configurable:!0,enumerable:!0}),o}wrapTextBoxProperties(t){const e=this.findPropertyDescriptor(t,"fontFamily"),i=this.findPropertyDescriptor(t,"fontSize"),n=this.findPropertyDescriptor(t,"color"),o=this.findPropertyDescriptor(t,"backgroundColor"),s=this.findPropertyDescriptor(t,"border"),r=this.findPropertyDescriptor(t,"padding"),a={fontFamilySetter:e?.set?.bind(t)||(()=>{}),fontSizeSetter:i?.set?.bind(t)||(()=>{}),colorSetter:n?.set?.bind(t)||(()=>{}),backgroundColorSetter:o?.set?.bind(t)||(()=>{}),borderSetter:s?.set?.bind(t)||(()=>{}),paddingSetter:r?.set?.bind(t)||(()=>{})};return Object.defineProperty(t,"fontFamily",{get:e?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void a.fontFamilySetter(e);const i=t.fontFamily;a.fontFamilySetter(e),i!==e&&this.recordPropertyMutation(t,"fontFamily",i,e)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"fontSize",{get:i?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void a.fontSizeSetter(e);const i=t.fontSize;a.fontSizeSetter(e),i!==e&&this.recordPropertyMutation(t,"fontSize",i,e)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"color",{get:n?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void a.colorSetter(e);const i=t.color;a.colorSetter(e),i!==e&&this.recordPropertyMutation(t,"color",i,e)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"backgroundColor",{get:o?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void a.backgroundColorSetter(e);const i=t.backgroundColor;a.backgroundColorSetter(e),i!==e&&this.recordPropertyMutation(t,"backgroundColor",i,e)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"border",{get:s?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void a.borderSetter(e);const i={...t.border};a.borderSetter(e),JSON.stringify(i)!==JSON.stringify(e)&&this.recordPropertyMutation(t,"border",i,e)},configurable:!0,enumerable:!0}),Object.defineProperty(t,"padding",{get:r?.get?.bind(t),set:e=>{if(this.manager.isUndoRedoInProgress)return void a.paddingSetter(e);const i=t.padding;a.paddingSetter(e),i!==e&&this.recordPropertyMutation(t,"padding",i,e)},configurable:!0,enumerable:!0}),a}wrapTableMethods(t,e){t.insertRow=(i,n)=>{if(this.manager.isUndoRedoInProgress)return e.insertRow(i,n);const o=this.captureTableSnapshot(t),s=e.insertRow(i,n),r=this.captureTableSnapshot(t);return this.recordTableStructureMutation(t,"table-add-row",o,r),s},t.removeRow=i=>{if(this.manager.isUndoRedoInProgress)return e.removeRow(i);const n=this.captureTableSnapshot(t),o=e.removeRow(i),s=this.captureTableSnapshot(t);return this.recordTableStructureMutation(t,"table-delete-row",n,s),o},t.insertColumn=(i,n)=>{if(this.manager.isUndoRedoInProgress)return e.insertColumn(i,n);const o=this.captureTableSnapshot(t);e.insertColumn(i,n);const s=this.captureTableSnapshot(t);this.recordTableStructureMutation(t,"table-add-column",o,s)},t.removeColumn=i=>{if(this.manager.isUndoRedoInProgress)return e.removeColumn(i);const n=this.captureTableSnapshot(t);e.removeColumn(i);const o=this.captureTableSnapshot(t);this.recordTableStructureMutation(t,"table-delete-column",n,o)},t.mergeCells=i=>{if(this.manager.isUndoRedoInProgress)return e.mergeCells(i);const n=this.captureTableSnapshot(t),o=e.mergeCells(i);if(o.success){const e=this.captureTableSnapshot(t);this.recordTableStructureMutation(t,"table-merge",n,e)}return o},t.splitCell=(i,n)=>{if(this.manager.isUndoRedoInProgress)return e.splitCell(i,n);const o=this.captureTableSnapshot(t),s=e.splitCell(i,n);if(s.success){const e=this.captureTableSnapshot(t);this.recordTableStructureMutation(t,"table-split",o,e)}return s}}unobserve(t){const e=this.observedObjects.get(t);if(!e)return;const{originalMethods:i,originalTableMethods:n,originalImageProperties:o,originalTextBoxProperties:s}=e;t.resize=i.resize;const r=Object.getPrototypeOf(t),a=["size","width","height","relativeOffset"];for(const e of a){const i=Object.getOwnPropertyDescriptor(r,e);i&&Object.defineProperty(t,e,i)}if(n&&t instanceof U&&(t.insertRow=n.insertRow,t.removeRow=n.removeRow,t.insertColumn=n.insertColumn,t.removeColumn=n.removeColumn,t.mergeCells=n.mergeCells,t.splitCell=n.splitCell),o&&t instanceof T){const e=["fit","resizeMode","alt"];for(const i of e){const e=Object.getOwnPropertyDescriptor(r,i);e&&Object.defineProperty(t,i,e)}}if(s&&t instanceof L){const e=["fontFamily","fontSize","color","backgroundColor","border","padding"];for(const i of e){const e=Object.getOwnPropertyDescriptor(r,i);e&&Object.defineProperty(t,i,e)}}this.observedObjects.delete(t)}isObserving(t){return this.observedObjects.has(t)}getObjectType(t){return t instanceof U?"table":t instanceof L?"textbox":t instanceof T?"image":"textbox"}createObjectState(t){return{data:t.toData()}}recordResizeMutation(t,e,i){this.manager.createBoundary();const n={id:kt(),sourceId:{type:this.getObjectType(t),objectId:t.id},type:"object-resize",timestamp:Date.now(),beforeState:this.createObjectState(t),afterState:this.createObjectState(t),data:{previousSize:e,newSize:i}};this.manager.recordMutation(n)}recordMoveMutation(t,e,i){this.manager.createBoundary();const n={id:kt(),sourceId:{type:this.getObjectType(t),objectId:t.id},type:"object-move",timestamp:Date.now(),beforeState:this.createObjectState(t),afterState:this.createObjectState(t),data:{previousOffset:e,newOffset:i}};this.manager.recordMutation(n)}recordPropertyMutation(t,e,i,n){this.manager.createBoundary();const o={id:kt(),sourceId:{type:this.getObjectType(t),objectId:t.id},type:"object-property",timestamp:Date.now(),beforeState:this.createObjectState(t),afterState:this.createObjectState(t),data:{propertyName:e,previousValue:i,newValue:n}};this.manager.recordMutation(o)}recordTableStructureMutation(t,e,i,n){this.manager.createBoundary();const o={id:kt(),sourceId:{type:"table",objectId:t.id},type:e,timestamp:Date.now(),beforeState:{data:i},afterState:{data:n},data:{beforeSnapshot:i,afterSnapshot:n}};this.manager.recordMutation(o)}captureTableSnapshot(t){return t.toData()}}class Bt{constructor(t,e){this.getContent=t,this.getObject=e}undoMutation(t){switch(t.type){case"insert":this.undoInsert(t);break;case"delete":this.undoDelete(t);break;case"format":this.undoFormat(t);break;case"alignment":this.undoAlignment(t);break;case"field-insert":this.undoFieldInsert(t);break;case"field-update":this.undoFieldUpdate(t);break;case"object-insert":this.undoObjectInsert(t);break;case"object-delete":this.undoObjectDelete(t);break;case"object-resize":this.undoResize(t);break;case"object-move":this.undoMove(t);break;case"object-property":this.undoProperty(t);break;case"table-add-row":case"table-add-column":case"table-delete-row":case"table-delete-column":case"table-merge":case"table-split":this.undoTableStructure(t);break;default:j.warn("[pc-editor:MutationUndo] Unknown mutation type for undo:",t.type)}}redoMutation(t){switch(t.type){case"insert":this.redoInsert(t);break;case"delete":this.redoDelete(t);break;case"format":this.redoFormat(t);break;case"alignment":this.redoAlignment(t);break;case"field-insert":this.redoFieldInsert(t);break;case"field-update":this.redoFieldUpdate(t);break;case"object-insert":this.redoObjectInsert(t);break;case"object-delete":this.redoObjectDelete(t);break;case"object-resize":this.redoResize(t);break;case"object-move":this.redoMove(t);break;case"object-property":this.redoProperty(t);break;case"table-add-row":case"table-add-column":case"table-delete-row":case"table-delete-column":case"table-merge":case"table-split":this.redoTableStructure(t);break;default:j.warn("[pc-editor:MutationUndo] Unknown mutation type for redo:",t.type)}}undoInsert(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.deleteTextAt(i.position,i.text.length)}redoInsert(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;if(e.insertTextAt(i.position,i.text),i.formatting){e.getFormattingManager().applyFormatting(i.position,i.position+i.text.length,i.formatting)}}undoDelete(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;if(e.insertTextAt(i.position,i.deletedText),i.deletedFormatting){const t=e.getFormattingManager();i.deletedFormatting.forEach((e,n)=>{t.setFormattingAt(i.position+n,e,!0)})}if(i.deletedFields){const t=e.getSubstitutionFieldManager();for(const{offset:e,field:n}of i.deletedFields)t.insertAt(i.position+e,n)}}redoDelete(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.deleteTextAt(i.position,i.deletedText.length)}undoFormat(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data,n=e.getFormattingManager();i.previousFormatting.forEach((t,e)=>{n.setFormattingAt(i.start+e,t,!0)})}redoFormat(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.getFormattingManager().applyFormatting(i.start,i.end,i.newFormatting)}undoAlignment(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data,n=e.getParagraphFormattingManager(),o=e.getParagraphBoundaries();i.paragraphIndex<o.length&&n.setAlignment(o[i.paragraphIndex],i.previousAlignment)}redoAlignment(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data,n=e.getParagraphFormattingManager(),o=e.getParagraphBoundaries();i.paragraphIndex<o.length&&n.setAlignment(o[i.paragraphIndex],i.newAlignment)}undoFieldInsert(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.removeSubstitutionField(i.position)}redoFieldInsert(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.setCursorPosition(i.position),e.insertSubstitutionField(i.field.fieldName,{fieldType:i.field.fieldType,displayFormat:i.field.displayFormat,defaultValue:i.field.defaultValue,formatting:i.field.formatting})}undoFieldUpdate(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.getSubstitutionFieldManager().updateFieldConfig(i.textIndex,i.previousData)}redoFieldUpdate(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.getSubstitutionFieldManager().updateFieldConfig(i.textIndex,i.newData)}undoObjectInsert(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.deleteTextAt(i.position,1)}redoObjectInsert(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data,n=i.objectData,o=V.create(n);e.insertEmbeddedObjectAt(o,i.position,o.position)}undoObjectDelete(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data,n=i.objectData,o=V.create(n);e.insertEmbeddedObjectAt(o,i.position,o.position)}redoObjectDelete(t){const e=this.getContent(t.sourceId);if(!e)return;const i=t.data;e.deleteTextAt(i.position,1)}undoResize(t){const e=this.getObject(t.sourceId);if(!e)return;const i=t.data;e.width=i.previousSize.width,e.height=i.previousSize.height}redoResize(t){const e=this.getObject(t.sourceId);if(!e)return;const i=t.data;e.width=i.newSize.width,e.height=i.newSize.height}undoMove(t){const e=this.getObject(t.sourceId);if(!e)return;const i=t.data;e.relativeOffset=i.previousOffset}redoMove(t){const e=this.getObject(t.sourceId);if(!e)return;const i=t.data;e.relativeOffset=i.newOffset}undoProperty(t){const e=this.getObject(t.sourceId);if(!e)return;const i=t.data;e[i.propertyName]=i.previousValue}redoProperty(t){const e=this.getObject(t.sourceId);if(!e)return;const i=t.data;e[i.propertyName]=i.newValue}undoTableStructure(t){const e=this.getObject(t.sourceId);if(!(e&&e instanceof U))return;const i=t.data;"restoreFromData"in e&&"function"==typeof e.restoreFromData&&e.restoreFromData(i.beforeSnapshot)}redoTableStructure(t){const e=this.getObject(t.sourceId);if(!(e&&e instanceof U))return;const i=t.data;"restoreFromData"in e&&"function"==typeof e.restoreFromData&&e.restoreFromData(i.afterSnapshot)}}class Ot{constructor(t,e,i){this.currentFocusedContent=null,this.currentSourceId=null,this.registeredContent=new Map,this.mutationObserver=t,this.document=e,this.focusEventSource=i,this.registerDocumentContent(),this.setupFocusTracking()}registerDocumentContent(){this.registerContent(this.document.bodyFlowingContent,{type:"body"}),this.registerContent(this.document.headerFlowingContent,{type:"header"}),this.registerContent(this.document.footerFlowingContent,{type:"footer"})}setupFocusTracking(){this.focusEventSource.on("tablecell-focused",t=>{if(t.cell&&"flowingContent"in t.cell){const e=t.cell.flowingContent,i={type:"tablecell",objectId:t.table.id,cellAddress:{row:t.row,col:t.col}};this.registerContent(e,i),this.setCurrentFocus(e,i)}}),this.focusEventSource.on("textbox-editing-started",t=>{if(t.textBox){const e=t.textBox.flowingContent,i={type:"textbox",objectId:t.textBox.id};this.registerContent(e,i),this.setCurrentFocus(e,i)}}),this.focusEventSource.on("textbox-editing-ended",()=>{this.clearCurrentFocus()}),this.focusEventSource.on("table-editing-ended",()=>{this.clearCurrentFocus()}),this.focusEventSource.on("section-focused",t=>{const e=this.getContentForSection(t.section);e&&this.setCurrentFocus(e,{type:t.section})})}registerContent(t,e){this.mutationObserver.observe(t,e),this.registeredContent.set(t,e)}unregisterContent(t){this.mutationObserver.unobserve(t),this.registeredContent.delete(t)}setCurrentFocus(t,e){this.currentFocusedContent=t,this.currentSourceId=e}clearCurrentFocus(){this.currentFocusedContent=null,this.currentSourceId=null}getCurrentFocus(){return this.currentFocusedContent&&this.currentSourceId?{content:this.currentFocusedContent,sourceId:this.currentSourceId}:null}getContentForSection(t){switch(t){case"body":return this.document.bodyFlowingContent;case"header":return this.document.headerFlowingContent;case"footer":return this.document.footerFlowingContent}}getContentBySourceId(t){if("body"===t.type)return this.document.bodyFlowingContent;if("header"===t.type)return this.document.headerFlowingContent;if("footer"===t.type)return this.document.footerFlowingContent;for(const[e,i]of this.registeredContent)if(this.sameSourceId(t,i))return e;return null}sameSourceId(t,e){return t.type===e.type&&(t.objectId===e.objectId&&(t.cellAddress&&e.cellAddress?t.cellAddress.row===e.cellAddress.row&&t.cellAddress.col===e.cellAddress.col:t.cellAddress===e.cellAddress))}registerObject(t){if(t instanceof L){const e=t.flowingContent,i={type:"textbox",objectId:t.id};this.registerContent(e,i)}t instanceof U&&this.registerTableCells(t)}registerTableCells(t){const e=t.rowCount,i=t.columnCount;for(let n=0;n<e;n++)for(let e=0;e<i;e++){const i=t.getCell(n,e);if(i&&"flowingContent"in i){const o=i.flowingContent,s={type:"tablecell",objectId:t.id,cellAddress:{row:n,col:e}};this.registerContent(o,s)}}}unregisterObject(t){t instanceof L&&this.unregisterContent(t.flowingContent),t instanceof U&&this.unregisterTableCells(t)}unregisterTableCells(t){const e=t.rowCount,i=t.columnCount;for(let n=0;n<e;n++)for(let e=0;e<i;e++){const i=t.getCell(n,e);if(i&&"flowingContent"in i){const t=i.flowingContent;this.unregisterContent(t)}}}clear(){for(const t of this.registeredContent.keys())this.mutationObserver.unobserve(t);this.registeredContent.clear(),this.currentFocusedContent=null,this.currentSourceId=null}}const zt="application/x-pceditor-content";class Dt{toHtml(t){const{text:e,formattingRuns:i}=t;if(!e)return"";if(!i||0===i.length)return this.escapeHtml(e).replace(/\n/g,"<br>");let n="",o=0;for(let t=0;t<e.length;t++){const s=e[t];if(o<i.length&&i[o].index===t){t>0&&(n+="</span>");const e=i[o].formatting;n+=this.createStyledSpan(e),o++}else 0===t&&(0===i.length||i[0].index>0)&&(n+="<span>");n+="\n"===s?"<br>":""===s?'<span data-object="true">[Object]</span>':this.escapeHtml(s)}return e.length>0&&(n+="</span>"),n}fromHtml(t){const e=(new DOMParser).parseFromString(t,"text/html").body,i={text:"",runs:[]};return this.processNode(e,i,null),{text:i.text,formattingRuns:i.runs.length>0?i.runs:void 0}}processNode(t,e,i){if(t.nodeType===Node.TEXT_NODE){const n=t.textContent||"";if(n&&i){const t=e.runs[e.runs.length-1];t&&this.formattingEquals(t.formatting,i)||e.runs.push({index:e.text.length,formatting:i})}return void(e.text+=n)}if(t.nodeType!==Node.ELEMENT_NODE)return;const n=t,o=n.tagName.toLowerCase();if(["p","div","h1","h2","h3","h4","h5","h6","li"].includes(o)&&e.text.length>0&&!e.text.endsWith("\n")&&(e.text+="\n"),"br"===o)return void(e.text+="\n");const s=this.extractFormatting(n,i);for(const i of Array.from(t.childNodes))this.processNode(i,e,s);["p","div","h1","h2","h3","h4","h5","h6","li","tr"].includes(o)&&(e.text.endsWith("\n")||(e.text+="\n"))}extractFormatting(t,e){const i=t.tagName.toLowerCase(),n=t.style,o=e?{...e}:{fontFamily:"Arial",fontSize:12,color:"#000000"};if("b"!==i&&"strong"!==i||(o.fontWeight="bold"),"i"!==i&&"em"!==i||(o.fontStyle="italic"),n.fontFamily&&(o.fontFamily=n.fontFamily.replace(/['"]/g,"").split(",")[0].trim()),n.fontSize){const t=parseFloat(n.fontSize);isNaN(t)||(o.fontSize=n.fontSize.includes("pt")?t:Math.round(.75*t))}return("bold"===n.fontWeight||parseInt(n.fontWeight)>=700)&&(o.fontWeight="bold"),"italic"===n.fontStyle&&(o.fontStyle="italic"),n.color&&(o.color=this.normalizeColor(n.color)),n.backgroundColor&&(o.backgroundColor=this.normalizeColor(n.backgroundColor)),o}formattingEquals(t,e){return t.fontFamily===e.fontFamily&&t.fontSize===e.fontSize&&t.fontWeight===e.fontWeight&&t.fontStyle===e.fontStyle&&t.color===e.color&&t.backgroundColor===e.backgroundColor}createStyledSpan(t){const e=[];return t.fontFamily&&e.push(`font-family: ${t.fontFamily}`),t.fontSize&&e.push(`font-size: ${t.fontSize}pt`),t.fontWeight&&e.push(`font-weight: ${t.fontWeight}`),t.fontStyle&&e.push(`font-style: ${t.fontStyle}`),t.color&&e.push(`color: ${t.color}`),t.backgroundColor&&e.push(`background-color: ${t.backgroundColor}`),`<span style="${e.join("; ")}">`}escapeHtml(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}normalizeColor(t){const e=t.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(e){return`#${parseInt(e[1]).toString(16).padStart(2,"0")}${parseInt(e[2]).toString(16).padStart(2,"0")}${parseInt(e[3]).toString(16).padStart(2,"0")}`}return t}}class jt extends r{constructor(){super(),this.cachedClipboardData=null,this.htmlConverter=new Dt}async copy(t,e={}){const{includePlainText:i=!0,includeHtml:n=!0}=e,o=t.getSelection();if(!o||o.start===o.end)return!1;const s=this.extractSelectionContent(t,o.start,o.end),r={},a=JSON.stringify(s);if(r[zt]=new Blob([a],{type:zt}),i){const t=this.extractPlainText(s.content.text);r["text/plain"]=new Blob([t],{type:"text/plain"})}if(n){const t=this.htmlConverter.toHtml(s.content);r["text/html"]=new Blob([t],{type:"text/html"})}try{return await navigator.clipboard.write([new ClipboardItem(r)]),this.emit("copy",{success:!0,contentType:s.type}),!0}catch(t){try{const t=this.extractPlainText(s.content.text);return await navigator.clipboard.writeText(t),this.cachedClipboardData=s,this.emit("copy",{success:!0,contentType:s.type,fallback:!0}),!0}catch(t){return console.error("Clipboard write failed:",t),this.emit("copy",{success:!1,error:t}),!1}}}async read(t={}){const{preferredFormat:e,asPlainText:i=!1}=t;if(i)try{return{type:"text",data:await navigator.clipboard.readText()}}catch{return{type:"empty",data:null}}try{const t=await navigator.clipboard.read();for(const i of t){if(i.types.includes(zt)&&"html"!==e&&"text"!==e){const t=await i.getType(zt),e=await t.text();return{type:"pceditor",data:JSON.parse(e)}}for(const t of i.types)if(t.startsWith("image/")){return{type:"image",data:await i.getType(t)}}if(i.types.includes("text/html")&&"text"!==e){const t=await i.getType("text/html");return{type:"html",data:await t.text()}}if(i.types.includes("text/plain")){const t=await i.getType("text/plain"),e=await t.text();return this.cachedClipboardData&&this.extractPlainText(this.cachedClipboardData.content.text)===e?{type:"pceditor",data:this.cachedClipboardData}:{type:"text",data:e}}}return{type:"empty",data:null}}catch(t){try{const t=await navigator.clipboard.readText();return this.cachedClipboardData&&this.extractPlainText(this.cachedClipboardData.content.text)===t?{type:"pceditor",data:this.cachedClipboardData}:{type:"text",data:t}}catch{return{type:"empty",data:null}}}}extractSelectionContent(t,e,i){const n=t.getText().substring(e,i);let o="text";const s=n.includes("");s&&""===n.replace(/\uFFFC/g,"").trim()?o="object":s&&(o="mixed");const r=this.extractFormattingRuns(t,e,i),a=this.extractParagraphFormatting(t,e,i),l=this.extractSubstitutionFields(t,e,i),d=this.extractEmbeddedObjects(t,e,i),h=this.extractHyperlinks(t,e,i);return{version:"1.0.0",type:o,content:{text:n,formattingRuns:r.length>0?r:void 0,paragraphFormatting:a.length>0?a:void 0,substitutionFields:l.length>0?l:void 0,embeddedObjects:d.length>0?d:void 0,hyperlinks:h.length>0?h:void 0},metadata:{copiedAt:(new Date).toISOString()}}}extractFormattingRuns(t,e,i){const n=[],o=t.getFormattingManager(),s=o.defaultFormatting;let r=null;for(let t=e;t<i;t++){const i=o.getFormattingAt(t);if(null===r||i.fontFamily!==r.fontFamily||i.fontSize!==r.fontSize||i.fontWeight!==r.fontWeight||i.fontStyle!==r.fontStyle||i.color!==r.color||i.backgroundColor!==r.backgroundColor){(!(i.fontFamily===s.fontFamily&&i.fontSize===s.fontSize&&i.fontWeight===s.fontWeight&&i.fontStyle===s.fontStyle&&i.color===s.color&&i.backgroundColor===s.backgroundColor)||n.length>0)&&n.push({index:t-e,formatting:{fontFamily:i.fontFamily,fontSize:i.fontSize,fontWeight:i.fontWeight,fontStyle:i.fontStyle,color:i.color,backgroundColor:i.backgroundColor}}),r=i}}return n}extractParagraphFormatting(t,e,i){const n=t.getText(),o=t.getParagraphFormattingManager(),s=[],r=new Set;for(let t=e;t<i;t++){const i=o.getParagraphStart(t,n);if(!r.has(i)&&i>=e){r.add(i);const t=o.getFormattingForParagraph(i);s.push({paragraphStart:i-e,formatting:{alignment:t.alignment}})}}const a=o.getParagraphStart(e,n);if(a<e&&!r.has(a)){const t=o.getFormattingForParagraph(a);s.unshift({paragraphStart:0,formatting:{alignment:t.alignment}})}return s}extractSubstitutionFields(t,e,i){return t.getSubstitutionFieldsInRange(e,i).map(t=>({id:t.id,textIndex:t.textIndex-e,fieldName:t.fieldName,fieldType:t.fieldType,displayFormat:t.displayFormat,defaultValue:t.defaultValue,formatting:t.formatting?{fontFamily:t.formatting.fontFamily,fontSize:t.formatting.fontSize,fontWeight:t.formatting.fontWeight,fontStyle:t.formatting.fontStyle,color:t.formatting.color,backgroundColor:t.formatting.backgroundColor}:void 0}))}extractEmbeddedObjects(t,e,i){return t.getEmbeddedObjectsInRange(e,i).map(({textIndex:t,object:i})=>({textIndex:t-e,object:i.toData()}))}extractHyperlinks(t,e,i){return t.getHyperlinksInRange(e,i).map(t=>{const n=Math.max(t.startIndex,e)-e,o=Math.min(t.endIndex,i)-e;return{id:t.id,url:t.url,startIndex:n,endIndex:o,title:t.title,formatting:t.formatting}})}extractPlainText(t){return t.replace(/\uFFFC/g," ").replace(/\s+/g," ").trim()||t.replace(/\uFFFC/g,"")}parseHtml(t){return this.htmlConverter.fromHtml(t)}generateNewIds(t){const e=new Map,i=t=>`${t}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,n={text:t.text,formattingRuns:t.formattingRuns,paragraphFormatting:t.paragraphFormatting};return t.substitutionFields&&(n.substitutionFields=t.substitutionFields.map(t=>{const n=i("field");return e.set(t.id,n),{...t,id:n}})),t.embeddedObjects&&(n.embeddedObjects=t.embeddedObjects.map(t=>{const n=i("obj");return e.set(t.object.id,n),{textIndex:t.textIndex,object:{...t.object,id:n}}})),t.hyperlinks&&(n.hyperlinks=t.hyperlinks.map(t=>{const n=i("link");return e.set(t.id,n),{...t,id:n}})),n}async createImageFromBlob(t){return new Promise((e,i)=>{const n=new FileReader;n.onload=()=>{const t=n.result,o=new Image;o.onload=()=>{e({dataUrl:t,width:o.naturalWidth,height:o.naturalHeight})},o.onerror=i,o.src=t},n.onerror=i,n.readAsDataURL(t)})}}const Ht={detectTables:!0,extractImages:!0,tableConfidenceThreshold:.7,password:""};var Nt;t.PDFImportErrorCode=void 0,(Nt=t.PDFImportErrorCode||(t.PDFImportErrorCode={})).INVALID_PDF="INVALID_PDF",Nt.ENCRYPTED_PDF="ENCRYPTED_PDF",Nt.PASSWORD_REQUIRED="PASSWORD_REQUIRED",Nt.INCORRECT_PASSWORD="INCORRECT_PASSWORD",Nt.EXTRACTION_FAILED="EXTRACTION_FAILED",Nt.IMAGE_EXTRACTION_FAILED="IMAGE_EXTRACTION_FAILED",Nt.PARSING_ERROR="PARSING_ERROR",Nt.UNSUPPORTED_FEATURE="UNSUPPORTED_FEATURE";class Wt extends Error{constructor(t,e,i){super(t),this.code=e,this.details=i,this.name="PDFImportError"}}"undefined"!=typeof window&&(s.GlobalWorkerOptions.workerSrc=`//cdnjs.cloudflare.com/ajax/libs/pdf.js/${s.version}/pdf.worker.min.js`);class Gt{async parse(e,i){let n;try{const t=s.getDocument({data:e,password:i||void 0});n=await t.promise}catch(e){const i=e;if("PasswordException"===i.name)throw i.message?.includes("need a password")?new Wt("This PDF is encrypted and requires a password",t.PDFImportErrorCode.PASSWORD_REQUIRED):new Wt("Incorrect password for encrypted PDF",t.PDFImportErrorCode.INCORRECT_PASSWORD);throw new Wt("Failed to load PDF document",t.PDFImportErrorCode.INVALID_PDF,e)}try{const t=[];for(let e=1;e<=n.numPages;e++){const i=await n.getPage(e),o=await this.extractPage(i,e);t.push(o)}const e=await this.extractMetadata(n);return{pageCount:n.numPages,pages:t,metadata:e}}catch(e){throw new Wt("Failed to extract content from PDF",t.PDFImportErrorCode.EXTRACTION_FAILED,e)}finally{await n.destroy()}}async extractPage(t,e){const i=t.getViewport({scale:1}),n=await t.getTextContent(),o=[];for(const t of n.items)if("str"in t&&t.str){const e=this.convertTextItem(t,i.height);e.text.trim()&&o.push(e)}const s=await this.extractImages(t,i.height);return{pageNumber:e,width:i.width,height:i.height,textItems:o,images:s}}convertTextItem(t,e){const i=t.transform,[n,o,,,s,r]=i,a=Math.sqrt(n*n+o*o),l=this.parseFontName(t.fontName);return{text:t.str,x:s,y:e-r,width:t.width,height:t.height,fontName:t.fontName,fontSize:Math.round(10*a)/10,fontWeight:l.fontWeight,fontStyle:l.fontStyle,transform:i}}parseFontName(t){const e=t.toLowerCase();return{fontWeight:/bold|black|heavy|semibold|demibold/i.test(e)?"bold":"normal",fontStyle:/italic|oblique/i.test(e)?"italic":"normal"}}async extractImages(t,e){const i=[];try{const n=await t.getOperatorList(),o=t.commonObjs,r=t.objs,a=[[1,0,0,1,0,0]];for(let t=0;t<n.fnArray.length;t++){const l=n.fnArray[t],d=n.argsArray[t];if(l===s.OPS.save)a.push([...a[a.length-1]]);else if(l===s.OPS.restore)a.length>1&&a.pop();else if(l===s.OPS.transform){const t=a[a.length-1],e=this.multiplyTransforms(t,d);a[a.length-1]=e}else if(l===s.OPS.paintImageXObject){const t=d[0];try{let n=null;if(r.has(t)?n=r.get(t):o.has(t)&&(n=o.get(t)),n&&n.width&&n.height){const t=a[a.length-1],o=Math.abs(t[0])||n.width,s=Math.abs(t[3])||n.height,r=t[4],l=e-t[5]-s;if(n.data){const t=this.imageDataToDataUrl(n.data,n.width,n.height);t&&i.push({x:r,y:l,width:o,height:s,dataUrl:t,mimeType:"image/png"})}}}catch{j.warn(`[pc-editor:PDFParser] Failed to extract image: ${t}`)}}}}catch(t){j.warn("[pc-editor:PDFParser] Image extraction failed:",t)}return i}multiplyTransforms(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}imageDataToDataUrl(t,e,i){try{const n=document.createElement("canvas");n.width=e,n.height=i;const o=n.getContext("2d");if(!o)return null;const s=new Uint8ClampedArray(t.length);s.set(t);const r=new ImageData(s,e,i);return o.putImageData(r,0,0),n.toDataURL("image/png")}catch{return null}}async extractMetadata(t){try{const e=(await t.getMetadata()).info;if(!e)return;return{title:e.Title,author:e.Author,subject:e.Subject,keywords:e.Keywords,creationDate:e.CreationDate?this.parseDate(e.CreationDate):void 0,modificationDate:e.ModDate?this.parseDate(e.ModDate):void 0}}catch{return}}parseDate(t){try{const e=t.match(/D:(\d{4})(\d{2})(\d{2})(\d{2})?(\d{2})?(\d{2})?/);if(!e)return;const[,i,n,o,s="00",r="00",a="00"]=e;return new Date(parseInt(i),parseInt(n)-1,parseInt(o),parseInt(s),parseInt(r),parseInt(a))}catch{return}}}class Ut{constructor(t){this.options={...Ht,...t}}analyze(t,e){e&&(this.options={...this.options,...e});const i=[],n=[],o=[],s=t.pages[0],r=this.analyzePageLayout(s);for(const e of t.pages){const t=this.groupIntoLines(e.textItems);let s=[];if(this.options.detectTables){s=this.detectTables(t,e.pageNumber);for(const t of s)t.table.confidence>=this.options.tableConfidenceThreshold&&o.push(t.table)}const a=this.groupIntoParagraphs(t,e.pageNumber,r,s);if(i.push(...a),this.options.extractImages){const t=this.analyzeImages(e.images,e.pageNumber);n.push(...t)}}return{paragraphs:i,images:n,tables:o,pageInfo:r}}analyzePageLayout(t){if(0===t.textItems.length)return{width:t.width,height:t.height,margins:{top:72,right:72,bottom:72,left:72}};const e=Math.min(...t.textItems.map(t=>t.x)),i=Math.max(...t.textItems.map(t=>t.x+t.width)),n=Math.min(...t.textItems.map(t=>t.y)),o=Math.max(...t.textItems.map(t=>t.y+t.height));return{width:t.width,height:t.height,margins:{left:Math.max(0,e),right:Math.max(0,t.width-i),top:Math.max(0,n),bottom:Math.max(0,t.height-o)}}}groupIntoLines(t){if(0===t.length)return[];const e=[...t].sort((t,e)=>t.y-e.y||t.x-e.x),i=[];let n=[e[0]],o=e[0].y;const s=t=>.5*t.fontSize;for(let t=1;t<e.length;t++){const r=e[t],a=s(r);Math.abs(r.y-o)<=a?n.push(r):(i.push(this.createLine(n)),n=[r],o=r.y)}return n.length>0&&i.push(this.createLine(n)),i}createLine(t){return t.sort((t,e)=>t.x-e.x),{items:t,y:t[0].y,minX:Math.min(...t.map(t=>t.x)),maxX:Math.max(...t.map(t=>t.x+t.width)),height:Math.max(...t.map(t=>t.height))}}groupIntoParagraphs(t,e,i,n){if(0===t.length)return[];const o=[];let s=[];const r=[];for(let e=1;e<t.length;e++)r.push(t[e].y-t[e-1].y);const a=r.length>0?r.reduce((t,e)=>t+e,0)/r.length:20,l=t=>n.some(e=>t>=e.startLine&&t<=e.endLine);for(let n=0;n<t.length;n++){if(l(n)){s.length>0&&(o.push(this.createParagraph(s,e,i)),s=[]);continue}const r=t[n];if(0===s.length){s.push(r);continue}const d=s[s.length-1],h=r.y-d.y>1.5*a,c=Math.abs(r.minX-d.minX);h||c>20?(o.push(this.createParagraph(s,e,i)),s=[r]):s.push(r)}return s.length>0&&o.push(this.createParagraph(s,e,i)),o}createParagraph(t,e,i){const n=[],o=[];let s=0;for(let e=0;e<t.length;e++){const i=t[e];for(const t of i.items){if(s>0){const t=n[n.length-1];t&&!t.endsWith(" ")&&(n.push(" "),s++)}const e=s;n.push(t.text),s+=t.text.length;const i=this.mapFormatting(t);o.push({startIndex:e,endIndex:s,formatting:i})}e<t.length-1&&(n.push(" "),s++)}const r=this.mergeFormattingRuns(o),a=this.detectAlignment(t,i);return{text:n.join(""),formattingRuns:r,alignment:a,pageNumber:e,y:t[0].y,endsWithNewline:!0}}mapFormatting(t){return{fontFamily:this.mapFontFamily(t.fontName),fontSize:Math.round(t.fontSize),fontWeight:t.fontWeight||"normal",fontStyle:t.fontStyle||"normal",color:t.color?`#${t.color.r.toString(16).padStart(2,"0")}${t.color.g.toString(16).padStart(2,"0")}${t.color.b.toString(16).padStart(2,"0")}`:"#000000"}}mapFontFamily(t){const e={helvetica:"Arial",arial:"Arial",times:"Times New Roman",timesnewroman:"Times New Roman",courier:"Courier New",couriernew:"Courier New",georgia:"Georgia",verdana:"Verdana",tahoma:"Tahoma",trebuchet:"Trebuchet MS",impact:"Impact",comic:"Comic Sans MS"},i=t.toLowerCase().replace(/[-_,.\s]/g,"").replace(/(bold|italic|oblique|regular|medium|light|black|heavy)/gi,"");for(const[t,n]of Object.entries(e))if(i.includes(t))return n;return"Arial"}mergeFormattingRuns(t){if(0===t.length)return[];const e=[t[0]];for(let i=1;i<t.length;i++){const n=t[i],o=e[e.length-1];this.isFormattingEqual(o.formatting,n.formatting)?o.endIndex=n.endIndex:e.push(n)}return e}isFormattingEqual(t,e){return t.fontFamily===e.fontFamily&&t.fontSize===e.fontSize&&t.fontWeight===e.fontWeight&&t.fontStyle===e.fontStyle&&t.color===e.color}detectAlignment(t,e){if(0===t.length)return"left";const i=e.width-e.margins.left-e.margins.right;let n=0,o=0,s=0,r=0;for(const a of t){const t=a.maxX-a.minX,l=Math.abs(a.minX-e.margins.left),d=Math.abs(e.width-e.margins.right-a.maxX),h=Math.abs(a.minX+t/2-e.width/2);t>.9*i&&l<10&&d<10?r++:h<20?s++:d<10&&l>30?o++:n++}const a=Math.max(n,o,s,r);return r===a&&r>0?"justify":s===a?"center":o===a?"right":"left"}detectTables(t,e){const i=[],n=this.detectColumnBoundaries(t);if(n.length<2)return i;let o=-1,s=[];for(let r=0;r<t.length;r++){const a=t[r];if(this.countColumnsUsed(a,n)>=2)-1===o&&(o=r),s.push(a);else{if(s.length>=2){const t=this.createTable(s,n,e);t.confidence>=this.options.tableConfidenceThreshold&&i.push({startLine:o,endLine:r-1,table:t})}o=-1,s=[]}}if(s.length>=2){const r=this.createTable(s,n,e);r.confidence>=this.options.tableConfidenceThreshold&&i.push({startLine:o,endLine:t.length-1,table:r})}return i}detectColumnBoundaries(t){const e=new Map;for(const i of t)for(const t of i.items){const i=5*Math.round(t.x/5);e.set(i,(e.get(i)||0)+1)}const i=Math.max(2,.3*t.length),n=Array.from(e.entries()).filter(([,t])=>t>=i).map(([t])=>t).sort((t,e)=>t-e),o=[];for(const t of n)(0===o.length||t-o[o.length-1]>=30)&&o.push(t);return o}countColumnsUsed(t,e){const i=new Set;for(const n of t.items)for(let t=0;t<e.length;t++){const o=e[t],s=e[t+1]??1/0;if(n.x>=o-15&&n.x<s){i.add(t);break}}return i.size}createTable(t,e,i){const n=[];for(const i of t){const t=e.map(()=>({text:"",items:[]}));for(const n of i.items)for(let i=0;i<e.length;i++){const o=e[i],s=e[i+1]??1/0;if(n.x>=o-15&&n.x<s){t[i].text&&(t[i].text+=" "),t[i].text+=n.text,t[i].items.push(n);break}}n.push({cells:t.map(t=>({text:t.text.trim(),formattingRuns:t.items.length>0?[{startIndex:0,endIndex:t.text.length,formatting:this.mapFormatting(t.items[0])}]:[]}))})}const o=e.map((t,i)=>{const n=e[i+1];return n?n-t:100});let s=0,r=0;for(const t of n)for(const e of t.cells)r++,e.text.length>0&&s++;const a=r>0?s/r:0;return{rows:n,columnWidths:o,pageNumber:i,y:t[0].y,confidence:a}}analyzeImages(t,e){return t.map(t=>({dataUrl:t.dataUrl,width:t.width,height:t.height,pageNumber:e,y:t.y,position:t.width>200?"block":"inline"}))}}class $t{constructor(){this.nextObjectId=1}build(t,e){const i=this.buildFlowingContent(t);return{version:"1.0",pages:this.createPages(e),settings:this.createSettings(t.pageInfo),bodyContent:i,headerContent:this.createEmptyContent(),footerContent:this.createEmptyContent()}}buildFlowingContent(t){const e=[];for(const i of t.paragraphs)e.push({type:"paragraph",pageNumber:i.pageNumber,y:i.y,data:i});for(const i of t.images)e.push({type:"image",pageNumber:i.pageNumber,y:i.y,data:i});for(const i of t.tables)e.push({type:"table",pageNumber:i.pageNumber,y:i.y,data:i});e.sort((t,e)=>t.pageNumber!==e.pageNumber?t.pageNumber-e.pageNumber:t.y-e.y);let i="";const n=[],o=[],s=[];let r=1;for(const t of e){if(t.pageNumber>r)for(;r<t.pageNumber;)i+=g,r++;if("paragraph"===t.type){const e=t.data,s=i.length;o.push({paragraphStart:s,alignment:e.alignment});for(const t of e.formattingRuns)n.push({index:s+t.startIndex,formatting:t.formatting});i+=e.text,e.endsWithNewline&&(i+="\n")}else if("image"===t.type){const e=t.data,n=i.length,o={id:"imported-image-"+this.nextObjectId++,objectType:"image",textIndex:n,position:e.position,size:{width:e.width,height:e.height},data:{src:e.dataUrl,alt:"Imported image"}};s.push({textIndex:n,object:o}),i+=c,"block"===e.position&&(i+="\n")}else if("table"===t.type){const e=t.data,n=i.length,o={id:"imported-table-"+this.nextObjectId++,objectType:"table",textIndex:n,position:"block",size:{width:e.columnWidths.reduce((t,e)=>t+e,0),height:30*e.rows.length},data:{rows:e.rows.length,columns:e.columnWidths.length,columnWidths:e.columnWidths,cells:this.buildTableCells(e)}};s.push({textIndex:n,object:o}),i+=c,i+="\n"}}return{text:i,formattingRuns:this.convertFormattingRuns(n),paragraphFormatting:this.convertParagraphFormatting(o),substitutionFields:[],embeddedObjects:s,repeatingSections:[],hyperlinks:[]}}buildTableCells(t){const e=[];for(let i=0;i<t.rows.length;i++){const n=t.rows[i];for(let t=0;t<n.cells.length;t++){const o=n.cells[t],s=[];o.formattingRuns.length>0&&s.push({index:0,formatting:{fontFamily:o.formattingRuns[0].formatting.fontFamily||d.fontFamily,fontSize:o.formattingRuns[0].formatting.fontSize||d.fontSize,fontWeight:o.formattingRuns[0].formatting.fontWeight,fontStyle:o.formattingRuns[0].formatting.fontStyle,color:o.formattingRuns[0].formatting.color||d.color}}),e.push({row:i,col:t,content:{text:o.text,formattingRuns:s,paragraphFormatting:[],substitutionFields:[],embeddedObjects:[],repeatingSections:[],hyperlinks:[]}})}}return e}convertFormattingRuns(t){return t.map(t=>({index:t.index,formatting:{fontFamily:t.formatting.fontFamily||d.fontFamily,fontSize:t.formatting.fontSize||d.fontSize,fontWeight:t.formatting.fontWeight,fontStyle:t.formatting.fontStyle,color:t.formatting.color||d.color,backgroundColor:t.formatting.backgroundColor}}))}convertParagraphFormatting(t){return t.map(t=>({paragraphStart:t.paragraphStart,formatting:{alignment:t.alignment}}))}createPages(t){const e=[];for(let i=0;i<t;i++)e.push({id:`imported-page-${i+1}`});return e}createSettings(t){let e="A4";const i=t.width,n=t.height;Math.abs(i-612)<10&&Math.abs(n-792)<10?e="Letter":Math.abs(i-612)<10&&Math.abs(n-1008)<10?e="Legal":Math.abs(i-842)<10&&Math.abs(n-1191)<10&&(e="A3");const o=.352778;return{pageSize:e,pageOrientation:i>n?"landscape":"portrait",margins:{top:Math.round(t.margins.top*o),right:Math.round(t.margins.right*o),bottom:Math.round(t.margins.bottom*o),left:Math.round(t.margins.left*o)},units:"mm"}}createEmptyContent(){return{text:"",formattingRuns:[],paragraphFormatting:[],substitutionFields:[],embeddedObjects:[],repeatingSections:[],hyperlinks:[]}}}class Vt{constructor(){this.parser=new Gt,this.analyzer=new Ut,this.builder=new $t}async import(e,i={},n){const o={...Ht,...i},s=[];try{n?.({stage:"parsing",progress:0,message:"Loading PDF document..."});const t=await this.parser.parse(e,o.password);n?.({stage:"parsing",progress:100,message:"PDF parsed successfully"}),n?.({stage:"analyzing",progress:0,message:"Analyzing document structure..."});const i=this.analyzer.analyze(t,{detectTables:o.detectTables,extractImages:o.extractImages,tableConfidenceThreshold:o.tableConfidenceThreshold});if(i.tables.length>0){const t=i.tables.filter(t=>t.confidence<.8);t.length>0&&s.push(`${t.length} table(s) detected with low confidence - please verify structure`)}n?.({stage:"analyzing",progress:100,message:"Content analysis complete"}),n?.({stage:"building",progress:0,message:"Building document..."});const r=this.builder.build(i,t.pageCount);return n?.({stage:"building",progress:100,message:"Document built successfully"}),{document:r,warnings:s,metadata:{title:t.metadata?.title,author:t.metadata?.author,pageCount:t.pageCount}}}catch(e){if(e instanceof Wt)throw e;throw new Wt("Failed to import PDF document",t.PDFImportErrorCode.PARSING_ERROR,e)}}async importFile(e,i={},n){if(!e.type.includes("pdf")&&!e.name.toLowerCase().endsWith(".pdf"))throw new Wt("Invalid file type. Please select a PDF file.",t.PDFImportErrorCode.INVALID_PDF);const o=await e.arrayBuffer();return this.import(o,i,n)}async importUrl(e,i={},n){try{const o=await fetch(e);if(!o.ok)throw new Wt(`Failed to fetch PDF: ${o.statusText}`,t.PDFImportErrorCode.INVALID_PDF);const s=await o.arrayBuffer();return this.import(s,i,n)}catch(e){if(e instanceof Wt)throw e;throw new Wt("Failed to fetch PDF from URL",t.PDFImportErrorCode.INVALID_PDF,e)}}}const Xt=["Arial","Times New Roman","Courier New","Georgia","Verdana"];class Kt extends r{constructor(){super(),this.fonts=new Map;for(const t of Xt)this.fonts.set(t.toLowerCase(),{family:t,source:"built-in",variants:[{weight:"normal",style:"normal",fontData:null,loaded:!0}]})}async registerFont(t){const{family:e,url:i,data:n,weight:o="normal",style:s="normal"}=t;j.log("[pc-editor:FontManager] registerFont",e,o,s);let r=null;if(n)r=n;else if(i)try{const t=await fetch(i);if(!t.ok)throw new Error(`Failed to fetch font: ${t.status} ${t.statusText}`);r=await t.arrayBuffer()}catch(t){throw j.error(`[pc-editor:FontManager] Failed to fetch font "${e}" from ${i}:`,t),t}if(r&&"undefined"!=typeof FontFace)try{const t=new FontFace(e,r,{weight:o,style:s});await t.load(),document.fonts.add(t),j.log("[pc-editor:FontManager] FontFace loaded:",e,o,s)}catch(t){throw j.error(`[pc-editor:FontManager] Failed to load FontFace "${e}":`,t),t}const a=e.toLowerCase();let l=this.fonts.get(a);l?"built-in"===l.source&&(l.source="custom"):(l={family:e,source:"custom",variants:[]},this.fonts.set(a,l));const d=l.variants.find(t=>t.weight===o&&t.style===s);d?(d.fontData=r,d.loaded=!0):l.variants.push({weight:o,style:s,fontData:r,loaded:!0}),this.emit("font-registered",{family:e,weight:o,style:s})}getAvailableFonts(){return Array.from(this.fonts.values())}getAvailableFontFamilies(){return Array.from(this.fonts.values()).map(t=>t.family)}isBuiltIn(t){const e=this.fonts.get(t.toLowerCase());return"built-in"===e?.source}isRegistered(t){return this.fonts.has(t.toLowerCase())}getFontData(t,e="normal",i="normal"){const n=this.fonts.get(t.toLowerCase());if(!n)return null;const o=n.variants.find(t=>t.weight===e&&t.style===i);if(o?.fontData)return o.fontData;const s=n.variants.find(t=>"normal"===t.weight&&"normal"===t.style);return s?.fontData||null}}class Yt extends r{constructor(t,e={}){super(),this._isAttached=!1,this._isVisible=!0,this.editor=null,this.container=null,this.element=null,this.eventCleanup=[],this.id=t,this._isVisible=!1!==e.visible}get isAttached(){return this._isAttached}get isVisible(){return this._isVisible}attach(t){if(this._isAttached)throw new Error(`Control ${this.id} is already attached`);this.editor=t.editor,this.container=t.container,this.element=this.createElement(),this.container.appendChild(this.element),this.setupEventListeners(),this._isAttached=!0,this.update(),this._isVisible||(this.element.style.display="none"),this.emit("attached",{editor:this.editor})}detach(){this._isAttached&&(this.cleanupEventListeners(),this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element),this._isAttached=!1,this.editor=null,this.container=null,this.element=null,this.emit("detached",void 0))}show(){this._isVisible=!0,this.element&&(this.element.style.display="",this.update()),this.emit("visibility-changed",{visible:!0})}hide(){this._isVisible=!1,this.element&&(this.element.style.display="none"),this.emit("visibility-changed",{visible:!1})}toggle(){this._isVisible?this.hide():this.show()}destroy(){this.detach(),this.removeAllListeners()}setupEventListeners(){}cleanupEventListeners(){for(const t of this.eventCleanup)t();this.eventCleanup=[]}addEditorListener(t,e){this.editor&&(this.editor.on(t,e),this.eventCleanup.push(()=>this.editor?.off(t,e)))}}const qt={visible:!0,units:"mm",majorTickInterval:10,minorTicksPerMajor:10,showLabels:!0,thickness:20,backgroundColor:"#f5f5f5",tickColor:"#666666",labelColor:"#333333",activeColor:"#2196f3",labelFontSize:9,showMargins:!0,marginColor:"#666666"},Jt={px:1,pt:96/72,mm:96/25.4,in:96};function Zt(t){return Jt[t]}class Qt extends Yt{constructor(t,e={}){super(t,e),this.canvas=null,this.ctx=null,this.currentMousePosition=null,this.zoomLevel=1,this.scrollOffset=0,this.documentSize=0,this.marginStart=0,this.marginEnd=0,this.resizeObserver=null,this.options={...qt,...e}}createElement(){const t=document.createElement("div");t.className=`pc-ruler pc-ruler-${this.orientation}`,t.style.position="absolute",t.style.overflow="hidden",t.style.backgroundColor=this.options.backgroundColor,"horizontal"===this.orientation?(t.style.height=`${this.options.thickness}px`,t.style.width="100%",t.style.top="0",t.style.left="0",t.style.right="0"):(t.style.width=`${this.options.thickness}px`,t.style.top="0",t.style.bottom="0",t.style.left="0"),this.canvas=document.createElement("canvas"),this.canvas.style.display="block",t.appendChild(this.canvas),this.setupMouseTracking(t),this.resizeObserver=new ResizeObserver(()=>{this.resizeCanvas(),this.render()}),this.resizeObserver.observe(t);const e=()=>{this.update()};return window.addEventListener("resize",e),this.eventCleanup.push(()=>{window.removeEventListener("resize",e)}),t}setupMouseTracking(t){const e=e=>{const i=t.getBoundingClientRect();"horizontal"===this.orientation?this.currentMousePosition=e.clientX-i.left:this.currentMousePosition=e.clientY-i.top,this.render()},i=()=>{this.currentMousePosition=null,this.render()};t.addEventListener("mousemove",e),t.addEventListener("mouseleave",i),this.eventCleanup.push(()=>{t.removeEventListener("mousemove",e),t.removeEventListener("mouseleave",i)})}setupEventListeners(){super.setupEventListeners(),this.addEditorListener("zoom-changed",t=>{this.zoomLevel=t.zoom,this.update()}),this.addEditorListener("settings-changed",()=>{this.update()}),this.addEditorListener("scroll",t=>{this.scrollOffset="horizontal"===this.orientation?t.x:t.y,this.update()}),this.addEditorListener("mouse-move",t=>{this.currentMousePosition="horizontal"===this.orientation?t.x:t.y,this.render()}),this.addEditorListener("mouse-leave",()=>{this.currentMousePosition=null,this.render()})}cleanupEventListeners(){super.cleanupEventListeners(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null)}update(){if(!this._isAttached||!this._isVisible||!this.editor)return;this.zoomLevel=this.editor.getZoomLevel();const t=this.editor.getDocumentMetrics();t&&this.updateFromMetrics(t),this.resizeCanvas(),this.render()}resizeCanvas(){if(!this.canvas||!this.element)return;const t=this.element.getBoundingClientRect();if(0===t.width&&0===t.height)return;const e=window.devicePixelRatio||1;"horizontal"===this.orientation?(this.canvas.width=t.width*e,this.canvas.height=this.options.thickness*e,this.canvas.style.width=`${t.width}px`,this.canvas.style.height=`${this.options.thickness}px`):(this.canvas.width=this.options.thickness*e,this.canvas.height=t.height*e,this.canvas.style.width=`${this.options.thickness}px`,this.canvas.style.height=`${t.height}px`),this.ctx=this.canvas.getContext("2d"),this.ctx&&this.ctx.scale(e,e)}calculateTickMarks(){const t=[],e=Zt(this.options.units)*this.zoomLevel,i=this.options.majorTickInterval,n=i/this.options.minorTicksPerMajor,o=this.getContentOffset(),s=this.getVisibleLength(),r=Math.max(0,-o),a=s-o,l=Math.floor(r/e/n)*n-n,d=Math.ceil(a/e/n)*n+n;for(let o=Math.max(0,l);o<=d;o+=n){const n=o*e,s=Math.abs(o%i)<.001,r={position:n,isMajor:s};s&&this.options.showLabels&&(r.label=String(Math.round(o))),t.push(r)}return t}getVisibleLength(){if(!this.element)return 0;const t=this.element.getBoundingClientRect();return"horizontal"===this.orientation?t.width:t.height}render(){if(!this.ctx||!this.canvas)return;const t="horizontal"===this.orientation?this.canvas.width/(window.devicePixelRatio||1):this.options.thickness,e="horizontal"===this.orientation?this.options.thickness:this.canvas.height/(window.devicePixelRatio||1);this.ctx.fillStyle=this.options.backgroundColor,this.ctx.fillRect(0,0,t,e),this.options.showMargins&&this.renderMargins(t,e);const i=this.calculateTickMarks();this.renderTicks(i,t,e),null!==this.currentMousePosition&&this.renderCursorIndicator(t,e)}}class te extends Yt{constructor(t,e={}){super(t,e),this.sectionElement=null,this.className=e.className||""}attach(t){this.sectionElement=t.sectionElement||null,super.attach(t)}show(){this._isVisible=!0,this.sectionElement&&(this.sectionElement.style.display=""),this.element&&(this.element.style.display="",this.update()),this.emit("visibility-changed",{visible:!0})}hide(){this._isVisible=!1,this.sectionElement&&(this.sectionElement.style.display="none"),this.element&&(this.element.style.display="none"),this.emit("visibility-changed",{visible:!1})}createFormGroup(t,e,i){const n=document.createElement("div");n.className="pc-pane-form-group",i?.inline&&n.classList.add("pc-pane-form-group--inline");const o=document.createElement("label");if(o.className="pc-pane-label",o.textContent=t,n.appendChild(o),n.appendChild(e),i?.hint){const t=document.createElement("span");t.className="pc-pane-hint",t.textContent=i.hint,n.appendChild(t)}return n}createTextInput(t){const e=document.createElement("input");return e.type=t?.type||"text",e.className="pc-pane-input",t?.placeholder&&(e.placeholder=t.placeholder),void 0!==t?.value&&(e.value=t.value),e}createNumberInput(t){const e=document.createElement("input");return e.type="number",e.className="pc-pane-input pc-pane-input--number",void 0!==t?.min&&(e.min=String(t.min)),void 0!==t?.max&&(e.max=String(t.max)),void 0!==t?.step&&(e.step=String(t.step)),void 0!==t?.value&&(e.value=String(t.value)),e}createSelect(t,e){const i=document.createElement("select");i.className="pc-pane-select";for(const n of t){const t=document.createElement("option");t.value=n.value,t.textContent=n.label,n.value===e&&(t.selected=!0),i.appendChild(t)}return i}createColorInput(t){const e=document.createElement("input");return e.type="color",e.className="pc-pane-color",t&&(e.value=t),e}createCheckbox(t,e){const i=document.createElement("label");i.className="pc-pane-checkbox";const n=document.createElement("input");n.type="checkbox",e&&(n.checked=!0);const o=document.createElement("span");return o.textContent=t,i.appendChild(n),i.appendChild(o),i}createButton(t,e){const i=document.createElement("button");return i.type="button",i.className="pc-pane-button",e?.variant&&i.classList.add(`pc-pane-button--${e.variant}`),i.textContent=t,i}createButtonGroup(){const t=document.createElement("div");return t.className="pc-pane-button-group",t}createSection(t){const e=document.createElement("div");if(e.className="pc-pane-section",t){const i=document.createElement("div");i.className="pc-pane-section-label",i.textContent=t,e.appendChild(i)}return e}createRow(){const t=document.createElement("div");return t.className="pc-pane-row",t}createHint(t){const e=document.createElement("div");return e.className="pc-pane-hint",e.textContent=t,e}addImmediateApplyListener(t,e){const i=()=>{e(t.value)};if(t instanceof HTMLSelectElement||t instanceof HTMLInputElement&&"color"===t.type)t.addEventListener("change",i),this.eventCleanup.push(()=>t.removeEventListener("change",i));else{t.addEventListener("blur",i);const e=t=>{"Enter"===t.key&&(t.preventDefault(),i())};t.addEventListener("keydown",e),this.eventCleanup.push(()=>{t.removeEventListener("blur",i),t.removeEventListener("keydown",e)})}}addCheckboxListener(t,e){const i=()=>e(t.checked);t.addEventListener("change",i),this.eventCleanup.push(()=>t.removeEventListener("change",i))}addButtonListener(t,e){const i=t=>{t.preventDefault(),this.saveEditorContext()};t.addEventListener("mousedown",i),t.addEventListener("click",e),this.eventCleanup.push(()=>{t.removeEventListener("mousedown",i),t.removeEventListener("click",e)})}saveEditorContext(){this.editor&&this.editor.saveEditingContext()}createElement(){const t=document.createElement("div");t.className="pc-pane",this.className&&t.classList.add(this.className),t.setAttribute("data-pane-id",this.id);const e=this.createContent();return t.appendChild(e),t}}const ee=["Arial","Times New Roman","Georgia","Verdana","Courier New"],ie=[10,12,14,16,18,20,24,28,32,36];t.BaseControl=Yt,t.BaseEmbeddedObject=_,t.BasePane=te,t.BaseTextRegion=q,t.BodyTextRegion=Z,t.ClipboardManager=jt,t.ConditionalSectionManager=C,t.ConditionalSectionPane=class extends te{constructor(t="conditional-section",e={}){super(t,{className:"pc-pane-conditional-section",...e}),this.predicateInput=null,this.positionHint=null,this.currentSection=null,this.onApplyCallback=e.onApply,this.onRemoveCallback=e.onRemove}attach(t){if(super.attach(t),this.editor){const t=t=>{const e=t.selection||t;if("conditional-section"===e.type&&e.sectionId){const t=this.editor?.getConditionalSection(e.sectionId);t&&this.showSection(t)}else this.hideSection()},e=()=>{this.hideSection()};this.editor.on("selection-change",t),this.editor.on("conditional-section-removed",e),this.eventCleanup.push(()=>{this.editor?.off("selection-change",t),this.editor?.off("conditional-section-removed",e)})}}createContent(){const t=document.createElement("div");this.predicateInput=this.createTextInput({placeholder:"isActive"}),t.appendChild(this.createFormGroup("Condition:",this.predicateInput,{hint:'Boolean expression evaluated against merge data (e.g., "isActive", "count > 0")'}));const e=this.createButton("Apply Changes",{variant:"primary"});this.addButtonListener(e,()=>this.applyChanges()),t.appendChild(e);const i=this.createButton("Remove Condition",{variant:"danger"});return i.style.marginTop="0.5rem",this.addButtonListener(i,()=>this.removeSection()),t.appendChild(i),this.positionHint=this.createHint(""),t.appendChild(this.positionHint),t}showSection(t){this.currentSection=t,this.predicateInput&&(this.predicateInput.value=t.predicate),this.positionHint&&(this.positionHint.textContent=`Condition from position ${t.startIndex} to ${t.endIndex}`),this.show()}hideSection(){this.currentSection=null,this.hide()}applyChanges(){if(!this.editor||!this.currentSection)return void this.onApplyCallback?.(!1,new Error("No section selected"));const t=this.predicateInput?.value.trim();if(t){if(t!==this.currentSection.predicate)try{this.editor.updateConditionalSectionPredicate(this.currentSection.id,t)?(this.currentSection=this.editor.getConditionalSection(this.currentSection.id)||null,this.currentSection&&this.showSection(this.currentSection),this.onApplyCallback?.(!0)):this.onApplyCallback?.(!1,new Error("Failed to update section"))}catch(t){this.onApplyCallback?.(!1,t instanceof Error?t:new Error(String(t)))}}else this.onApplyCallback?.(!1,new Error("Predicate cannot be empty"))}removeSection(){if(this.editor&&this.currentSection)try{this.editor.removeConditionalSection(this.currentSection.id),this.hideSection(),this.onRemoveCallback?.(!0)}catch{this.onRemoveCallback?.(!1)}}getCurrentSection(){return this.currentSection}hasSection(){return null!==this.currentSection}update(){}},t.ContentAnalyzer=Ut,t.DEFAULT_IMPORT_OPTIONS=Ht,t.Document=st,t.DocumentBuilder=$t,t.DocumentInfoPane=class extends te{constructor(t="document-info"){super(t,{className:"pc-pane-document-info"}),this.pageCountEl=null,this.pageSizeEl=null,this.pageOrientationEl=null}attach(t){if(super.attach(t),this.editor){const t=()=>this.update();this.editor.on("document-changed",t),this.editor.on("page-added",t),this.editor.on("page-removed",t),this.eventCleanup.push(()=>{this.editor?.off("document-changed",t),this.editor?.off("page-added",t),this.editor?.off("page-removed",t)}),this.update()}}createContent(){const t=document.createElement("div");return t.className="pc-pane-label-value-grid",t.appendChild(this.createLabel("Pages:")),this.pageCountEl=this.createValue("0"),t.appendChild(this.pageCountEl),t.appendChild(this.createSpacer()),t.appendChild(this.createLabel("Size:")),this.pageSizeEl=this.createValue("-"),t.appendChild(this.pageSizeEl),t.appendChild(this.createSpacer()),t.appendChild(this.createLabel("Orientation:")),this.pageOrientationEl=this.createValue("-"),t.appendChild(this.pageOrientationEl),t.appendChild(this.createSpacer()),t}createLabel(t){const e=document.createElement("span");return e.className="pc-pane-label pc-pane-margin-label",e.textContent=t,e}createValue(t){const e=document.createElement("span");return e.className="pc-pane-info-value",e.textContent=t,e}createSpacer(){return document.createElement("div")}update(){if(!this.editor)return;const t=this.editor.getDocument();if(this.pageCountEl&&(this.pageCountEl.textContent=t.pages.length.toString()),this.pageSizeEl&&t.settings&&(this.pageSizeEl.textContent=t.settings.pageSize),this.pageOrientationEl&&t.settings){const e=t.settings.pageOrientation;this.pageOrientationEl.textContent=e.charAt(0).toUpperCase()+e.slice(1)}}},t.DocumentSettingsPane=class extends te{constructor(t="document-settings"){super(t,{className:"pc-pane-document-settings"}),this.marginTopInput=null,this.marginRightInput=null,this.marginBottomInput=null,this.marginLeftInput=null,this.pageSizeSelect=null,this.orientationSelect=null}attach(t){if(super.attach(t),this.editor){this.loadSettings();const t=()=>this.loadSettings();this.editor.on("document-changed",t),this.eventCleanup.push(()=>{this.editor?.off("document-changed",t)})}}createContent(){const t=document.createElement("div"),e=this.createSection("Margins (mm)"),i=document.createElement("div");i.className="pc-pane-margins-grid-5col",this.marginTopInput=this.createNumberInput({min:5,max:50,step:.5,value:20}),this.marginRightInput=this.createNumberInput({min:5,max:50,step:.5,value:20}),this.marginBottomInput=this.createNumberInput({min:5,max:50,step:.5,value:20}),this.marginLeftInput=this.createNumberInput({min:5,max:50,step:.5,value:20});const n=()=>this.applyMargins();this.marginTopInput.addEventListener("blur",n),this.marginRightInput.addEventListener("blur",n),this.marginBottomInput.addEventListener("blur",n),this.marginLeftInput.addEventListener("blur",n),this.eventCleanup.push(()=>{this.marginTopInput?.removeEventListener("blur",n),this.marginRightInput?.removeEventListener("blur",n),this.marginBottomInput?.removeEventListener("blur",n),this.marginLeftInput?.removeEventListener("blur",n)});const o=this.createMarginLabel("Top:"),s=this.createMarginLabel("Right:");i.appendChild(o),i.appendChild(this.marginTopInput),i.appendChild(s),i.appendChild(this.marginRightInput),i.appendChild(this.createSpacer());const r=this.createMarginLabel("Bottom:"),a=this.createMarginLabel("Left:");i.appendChild(r),i.appendChild(this.marginBottomInput),i.appendChild(a),i.appendChild(this.marginLeftInput),i.appendChild(this.createSpacer()),e.appendChild(i),t.appendChild(e);const l=this.createSection(),d=document.createElement("div");return d.className="pc-pane-label-value-grid",this.pageSizeSelect=this.createSelect([{value:"A4",label:"A4"},{value:"Letter",label:"Letter"},{value:"Legal",label:"Legal"},{value:"A3",label:"A3"}],"A4"),this.addImmediateApplyListener(this.pageSizeSelect,()=>this.applyPageSettings()),d.appendChild(this.createMarginLabel("Page Size:")),d.appendChild(this.pageSizeSelect),d.appendChild(this.createSpacer()),this.orientationSelect=this.createSelect([{value:"portrait",label:"Portrait"},{value:"landscape",label:"Landscape"}],"portrait"),this.addImmediateApplyListener(this.orientationSelect,()=>this.applyPageSettings()),d.appendChild(this.createMarginLabel("Orientation:")),d.appendChild(this.orientationSelect),d.appendChild(this.createSpacer()),l.appendChild(d),t.appendChild(l),t}createMarginLabel(t){const e=document.createElement("label");return e.className="pc-pane-label pc-pane-margin-label",e.textContent=t,e}createSpacer(){return document.createElement("div")}loadSettings(){if(this.editor)try{const t=this.editor.getDocumentSettings();this.marginTopInput&&(this.marginTopInput.value=t.margins.top.toString()),this.marginRightInput&&(this.marginRightInput.value=t.margins.right.toString()),this.marginBottomInput&&(this.marginBottomInput.value=t.margins.bottom.toString()),this.marginLeftInput&&(this.marginLeftInput.value=t.margins.left.toString()),this.pageSizeSelect&&(this.pageSizeSelect.value=t.pageSize),this.orientationSelect&&(this.orientationSelect.value=t.pageOrientation)}catch(t){console.error("Failed to load document settings:",t)}}applyMargins(){if(!this.editor)return;const t={top:parseFloat(this.marginTopInput?.value||"20"),right:parseFloat(this.marginRightInput?.value||"20"),bottom:parseFloat(this.marginBottomInput?.value||"20"),left:parseFloat(this.marginLeftInput?.value||"20")};try{this.editor.updateDocumentSettings({margins:t})}catch(t){console.error("Failed to update margins:",t)}}applyPageSettings(){if(!this.editor)return;const t={};this.pageSizeSelect&&(t.pageSize=this.pageSizeSelect.value),this.orientationSelect&&(t.pageOrientation=this.orientationSelect.value);try{this.editor.updateDocumentSettings(t)}catch(t){console.error("Failed to update page settings:",t)}}update(){this.loadSettings()}},t.EmbeddedObjectFactory=V,t.EmbeddedObjectManager=y,t.EventEmitter=r,t.FlowingTextContent=X,t.FontManager=Kt,t.FooterTextRegion=tt,t.FormattingPane=class extends te{constructor(t="formatting",e={}){super(t,{className:"pc-pane-formatting",...e}),this.boldBtn=null,this.italicBtn=null,this.alignLeftBtn=null,this.alignCenterBtn=null,this.alignRightBtn=null,this.alignJustifyBtn=null,this.bulletListBtn=null,this.numberedListBtn=null,this.indentBtn=null,this.outdentBtn=null,this.fontFamilySelect=null,this.fontSizeSelect=null,this.colorInput=null,this.highlightInput=null,this.fontFamilies=e.fontFamilies??ee,this.fontSizes=e.fontSizes??ie}attach(t){if(super.attach(t),this.editor){this.fontFamilies===ee&&(this.fontFamilies=this.editor.getAvailableFontFamilies(),this.rebuildFontSelect());const t=()=>this.updateFromEditor();this.editor.on("cursor-changed",t),this.editor.on("selection-changed",t),this.editor.on("text-changed",t),this.editor.on("formatting-changed",t);const e=()=>{this.fontFamilies=this.editor.getAvailableFontFamilies(),this.rebuildFontSelect()};this.editor.on("font-registered",e),this.eventCleanup.push(()=>{this.editor?.off("cursor-changed",t),this.editor?.off("selection-changed",t),this.editor?.off("text-changed",t),this.editor?.off("formatting-changed",t),this.editor?.off("font-registered",e)}),this.updateFromEditor()}}createContent(){const t=document.createElement("div"),e=this.createSection("Style"),i=this.createButtonGroup();this.boldBtn=this.createButton("B"),this.boldBtn.title="Bold",this.boldBtn.style.fontWeight="bold",this.addButtonListener(this.boldBtn,()=>this.toggleBold()),this.italicBtn=this.createButton("I"),this.italicBtn.title="Italic",this.italicBtn.style.fontStyle="italic",this.addButtonListener(this.italicBtn,()=>this.toggleItalic()),i.appendChild(this.boldBtn),i.appendChild(this.italicBtn),e.appendChild(i),t.appendChild(e);const n=this.createSection("Alignment"),o=this.createButtonGroup();this.alignLeftBtn=this.createButton(""),this.alignLeftBtn.title="Align Left",this.alignLeftBtn.classList.add("pc-pane-button--icon","pc-pane-button--align-left"),this.addButtonListener(this.alignLeftBtn,()=>this.setAlignment("left")),this.alignCenterBtn=this.createButton(""),this.alignCenterBtn.title="Center",this.alignCenterBtn.classList.add("pc-pane-button--icon","pc-pane-button--align-center"),this.addButtonListener(this.alignCenterBtn,()=>this.setAlignment("center")),this.alignRightBtn=this.createButton(""),this.alignRightBtn.title="Align Right",this.alignRightBtn.classList.add("pc-pane-button--icon","pc-pane-button--align-right"),this.addButtonListener(this.alignRightBtn,()=>this.setAlignment("right")),this.alignJustifyBtn=this.createButton(""),this.alignJustifyBtn.title="Justify",this.alignJustifyBtn.classList.add("pc-pane-button--icon","pc-pane-button--align-justify"),this.addButtonListener(this.alignJustifyBtn,()=>this.setAlignment("justify")),o.appendChild(this.alignLeftBtn),o.appendChild(this.alignCenterBtn),o.appendChild(this.alignRightBtn),o.appendChild(this.alignJustifyBtn),n.appendChild(o),t.appendChild(n);const s=this.createSection("Lists"),r=this.createButtonGroup();this.bulletListBtn=this.createButton("•"),this.bulletListBtn.title="Bullet List",this.addButtonListener(this.bulletListBtn,()=>this.toggleBulletList()),this.numberedListBtn=this.createButton("1."),this.numberedListBtn.title="Numbered List",this.addButtonListener(this.numberedListBtn,()=>this.toggleNumberedList()),this.indentBtn=this.createButton("→"),this.indentBtn.title="Increase Indent",this.addButtonListener(this.indentBtn,()=>this.indent()),this.outdentBtn=this.createButton("←"),this.outdentBtn.title="Decrease Indent",this.addButtonListener(this.outdentBtn,()=>this.outdent()),r.appendChild(this.bulletListBtn),r.appendChild(this.numberedListBtn),r.appendChild(this.indentBtn),r.appendChild(this.outdentBtn),s.appendChild(r),t.appendChild(s);const a=this.createSection("Font"),l=document.createElement("div");l.className="pc-pane-label-value-grid";const d=document.createElement("label");d.className="pc-pane-label pc-pane-margin-label",d.textContent="Family:",this.fontFamilySelect=this.createSelect(this.fontFamilies.map(t=>({value:t,label:t})),"Arial"),this.addImmediateApplyListener(this.fontFamilySelect,()=>this.applyFontFamily()),l.appendChild(d),l.appendChild(this.fontFamilySelect),l.appendChild(document.createElement("div"));const h=document.createElement("label");h.className="pc-pane-label pc-pane-margin-label",h.textContent="Size:",this.fontSizeSelect=this.createSelect(this.fontSizes.map(t=>({value:t.toString(),label:t.toString()})),"14"),this.addImmediateApplyListener(this.fontSizeSelect,()=>this.applyFontSize()),l.appendChild(h),l.appendChild(this.fontSizeSelect),l.appendChild(document.createElement("div")),a.appendChild(l),t.appendChild(a);const c=this.createSection("Color"),g=document.createElement("div");g.className="pc-pane-label-value-grid";const u=document.createElement("label");u.className="pc-pane-label pc-pane-margin-label",u.textContent="Text:",this.colorInput=this.createColorInput("#000000"),this.addImmediateApplyListener(this.colorInput,()=>this.applyTextColor()),g.appendChild(u),g.appendChild(this.colorInput),g.appendChild(document.createElement("div"));const f=document.createElement("label");f.className="pc-pane-label pc-pane-margin-label",f.textContent="Highlight:",this.highlightInput=this.createColorInput("#ffff00"),this.addImmediateApplyListener(this.highlightInput,()=>this.applyHighlight());const p=document.createElement("div");p.style.display="flex",p.style.alignItems="center",p.style.gap="4px",p.appendChild(this.highlightInput);const m=this.createButton("Clear");return m.className="pc-pane-button",this.addButtonListener(m,()=>this.clearHighlight()),p.appendChild(m),g.appendChild(f),g.appendChild(p),g.appendChild(document.createElement("div")),c.appendChild(g),t.appendChild(c),t}rebuildFontSelect(){if(!this.fontFamilySelect)return;const t=this.fontFamilySelect.value;this.fontFamilySelect.innerHTML="";for(const t of this.fontFamilies){const e=document.createElement("option");e.value=t,e.textContent=t,e.style.fontFamily=t,this.fontFamilySelect.appendChild(e)}this.fontFamilies.includes(t)&&(this.fontFamilySelect.value=t)}updateFromEditor(){if(!this.editor)return;const t=this.editor.getUnifiedFormattingAtCursor();t&&(this.boldBtn?.classList.toggle("pc-pane-button--active","bold"===t.fontWeight),this.italicBtn?.classList.toggle("pc-pane-button--active","italic"===t.fontStyle),this.fontFamilySelect&&t.fontFamily&&(this.fontFamilySelect.value=t.fontFamily),this.fontSizeSelect&&t.fontSize&&(this.fontSizeSelect.value=t.fontSize.toString()),this.colorInput&&t.color&&(this.colorInput.value=t.color),this.highlightInput&&t.backgroundColor&&(this.highlightInput.value=t.backgroundColor));const e=this.editor.getUnifiedAlignmentAtCursor();this.updateAlignmentButtons(e),this.updateListButtons()}updateAlignmentButtons(t){const e=[{btn:this.alignLeftBtn,align:"left"},{btn:this.alignCenterBtn,align:"center"},{btn:this.alignRightBtn,align:"right"},{btn:this.alignJustifyBtn,align:"justify"}];for(const{btn:i,align:n}of e)i?.classList.toggle("pc-pane-button--active",n===t)}updateListButtons(){if(this.editor)try{const t=this.editor.getListFormatting();t?(this.bulletListBtn?.classList.toggle("pc-pane-button--active","bullet"===t.listType),this.numberedListBtn?.classList.toggle("pc-pane-button--active","number"===t.listType)):(this.bulletListBtn?.classList.remove("pc-pane-button--active"),this.numberedListBtn?.classList.remove("pc-pane-button--active"))}catch{this.bulletListBtn?.classList.remove("pc-pane-button--active"),this.numberedListBtn?.classList.remove("pc-pane-button--active")}}getSelection(){return this.editor?this.editor.getSavedOrCurrentSelection():null}applyFormatting(t){if(!this.editor)return;const e=this.getSelection();try{e?this.editor.applyFormattingWithFallback(e.start,e.end,t):this.editor.setPendingFormatting(t),this.editor.clearSavedEditingContext(),this.updateFromEditor(),this.editor.enableTextInput()}catch(t){console.error("Formatting error:",t)}}toggleBold(){const t=this.boldBtn?.classList.contains("pc-pane-button--active");this.applyFormatting({fontWeight:t?"normal":"bold"})}toggleItalic(){const t=this.italicBtn?.classList.contains("pc-pane-button--active");this.applyFormatting({fontStyle:t?"normal":"italic"})}applyFontFamily(){this.fontFamilySelect&&this.applyFormatting({fontFamily:this.fontFamilySelect.value})}applyFontSize(){this.fontSizeSelect&&this.applyFormatting({fontSize:parseInt(this.fontSizeSelect.value,10)})}applyTextColor(){this.colorInput&&this.applyFormatting({color:this.colorInput.value})}applyHighlight(){this.highlightInput&&this.applyFormatting({backgroundColor:this.highlightInput.value})}clearHighlight(){this.applyFormatting({backgroundColor:void 0})}setAlignment(t){if(this.editor)try{this.editor.setUnifiedAlignment(t),this.updateAlignmentButtons(t)}catch(t){console.error("Alignment error:",t)}}toggleBulletList(){if(this.editor)try{this.editor.toggleBulletList(),this.updateListButtons()}catch(t){console.error("Bullet list error:",t)}}toggleNumberedList(){if(this.editor)try{this.editor.toggleNumberedList(),this.updateListButtons()}catch(t){console.error("Numbered list error:",t)}}indent(){if(this.editor)try{this.editor.indentParagraph(),this.updateListButtons()}catch(t){console.error("Indent error:",t)}}outdent(){if(this.editor)try{this.editor.outdentParagraph(),this.updateListButtons()}catch(t){console.error("Outdent error:",t)}}update(){this.updateFromEditor()}},t.HeaderTextRegion=Q,t.HorizontalRuler=class extends Qt{constructor(t={}){super("horizontal-ruler",t),this.orientation="horizontal",this.contentOffsetX=0}updateScrollOffset(){if(!this.editor)return;const t=this.editor.getScrollPosition();this.scrollOffset=t.x}getContentOffset(){return this.contentOffsetX}updateFromMetrics(t){if(!t||!this.editor)return;const e=Zt("mm");this.documentSize=t.pageWidth*e*this.zoomLevel,this.marginStart=t.margins.left*e*this.zoomLevel,this.marginEnd=(t.pageWidth-t.margins.right)*e*this.zoomLevel;const i=this.editor.getContentOffset(),n=this.editor.getScrollPosition();this.contentOffsetX=i.x-n.x}calculateTickMarks(){const t=[],e=Zt(this.options.units)*this.zoomLevel,i=this.options.majorTickInterval,n=i/this.options.minorTicksPerMajor,o=this.getContentOffset(),s=this.getVisibleLength(),r=Math.max(0,-o),a=Math.min(this.documentSize,s-o),l=Math.floor(r/e/n)*n-n,d=Math.ceil(a/e/n)*n+n;for(let o=Math.max(0,l);o<=d;o+=n){const n=o*e;if(n>this.documentSize)break;const s=Math.abs(o%i)<.001,r={position:n,isMajor:s};s&&this.options.showLabels&&(r.label=String(Math.round(o))),t.push(r)}return t}renderMargins(t,e){if(!this.ctx)return;const i=this.contentOffsetX,n=i+this.documentSize;i>0&&(this.ctx.fillStyle=this.options.marginColor,this.ctx.fillRect(0,0,i,e)),n<t&&(this.ctx.fillStyle=this.options.marginColor,this.ctx.fillRect(n,0,t-n,e));const o=i+this.marginStart,s=i+this.marginEnd;this.ctx.strokeStyle=this.options.tickColor,this.ctx.lineWidth=1,o>=0&&o<=t&&(this.ctx.beginPath(),this.ctx.moveTo(o,0),this.ctx.lineTo(o,e),this.ctx.stroke()),s>=0&&s<=t&&(this.ctx.beginPath(),this.ctx.moveTo(s,0),this.ctx.lineTo(s,e),this.ctx.stroke())}renderTicks(t,e,i){if(!this.ctx)return;const n=.6*i,o=.3*i;this.ctx.strokeStyle=this.options.tickColor,this.ctx.lineWidth=1,this.ctx.font=`${this.options.labelFontSize}px sans-serif`,this.ctx.fillStyle=this.options.labelColor,this.ctx.textAlign="center",this.ctx.textBaseline="top";const s=this.contentOffsetX;for(const r of t){const t=r.position+s;if(t<-10||t>e+10)continue;const a=r.isMajor?n:o;this.ctx.beginPath(),this.ctx.moveTo(t,i),this.ctx.lineTo(t,i-a),this.ctx.stroke(),r.label&&this.ctx.fillText(r.label,t,2)}}renderCursorIndicator(t,e){this.ctx&&null!==this.currentMousePosition&&(this.ctx.fillStyle=this.options.activeColor,this.ctx.fillRect(this.currentMousePosition-1,0,2,e),this.ctx.beginPath(),this.ctx.moveTo(this.currentMousePosition-4,e),this.ctx.lineTo(this.currentMousePosition+4,e),this.ctx.lineTo(this.currentMousePosition,e-6),this.ctx.closePath(),this.ctx.fill())}},t.HtmlConverter=Dt,t.HyperlinkPane=class extends te{constructor(t="hyperlink",e={}){super(t,{className:"pc-pane-hyperlink",...e}),this.urlInput=null,this.titleInput=null,this.rangeHint=null,this.currentHyperlink=null,this._isUpdating=!1,this.onApply=e.onApply,this.onRemove=e.onRemove}attach(t){if(super.attach(t),this.editor){const t=()=>this.updateFromCursor();this.editor.on("cursor-changed",t),this.editor.on("selection-changed",t),this.eventCleanup.push(()=>{this.editor?.off("cursor-changed",t),this.editor?.off("selection-changed",t)}),this.updateFromCursor()}}createContent(){const t=document.createElement("div");this.urlInput=this.createTextInput({placeholder:"https://example.com"}),t.appendChild(this.createFormGroup("URL:",this.urlInput)),this.titleInput=this.createTextInput({placeholder:"Link title (optional)"}),t.appendChild(this.createFormGroup("Title:",this.titleInput));const e=this.createButton("Apply Changes",{variant:"primary"});this.addButtonListener(e,()=>this.applyChanges()),t.appendChild(e);const i=this.createButton("Remove Link",{variant:"danger"});return i.style.marginTop="0.5rem",this.addButtonListener(i,()=>this.removeHyperlink()),t.appendChild(i),this.rangeHint=this.createHint(""),t.appendChild(this.rangeHint),t}updateFromCursor(){if(this.editor&&!this._isUpdating){this._isUpdating=!0;try{const t=this.editor.getCursorPosition(),e=this.editor.getHyperlinkAt(t);e?this.showHyperlink(e):this.hideHyperlink()}finally{this._isUpdating=!1}}}showHyperlink(t){this.currentHyperlink=t,this.urlInput&&(this.urlInput.value=t.url),this.titleInput&&(this.titleInput.value=t.title||""),this.rangeHint&&(this.rangeHint.textContent=`Link spans characters ${t.startIndex} to ${t.endIndex}`),this.show()}hideHyperlink(){this.currentHyperlink=null,this.hide()}applyChanges(){if(this.editor&&this.currentHyperlink)try{const t=this.urlInput?.value.trim()||"",e=this.titleInput?.value.trim()||void 0;if(!t)return void this.onApply?.(!1,new Error("URL is required"));this.editor.updateHyperlink(this.currentHyperlink.id,{url:t,title:e}),this.currentHyperlink.url=t,this.currentHyperlink.title=e,this.onApply?.(!0)}catch(t){this.onApply?.(!1,t instanceof Error?t:new Error(String(t)))}}removeHyperlink(){if(this.editor&&this.currentHyperlink)try{this.editor.removeHyperlink(this.currentHyperlink.id),this.hideHyperlink(),this.onRemove?.(!0)}catch{this.onRemove?.(!1)}}getCurrentHyperlink(){return this.currentHyperlink}hasHyperlink(){return null!==this.currentHyperlink}update(){this.updateFromCursor()}},t.ImageObject=T,t.ImagePane=class extends te{constructor(t="image",e={}){super(t,{className:"pc-pane-image",...e}),this.positionSelect=null,this.offsetGroup=null,this.offsetXInput=null,this.offsetYInput=null,this.fitModeSelect=null,this.resizeModeSelect=null,this.altTextInput=null,this.fileInput=null,this.currentImage=null,this._isUpdating=!1,this.maxImageWidth=e.maxImageWidth??400,this.maxImageHeight=e.maxImageHeight??400,this.onApplyCallback=e.onApply}attach(t){if(super.attach(t),this.editor){const t=()=>this.updateFromSelection();this.editor.on("selection-change",t),this.editor.on("image-updated",t),this.eventCleanup.push(()=>{this.editor?.off("selection-change",t),this.editor?.off("image-updated",t)}),this.updateFromSelection()}}createContent(){const t=document.createElement("div"),e=this.createSection("Position");this.positionSelect=this.createSelect([{value:"inline",label:"Inline"},{value:"block",label:"Block"},{value:"relative",label:"Relative"}],"inline"),this.addImmediateApplyListener(this.positionSelect,()=>{this.updateOffsetVisibility(),this.applyChanges()}),e.appendChild(this.createFormGroup("Type:",this.positionSelect,{inline:!0})),this.offsetGroup=document.createElement("div"),this.offsetGroup.style.display="none";const i=this.createRow();this.offsetXInput=this.createNumberInput({value:0}),this.offsetYInput=this.createNumberInput({value:0}),this.addImmediateApplyListener(this.offsetXInput,()=>this.applyChanges()),this.addImmediateApplyListener(this.offsetYInput,()=>this.applyChanges()),i.appendChild(this.createFormGroup("X:",this.offsetXInput,{inline:!0})),i.appendChild(this.createFormGroup("Y:",this.offsetYInput,{inline:!0})),this.offsetGroup.appendChild(i),e.appendChild(this.offsetGroup),t.appendChild(e),t.appendChild(document.createElement("hr"));const n=document.createElement("div");n.className="pc-pane-image-display",this.fitModeSelect=this.createSelect([{value:"contain",label:"Contain"},{value:"cover",label:"Cover"},{value:"fill",label:"Fill"},{value:"none",label:"None (original size)"},{value:"tile",label:"Tile"}],"contain"),this.addImmediateApplyListener(this.fitModeSelect,()=>this.applyChanges()),n.appendChild(this.createFormGroup("Fit Mode:",this.fitModeSelect,{inline:!0})),this.resizeModeSelect=this.createSelect([{value:"locked-aspect-ratio",label:"Lock Aspect Ratio"},{value:"free",label:"Free Resize"}],"locked-aspect-ratio"),this.addImmediateApplyListener(this.resizeModeSelect,()=>this.applyChanges()),n.appendChild(this.createFormGroup("Resize Mode:",this.resizeModeSelect,{inline:!0})),t.appendChild(n),t.appendChild(document.createElement("hr")),this.altTextInput=this.createTextInput({placeholder:"Description of the image"}),this.addImmediateApplyListener(this.altTextInput,()=>this.applyChanges()),t.appendChild(this.createFormGroup("Alt Text:",this.altTextInput,{inline:!0})),t.appendChild(document.createElement("hr")),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/*",this.fileInput.style.display="none",this.fileInput.addEventListener("change",t=>this.handleFileChange(t)),t.appendChild(this.fileInput);const o=this.createButton("Change Image...");return this.addButtonListener(o,()=>this.fileInput?.click()),t.appendChild(o),t}updateFromSelection(){if(this.editor&&!this._isUpdating){this._isUpdating=!0;try{const t=this.editor.getSelectedImage?.();t?this.showImage(t):this.hideImage()}finally{this._isUpdating=!1}}}showImage(t){this.currentImage=t,this.positionSelect&&(this.positionSelect.value=t.position||"inline"),this.updateOffsetVisibility(),this.offsetXInput&&(this.offsetXInput.value=String(t.relativeOffset?.x??0)),this.offsetYInput&&(this.offsetYInput.value=String(t.relativeOffset?.y??0)),this.fitModeSelect&&(this.fitModeSelect.value=t.fit||"contain"),this.resizeModeSelect&&(this.resizeModeSelect.value=t.resizeMode||"locked-aspect-ratio"),this.altTextInput&&(this.altTextInput.value=t.alt||""),this.show()}hideImage(){this.currentImage=null,this.hide()}updateOffsetVisibility(){this.offsetGroup&&this.positionSelect&&(this.offsetGroup.style.display="relative"===this.positionSelect.value?"block":"none")}handleFileChange(t){if(!this.editor||!this.currentImage)return;const e=t.target,i=e.files?.[0];if(!i)return;const n=new FileReader;n.onload=t=>{const e=t.target?.result;e&&this.currentImage&&this.editor&&this.editor.setImageSource(this.currentImage.id,e,{maxWidth:this.maxImageWidth,maxHeight:this.maxImageHeight})},n.readAsDataURL(i),e.value=""}applyChanges(){if(!this.editor||!this.currentImage)return void this.onApplyCallback?.(!1,new Error("No image selected"));const t={};this.positionSelect&&(t.position=this.positionSelect.value),"relative"===this.positionSelect?.value&&(t.relativeOffset={x:parseInt(this.offsetXInput?.value||"0",10),y:parseInt(this.offsetYInput?.value||"0",10)}),this.fitModeSelect&&(t.fit=this.fitModeSelect.value),this.resizeModeSelect&&(t.resizeMode=this.resizeModeSelect.value),this.altTextInput&&(t.alt=this.altTextInput.value);try{this.editor.updateImage(this.currentImage.id,t)?this.onApplyCallback?.(!0):this.onApplyCallback?.(!1,new Error("Failed to update image"))}catch(t){this.onApplyCallback?.(!1,t instanceof Error?t:new Error(String(t)))}}getCurrentImage(){return this.currentImage}hasImage(){return null!==this.currentImage}update(){this.updateFromSelection()}},t.Logger=j,t.MergeDataPane=class extends te{constructor(t="merge-data",e={}){super(t,{className:"pc-pane-merge-data",...e}),this.textarea=null,this.errorHint=null,this.initialData=e.initialData,this.placeholder=e.placeholder||'{"customerName": "John Doe", "orderNumber": "12345"}',this.rows=e.rows??10,this.onApply=e.onApply}createContent(){const t=document.createElement("div"),e=this.createFormGroup("JSON Data:",this.createTextarea());t.appendChild(e),this.errorHint=this.createHint(""),this.errorHint.style.display="none",this.errorHint.style.color="#dc3545",t.appendChild(this.errorHint);const i=this.createButton("Apply Merge Data",{variant:"primary"});return this.addButtonListener(i,()=>this.applyMergeData()),t.appendChild(i),t}createTextarea(){return this.textarea=document.createElement("textarea"),this.textarea.className="pc-pane-textarea pc-pane-merge-data-input",this.textarea.rows=this.rows,this.textarea.placeholder=this.placeholder,this.textarea.spellcheck=!1,this.initialData&&(this.textarea.value=JSON.stringify(this.initialData,null,2)),this.textarea.addEventListener("input",()=>{this.errorHint&&(this.errorHint.style.display="none")}),this.textarea}applyMergeData(){if(this.editor&&this.textarea)try{const t=JSON.parse(this.textarea.value);this.editor.applyMergeData(t),this.errorHint&&(this.errorHint.style.display="none"),this.onApply?.(!0)}catch(t){const e=t instanceof Error?t:new Error(String(t));this.errorHint&&(t instanceof SyntaxError?this.errorHint.textContent="Invalid JSON syntax":this.errorHint.textContent=e.message,this.errorHint.style.display="block"),this.onApply?.(!1,e)}}getData(){if(!this.textarea)return null;try{return JSON.parse(this.textarea.value)}catch{return null}}setData(t){this.textarea&&(this.textarea.value=JSON.stringify(t,null,2),this.errorHint&&(this.errorHint.style.display="none"))}update(){}},t.PCEditor=class extends r{constructor(t,e){if(super(),this._isReady=!1,this.keyboardListenerActive=!1,this.currentSelection={type:"none"},this._activeEditingSection="body",this._wasTextEditing=!1,this._textEditingSource=null,this._savedEditingContext=null,!t)throw new Error("Container element is required");this.container=t,this.options=this.mergeOptions(e),j.setEnabled(this.options.enableLogging??!1),this.document=new st,this.document.updateSettings({pageSize:this.options.pageSize,pageOrientation:this.options.pageOrientation,units:this.options.units}),this.dataBinder=new yt,this.fontManager=new Kt,this.pdfGenerator=new _t(this.fontManager),this.clipboardManager=new jt,this.initialize()}mergeOptions(t){return{pageSize:t?.pageSize||"A4",pageOrientation:t?.pageOrientation||"portrait",customPageSize:t?.customPageSize,units:t?.units||"mm",gridSize:t?.gridSize||10,showGrid:t?.showGrid??!0,showRulers:t?.showRulers??!0,showControlCharacters:t?.showControlCharacters??!1,defaultFont:t?.defaultFont||"Arial",defaultFontSize:t?.defaultFontSize||12,theme:t?.theme||"light",enableLogging:t?.enableLogging??!1}}initialize(){try{this.setupContainer(),this.canvasManager=new xt(this.container,this.document,this.options),this.layoutEngine=new Pt(this.document,{autoFlow:!0,snapToGrid:this.options.showGrid,gridSize:this.options.gridSize}),this.canvasManager.initialize(),this.setupEventListeners(),this.setupKeyboardListeners(),this.setupTransactionUndo(),this._isReady=!0,queueMicrotask(()=>this.emit("ready"))}catch(t){console.error("Failed to initialize editor:",t),this.emit("error",{error:t})}}setupContainer(){this.container.style.position="relative","dark"===this.options.theme?this.container.classList.add("pc-editor-dark"):this.container.classList.add("pc-editor-light")}setupEventListeners(){this.document.on("change",()=>{this.emit("document-change",{document:this.document.toData()}),this.canvasManager&&this.canvasManager.render()}),this.document.on("settings-changed",()=>{this.canvasManager&&(this.canvasManager.updateCanvasSizes(),this.canvasManager.render(),setTimeout(()=>{this.canvasManager.checkForEmptyPages()},50)),this.emit("settings-changed")}),this.canvasManager.on("selection-change",t=>{this.emitSelectionChange()}),this.canvasManager.on("element-added",t=>{this.emit("element-added",t)}),this.canvasManager.on("element-removed",t=>{this.emit("element-removed",t)}),this.layoutEngine.on("page-added",t=>{this.canvasManager.setDocument(this.document),this.emit("page-added",t)}),this.layoutEngine.on("page-break-created",t=>{this.canvasManager.setDocument(this.document),this.emit("page-break-created",t)}),this.layoutEngine.on("layout-complete",t=>{this.canvasManager.render(),this.emit("layout-complete",t)}),this.canvasManager.on("text-clicked",t=>{this.enableTextInput(),this.emit("text-clicked",t)}),this.canvasManager.on("textbox-editing-started",t=>{this.keyboardListenerActive=!0,this.container.focus(),this.emit("textbox-editing-started",t)}),this.canvasManager.on("textbox-editing-ended",()=>{this.keyboardListenerActive=!1,this.emit("textbox-editing-ended",{})}),this.canvasManager.on("cursor-changed",t=>{if(void 0!==t.textIndex){const e=this.canvasManager.getFlowingContentForActiveSection();if(!(e?.hasSelection()??!1)){const e=t.section||this._activeEditingSection;e!==this._activeEditingSection&&(this._activeEditingSection=e),this.currentSelection={type:"cursor",position:t.textIndex,section:e},this.emitSelectionChange()}}this.emit("cursor-changed",t)}),this.canvasManager.on("text-selection-changed",t=>{if(t.selection&&t.selection.start!==t.selection.end){const e=t.section||this._activeEditingSection;e!==this._activeEditingSection&&(this._activeEditingSection=e),this.currentSelection={type:"text",start:t.selection.start,end:t.selection.end,section:e},this.emitSelectionChange()}}),this.canvasManager.on("tablecell-cursor-changed",t=>{this.emit("tablecell-cursor-changed",t)}),this.canvasManager.on("table-cell-selection-changed",t=>{this.emit("table-cell-selection-changed",t)}),this.canvasManager.on("table-row-loop-clicked",t=>{this.emit("table-row-loop-clicked",t)}),this.canvasManager.on("repeating-section-clicked",t=>{t.section&&t.section.id&&(this.currentSelection={type:"repeating-section",sectionId:t.section.id},this.emitSelectionChange())}),this.canvasManager.on("conditional-section-clicked",t=>{t.section&&t.section.id&&(this.currentSelection={type:"conditional-section",sectionId:t.section.id},this.emitSelectionChange())}),this.canvasManager.on("section-focus-changed",t=>{t.section&&t.section!==this._activeEditingSection&&(this._activeEditingSection=t.section,this.emit("section-focus-changed",t))}),this.canvasManager.on("focus-changed",t=>{t.control&&this.enableTextInput(),this.checkAndEmitTextEditingEvents()}),this.canvasManager.on("textbox-editing-started",()=>{this.checkAndEmitTextEditingEvents()}),this.canvasManager.on("textbox-editing-ended",()=>{this.checkAndEmitTextEditingEvents()}),this.canvasManager.on("zoom-change",t=>{this.emit("zoom-changed",t)}),this.canvasManager.on("scroll",t=>{this.emit("scroll",t)}),this.canvasManager.on("mouse-move",t=>{this.emit("mouse-move",t)}),this.canvasManager.on("mouse-leave",()=>{this.emit("mouse-leave")})}getFlowingContentForSection(t){switch(t){case"header":return this.document.headerFlowingContent;case"footer":return this.document.footerFlowingContent;default:return this.document.bodyFlowingContent}}setupTransactionUndo(){const t=new Mt(()=>{const t=this._activeEditingSection,e=this.canvasManager?.getFocusedControl();if(e instanceof U&&e.focusedCell){const i=e.getCell(e.focusedCell.row,e.focusedCell.col);if(i&&"flowingContent"in i)return{content:i.flowingContent,section:t,focusedObjectId:e.id,tableCellAddress:e.focusedCell}}if(this.canvasManager?.isEditingTextBox()){const e=this.canvasManager.getEditingTextBox();if(e)return{content:e.flowingContent,section:t,focusedObjectId:e.id,tableCellAddress:null}}return{content:this.getFlowingContentForSection(t),section:t,focusedObjectId:null,tableCellAddress:null}},t=>{this._activeEditingSection=t.activeSection,t.focusedObjectId;const e=this.getFlowingContentForSection(t.activeSection);e&&(e.setCursorPosition(t.cursorPosition),t.selection&&e.setSelection(t.selection.start,t.selection.end)),this.canvasManager?.render()});this.transactionManager=new At(t,t=>{if("body"===t.type)return this.document.bodyFlowingContent;if("header"===t.type)return this.document.headerFlowingContent;if("footer"===t.type)return this.document.footerFlowingContent;if("tablecell"===t.type&&t.objectId&&t.cellAddress){const e=this.findObjectById(t.objectId);if(e){const i=e.getCell(t.cellAddress.row,t.cellAddress.col);if(i&&"flowingContent"in i)return i.flowingContent}}if("textbox"===t.type&&t.objectId){const e=this.findObjectById(t.objectId);if(e)return e.flowingContent}return null},t=>this.findObjectById(t.objectId)),this.textMutationObserver=new Et(this.transactionManager),this.objectMutationObserver=new Lt(this.transactionManager),this.observeAllEmbeddedObjects(),this.mutationUndo=new Bt(t=>this.transactionManager.getContent(t),t=>this.transactionManager.getObject(t)),this.transactionManager.on("undo-mutation",t=>{this.mutationUndo.undoMutation(t.mutation)}),this.transactionManager.on("redo-mutation",t=>{this.mutationUndo.redoMutation(t.mutation)}),this.transactionManager.on("state-changed",t=>{this.emit("undo-state-changed",t)}),this._contentDiscovery=new Ot(this.textMutationObserver,{bodyFlowingContent:this.document.bodyFlowingContent,headerFlowingContent:this.document.headerFlowingContent,footerFlowingContent:this.document.footerFlowingContent},this.canvasManager),this._contentDiscovery}findObjectById(t){for(const[,e]of this.document.bodyFlowingContent.getEmbeddedObjects())if(e.id===t)return e;for(const[,e]of this.document.headerFlowingContent.getEmbeddedObjects())if(e.id===t)return e;for(const[,e]of this.document.footerFlowingContent.getEmbeddedObjects())if(e.id===t)return e;return null}observeAllEmbeddedObjects(){for(const[,t]of this.document.bodyFlowingContent.getEmbeddedObjects())this.objectMutationObserver.observe(t);for(const[,t]of this.document.headerFlowingContent.getEmbeddedObjects())this.objectMutationObserver.observe(t);for(const[,t]of this.document.footerFlowingContent.getEmbeddedObjects())this.objectMutationObserver.observe(t)}observeEmbeddedObject(t){this.objectMutationObserver&&this.objectMutationObserver.observe(t)}get isReady(){return this._isReady}getSelection(){return this.currentSelection}getTextSelection(){const t=this.getEditingFlowingContent()||this.getActiveFlowingContent();return t?t.getSelection():null}getActiveSection(){return this._activeEditingSection}setActiveSection(t){j.log("[pc-editor] setActiveSection",t),this._activeEditingSection!==t&&(this._activeEditingSection=t,this.canvasManager.setActiveSection(t))}getActiveFlowingContent(){switch(this._activeEditingSection){case"header":return this.document.headerFlowingContent;case"footer":return this.document.footerFlowingContent;default:return this.document.bodyFlowingContent}}emitSelectionChange(){this.emit("selection-change",{selection:this.currentSelection})}emitTableCellCursorChanged(t){if(!t.focusedCell)return;const e=t.getCell(t.focusedCell.row,t.focusedCell.col);e&&this.emit("tablecell-cursor-changed",{table:t,cell:e,cursorPosition:e.flowingContent.getCursorPosition(),selection:e.flowingContent.getSelection()})}getTextEditingSource(){const t=this.canvasManager.getFocusedControl();return t instanceof X?"body":this.canvasManager.isEditingTextBox()?"textbox":t instanceof U&&t.focusedCell?"tablecell":null}checkAndEmitTextEditingEvents(){const t=this.getTextEditingSource(),e=null!==t;if(e&&!this._wasTextEditing)this._wasTextEditing=!0,this._textEditingSource=t,this.emit("text-editing-started",{source:t});else if(!e&&this._wasTextEditing){const t=this._textEditingSource;this._wasTextEditing=!1,this._textEditingSource=null,this.emit("text-editing-ended",{source:t})}else if(e&&this._wasTextEditing&&t!==this._textEditingSource){const e=this._textEditingSource;this._textEditingSource=t,this.emit("text-editing-ended",{source:e}),this.emit("text-editing-started",{source:t})}}loadDocument(t){if(j.log("[pc-editor] loadDocument"),!this._isReady)throw new Error("Editor is not ready");this.document.clear(),this.document=new st(t),this.canvasManager.setDocument(this.document),this._activeEditingSection="body",this.currentSelection={type:"none"},this.clearUndoHistory(),this.layoutEngine.destroy(),this.layoutEngine=new Pt(this.document,{autoFlow:!0,snapToGrid:this.options.showGrid,gridSize:this.options.gridSize}),this.setupEventListeners(),this.setupTransactionUndo(),this.emit("document-loaded",{document:t})}getDocument(){return this.document.toData()}bindData(t){if(j.log("[pc-editor] bindData"),!this._isReady)throw new Error("Editor is not ready");const e=this.dataBinder.bind(this.document.toData(),t);this.loadDocument(e),this.emit("data-bound",{data:t})}async exportPDF(t){if(j.log("[pc-editor] exportPDF"),!this._isReady)throw new Error("Editor is not ready");let e=null;try{t?.applyMergeData&&t?.mergeData&&(e=this.document.toData(),this.applyMergeData(t.mergeData),this.canvasManager.render());const i=this.canvasManager.getFlowedPagesSnapshot(),n=await this.pdfGenerator.generate(this.document,i,t);return this.emit("pdf-exported"),n}catch(t){throw console.error("Failed to export PDF:",t),this.emit("error",{error:t,context:"pdf-export"}),t}finally{e&&this.loadDocument(e)}}saveDocument(){if(j.log("[pc-editor] saveDocument"),!this._isReady)throw new Error("Editor is not ready");const t=this.document.toData();return JSON.stringify(t,null,2)}saveDocumentToFile(t="document.pceditor.json"){j.log("[pc-editor] saveDocumentToFile",t);const e=this.saveDocument(),i=new Blob([e],{type:"application/json"}),n=URL.createObjectURL(i),o=document.createElement("a");o.href=n,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(n),this.emit("document-saved",{filename:t})}loadDocumentFromJSON(t){if(j.log("[pc-editor] loadDocumentFromJSON"),!this._isReady)throw new Error("Editor is not ready");try{const e=JSON.parse(t);this.validateDocumentData(e),this.loadDocument(e),this.emit("document-loaded-from-json",{version:e.version})}catch(t){throw this.emit("error",{error:t,context:"load-document"}),t}}async loadDocumentFromFile(t){if(j.log("[pc-editor] loadDocumentFromFile",t.name),!this._isReady)throw new Error("Editor is not ready");return new Promise((e,i)=>{const n=new FileReader;n.onload=t=>{try{const i=t.target?.result;this.loadDocumentFromJSON(i),e()}catch(t){i(t)}},n.onerror=()=>{const t=new Error("Failed to read file");this.emit("error",{error:t,context:"file-read"}),i(t)},n.readAsText(t)})}async importPDF(e,i,n){if(!this._isReady)throw new Error("Editor is not ready");const o=new Vt;let s;try{if(e instanceof File)s=await o.importFile(e,i,n);else if(e instanceof ArrayBuffer)s=await o.import(e,i,n);else{if("string"!=typeof e)throw new Wt("Invalid source type. Expected File, ArrayBuffer, or URL string.",t.PDFImportErrorCode.INVALID_PDF);s=await o.importUrl(e,i,n)}return this.loadDocument(s.document),this.emit("pdf-imported",{pageCount:s.metadata?.pageCount||0,warnings:s.warnings,metadata:s.metadata}),s}catch(t){throw this.emit("error",{error:t,context:"pdf-import"}),t}}validateDocumentData(t){if(!t||"object"!=typeof t)throw new Error("Invalid document data: expected object");const e=t;if("string"!=typeof e.version)throw new Error("Invalid document data: missing or invalid version");if(!Array.isArray(e.pages))throw new Error("Invalid document data: missing or invalid pages array");for(const t of e.pages)if(!t||"object"!=typeof t||"string"!=typeof t.id)throw new Error("Invalid document data: page missing id");const[i]=e.version.split(".").map(Number);i>1&&j.warn(`[pc-editor] Document version ${e.version} may not be fully compatible with this editor`)}selectElement(t){if(j.log("[pc-editor] selectElement",t),!this._isReady)throw new Error("Editor is not ready");this.canvasManager.selectElement(t)}clearSelection(){if(j.log("[pc-editor] clearSelection"),!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection()}removeEmbeddedObject(t){if(j.log("[pc-editor] removeEmbeddedObject",t),!this._isReady)throw new Error("Editor is not ready");this.canvasManager.removeEmbeddedObject(t)}undo(){if(j.log("[pc-editor] undo"),!this._isReady)return;this.transactionManager.undo()&&this.canvasManager.render(),this.emit("undo")}redo(){if(j.log("[pc-editor] redo"),!this._isReady)return;this.transactionManager.redo()&&this.canvasManager.render(),this.emit("redo")}canUndo(){return this.transactionManager.canUndo()}canRedo(){return this.transactionManager.canRedo()}clearUndoHistory(){this.transactionManager.clear()}setMaxUndoHistory(t){this.transactionManager.setMaxHistory(t)}zoomIn(){j.log("[pc-editor] zoomIn"),this._isReady&&this.canvasManager.zoomIn()}zoomOut(){j.log("[pc-editor] zoomOut"),this._isReady&&this.canvasManager.zoomOut()}setZoom(t){j.log("[pc-editor] setZoom",t),this._isReady&&this.canvasManager.setZoom(t)}getZoomLevel(){return this._isReady?this.canvasManager.getZoom():1}getContainer(){return this.container}getScrollPosition(){return this._isReady?this.canvasManager.getScrollPosition():{x:0,y:0}}getContentOffset(){return this._isReady?this.canvasManager.getContentOffset():{x:0,y:0}}fitToWidth(){j.log("[pc-editor] fitToWidth"),this._isReady&&this.canvasManager.fitToWidth()}render(){j.log("[pc-editor] render"),this._isReady&&this.canvasManager.render()}fitToPage(){j.log("[pc-editor] fitToPage"),this._isReady&&this.canvasManager.fitToPage()}setAutoFlow(t){if(j.log("[pc-editor] setAutoFlow",t),!this._isReady)throw new Error("Editor is not ready");this.layoutEngine.setAutoFlow(t)}reflowDocument(){if(j.log("[pc-editor] reflowDocument"),!this._isReady)throw new Error("Editor is not ready");this.layoutEngine.reflowDocument()}setSnapToGrid(t){if(!this._isReady)throw new Error("Editor is not ready");this.layoutEngine.setSnapToGrid(t,this.options.gridSize)}getDocumentMetrics(){if(!this._isReady)return null;const t=this.document.settings,e={A4:{width:210,height:297},Letter:{width:215.9,height:279.4},Legal:{width:215.9,height:355.6},A3:{width:297,height:420}};let i=e[t.pageSize]||e.A4;return"Custom"===t.pageSize&&t.customPageSize&&(i={width:t.customPageSize.width,height:t.customPageSize.height}),"landscape"===t.pageOrientation&&(i={width:i.height,height:i.width}),{pageWidth:i.width,pageHeight:i.height,margins:t.margins,totalPages:this.document.pages.length}}addPage(){if(j.log("[pc-editor] addPage"),!this._isReady)throw new Error("Editor is not ready");const t={id:`page_${Date.now()}_${Math.random().toString(36).substr(2,9)}`},e=new a(t,this.document.settings);this.document.addPage(e),this.canvasManager.setDocument(this.document)}removePage(t){if(j.log("[pc-editor] removePage",t),!this._isReady)throw new Error("Editor is not ready");if(this.document.pages.length<=1)throw new Error("Cannot remove the last page");this.document.removePage(t),this.canvasManager.setDocument(this.document)}setupKeyboardListeners(){this.container.setAttribute("tabindex","0"),this.container.addEventListener("keydown",t=>{this.keyboardListenerActive&&this.handleKeyDown(t)}),this.container.addEventListener("blur",()=>{this.disableTextInput()}),this.container.addEventListener("focus",()=>{this.enableTextInput()})}handleKeyDown(t){if((t.ctrlKey||t.metaKey)&&!t.shiftKey&&"z"===t.key)return t.preventDefault(),void this.undo();if((t.ctrlKey||t.metaKey)&&("y"===t.key||t.shiftKey&&"Z"===t.key))return t.preventDefault(),void this.redo();if((t.ctrlKey||t.metaKey)&&"c"===t.key)return t.preventDefault(),void this.copy();if((t.ctrlKey||t.metaKey)&&"x"===t.key)return t.preventDefault(),void this.cut();if((t.ctrlKey||t.metaKey)&&"v"===t.key)return t.preventDefault(),void this.paste();if((t.ctrlKey||t.metaKey)&&"a"===t.key)return t.preventDefault(),void this.selectAll();if(this.canvasManager.hasSelectedElements()){const e=this.canvasManager.getEditingTextBox(),i=this.canvasManager.getFocusedControl();if(!(e?.editing||i instanceof U&&i.editing)){if(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(t.key)&&this.canvasManager.clearSelection(),"Backspace"===t.key||"Delete"===t.key)return t.preventDefault(),void this.deleteSelectedElements()}}const e=this.canvasManager.getFocusedControl();if(j.log("[pc-editor:handleKeyDown] Key:",t.key,"focusedControl:",e?.constructor?.name),!e)return;if("ArrowUp"===t.key||"ArrowDown"===t.key)return t.preventDefault(),void this.handleVerticalNavigation(t,e);let i=null,n=null;const o=this.canvasManager.getEditingTextBox();"Escape"===t.key&&(o&&o.editing?(i=o.textIndex,n=o.id):e instanceof U&&e.editing&&(i=e.textIndex,n=e.id)),j.log("[pc-editor:handleKeyDown] Calling focusedControl.handleKeyDown");const s=e.handleKeyDown(t);if(j.log("[pc-editor:handleKeyDown] handled:",s),s){this.canvasManager.render();const o=this.canvasManager.getEditingTextBox();if(o&&(o.editing?this.emit("textbox-cursor-changed",{textBox:o,cursorPosition:o.flowingContent.getCursorPosition(),selection:o.flowingContent.getSelection()}):this.canvasManager.setEditingTextBox(null)),e instanceof U&&e.focusedCell){const t=e.getCell(e.focusedCell.row,e.focusedCell.col);t&&this.emit("tablecell-cursor-changed",{table:e,cell:t,cursorPosition:t.flowingContent.getCursorPosition(),selection:t.flowingContent.getSelection()})}"Escape"===t.key&&null!==n&&null!==i&&this.returnFocusToParentFlowingContent(n,i)}else"Escape"===t.key&&this.handleEscapeForSelectedElements()}handleEscapeForSelectedElements(){const t=this.canvasManager.getSelectedElements();if(0!==t.length){for(const e of t){const t=this.findEmbeddedObjectInfo(e);if(t)return this.canvasManager.clearSelection(),t.content.setCursorPosition(t.textIndex),this.canvasManager.setFocus(t.content),t.section!==this.canvasManager.getActiveSection()&&this.canvasManager.setActiveSection(t.section),void this.canvasManager.render()}this.canvasManager.clearSelection(),this.canvasManager.render()}}deleteSelectedElements(){const t=this.canvasManager.getSelectedElements();if(0!==t.length){for(const e of t){const t=this.findEmbeddedObjectInfo(e);if(t){t.content.deleteText(t.textIndex,1);const e=Math.min(t.textIndex,t.content.getText().length);t.content.setCursorPosition(e),this.canvasManager.setFocus(t.content),t.section!==this.canvasManager.getActiveSection()&&this.canvasManager.setActiveSection(t.section)}}this.canvasManager.clearSelection(),this.canvasManager.render(),this.emit("content-changed",{})}}findEmbeddedObjectInfo(t){const e=[];this.document.headerFlowingContent&&e.push({content:this.document.headerFlowingContent,section:"header"}),e.push({content:this.document.bodyFlowingContent,section:"body"}),this.document.footerFlowingContent&&e.push({content:this.document.footerFlowingContent,section:"footer"});for(const{content:i,section:n}of e){const e=i.getEmbeddedObjectManager().findById(t);if(e)return{content:i,section:n,textIndex:e.object.textIndex}}return null}returnFocusToParentFlowingContent(t,e){const i=[];this.document.headerFlowingContent&&i.push({content:this.document.headerFlowingContent,section:"header"}),i.push({content:this.document.bodyFlowingContent,section:"body"}),this.document.footerFlowingContent&&i.push({content:this.document.footerFlowingContent,section:"footer"});for(const{content:n,section:o}of i){if(n.getEmbeddedObjectManager().findById(t))return n.setCursorPosition(e),this.canvasManager.setFocus(n),o!==this.canvasManager.getActiveSection()&&this.canvasManager.setActiveSection(o),void this.canvasManager.render()}}handleVerticalNavigation(t,e){const i="ArrowUp"===t.key?-1:1,n=this.canvasManager.getEditingTextBox();if(e instanceof U){const n=e;if(n.focusedCell){const e=n.getCell(n.focusedCell.row,n.focusedCell.col);if(e){const o=e.flowingContent,s=e.getFlowedLines(0),r=o.getCursorPosition();t.shiftKey?o.hasSelectionAnchor()||o.setSelectionAnchor():o.clearSelection();let a=0;for(let t=0;t<s.length;t++){if(r<=s[t].endIndex){a=t;break}t===s.length-1&&(a=t)}const l=0===a,d=a===s.length-1||0===s.length;if(-1===i&&l){const t=n.focusedCell.row-1;if(t>=0){n.focusCell(t,n.focusedCell.col);const e=n.getCell(t,n.focusedCell.col);if(e){const t=e.flowingContent.getText();e.flowingContent.setCursorPosition(t.length)}}return this.canvasManager.render(),void this.emitTableCellCursorChanged(n)}if(1===i&&d){const t=n.focusedCell.row+1;if(t<n.rowCount){n.focusCell(t,n.focusedCell.col);const e=n.getCell(t,n.focusedCell.col);e&&e.flowingContent.setCursorPosition(0)}return this.canvasManager.render(),void this.emitTableCellCursorChanged(n)}const h=a+i;if(h>=0&&h<s.length){const t=s[h],e=r-s[a].startIndex,i=t.endIndex-t.startIndex,n=Math.min(e,i);o.setCursorPosition(t.startIndex+n),o.resetCursorBlink()}this.canvasManager.render(),this.emitTableCellCursorChanged(n)}}return}const o=n?n.flowingContent:this.getActiveFlowingContent();if(t.shiftKey?o.hasSelectionAnchor()||o.setSelectionAnchor():o.clearSelection(),n){const t=this.canvasManager.getEditingTextBoxPageId();if(t){const e=this.canvasManager.getContext(t);e&&(n.moveCursorVertical(i,e),this.canvasManager.render(),this.emit("textbox-cursor-changed",{textBox:n,cursorPosition:n.flowingContent.getCursorPosition(),selection:n.flowingContent.getSelection()}))}}else{const t=this.canvasManager.moveCursorVertical(i);null!==t&&(o.setCursorPosition(t),o.resetCursorBlink()),this.canvasManager.render()}}enableTextInput(){if(this.keyboardListenerActive=!0,this.canvasManager.isEditingTextBox())this.emit("text-input-enabled");else{if(this.canvasManager.getFocusedControl())return this.canvasManager.isCursorSuspended()&&this.canvasManager.resumeCursor(),this.container.focus(),void this.emit("text-input-enabled");this.canvasManager.showTextCursor(),this.container.focus(),this.emit("text-input-enabled")}}disableTextInput(){this.keyboardListenerActive=!1,this.canvasManager.hideTextCursor(),this.emit("text-input-disabled")}isEditingTextBox(){return this.canvasManager.isEditingTextBox()}isTextEditing(){const t=this.canvasManager.getFocusedControl();return t instanceof X||(!!this.canvasManager.isEditingTextBox()||!!(t instanceof U&&t.focusedCell))}getEditingFlowingContent(){const t=this.canvasManager.getFocusedControl();if(t instanceof X)return t;const e=this.canvasManager.getEditingTextBox();if(e)return e.flowingContent;if(t instanceof U&&t.focusedCell){const e=t.getCell(t.focusedCell.row,t.focusedCell.col);if(e)return e.flowingContent}return null}saveEditingContext(){const t=this.getEditingFlowingContent();if(t){const e=t.getSelection();this._savedEditingContext={flowingContent:t,selection:e&&e.start!==e.end?{start:e.start,end:e.end}:null}}}getSavedOrCurrentSelection(){const t=this.getUnifiedSelection();return t||(this._savedEditingContext?.selection?this._savedEditingContext.selection:null)}applyFormattingWithFallback(t,e,i){j.log("[pc-editor] applyFormattingWithFallback",t,e,i);let n=this.getEditingFlowingContent();if(!n&&this._savedEditingContext&&(n=this._savedEditingContext.flowingContent),!n)throw new Error("No text is being edited");n.applyFormatting(t,e,i),this.canvasManager.render()}setPendingFormatting(t){let e=this.getEditingFlowingContent();if(!e&&this._savedEditingContext&&(e=this._savedEditingContext.flowingContent),!e)throw new Error("No text is being edited");e.setPendingFormatting(t)}getPendingFormatting(){const t=this.getEditingFlowingContent();return t?t.getPendingFormatting():null}hasPendingFormatting(){const t=this.getEditingFlowingContent();return!!t&&t.hasPendingFormatting()}clearPendingFormatting(){const t=this.getEditingFlowingContent();t&&t.clearPendingFormatting()}clearSavedEditingContext(){this._savedEditingContext=null}getEditingTextBox(){return this.canvasManager.getEditingTextBox()}getTextBoxSelection(){const t=this.canvasManager.getEditingTextBox();if(!t)return null;const e=t.flowingContent.getSelection();return e?{start:e.start,end:e.end}:null}applyTextBoxFormatting(t,e,i){const n=this.canvasManager.getEditingTextBox();if(!n)throw new Error("No text box is being edited");n.flowingContent.applyFormatting(t,e,i),this.canvasManager.render()}getTextBoxFormattingAtCursor(){const t=this.canvasManager.getEditingTextBox();if(!t)return null;const e=t.flowingContent.getSelection();if(e&&e.start!==e.end)return t.flowingContent.getFormattingAt(e.start);const i=t.flowingContent.getCursorPosition();return t.flowingContent.getFormattingAt(i)}setTextBoxAlignment(t){const e=this.canvasManager.getEditingTextBox();if(!e)throw new Error("No text box is being edited");const i=e.flowingContent.getSelection();i&&i.start!==i.end?e.flowingContent.setAlignmentForRange(i.start,i.end,t):e.flowingContent.setAlignment(t),this.canvasManager.render()}getTextBoxAlignmentAtCursor(){const t=this.canvasManager.getEditingTextBox();if(!t)return"left";const e=t.flowingContent.getCursorPosition();return t.flowingContent.getAlignmentAt(e)}getUnifiedFormattingAtCursor(){const t=this.getEditingFlowingContent();if(!t)return null;const e=t.getSelection();return e&&e.start!==e.end?t.getFormattingAt(e.start):t.getEffectiveFormattingAtCursor()}applyUnifiedFormatting(t,e,i){const n=this.getEditingFlowingContent();if(!n)throw new Error("No text is being edited");n.applyFormatting(t,e,i),this.canvasManager.render()}getUnifiedSelection(){const t=this.getEditingFlowingContent();if(!t)return null;const e=t.getSelection();return e&&e.start!==e.end?{start:e.start,end:e.end}:null}getUnifiedAlignmentAtCursor(){const t=this.getEditingFlowingContent();if(!t)return"left";const e=t.getCursorPosition();return t.getAlignmentAt(e)}setUnifiedAlignment(t){j.log("[pc-editor] setUnifiedAlignment",t);const e=this.getEditingFlowingContent();if(!e)throw new Error("No text is being edited");const i=e.getSelection();i&&i.start!==i.end?e.setAlignmentForRange(i.start,i.end,t):e.setAlignment(t),this.canvasManager.render()}insertText(t){if(j.log("[pc-editor] insertText",t),!this._isReady)throw new Error("Editor is not ready");const e=this.getActiveFlowingContent();e&&e.insertText(t)}getFlowingText(){if(!this._isReady)throw new Error("Editor is not ready");const t=this.getActiveFlowingContent();return t?t.getText():""}setFlowingText(t){if(j.log("[pc-editor] setFlowingText"),!this._isReady)throw new Error("Editor is not ready");const e=this.getActiveFlowingContent();e&&e.setText(t)}setCursorPosition(t){if(j.log("[pc-editor] setCursorPosition",t),!this._isReady)throw new Error("Editor is not ready");let e=this.getEditingFlowingContent();e||(e=this.getActiveFlowingContent()),e&&(e.setCursorPosition(t),this.currentSelection={type:"cursor",position:t,section:this._activeEditingSection},this.emitSelectionChange())}getCursorPosition(){const t=this.currentSelection;if("cursor"===t.type)return t.position;if("text"===t.type)return t.start;const e=this.getEditingFlowingContent()||this.getActiveFlowingContent();return e?e.getCursorPosition():0}insertEmbeddedObject(t,e="inline"){if(j.log("[pc-editor] insertEmbeddedObject",t.id,e),!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection();let i=this.getEditingFlowingContent();if(i||(i=this.getActiveFlowingContent()),!i)throw new Error("No active section available");i.insertEmbeddedObject(t,e),this.observeEmbeddedObject(t),this.canvasManager.render(),this.emit("embedded-object-added",{object:t,position:e,section:this._activeEditingSection})}insertSubstitutionField(t,e){if(j.log("[pc-editor] insertSubstitutionField",t),!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection();let i=this.getEditingFlowingContent();if(i||(i=this.getActiveFlowingContent()),!i)throw new Error("No active section available");const n=i.insertSubstitutionField(t,e);this.canvasManager.render(),this.emit("substitution-field-added",{field:n,section:this._activeEditingSection})}insertPageNumberField(t){if(j.log("[pc-editor] insertPageNumberField"),!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection();let e=this.getEditingFlowingContent();if(e||(e=this.getActiveFlowingContent()),!e)throw new Error("No active section available");const i=e.insertPageNumberField(t);this.canvasManager.render(),this.emit("page-number-field-added",{field:i,section:this._activeEditingSection})}insertPageCountField(t){if(j.log("[pc-editor] insertPageCountField"),!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection();let e=this.getEditingFlowingContent();if(e||(e=this.getActiveFlowingContent()),!e)throw new Error("No active section available");const i=e.insertPageCountField(t);this.canvasManager.render(),this.emit("page-count-field-added",{field:i,section:this._activeEditingSection})}insertPageBreak(){if(j.log("[pc-editor] insertPageBreak"),!this._isReady)throw new Error("Editor is not ready");const t=this.document.bodyFlowingContent;if(!t.hasFocus())throw new Error("Page breaks can only be inserted in body content");t.insertPageBreak(),this.canvasManager.render(),this.emit("page-break-inserted",{position:t.getCursorPosition()})}getFieldAt(t){if(!this._isReady)return null;const e=this.getActiveFlowingContent();if(!e)return null;const i=e.getSubstitutionFieldManager();return i.getFieldAt(t)||i.getFieldAt(t-1)||null}getSelectedField(){const t=this.currentSelection;return"cursor"===t.type?this.getFieldAt(t.position):"text"===t.type?this.getFieldAt(t.start):null}getSelectedTextBox(){const t=this.canvasManager.getSelectedElements();if(0===t.length)return null;const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjects();for(const i of t)for(const[,t]of e.entries())if(t.id===i&&t instanceof L)return t}return null}getSelectedTable(){const t=this.canvasManager.getSelectedElements();if(0===t.length)return null;const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjects();for(const i of t)for(const[,t]of e.entries())if(t.id===i&&t instanceof U)return t}return null}getSelectedImage(){const t=this.canvasManager.getSelectedElements();if(0===t.length)return null;const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjects();for(const i of t)for(const[,t]of e.entries())if(t.id===i&&t instanceof T)return t}return null}getFocusedTable(){const t=this.canvasManager?.getFocusedControl();return t&&t instanceof U?t:null}updateTextBox(t,e){if(!this._isReady)return!1;const i=this.findTextBoxById(t);if(!i)return j.warn(`[pc-editor:updateTextBox] Text box not found: ${t}`),!1;if(void 0!==e.position&&(i.position=e.position),void 0!==e.relativeOffset&&(i.relativeOffset=e.relativeOffset),void 0!==e.backgroundColor&&(i.backgroundColor=e.backgroundColor),void 0!==e.border){const t=i.border;i.border={top:e.border.top||t.top,right:e.border.right||t.right,bottom:e.border.bottom||t.bottom,left:e.border.left||t.left}}return void 0!==e.padding&&(i.padding=e.padding),this.render(),this.emit("textbox-updated",{textBoxId:t,updates:e}),!0}findTextBoxById(t){const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjects();for(const[,i]of e.entries())if(i.id===t&&i instanceof L)return i}return null}updateImage(t,e){if(!this._isReady)return!1;const i=this.findImageById(t);return i?(void 0!==e.position&&(i.position=e.position),void 0!==e.relativeOffset&&(i.relativeOffset=e.relativeOffset),void 0!==e.fit&&(i.fit=e.fit),void 0!==e.resizeMode&&(i.resizeMode=e.resizeMode),void 0!==e.alt&&(i.alt=e.alt),this.render(),this.emit("image-updated",{imageId:t,updates:e}),!0):(j.warn(`[pc-editor:updateImage] Image not found: ${t}`),!1)}setImageSource(t,e,i){if(!this._isReady)return!1;const n=this.findImageById(t);return n?(n.setSource(e,i),this.render(),this.emit("image-source-changed",{imageId:t}),!0):(j.warn(`[pc-editor:setImageSource] Image not found: ${t}`),!1)}findImageById(t){const e=[this.document.bodyFlowingContent,this.document.headerFlowingContent,this.document.footerFlowingContent].filter(Boolean);for(const i of e){const e=i.getEmbeddedObjects();for(const[,i]of e.entries())if(i.id===t&&i instanceof T)return i}return null}tableInsertRow(t,e,i){this._isReady&&(t.insertRow(e,i),this.canvasManager.render())}tableRemoveRow(t,e){this._isReady&&(t.removeRow(e),this.canvasManager.render())}tableInsertColumn(t,e,i){this._isReady&&(t.insertColumn(e,i),this.canvasManager.render())}tableRemoveColumn(t,e){this._isReady&&(t.removeColumn(e),this.canvasManager.render())}tableMergeCells(t){if(j.log("[pc-editor] tableMergeCells"),!this._isReady)return!1;const e=t.mergeCells();return e.success&&this.canvasManager.render(),e.success}tableSplitCell(t,e,i){if(j.log("[pc-editor] tableSplitCell",e,i),!this._isReady)return!1;const n=t.splitCell(e,i);return n.success&&this.canvasManager.render(),n.success}beginCompoundOperation(t){this.transactionManager.beginCompoundOperation(t)}endCompoundOperation(t){this.transactionManager.endCompoundOperation(t),this.canvasManager.render()}updateField(t,e){if(!this._isReady)return!1;const i=this.getActiveFlowingContent();if(!i)return!1;const n=i.getSubstitutionFieldManager();if(!n.getFieldAt(t))return!1;const o=n.updateFieldConfig(t,e);return o&&(this.canvasManager.render(),this.emit("substitution-field-updated",{textIndex:t,updates:e,section:this._activeEditingSection})),o}insertInlineElement(t,e="inline"){j.warn("[pc-editor] insertInlineElement is deprecated and no longer functional. Use insertEmbeddedObject instead.")}applyMergeData(t){if(!this._isReady)throw new Error("Editor is not ready");const e=this.document.bodyFlowingContent;let i=0;this.expandRepeatingSections(e,t),this.evaluateConditionalSections(e,t),this.expandTableRowLoops(e,t),this.expandTableRowLoops(this.document.headerFlowingContent,t),this.expandTableRowLoops(this.document.footerFlowingContent,t),this.evaluateTableRowConditionals(e,t),this.evaluateTableRowConditionals(this.document.headerFlowingContent,t),this.evaluateTableRowConditionals(this.document.footerFlowingContent,t),i+=this.substituteFieldsInContent(e,t),i+=this.substituteFieldsInEmbeddedObjects(e,t),i+=this.substituteFieldsInContent(this.document.headerFlowingContent,t),i+=this.substituteFieldsInEmbeddedObjects(this.document.headerFlowingContent,t),i+=this.substituteFieldsInContent(this.document.footerFlowingContent,t),i+=this.substituteFieldsInEmbeddedObjects(this.document.footerFlowingContent,t),this.canvasManager.render(),this.emit("merge-data-applied",{data:t,fieldCount:i})}substituteFieldsInContent(t,e){const i=t.getSubstitutionFieldManager().getFieldsArray().filter(t=>!t.fieldType||"data"===t.fieldType).sort((t,e)=>e.textIndex-t.textIndex);for(const n of i){const i=this.resolveFieldPath(n.fieldName,e);let o;o=void 0!==i?it(i,n.formatConfig):n.defaultValue||`{{${n.fieldName}}}`;const s=n.formatting,r=n.textIndex;t.deleteText(n.textIndex,1),t.setCursorPosition(r),t.insertText(o),s&&t.applyFormatting(r,r+o.length,s)}return i.length}substituteFieldsInEmbeddedObjects(t,e){let i=0;const n=t.getEmbeddedObjects();for(const[,t]of n.entries())if(t instanceof L)i+=this.substituteFieldsInContent(t.flowingContent,e);else if(t instanceof U)for(const n of t.rows)for(const t of n.cells)i+=this.substituteFieldsInContent(t.flowingContent,e);return i}expandTableRowLoops(t,e){const i=t.getEmbeddedObjects();for(const[,t]of i.entries())t instanceof U&&this.expandTableRowLoopsInTable(t,e)}expandTableRowLoopsInTable(t,e){const i=t.getAllRowLoops();if(0===i.length)return;const n=[...i].sort((t,e)=>e.startRowIndex-t.startRowIndex);for(const i of n){const n=this.getValueAtPath(e,i.fieldPath);if(!Array.isArray(n)||0===n.length){t.removeRowLoop(i.id);continue}const o=n.length,s=t.getRowsInRange(i.startRowIndex,i.endRowIndex);t.removeRowsInRange(i.startRowIndex,i.endRowIndex);for(let e=o-1;e>=0;e--){const n=s.map(t=>t.clone());for(const t of n)for(const n of t.cells)this.rewriteFieldsInContent(n.flowingContent,i.fieldPath,e);t.insertRowsAt(i.startRowIndex,n)}t.removeRowLoop(i.id)}t.markLayoutDirty()}rewriteFieldsInContent(t,e,i){const n=t.getSubstitutionFieldManager().getFieldsArray();for(const t of n)if(t.fieldName.startsWith(e+".")||t.fieldName===e){const n=this.rewriteFieldNameWithIndex(t.fieldName,e,i);t.fieldName=n}}expandRepeatingSections(t,e){const i=t.getRepeatingSectionManager(),n=t.getSubstitutionFieldManager(),o=i.getSectionsDescending();for(const s of o){const o=this.getValueAtPath(e,s.fieldPath);if(!Array.isArray(o)||0===o.length){i.remove(s.id);continue}const r=o.length,a=t.getText().substring(s.startIndex,s.endIndex),l=s.endIndex-s.startIndex,d=n.getFieldsArray().filter(t=>t.textIndex>=s.startIndex&&t.textIndex<s.endIndex);if(r>1){const e=s.endIndex;for(let i=1;i<r;i++){t.setCursorPosition(e+(i-1)*l),t.insertText(a);for(const t of d){const o=e+(i-1)*l+(t.textIndex-s.startIndex),r=this.rewriteFieldNameWithIndex(t.fieldName,s.fieldPath,i);n.insert(r,o,{displayFormat:t.displayFormat,defaultValue:t.defaultValue}),t.formatting&&n.setFieldFormatting(o,t.formatting)}}}for(const t of d){const e=this.rewriteFieldNameWithIndex(t.fieldName,s.fieldPath,0);n.updateFieldConfig(t.textIndex,{fieldName:e})}i.remove(s.id)}}evaluateConditionalSections(t,e){const i=t.getConditionalSectionManager(),n=i.getSectionsDescending();for(const o of n){if(!Y.evaluate(o.predicate,e)){const e=o.startIndex,i=o.endIndex-o.startIndex;t.deleteText(e,i)}i.remove(o.id)}}evaluateTableRowConditionals(t,e){const i=t.getEmbeddedObjects();for(const[,t]of i.entries())t instanceof U&&this.evaluateTableRowConditionalsInTable(t,e)}evaluateTableRowConditionalsInTable(t,e){const i=t.getAllRowConditionals();if(0===i.length)return;const n=[...i].sort((t,e)=>e.startRowIndex-t.startRowIndex);for(const i of n){Y.evaluate(i.predicate,e)||t.removeRowsInRange(i.startRowIndex,i.endRowIndex),t.removeRowConditional(i.id)}t.markLayoutDirty()}getValueAtPath(t,e){const i=e.split(".");let n=t;for(const t of i){if(null==n)return;if("object"!=typeof n||null===n)return;n=n[t]}return n}rewriteFieldNameWithIndex(t,e,i){if(t.startsWith(e+".")){return`${e}[${i}]${t.substring(e.length)}`}return t===e?`${e}[${i}]`:t}resolveFieldPath(t,e){const i=this.parseFieldPath(t);let n=e;for(const t of i){if(null==n)return;const e=t.match(/^\[(\d+)\]$/);if(e){const t=parseInt(e[1],10);if(!Array.isArray(n))return;n=n[t];continue}if(Array.isArray(n)&&(n=n[0],null==n))return;if("object"!=typeof n||null===n)return;n=n[t]}return Array.isArray(n)?n[0]:n}parseFieldPath(t){const e=[];let i="";for(let n=0;n<t.length;n++){const o=t[n];if("."===o)i&&(e.push(i),i="");else if("["===o){i&&(e.push(i),i="");const o=t.indexOf("]",n);-1!==o&&(e.push(t.substring(n,o+1)),n=o)}else i+=o}return i&&e.push(i),e}applyTextFormatting(t,e,i){if(!this._isReady)throw new Error("Editor is not ready");const n=this.getActiveFlowingContent();n&&n.applyFormatting(t,e,i)}getFormattingAt(t){if(!this._isReady)return null;const e=this.getActiveFlowingContent();return e?e.getFormattingAt(t):null}getSelectionFormatting(){if(!this._isReady)return null;const t=this.currentSelection;let e;if("text"===t.type)e=t.start;else{if("cursor"!==t.type)return null;e=t.position}const i=this.getActiveFlowingContent();return i?i.getFormattingAt(e):null}setAlignment(t){if(!this._isReady)throw new Error("Editor is not ready");const e=this.getActiveFlowingContent();e&&(e.setAlignment(t),this.canvasManager.render(),this.emit("alignment-changed",{alignment:t,section:this._activeEditingSection}))}setAlignmentForSelection(t){if(!this._isReady)throw new Error("Editor is not ready");const e=this.currentSelection,i=this.getActiveFlowingContent();i&&("text"===e.type?i.setAlignmentForRange(e.start,e.end,t):i.setAlignment(t),this.canvasManager.render(),this.emit("alignment-changed",{alignment:t,section:this._activeEditingSection}))}getAlignmentAtCursor(){if(!this._isReady)return"left";const t=this.currentSelection,e=this.getActiveFlowingContent();if(!e)return"left";let i;return i="text"===t.type?t.start:"cursor"===t.type?t.position:e.getCursorPosition(),e.getAlignmentAt(i)}toggleBulletList(){if(!this._isReady)return;const t=this.getEditingFlowingContent()||this.getActiveFlowingContent();t&&(t.toggleBulletList(),this.canvasManager.render(),this.emit("list-changed",{type:"bullet",section:this._activeEditingSection}))}toggleNumberedList(){if(!this._isReady)return;const t=this.getEditingFlowingContent()||this.getActiveFlowingContent();t&&(t.toggleNumberedList(),this.canvasManager.render(),this.emit("list-changed",{type:"number",section:this._activeEditingSection}))}indentParagraph(){if(!this._isReady)return;const t=this.getEditingFlowingContent()||this.getActiveFlowingContent();t&&(t.indentParagraph(),this.canvasManager.render(),this.emit("indent-changed",{section:this._activeEditingSection}))}outdentParagraph(){if(!this._isReady)return;const t=this.getEditingFlowingContent()||this.getActiveFlowingContent();t&&(t.outdentParagraph(),this.canvasManager.render(),this.emit("indent-changed",{section:this._activeEditingSection}))}getListFormatting(){if(!this._isReady)return;const t=this.getEditingFlowingContent()||this.getActiveFlowingContent();return t?t.getListFormatting():void 0}insertHyperlink(t,e){if(!this._isReady)return null;const i=this.getActiveFlowingContent();if(!i)return null;const n=i.insertHyperlink(t,e);return n&&(this.canvasManager.render(),this.emit("hyperlink-inserted",{hyperlink:n})),n}insertHyperlinkAt(t,e,i,n){if(!this._isReady)return null;const o=this.getActiveFlowingContent();if(!o)return null;const s=o.insertHyperlinkAt(t,e,i,n);return this.canvasManager.render(),this.emit("hyperlink-inserted",{hyperlink:s}),s}removeHyperlink(t){if(!this._isReady)return;const e=this.getActiveFlowingContent();e&&(e.removeHyperlink(t),this.canvasManager.render(),this.emit("hyperlink-removed",{id:t}))}updateHyperlink(t,e){if(!this._isReady)return;const i=this.getActiveFlowingContent();i&&(i.updateHyperlink(t,e),this.canvasManager.render(),this.emit("hyperlink-updated",{id:t,updates:e}))}getHyperlinkAt(t){if(!this._isReady)return;const e=this.getActiveFlowingContent();return e?e.getHyperlinkAt(t):void 0}getHyperlinkById(t){if(!this._isReady)return;const e=this.getActiveFlowingContent();return e?e.getHyperlinkById(t):void 0}getHyperlinksInRange(t,e){if(!this._isReady)return[];const i=this.getActiveFlowingContent();return i?i.getHyperlinksInRange(t,e):[]}getAllHyperlinks(){if(!this._isReady)return[];const t=this.getActiveFlowingContent();return t?t.getAllHyperlinks():[]}updateDocumentSettings(t){if(!this._isReady)throw new Error("Editor is not ready");this.document.updateSettings(t),this.emit("document-settings-changed",{settings:t})}getDocumentSettings(){if(!this._isReady)throw new Error("Editor is not ready");return this.document.settings}setShowControlCharacters(t){this.options.showControlCharacters=t,this.canvasManager&&this.canvasManager.setShowControlCharacters(t),this.emit("control-characters-changed",{show:t})}getShowControlCharacters(){return this.options.showControlCharacters}setShowGrid(t){this.options.showGrid=t,this.canvasManager&&this.canvasManager.setShowGrid(t),this.emit("grid-changed",{show:t})}getShowGrid(){return this.options.showGrid}setShowMarginLines(t){this.canvasManager&&this.canvasManager.setShowMarginLines(t),this.emit("margin-lines-changed",{show:t})}getShowMarginLines(){return!this.canvasManager||this.canvasManager.getShowMarginLines()}getParagraphBoundaries(){return this._isReady?this.document.bodyFlowingContent.getParagraphBoundaries():[]}createRepeatingSection(t,e,i){if(!this._isReady)throw new Error("Editor is not ready");const n=this.getFocusedTable();if(n&&n.focusedCell){const t=n.selectedRange,e=t?t.start.row:n.focusedCell.row,o=t?t.end.row:n.focusedCell.row;j.log("[pc-editor] createRepeatingSection → table row loop",e,o,i);const s=n.createRowLoop(e,o,i);return s&&(this.canvasManager.render(),this.emit("table-row-loop-added",{table:n,loop:s})),null}j.log("[pc-editor] createRepeatingSection",t,e,i);const o=this.document.bodyFlowingContent.createRepeatingSection(t,e,i);return o&&(this.canvasManager.render(),this.emit("repeating-section-added",{section:o})),o}getRepeatingSection(t){return this._isReady&&this.document.bodyFlowingContent.getRepeatingSection(t)||null}getRepeatingSections(){return this._isReady?this.document.bodyFlowingContent.getRepeatingSections():[]}updateRepeatingSectionFieldPath(t,e){if(!this._isReady)return!1;const i=this.document.bodyFlowingContent.updateRepeatingSectionFieldPath(t,e);return i&&(this.canvasManager.render(),this.emit("repeating-section-updated",{id:t,fieldPath:e})),i}removeRepeatingSection(t){if(!this._isReady)return!1;const e=this.document.bodyFlowingContent.removeRepeatingSection(t);return e&&(this.canvasManager.render(),this.emit("repeating-section-removed",{id:t})),e}getRepeatingSectionAtBoundary(t){return this._isReady&&this.document.bodyFlowingContent.getRepeatingSectionAtBoundary(t)||null}addConditionalSection(t,e,i){if(!this._isReady)throw new Error("Editor is not ready");const n=this.getFocusedTable();if(n&&n.focusedCell){const t=n.selectedRange,e=t?t.start.row:n.focusedCell.row,o=t?t.end.row:n.focusedCell.row;j.log("[pc-editor] addConditionalSection → table row conditional",e,o,i);const s=n.createRowConditional(e,o,i);return s&&(this.canvasManager.render(),this.emit("table-row-conditional-added",{table:n,conditional:s})),null}j.log("[pc-editor] addConditionalSection",t,e,i);const o=this.document.bodyFlowingContent.createConditionalSection(t,e,i);return o&&(this.canvasManager.render(),this.emit("conditional-section-added",{section:o})),o}getConditionalSection(t){return this._isReady&&this.document.bodyFlowingContent.getConditionalSection(t)||null}getConditionalSections(){return this._isReady?this.document.bodyFlowingContent.getConditionalSections():[]}updateConditionalSectionPredicate(t,e){if(!this._isReady)return!1;const i=this.document.bodyFlowingContent.updateConditionalSectionPredicate(t,e);return i&&(this.canvasManager.render(),this.emit("conditional-section-updated",{id:t,predicate:e})),i}removeConditionalSection(t){if(!this._isReady)return!1;const e=this.document.bodyFlowingContent.removeConditionalSection(t);return e&&(this.canvasManager.render(),this.emit("conditional-section-removed",{id:t})),e}getConditionalSectionAtBoundary(t){return this._isReady&&this.document.bodyFlowingContent.getConditionalSectionAtBoundary(t)||null}getHeaderText(){if(!this._isReady)throw new Error("Editor is not ready");return this.document.headerFlowingContent.getText()}setHeaderText(t){if(!this._isReady)throw new Error("Editor is not ready");this.document.headerFlowingContent.setText(t)}getFooterText(){if(!this._isReady)throw new Error("Editor is not ready");return this.document.footerFlowingContent.getText()}setFooterText(t){if(!this._isReady)throw new Error("Editor is not ready");this.document.footerFlowingContent.setText(t)}insertHeaderSubstitutionField(t,e){if(!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection();const i=this.document.headerFlowingContent.insertSubstitutionField(t,e);this.canvasManager.render(),this.emit("substitution-field-added",{field:i,section:"header"})}insertFooterSubstitutionField(t,e){if(!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection();const i=this.document.footerFlowingContent.insertSubstitutionField(t,e);this.canvasManager.render(),this.emit("substitution-field-added",{field:i,section:"footer"})}insertHeaderEmbeddedObject(t,e="inline"){if(!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection(),this.document.headerFlowingContent.insertEmbeddedObject(t,e),this.observeEmbeddedObject(t),this.canvasManager.render(),this.emit("embedded-object-added",{object:t,position:e,section:"header"})}insertFooterEmbeddedObject(t,e="inline"){if(!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection(),this.document.footerFlowingContent.insertEmbeddedObject(t,e),this.observeEmbeddedObject(t),this.canvasManager.render(),this.emit("embedded-object-added",{object:t,position:e,section:"footer"})}async copy(){const t=this.getEditingFlowingContent()||this.getActiveFlowingContent();if(!t)return!1;const e=await this.clipboardManager.copy(t);return e&&this.emit("copy",{success:!0}),e}async cut(){const t=this.getEditingFlowingContent()||this.getActiveFlowingContent();if(!t)return!1;const e=t.getSelection();if(!e||e.start===e.end)return!1;if(!await this.clipboardManager.copy(t))return!1;this.transactionManager.beginCompoundOperation("Cut");try{return t.deleteSelection(),this.transactionManager.endCompoundOperation(),this.canvasManager.render(),this.emit("cut",{success:!0}),!0}catch(t){return this.transactionManager.endCompoundOperation(),console.error("Cut failed:",t),!1}}async paste(){const t=this.getEditingFlowingContent()||this.getActiveFlowingContent();if(!t)return!1;const e=await this.clipboardManager.read();if("empty"===e.type||null===e.data)return!1;this.transactionManager.beginCompoundOperation("Paste");try{t.hasSelection()&&t.deleteSelection();let i=!1;if("pceditor"===e.type)i=this.pasteProprietaryContent(t,e.data);else if("html"===e.type){const n=this.clipboardManager.parseHtml(e.data);i=this.pasteClipboardContent(t,n)}else if("text"===e.type){const n=e.data;t.insertText(n),i=!0}else"image"===e.type&&(i=await this.pasteImage(t,e.data));return this.transactionManager.endCompoundOperation(),!!i&&(this.canvasManager.render(),this.emit("paste",{success:!0,type:e.type}),!0)}catch(t){return this.transactionManager.endCompoundOperation(),console.error("Paste failed:",t),!1}}selectAll(){const t=this.canvasManager.getEditingTextBox();if(t)return t.flowingContent.selectAll(),void this.canvasManager.render();const e=this.canvasManager.getFocusedControl();if(e instanceof U&&e.focusedCell){const t=e.getCell(e.focusedCell.row,e.focusedCell.col);if(t)return t.flowingContent.selectAll(),void this.canvasManager.render()}const i=this.getActiveFlowingContent();i&&(i.selectAll(),this.canvasManager.render(),this.emit("text-selection-changed",{selection:i.getSelection(),section:this._activeEditingSection}))}pasteProprietaryContent(t,e){const i=this.clipboardManager.generateNewIds(e.content);return this.pasteClipboardContent(t,i)}pasteClipboardContent(t,e){const i=t.getCursorPosition(),{text:n,formattingRuns:o,substitutionFields:s,embeddedObjects:r,hyperlinks:a}=e;if(t.insertText(n),o&&o.length>0){const e=t.getFormattingManager();for(let t=0;t<o.length;t++){const s=o[t],r=o[t+1],a=i+s.index,l=r?i+r.index:i+n.length;e.applyFormatting(a,l,{fontFamily:s.formatting.fontFamily,fontSize:s.formatting.fontSize,fontWeight:s.formatting.fontWeight,fontStyle:s.formatting.fontStyle,color:s.formatting.color,backgroundColor:s.formatting.backgroundColor})}}if(s&&s.length>0)for(const e of s){const n=i+e.textIndex;t.insertSubstitutionFieldAt(e.fieldName,n,{fieldType:e.fieldType,displayFormat:e.displayFormat,defaultValue:e.defaultValue,formatting:e.formatting})}if(r&&r.length>0)for(const e of r){const n=i+e.textIndex,o=this.createEmbeddedObjectFromData(e.object);o&&(t.insertEmbeddedObjectAt(o,n,o.position),this.observeEmbeddedObject(o))}if(a&&a.length>0)for(const e of a){const n=i+e.startIndex,o=i+e.endIndex;t.insertHyperlinkAt(e.url,n,o,{title:e.title,formatting:e.formatting})}return!0}createEmbeddedObjectFromData(t){const e=V.tryCreate(t);return e||j.warn("[pc-editor] Unknown object type:",t.objectType),e}async pasteImage(t,e){try{const{dataUrl:i,width:n,height:o}=await this.clipboardManager.createImageFromBlob(e),s=400,r=n>s?s/n:1,a=new T({id:`img_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,textIndex:t.getCursorPosition(),size:{width:n*r,height:o*r},src:i,alt:"Pasted image"});return t.insertEmbeddedObject(a,"inline"),this.observeEmbeddedObject(a),!0}catch(t){return console.error("Failed to paste image:",t),!1}}setLogging(t){j.setEnabled(t)}async registerFont(t){j.log("[pc-editor] registerFont",t.family),await this.fontManager.registerFont(t),this.emit("font-registered",{family:t.family}),this._isReady&&this.canvasManager.render()}getAvailableFonts(){return this.fontManager.getAvailableFonts().map(t=>({family:t.family,source:t.source}))}getAvailableFontFamilies(){return this.fontManager.getAvailableFontFamilies()}destroy(){this.disableTextInput(),this.canvasManager&&this.canvasManager.destroy(),this.layoutEngine&&this.layoutEngine.destroy(),this.document.clear(),this.removeAllListeners(),this._isReady=!1}},t.PDFImportError=Wt,t.PDFImporter=Vt,t.PDFParser=Gt,t.Page=a,t.PredicateEvaluator=Y,t.RegionManager=J,t.RepeatingSectionManager=w,t.RepeatingSectionPane=class extends te{constructor(t="repeating-section",e={}){super(t,{className:"pc-pane-repeating-section",...e}),this.fieldPathInput=null,this.positionHint=null,this.currentSection=null,this.onApplyCallback=e.onApply,this.onRemoveCallback=e.onRemove}attach(t){if(super.attach(t),this.editor){const t=t=>{const e=t.selection||t;if("repeating-section"===e.type&&e.sectionId){const t=this.editor?.getRepeatingSection(e.sectionId);t&&this.showSection(t)}else this.hideSection()},e=()=>{this.hideSection()};this.editor.on("selection-change",t),this.editor.on("repeating-section-removed",e),this.eventCleanup.push(()=>{this.editor?.off("selection-change",t),this.editor?.off("repeating-section-removed",e)})}}createContent(){const t=document.createElement("div");this.fieldPathInput=this.createTextInput({placeholder:"items"}),t.appendChild(this.createFormGroup("Array Field Path:",this.fieldPathInput,{hint:'Path to array in merge data (e.g., "items" or "contact.addresses")'}));const e=this.createButton("Apply Changes",{variant:"primary"});this.addButtonListener(e,()=>this.applyChanges()),t.appendChild(e);const i=this.createButton("Remove Loop",{variant:"danger"});return i.style.marginTop="0.5rem",this.addButtonListener(i,()=>this.removeSection()),t.appendChild(i),this.positionHint=this.createHint(""),t.appendChild(this.positionHint),t}showSection(t){this.currentSection=t,this.fieldPathInput&&(this.fieldPathInput.value=t.fieldPath),this.positionHint&&(this.positionHint.textContent=`Loop from position ${t.startIndex} to ${t.endIndex}`),this.show()}hideSection(){this.currentSection=null,this.hide()}applyChanges(){if(!this.editor||!this.currentSection)return void this.onApplyCallback?.(!1,new Error("No section selected"));const t=this.fieldPathInput?.value.trim();if(t){if(t!==this.currentSection.fieldPath)try{this.editor.updateRepeatingSectionFieldPath(this.currentSection.id,t)?(this.currentSection=this.editor.getRepeatingSection(this.currentSection.id)||null,this.currentSection&&this.showSection(this.currentSection),this.onApplyCallback?.(!0)):this.onApplyCallback?.(!1,new Error("Failed to update section"))}catch(t){this.onApplyCallback?.(!1,t instanceof Error?t:new Error(String(t)))}}else this.onApplyCallback?.(!1,new Error("Field path cannot be empty"))}removeSection(){if(this.editor&&this.currentSection)try{this.editor.removeRepeatingSection(this.currentSection.id),this.hideSection(),this.onRemoveCallback?.(!0)}catch{this.onRemoveCallback?.(!1)}}getCurrentSection(){return this.currentSection}hasSection(){return null!==this.currentSection}update(){}},t.RulerControl=Qt,t.SubstitutionFieldManager=x,t.SubstitutionFieldPane=class extends te{constructor(t="substitution-field",e={}){super(t,{className:"pc-pane-substitution-field",...e}),this.fieldNameInput=null,this.fieldDefaultInput=null,this.valueTypeSelect=null,this.numberFormatSelect=null,this.currencyFormatSelect=null,this.dateFormatSelect=null,this.positionHint=null,this.numberFormatGroup=null,this.currencyFormatGroup=null,this.dateFormatGroup=null,this.currentField=null,this.onApplyCallback=e.onApply}attach(t){if(super.attach(t),this.editor){const t=t=>{"field"===t.type&&t.field?this.showField(t.field):!t.type||t.type};this.editor.on("selection-change",t),this.eventCleanup.push(()=>{this.editor?.off("selection-change",t)})}}createContent(){const t=document.createElement("div");this.fieldNameInput=this.createTextInput({placeholder:"Field name"}),t.appendChild(this.createFormGroup("Field Name:",this.fieldNameInput)),this.fieldDefaultInput=this.createTextInput({placeholder:"Default value (optional)"}),t.appendChild(this.createFormGroup("Default Value:",this.fieldDefaultInput)),this.valueTypeSelect=this.createSelect([{value:"",label:"(None)"},{value:"number",label:"Number"},{value:"currency",label:"Currency"},{value:"date",label:"Date"}]),this.addImmediateApplyListener(this.valueTypeSelect,()=>this.updateFormatGroups()),t.appendChild(this.createFormGroup("Value Type:",this.valueTypeSelect)),this.numberFormatGroup=this.createSection(),this.numberFormatGroup.style.display="none",this.numberFormatSelect=this.createSelect([{value:"0",label:"Integer (0)"},{value:"0.00",label:"Two decimals (0.00)"},{value:"0,0",label:"Thousands separator (0,0)"},{value:"0,0.00",label:"Thousands + decimals (0,0.00)"}]),this.numberFormatGroup.appendChild(this.createFormGroup("Number Format:",this.numberFormatSelect)),t.appendChild(this.numberFormatGroup),this.currencyFormatGroup=this.createSection(),this.currencyFormatGroup.style.display="none",this.currencyFormatSelect=this.createSelect([{value:"USD",label:"USD ($)"},{value:"EUR",label:"EUR"},{value:"GBP",label:"GBP"},{value:"JPY",label:"JPY"}]),this.currencyFormatGroup.appendChild(this.createFormGroup("Currency:",this.currencyFormatSelect)),t.appendChild(this.currencyFormatGroup),this.dateFormatGroup=this.createSection(),this.dateFormatGroup.style.display="none",this.dateFormatSelect=this.createSelect([{value:"MMMM D, YYYY",label:"January 1, 2026"},{value:"MM/DD/YYYY",label:"01/01/2026"},{value:"DD/MM/YYYY",label:"01/01/2026 (EU)"},{value:"YYYY-MM-DD",label:"2026-01-01 (ISO)"}]),this.dateFormatGroup.appendChild(this.createFormGroup("Date Format:",this.dateFormatSelect)),t.appendChild(this.dateFormatGroup);const e=this.createButton("Apply Changes",{variant:"primary"});return this.addButtonListener(e,()=>this.applyChanges()),t.appendChild(e),this.positionHint=this.createHint(""),t.appendChild(this.positionHint),t}updateFormatGroups(){const t=this.valueTypeSelect?.value||"";this.numberFormatGroup&&(this.numberFormatGroup.style.display="number"===t?"block":"none"),this.currencyFormatGroup&&(this.currencyFormatGroup.style.display="currency"===t?"block":"none"),this.dateFormatGroup&&(this.dateFormatGroup.style.display="date"===t?"block":"none")}showField(t){this.currentField=t,this.fieldNameInput&&(this.fieldNameInput.value=t.fieldName),this.fieldDefaultInput&&(this.fieldDefaultInput.value=t.defaultValue||""),this.positionHint&&(this.positionHint.textContent=`Field at position ${t.textIndex}`),this.valueTypeSelect&&(this.valueTypeSelect.value=t.formatConfig?.valueType||""),this.numberFormatSelect&&t.formatConfig?.numberFormat&&(this.numberFormatSelect.value=t.formatConfig.numberFormat),this.currencyFormatSelect&&t.formatConfig?.currencyFormat&&(this.currencyFormatSelect.value=t.formatConfig.currencyFormat),this.dateFormatSelect&&t.formatConfig?.dateFormat&&(this.dateFormatSelect.value=t.formatConfig.dateFormat),this.updateFormatGroups(),this.show()}hideField(){this.currentField=null,this.hide()}applyChanges(){if(!this.editor||!this.currentField)return void this.onApplyCallback?.(!1,new Error("No field selected"));const t=this.fieldNameInput?.value.trim();if(!t)return void this.onApplyCallback?.(!1,new Error("Field name cannot be empty"));const e={};t!==this.currentField.fieldName&&(e.fieldName=t);const i=this.fieldDefaultInput?.value||void 0;i!==this.currentField.defaultValue&&(e.defaultValue=i);const n=this.valueTypeSelect?.value;if(n){const t={valueType:n};"number"===n&&this.numberFormatSelect?.value?t.numberFormat=this.numberFormatSelect.value:"currency"===n&&this.currencyFormatSelect?.value?t.currencyFormat=this.currencyFormatSelect.value:"date"===n&&this.dateFormatSelect?.value&&(t.dateFormat=this.dateFormatSelect.value),e.formatConfig=t}else this.currentField.formatConfig&&(e.formatConfig=void 0);if(0!==Object.keys(e).length)try{this.editor.updateField(this.currentField.textIndex,e)?(this.currentField=this.editor.getFieldAt(this.currentField.textIndex)||null,this.onApplyCallback?.(!0)):this.onApplyCallback?.(!1,new Error("Failed to update field"))}catch(t){this.onApplyCallback?.(!1,t instanceof Error?t:new Error(String(t)))}}getCurrentField(){return this.currentField}hasField(){return null!==this.currentField}update(){}},t.TableCell=H,t.TableObject=U,t.TablePane=class extends te{constructor(t="table",e={}){super(t,{className:"pc-pane-table",...e}),this.rowCountDisplay=null,this.colCountDisplay=null,this.cellSelectionDisplay=null,this.headerRowInput=null,this.headerColInput=null,this.defaultPaddingInput=null,this.defaultBorderColorInput=null,this.mergeCellsBtn=null,this.splitCellBtn=null,this.cellBgColorInput=null,this.borderTopCheck=null,this.borderRightCheck=null,this.borderBottomCheck=null,this.borderLeftCheck=null,this.borderWidthInput=null,this.borderColorInput=null,this.borderStyleSelect=null,this.currentTable=null,this._isUpdating=!1,this.onApplyCallback=e.onApply}attach(t){if(super.attach(t),this.editor){const t=()=>this.updateFromFocusedTable();this.editor.on("selection-change",t),this.editor.on("tablecell-cursor-changed",t),this.editor.on("table-cell-selection-changed",t),this.eventCleanup.push(()=>{this.editor?.off("selection-change",t),this.editor?.off("tablecell-cursor-changed",t),this.editor?.off("table-cell-selection-changed",t)}),this.updateFromFocusedTable()}}createContent(){const t=document.createElement("div"),e=this.createSection("Structure"),i=document.createElement("div");i.className="pc-pane-table-structure-info",this.rowCountDisplay=document.createElement("span"),this.rowCountDisplay.className="pc-pane-info-value",this.colCountDisplay=document.createElement("span"),this.colCountDisplay.className="pc-pane-info-value",i.appendChild(this.createFormGroup("Rows:",this.rowCountDisplay,{inline:!0})),i.appendChild(this.createFormGroup("Columns:",this.colCountDisplay,{inline:!0})),e.appendChild(i);const n=this.createButtonGroup(),o=this.createButton("+ Row");this.addButtonListener(o,()=>this.insertRow());const s=this.createButton("- Row");this.addButtonListener(s,()=>this.removeRow()),n.appendChild(o),n.appendChild(s),e.appendChild(n);const r=this.createButtonGroup(),a=this.createButton("+ Column");this.addButtonListener(a,()=>this.insertColumn());const l=this.createButton("- Column");this.addButtonListener(l,()=>this.removeColumn()),r.appendChild(a),r.appendChild(l),e.appendChild(r),e.appendChild(document.createElement("hr"));const d=document.createElement("div");d.className="pc-pane-table-headers",this.headerRowInput=this.createNumberInput({min:0,max:10,value:0}),this.addImmediateApplyListener(this.headerRowInput,()=>this.applyHeaders()),d.appendChild(this.createFormGroup("Header Rows:",this.headerRowInput,{inline:!0})),this.headerColInput=this.createNumberInput({min:0,max:10,value:0}),this.addImmediateApplyListener(this.headerColInput,()=>this.applyHeaders()),d.appendChild(this.createFormGroup("Header Cols:",this.headerColInput,{inline:!0})),e.appendChild(d),t.appendChild(e);const h=this.createSection("Defaults"),c=document.createElement("div");c.className="pc-pane-table-defaults",this.defaultPaddingInput=this.createNumberInput({min:0,max:20,value:8}),this.addImmediateApplyListener(this.defaultPaddingInput,()=>this.applyDefaults()),c.appendChild(this.createFormGroup("Padding:",this.defaultPaddingInput,{inline:!0})),this.defaultBorderColorInput=this.createColorInput("#cccccc"),this.addImmediateApplyListener(this.defaultBorderColorInput,()=>this.applyDefaults()),c.appendChild(this.createFormGroup("Border:",this.defaultBorderColorInput,{inline:!0})),h.appendChild(c),t.appendChild(h);const g=this.createSection("Cell Formatting");this.cellSelectionDisplay=this.createHint("No cell selected"),g.appendChild(this.cellSelectionDisplay);const u=this.createButtonGroup();this.mergeCellsBtn=this.createButton("Merge Cells"),this.mergeCellsBtn.disabled=!0,this.splitCellBtn=this.createButton("Split Cell"),this.splitCellBtn.disabled=!0,this.addButtonListener(this.mergeCellsBtn,()=>this.doMergeCells()),this.addButtonListener(this.splitCellBtn,()=>this.doSplitCell()),u.appendChild(this.mergeCellsBtn),u.appendChild(this.splitCellBtn),g.appendChild(u),g.appendChild(document.createElement("hr")),this.cellBgColorInput=this.createColorInput("#ffffff"),this.addImmediateApplyListener(this.cellBgColorInput,()=>this.applyCellFormatting()),g.appendChild(this.createFormGroup("Background:",this.cellBgColorInput,{inline:!0}));const f=document.createElement("div");f.className="pc-pane-row",f.style.flexWrap="wrap",f.style.gap="4px",this.borderTopCheck=document.createElement("input"),this.borderTopCheck.type="checkbox",this.borderTopCheck.checked=!0,this.borderRightCheck=document.createElement("input"),this.borderRightCheck.type="checkbox",this.borderRightCheck.checked=!0,this.borderBottomCheck=document.createElement("input"),this.borderBottomCheck.type="checkbox",this.borderBottomCheck.checked=!0,this.borderLeftCheck=document.createElement("input"),this.borderLeftCheck.type="checkbox",this.borderLeftCheck.checked=!0,f.appendChild(this.createCheckbox("Top",!0)),f.appendChild(this.createCheckbox("Right",!0)),f.appendChild(this.createCheckbox("Bottom",!0)),f.appendChild(this.createCheckbox("Left",!0));const p=f.querySelectorAll("label");p[0]&&p[0].replaceChild(this.borderTopCheck,p[0].querySelector("input")),p[1]&&p[1].replaceChild(this.borderRightCheck,p[1].querySelector("input")),p[2]&&p[2].replaceChild(this.borderBottomCheck,p[2].querySelector("input")),p[3]&&p[3].replaceChild(this.borderLeftCheck,p[3].querySelector("input"));for(const t of[this.borderTopCheck,this.borderRightCheck,this.borderBottomCheck,this.borderLeftCheck])t.addEventListener("change",()=>this.applyCellFormatting());g.appendChild(this.createFormGroup("Borders:",f));const m=this.createRow();return this.borderWidthInput=this.createNumberInput({min:0,max:5,value:1}),this.borderColorInput=this.createColorInput("#cccccc"),this.addImmediateApplyListener(this.borderWidthInput,()=>this.applyCellFormatting()),this.addImmediateApplyListener(this.borderColorInput,()=>this.applyCellFormatting()),m.appendChild(this.createFormGroup("Width:",this.borderWidthInput,{inline:!0})),m.appendChild(this.createFormGroup("Color:",this.borderColorInput,{inline:!0})),g.appendChild(m),this.borderStyleSelect=this.createSelect([{value:"solid",label:"Solid"},{value:"dashed",label:"Dashed"},{value:"dotted",label:"Dotted"},{value:"none",label:"None"}],"solid"),this.addImmediateApplyListener(this.borderStyleSelect,()=>this.applyCellFormatting()),g.appendChild(this.createFormGroup("Style:",this.borderStyleSelect,{inline:!0})),t.appendChild(g),t}updateFromFocusedTable(){if(this.editor&&!this._isUpdating){this._isUpdating=!0;try{const t=this.editor.getFocusedTable();t?this.showTable(t):this.hideTable()}finally{this._isUpdating=!1}}}showTable(t){this.currentTable=t,this.rowCountDisplay&&(this.rowCountDisplay.textContent=String(t.rowCount),this.rowCountDisplay.className="pc-pane-info-value"),this.colCountDisplay&&(this.colCountDisplay.textContent=String(t.columnCount),this.colCountDisplay.className="pc-pane-info-value"),this.headerRowInput&&(this.headerRowInput.value=String(t.headerRowCount)),this.headerColInput&&(this.headerColInput.value=String(t.headerColumnCount)),this.defaultPaddingInput&&(this.defaultPaddingInput.value=String(t.defaultCellPadding)),this.defaultBorderColorInput&&(this.defaultBorderColorInput.value=t.defaultBorderColor),this.updateCellSelectionInfo(t),this.show()}hideTable(){this.currentTable=null,this.hide()}updateCellSelectionInfo(t){if(!this.cellSelectionDisplay)return;const e=t.focusedCell,i=t.selectedRange;if(this.mergeCellsBtn){const e=!!i&&t.canMergeRange(i).canMerge;this.mergeCellsBtn.disabled=!e}if(this.splitCellBtn){const i=!!e&&t.canSplitCell(e.row,e.col).canSplit;this.splitCellBtn.disabled=!i}if(i){const t=(i.end.row-i.start.row+1)*(i.end.col-i.start.col+1);this.cellSelectionDisplay.textContent=`${t} cells selected`}else if(e){this.cellSelectionDisplay.textContent=`Cell [${e.row}, ${e.col}]`;const i=t.getCell(e.row,e.col);if(i){this.cellBgColorInput&&(this.cellBgColorInput.value=i.backgroundColor||"#ffffff");const t=i.border;this.borderTopCheck&&(this.borderTopCheck.checked="none"!==t.top.style),this.borderRightCheck&&(this.borderRightCheck.checked="none"!==t.right.style),this.borderBottomCheck&&(this.borderBottomCheck.checked="none"!==t.bottom.style),this.borderLeftCheck&&(this.borderLeftCheck.checked="none"!==t.left.style);const e="none"!==t.top.style?t.top:"none"!==t.right.style?t.right:"none"!==t.bottom.style?t.bottom:"none"!==t.left.style?t.left:t.top;this.borderWidthInput&&(this.borderWidthInput.value=String(e.width)),this.borderColorInput&&(this.borderColorInput.value=e.color),this.borderStyleSelect&&(this.borderStyleSelect.value=e.style)}}else this.cellSelectionDisplay.textContent="No cell selected"}insertRow(){if(!this.editor||!this.currentTable)return;const t=this.currentTable.focusedCell,e=t?t.row+1:this.currentTable.rowCount;this.editor.tableInsertRow(this.currentTable,e),this.updateFromFocusedTable()}removeRow(){if(!this.editor||!this.currentTable)return;const t=this.currentTable.focusedCell;t&&this.currentTable.rowCount>1&&(this.editor.tableRemoveRow(this.currentTable,t.row),this.updateFromFocusedTable())}insertColumn(){if(!this.editor||!this.currentTable)return;const t=this.currentTable.focusedCell,e=t?t.col+1:this.currentTable.columnCount;this.editor.tableInsertColumn(this.currentTable,e),this.updateFromFocusedTable()}removeColumn(){if(!this.editor||!this.currentTable)return;const t=this.currentTable.focusedCell;t&&this.currentTable.columnCount>1&&(this.editor.tableRemoveColumn(this.currentTable,t.col),this.updateFromFocusedTable())}applyHeaders(){if(this.currentTable){if(this.headerRowInput){const t=parseInt(this.headerRowInput.value,10);this.currentTable.setHeaderRowCount(t)}if(this.headerColInput){const t=parseInt(this.headerColInput.value,10);this.currentTable.setHeaderColumnCount(t)}this.editor?.render(),this.onApplyCallback?.(!0)}}applyDefaults(){this.currentTable&&(this.defaultPaddingInput&&(this.currentTable.defaultCellPadding=parseInt(this.defaultPaddingInput.value,10)),this.defaultBorderColorInput&&(this.currentTable.defaultBorderColor=this.defaultBorderColorInput.value),this.editor?.render(),this.onApplyCallback?.(!0))}applyCellFormatting(){if(!this.currentTable)return;const t=this.currentTable.focusedCell,e=this.currentTable.selectedRange,i=[];if(e)for(let t=e.start.row;t<=e.end.row;t++)for(let n=e.start.col;n<=e.end.col;n++)i.push({row:t,col:n});else t&&i.push(t);if(0===i.length)return;const n={width:parseInt(this.borderWidthInput?.value||"1",10),color:this.borderColorInput?.value||"#cccccc",style:this.borderStyleSelect?.value||"solid"},o={width:0,color:"#000000",style:"none"},s={top:this.borderTopCheck?.checked?{...n}:{...o},right:this.borderRightCheck?.checked?{...n}:{...o},bottom:this.borderBottomCheck?.checked?{...n}:{...o},left:this.borderLeftCheck?.checked?{...n}:{...o}},r=this.cellBgColorInput?.value;for(const{row:t,col:e}of i){const i=this.currentTable.getCell(t,e);i&&(r&&(i.backgroundColor=r),i.border=s)}this.editor?.render(),this.onApplyCallback?.(!0)}getCurrentTable(){return this.currentTable}hasTable(){return null!==this.currentTable}doMergeCells(){this.editor&&this.currentTable&&(this.editor.tableMergeCells(this.currentTable),this.updateFromFocusedTable())}doSplitCell(){if(!this.editor||!this.currentTable)return;const t=this.currentTable.focusedCell;t&&(this.editor.tableSplitCell(this.currentTable,t.row,t.col),this.updateFromFocusedTable())}update(){this.updateFromFocusedTable()}},t.TableRow=N,t.TableRowLoopPane=class extends te{constructor(t="table-row-loop",e={}){super(t,{className:"pc-pane-table-row-loop",...e}),this.fieldPathInput=null,this.rangeHint=null,this.currentLoop=null,this.currentTable=null,this.onApplyCallback=e.onApply,this.onRemoveCallback=e.onRemove}attach(t){if(super.attach(t),this.editor){const t=t=>{this.showLoop(t.table,t.loop)},e=()=>{this.hideLoop()};this.editor.on("table-row-loop-clicked",t),this.editor.on("selection-change",e),this.eventCleanup.push(()=>{this.editor?.off("table-row-loop-clicked",t),this.editor?.off("selection-change",e)})}}createContent(){const t=document.createElement("div");this.fieldPathInput=this.createTextInput({placeholder:"items"}),t.appendChild(this.createFormGroup("Array Field Path:",this.fieldPathInput,{hint:'Path to array in merge data (e.g., "items" or "orders")'}));const e=this.createButton("Apply Changes",{variant:"primary"});this.addButtonListener(e,()=>this.applyChanges()),t.appendChild(e);const i=this.createButton("Remove Loop",{variant:"danger"});return i.style.marginTop="0.5rem",this.addButtonListener(i,()=>this.removeLoop()),t.appendChild(i),this.rangeHint=this.createHint(""),t.appendChild(this.rangeHint),t}showLoop(t,e){this.currentTable=t,this.currentLoop=e,this.fieldPathInput&&(this.fieldPathInput.value=e.fieldPath),this.rangeHint&&(this.rangeHint.textContent=`Rows ${e.startRowIndex} - ${e.endRowIndex}`),this.show()}hideLoop(){this.currentTable=null,this.currentLoop=null,this.hide()}applyChanges(){if(!this.currentTable||!this.currentLoop)return void this.onApplyCallback?.(!1,new Error("No loop selected"));const t=this.fieldPathInput?.value.trim();if(t){if(t!==this.currentLoop.fieldPath)try{this.currentTable.updateRowLoopFieldPath(this.currentLoop.id,t)?(this.currentLoop=this.currentTable.getRowLoop(this.currentLoop.id)||null,this.currentLoop&&this.showLoop(this.currentTable,this.currentLoop),this.onApplyCallback?.(!0)):this.onApplyCallback?.(!1,new Error("Failed to update loop"))}catch(t){this.onApplyCallback?.(!1,t instanceof Error?t:new Error(String(t)))}}else this.onApplyCallback?.(!1,new Error("Field path cannot be empty"))}removeLoop(){if(this.currentTable&&this.currentLoop)try{this.currentTable.removeRowLoop(this.currentLoop.id)?(this.hideLoop(),this.onRemoveCallback?.(!0)):this.onRemoveCallback?.(!1)}catch{this.onRemoveCallback?.(!1)}}getCurrentLoop(){return this.currentLoop}getCurrentTable(){return this.currentTable}hasLoop(){return null!==this.currentLoop}update(){}},t.TextBoxObject=L,t.TextBoxPane=class extends te{constructor(t="textbox",e={}){super(t,{className:"pc-pane-textbox",...e}),this.positionSelect=null,this.offsetGroup=null,this.offsetXInput=null,this.offsetYInput=null,this.bgColorInput=null,this.borderWidthInput=null,this.borderColorInput=null,this.borderStyleSelect=null,this.paddingInput=null,this._isUpdating=!1,this.currentTextBox=null,this.onApplyCallback=e.onApply}attach(t){if(super.attach(t),this.editor){const t=()=>this.updateFromSelection();this.editor.on("selection-change",t),this.editor.on("textbox-updated",t),this.eventCleanup.push(()=>{this.editor?.off("selection-change",t),this.editor?.off("textbox-updated",t)}),this.updateFromSelection()}}createContent(){const t=document.createElement("div"),e=this.createSection("Position");this.positionSelect=this.createSelect([{value:"inline",label:"Inline"},{value:"block",label:"Block"},{value:"relative",label:"Relative"}],"inline"),this.addImmediateApplyListener(this.positionSelect,()=>{this.updateOffsetVisibility(),this.applyChanges()}),e.appendChild(this.createFormGroup("Type:",this.positionSelect,{inline:!0})),this.offsetGroup=document.createElement("div"),this.offsetGroup.style.display="none";const i=this.createRow();this.offsetXInput=this.createNumberInput({value:0}),this.offsetYInput=this.createNumberInput({value:0}),this.addImmediateApplyListener(this.offsetXInput,()=>this.applyChanges()),this.addImmediateApplyListener(this.offsetYInput,()=>this.applyChanges()),i.appendChild(this.createFormGroup("X:",this.offsetXInput,{inline:!0})),i.appendChild(this.createFormGroup("Y:",this.offsetYInput,{inline:!0})),this.offsetGroup.appendChild(i),e.appendChild(this.offsetGroup),t.appendChild(e);const n=this.createSection();this.bgColorInput=this.createColorInput("#ffffff"),this.addImmediateApplyListener(this.bgColorInput,()=>this.applyChanges()),n.appendChild(this.createFormGroup("Background:",this.bgColorInput,{inline:!0})),t.appendChild(n);const o=this.createSection("Border"),s=this.createRow();this.borderWidthInput=this.createNumberInput({min:0,max:10,value:1}),this.borderColorInput=this.createColorInput("#cccccc"),this.addImmediateApplyListener(this.borderWidthInput,()=>this.applyChanges()),this.addImmediateApplyListener(this.borderColorInput,()=>this.applyChanges()),s.appendChild(this.createFormGroup("Width:",this.borderWidthInput,{inline:!0})),s.appendChild(this.createFormGroup("Color:",this.borderColorInput,{inline:!0})),o.appendChild(s),this.borderStyleSelect=this.createSelect([{value:"solid",label:"Solid"},{value:"dashed",label:"Dashed"},{value:"dotted",label:"Dotted"},{value:"none",label:"None"}],"solid"),this.addImmediateApplyListener(this.borderStyleSelect,()=>this.applyChanges()),o.appendChild(this.createFormGroup("Style:",this.borderStyleSelect,{inline:!0})),t.appendChild(o);const r=this.createSection();return this.paddingInput=this.createNumberInput({min:0,max:50,value:8}),this.addImmediateApplyListener(this.paddingInput,()=>this.applyChanges()),r.appendChild(this.createFormGroup("Padding:",this.paddingInput,{inline:!0})),t.appendChild(r),t}updateFromSelection(){if(this.editor&&!this._isUpdating){this._isUpdating=!0;try{const t=this.editor.getSelectedTextBox?.();t&&!t.editing?this.showTextBox(t):this.hideTextBox()}finally{this._isUpdating=!1}}}showTextBox(t){this.currentTextBox=t,this.positionSelect&&(this.positionSelect.value=t.position||"inline"),this.updateOffsetVisibility(),this.offsetXInput&&(this.offsetXInput.value=String(t.relativeOffset?.x??0)),this.offsetYInput&&(this.offsetYInput.value=String(t.relativeOffset?.y??0)),this.bgColorInput&&(this.bgColorInput.value=t.backgroundColor||"#ffffff");const e=t.border,i="none"!==e.top.style?e.top:"none"!==e.right.style?e.right:"none"!==e.bottom.style?e.bottom:"none"!==e.left.style?e.left:e.top;this.borderWidthInput&&(this.borderWidthInput.value=String(i.width)),this.borderColorInput&&(this.borderColorInput.value=i.color),this.borderStyleSelect&&(this.borderStyleSelect.value=i.style),this.paddingInput&&(this.paddingInput.value=String(t.padding??8)),this.show()}hideTextBox(){this.currentTextBox=null,this.hide()}updateOffsetVisibility(){this.offsetGroup&&this.positionSelect&&(this.offsetGroup.style.display="relative"===this.positionSelect.value?"block":"none")}applyChanges(){if(!this.editor||!this.currentTextBox)return;const t={};this.positionSelect&&(t.position=this.positionSelect.value),"relative"===this.positionSelect?.value&&(t.relativeOffset={x:parseInt(this.offsetXInput?.value||"0",10),y:parseInt(this.offsetYInput?.value||"0",10)}),this.bgColorInput&&(t.backgroundColor=this.bgColorInput.value);const e={width:parseInt(this.borderWidthInput?.value||"1",10),color:this.borderColorInput?.value||"#cccccc",style:this.borderStyleSelect?.value||"solid"};t.border={top:{...e},right:{...e},bottom:{...e},left:{...e}},this.paddingInput&&(t.padding=parseInt(this.paddingInput.value,10));try{const e=this.editor.updateTextBox(this.currentTextBox.id,t);this.onApplyCallback?.(e)}catch(t){this.onApplyCallback?.(!1,t instanceof Error?t:new Error(String(t)))}}getCurrentTextBox(){return this.currentTextBox}hasTextBox(){return null!==this.currentTextBox}update(){this.updateFromSelection()}},t.TextFormattingManager=f,t.TextLayout=v,t.TextMeasurer=F,t.TextPositionCalculator=P,t.TextState=u,t.VerticalRuler=class extends Qt{constructor(t={}){super("vertical-ruler",t),this.orientation="vertical",this.contentOffsetY=0,this.pageHeightPx=0,this.pageGap=40,this.totalPages=1}updateScrollOffset(){if(!this.editor)return;const t=this.editor.getScrollPosition();this.scrollOffset=t.y}getContentOffset(){return this.contentOffsetY}updateFromMetrics(t){if(!t||!this.editor)return;const e=Zt("mm");this.pageHeightPx=t.pageHeight*e*this.zoomLevel,this.totalPages=t.totalPages,this.documentSize=(this.pageHeightPx+this.pageGap)*this.totalPages-this.pageGap,this.marginStart=t.margins.top*e*this.zoomLevel,this.marginEnd=(t.pageHeight-t.margins.bottom)*e*this.zoomLevel;const i=this.editor.getContentOffset(),n=this.editor.getScrollPosition();this.contentOffsetY=i.y-n.y}renderMargins(t,e){if(!this.ctx)return;const i=this.contentOffsetY,n=i+this.documentSize;i>0&&(this.ctx.fillStyle=this.options.marginColor,this.ctx.fillRect(0,0,t,i)),n<e&&(this.ctx.fillStyle=this.options.marginColor,this.ctx.fillRect(0,n,t,e-n));for(let n=0;n<this.totalPages-1;n++){const o=i+(n+1)*this.pageHeightPx+n*this.pageGap,s=o,r=o+this.pageGap;r>0&&s<e&&(this.ctx.fillStyle=this.options.marginColor,this.ctx.fillRect(0,Math.max(0,s),t,Math.min(r,e)-Math.max(0,s)))}this.ctx.strokeStyle=this.options.tickColor,this.ctx.lineWidth=1;for(let n=0;n<this.totalPages;n++){const o=i+n*(this.pageHeightPx+this.pageGap),s=o+this.marginStart,r=o+this.marginEnd;s>=0&&s<=e&&(this.ctx.beginPath(),this.ctx.moveTo(0,s),this.ctx.lineTo(t,s),this.ctx.stroke()),r>=0&&r<=e&&(this.ctx.beginPath(),this.ctx.moveTo(0,r),this.ctx.lineTo(t,r),this.ctx.stroke())}}calculateTickMarks(){const t=[],e=Zt(this.options.units)*this.zoomLevel,i=this.options.majorTickInterval,n=i/this.options.minorTicksPerMajor,o=this.getVisibleLength();for(let s=0;s<this.totalPages;s++){const r=s*(this.pageHeightPx+this.pageGap),a=Math.max(0,-this.contentOffsetY-r),l=Math.min(this.pageHeightPx,o-this.contentOffsetY-r);if(l<0||a>this.pageHeightPx)continue;const d=Math.floor(a/e/n)*n-n,h=Math.ceil(l/e/n)*n+n;for(let o=Math.max(0,d);o*e<=this.pageHeightPx&&o<=h;o+=n){const n=r+o*e,s=Math.abs(o%i)<.001,a={position:n,isMajor:s};s&&this.options.showLabels&&(a.label=String(Math.round(o))),t.push(a)}}return t}renderTicks(t,e,i){if(!this.ctx)return;const n=.6*e,o=.3*e;this.ctx.strokeStyle=this.options.tickColor,this.ctx.lineWidth=1,this.ctx.font=`${this.options.labelFontSize}px sans-serif`,this.ctx.fillStyle=this.options.labelColor,this.ctx.textAlign="right",this.ctx.textBaseline="middle";const s=this.contentOffsetY;for(const r of t){const t=r.position+s;if(t<-10||t>i+10)continue;if(this.isInPageGap(r.position))continue;const a=r.isMajor?n:o;this.ctx.beginPath(),this.ctx.moveTo(e,t),this.ctx.lineTo(e-a,t),this.ctx.stroke(),r.label&&(this.ctx.save(),this.ctx.translate(e-n-2,t),this.ctx.rotate(-Math.PI/2),this.ctx.textAlign="center",this.ctx.fillText(r.label,0,0),this.ctx.restore())}}isInPageGap(t){for(let e=0;e<this.totalPages-1;e++){const i=(e+1)*this.pageHeightPx+e*this.pageGap,n=i+this.pageGap;if(t>=i&&t<n)return!0}return!1}renderCursorIndicator(t,e){this.ctx&&null!==this.currentMousePosition&&(this.ctx.fillStyle=this.options.activeColor,this.ctx.fillRect(0,this.currentMousePosition-1,t,2),this.ctx.beginPath(),this.ctx.moveTo(t,this.currentMousePosition-4),this.ctx.lineTo(t,this.currentMousePosition+4),this.ctx.lineTo(t-6,this.currentMousePosition),this.ctx.closePath(),this.ctx.fill())}},t.ViewSettingsPane=class extends te{constructor(t="view-settings",e={}){super(t,{className:"pc-pane-view-settings",...e}),this.rulersBtn=null,this.controlCharsBtn=null,this.marginLinesBtn=null,this.gridBtn=null,this.onToggleRulers=e.onToggleRulers,this.rulersVisible=e.rulersVisible??!0}attach(t){if(super.attach(t),this.editor){const t=()=>this.updateButtonStates();this.editor.on("grid-changed",t),this.editor.on("margin-lines-changed",t),this.editor.on("control-characters-changed",t),this.eventCleanup.push(()=>{this.editor?.off("grid-changed",t),this.editor?.off("margin-lines-changed",t),this.editor?.off("control-characters-changed",t)}),this.updateButtonStates()}}createContent(){const t=document.createElement("div");return t.className="pc-pane-button-group pc-pane-view-toggles",this.onToggleRulers&&(this.rulersBtn=this.createToggleButton("Rulers",this.rulersVisible),this.addButtonListener(this.rulersBtn,()=>this.toggleRulers()),t.appendChild(this.rulersBtn)),this.controlCharsBtn=this.createToggleButton("Control Chars",!1),this.addButtonListener(this.controlCharsBtn,()=>this.toggleControlChars()),t.appendChild(this.controlCharsBtn),this.marginLinesBtn=this.createToggleButton("Margin Lines",!0),this.addButtonListener(this.marginLinesBtn,()=>this.toggleMarginLines()),t.appendChild(this.marginLinesBtn),this.gridBtn=this.createToggleButton("Grid",!0),this.addButtonListener(this.gridBtn,()=>this.toggleGrid()),t.appendChild(this.gridBtn),t}createToggleButton(t,e){const i=document.createElement("button");return i.type="button",i.className="pc-pane-toggle",e&&i.classList.add("pc-pane-toggle--active"),i.textContent=t,i.title=`Toggle ${t}`,i}toggleRulers(){this.onToggleRulers&&(this.onToggleRulers(),this.rulersVisible=!this.rulersVisible,this.rulersBtn?.classList.toggle("pc-pane-toggle--active",this.rulersVisible))}toggleControlChars(){if(!this.editor)return;const t=this.editor.getShowControlCharacters();this.editor.setShowControlCharacters(!t)}toggleMarginLines(){if(!this.editor)return;const t=this.editor.getShowMarginLines();this.editor.setShowMarginLines(!t)}toggleGrid(){if(!this.editor)return;const t=this.editor.getShowGrid();this.editor.setShowGrid(!t)}updateButtonStates(){this.editor&&(this.controlCharsBtn&&this.controlCharsBtn.classList.toggle("pc-pane-toggle--active",this.editor.getShowControlCharacters()),this.marginLinesBtn&&this.marginLinesBtn.classList.toggle("pc-pane-toggle--active",this.editor.getShowMarginLines()),this.gridBtn&&this.gridBtn.classList.toggle("pc-pane-toggle--active",this.editor.getShowGrid()))}setRulersVisible(t){this.rulersVisible=t,this.rulersBtn?.classList.toggle("pc-pane-toggle--active",t)}update(){this.updateButtonStates()}}});
2
2
  //# sourceMappingURL=pc-editor.min.js.map