@productcloudos/editor 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +95 -0
- package/LICENSE +21 -0
- package/README.md +377 -0
- package/dist/pc-editor.esm.js +24820 -0
- package/dist/pc-editor.esm.js.map +1 -0
- package/dist/pc-editor.js +24877 -0
- package/dist/pc-editor.js.map +1 -0
- package/dist/pc-editor.min.js +2 -0
- package/dist/pc-editor.min.js.map +1 -0
- package/dist/types/lib/clipboard/ClipboardManager.d.ts +77 -0
- package/dist/types/lib/clipboard/ClipboardManager.d.ts.map +1 -0
- package/dist/types/lib/clipboard/HtmlConverter.d.ts +43 -0
- package/dist/types/lib/clipboard/HtmlConverter.d.ts.map +1 -0
- package/dist/types/lib/clipboard/index.d.ts +9 -0
- package/dist/types/lib/clipboard/index.d.ts.map +1 -0
- package/dist/types/lib/clipboard/types.d.ts +76 -0
- package/dist/types/lib/clipboard/types.d.ts.map +1 -0
- package/dist/types/lib/controls/BaseControl.d.ts +72 -0
- package/dist/types/lib/controls/BaseControl.d.ts.map +1 -0
- package/dist/types/lib/controls/index.d.ts +11 -0
- package/dist/types/lib/controls/index.d.ts.map +1 -0
- package/dist/types/lib/controls/rulers/HorizontalRuler.d.ts +55 -0
- package/dist/types/lib/controls/rulers/HorizontalRuler.d.ts.map +1 -0
- package/dist/types/lib/controls/rulers/RulerControl.d.ts +98 -0
- package/dist/types/lib/controls/rulers/RulerControl.d.ts.map +1 -0
- package/dist/types/lib/controls/rulers/VerticalRuler.d.ts +65 -0
- package/dist/types/lib/controls/rulers/VerticalRuler.d.ts.map +1 -0
- package/dist/types/lib/controls/rulers/index.d.ts +8 -0
- package/dist/types/lib/controls/rulers/index.d.ts.map +1 -0
- package/dist/types/lib/controls/rulers/types.d.ts +62 -0
- package/dist/types/lib/controls/rulers/types.d.ts.map +1 -0
- package/dist/types/lib/controls/types.d.ts +51 -0
- package/dist/types/lib/controls/types.d.ts.map +1 -0
- package/dist/types/lib/core/Document.d.ts +34 -0
- package/dist/types/lib/core/Document.d.ts.map +1 -0
- package/dist/types/lib/core/PCEditor.d.ts +761 -0
- package/dist/types/lib/core/PCEditor.d.ts.map +1 -0
- package/dist/types/lib/core/Page.d.ts +40 -0
- package/dist/types/lib/core/Page.d.ts.map +1 -0
- package/dist/types/lib/data/DataBinder.d.ts +11 -0
- package/dist/types/lib/data/DataBinder.d.ts.map +1 -0
- package/dist/types/lib/events/EventEmitter.d.ts +11 -0
- package/dist/types/lib/events/EventEmitter.d.ts.map +1 -0
- package/dist/types/lib/hit-test/HitTestManager.d.ts +81 -0
- package/dist/types/lib/hit-test/HitTestManager.d.ts.map +1 -0
- package/dist/types/lib/hit-test/index.d.ts +32 -0
- package/dist/types/lib/hit-test/index.d.ts.map +1 -0
- package/dist/types/lib/hit-test/types.d.ts +113 -0
- package/dist/types/lib/hit-test/types.d.ts.map +1 -0
- package/dist/types/lib/import/ContentAnalyzer.d.ts +76 -0
- package/dist/types/lib/import/ContentAnalyzer.d.ts.map +1 -0
- package/dist/types/lib/import/DocumentBuilder.d.ts +44 -0
- package/dist/types/lib/import/DocumentBuilder.d.ts.map +1 -0
- package/dist/types/lib/import/PDFImporter.d.ts +65 -0
- package/dist/types/lib/import/PDFImporter.d.ts.map +1 -0
- package/dist/types/lib/import/PDFParser.d.ts +46 -0
- package/dist/types/lib/import/PDFParser.d.ts.map +1 -0
- package/dist/types/lib/import/index.d.ts +9 -0
- package/dist/types/lib/import/index.d.ts.map +1 -0
- package/dist/types/lib/import/types.d.ts +182 -0
- package/dist/types/lib/import/types.d.ts.map +1 -0
- package/dist/types/lib/index.d.ts +16 -0
- package/dist/types/lib/index.d.ts.map +1 -0
- package/dist/types/lib/layout/FlowManager.d.ts +29 -0
- package/dist/types/lib/layout/FlowManager.d.ts.map +1 -0
- package/dist/types/lib/layout/LayoutEngine.d.ts +39 -0
- package/dist/types/lib/layout/LayoutEngine.d.ts.map +1 -0
- package/dist/types/lib/objects/BaseEmbeddedObject.d.ts +133 -0
- package/dist/types/lib/objects/BaseEmbeddedObject.d.ts.map +1 -0
- package/dist/types/lib/objects/EmbeddedObjectFactory.d.ts +57 -0
- package/dist/types/lib/objects/EmbeddedObjectFactory.d.ts.map +1 -0
- package/dist/types/lib/objects/ImageObject.d.ts +60 -0
- package/dist/types/lib/objects/ImageObject.d.ts.map +1 -0
- package/dist/types/lib/objects/TextBoxObject.d.ts +208 -0
- package/dist/types/lib/objects/TextBoxObject.d.ts.map +1 -0
- package/dist/types/lib/objects/index.d.ts +9 -0
- package/dist/types/lib/objects/index.d.ts.map +1 -0
- package/dist/types/lib/objects/table/TableCell.d.ts +165 -0
- package/dist/types/lib/objects/table/TableCell.d.ts.map +1 -0
- package/dist/types/lib/objects/table/TableCellMerger.d.ts +66 -0
- package/dist/types/lib/objects/table/TableCellMerger.d.ts.map +1 -0
- package/dist/types/lib/objects/table/TableObject.d.ts +434 -0
- package/dist/types/lib/objects/table/TableObject.d.ts.map +1 -0
- package/dist/types/lib/objects/table/TableResizeHandler.d.ts +80 -0
- package/dist/types/lib/objects/table/TableResizeHandler.d.ts.map +1 -0
- package/dist/types/lib/objects/table/TableRow.d.ts +65 -0
- package/dist/types/lib/objects/table/TableRow.d.ts.map +1 -0
- package/dist/types/lib/objects/table/index.d.ts +12 -0
- package/dist/types/lib/objects/table/index.d.ts.map +1 -0
- package/dist/types/lib/objects/table/types.d.ts +239 -0
- package/dist/types/lib/objects/table/types.d.ts.map +1 -0
- package/dist/types/lib/objects/types.d.ts +135 -0
- package/dist/types/lib/objects/types.d.ts.map +1 -0
- package/dist/types/lib/rendering/CanvasManager.d.ts +282 -0
- package/dist/types/lib/rendering/CanvasManager.d.ts.map +1 -0
- package/dist/types/lib/rendering/FlowingTextRenderer.d.ts +348 -0
- package/dist/types/lib/rendering/FlowingTextRenderer.d.ts.map +1 -0
- package/dist/types/lib/rendering/PDFGenerator.d.ts +103 -0
- package/dist/types/lib/rendering/PDFGenerator.d.ts.map +1 -0
- package/dist/types/lib/rendering/pdf-utils.d.ts +54 -0
- package/dist/types/lib/rendering/pdf-utils.d.ts.map +1 -0
- package/dist/types/lib/text/EditableTextRegion.d.ts +105 -0
- package/dist/types/lib/text/EditableTextRegion.d.ts.map +1 -0
- package/dist/types/lib/text/EmbeddedObjectManager.d.ts +97 -0
- package/dist/types/lib/text/EmbeddedObjectManager.d.ts.map +1 -0
- package/dist/types/lib/text/FieldFormatter.d.ts +26 -0
- package/dist/types/lib/text/FieldFormatter.d.ts.map +1 -0
- package/dist/types/lib/text/FlowingTextContent.d.ts +571 -0
- package/dist/types/lib/text/FlowingTextContent.d.ts.map +1 -0
- package/dist/types/lib/text/HyperlinkManager.d.ts +110 -0
- package/dist/types/lib/text/HyperlinkManager.d.ts.map +1 -0
- package/dist/types/lib/text/MarkdownParser.d.ts +55 -0
- package/dist/types/lib/text/MarkdownParser.d.ts.map +1 -0
- package/dist/types/lib/text/ParagraphFormatting.d.ts +123 -0
- package/dist/types/lib/text/ParagraphFormatting.d.ts.map +1 -0
- package/dist/types/lib/text/RegionManager.d.ts +75 -0
- package/dist/types/lib/text/RegionManager.d.ts.map +1 -0
- package/dist/types/lib/text/RepeatingSectionManager.d.ts +99 -0
- package/dist/types/lib/text/RepeatingSectionManager.d.ts.map +1 -0
- package/dist/types/lib/text/SubstitutionFieldManager.d.ts +153 -0
- package/dist/types/lib/text/SubstitutionFieldManager.d.ts.map +1 -0
- package/dist/types/lib/text/TextFormatting.d.ts +85 -0
- package/dist/types/lib/text/TextFormatting.d.ts.map +1 -0
- package/dist/types/lib/text/TextLayout.d.ts +126 -0
- package/dist/types/lib/text/TextLayout.d.ts.map +1 -0
- package/dist/types/lib/text/TextMeasurer.d.ts +107 -0
- package/dist/types/lib/text/TextMeasurer.d.ts.map +1 -0
- package/dist/types/lib/text/TextPositionCalculator.d.ts +72 -0
- package/dist/types/lib/text/TextPositionCalculator.d.ts.map +1 -0
- package/dist/types/lib/text/TextState.d.ts +236 -0
- package/dist/types/lib/text/TextState.d.ts.map +1 -0
- package/dist/types/lib/text/index.d.ts +27 -0
- package/dist/types/lib/text/index.d.ts.map +1 -0
- package/dist/types/lib/text/regions/BodyTextRegion.d.ts +68 -0
- package/dist/types/lib/text/regions/BodyTextRegion.d.ts.map +1 -0
- package/dist/types/lib/text/regions/FooterTextRegion.d.ts +68 -0
- package/dist/types/lib/text/regions/FooterTextRegion.d.ts.map +1 -0
- package/dist/types/lib/text/regions/HeaderTextRegion.d.ts +68 -0
- package/dist/types/lib/text/regions/HeaderTextRegion.d.ts.map +1 -0
- package/dist/types/lib/text/regions/index.d.ts +7 -0
- package/dist/types/lib/text/regions/index.d.ts.map +1 -0
- package/dist/types/lib/text/types.d.ts +268 -0
- package/dist/types/lib/text/types.d.ts.map +1 -0
- package/dist/types/lib/types/index.d.ts +206 -0
- package/dist/types/lib/types/index.d.ts.map +1 -0
- package/dist/types/lib/undo/index.d.ts +8 -0
- package/dist/types/lib/undo/index.d.ts.map +1 -0
- package/dist/types/lib/undo/transaction/ContentDiscovery.d.ts +101 -0
- package/dist/types/lib/undo/transaction/ContentDiscovery.d.ts.map +1 -0
- package/dist/types/lib/undo/transaction/FocusTracker.d.ts +49 -0
- package/dist/types/lib/undo/transaction/FocusTracker.d.ts.map +1 -0
- package/dist/types/lib/undo/transaction/MutationUndo.d.ts +57 -0
- package/dist/types/lib/undo/transaction/MutationUndo.d.ts.map +1 -0
- package/dist/types/lib/undo/transaction/ObjectMutationObserver.d.ts +79 -0
- package/dist/types/lib/undo/transaction/ObjectMutationObserver.d.ts.map +1 -0
- package/dist/types/lib/undo/transaction/TextMutationObserver.d.ts +60 -0
- package/dist/types/lib/undo/transaction/TextMutationObserver.d.ts.map +1 -0
- package/dist/types/lib/undo/transaction/TransactionManager.d.ts +148 -0
- package/dist/types/lib/undo/transaction/TransactionManager.d.ts.map +1 -0
- package/dist/types/lib/undo/transaction/index.d.ts +17 -0
- package/dist/types/lib/undo/transaction/index.d.ts.map +1 -0
- package/dist/types/lib/undo/transaction/types.d.ts +269 -0
- package/dist/types/lib/undo/transaction/types.d.ts.map +1 -0
- package/dist/types/lib/utils/blob-utils.d.ts +2 -0
- package/dist/types/lib/utils/blob-utils.d.ts.map +1 -0
- package/package.json +88 -0
|
@@ -0,0 +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"},d={alignment:"left"},h="",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)===h}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?{...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})}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)}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"],m=["decimal","lower-alpha","lower-roman"];class p extends o{constructor(t){super(),this.formatting=new Map,this._defaultFormatting={...d,...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 m[t%m.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 x 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 b 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 w 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 y 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,d=e.paragraphFormatting.getFormattingForParagraph(s),h=d.alignment,c=d.listFormatting,g=c?e.paragraphFormatting.getListNumber(s,e.content):void 0,u=this.wrapLogicalLine(r,s,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),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:d}=i,h=[],c=o?this.calculateListIndent(o.nestingLevel):0;let g="",u=0;if(o){g=this.getListMarkerText(o,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);return o&&(t.listMarker={text:g,width:u,indent:c,isFirstLineOfListItem:!0}),h.push(t),h}const m=this.splitIntoSegments(t,e,i);let p=this.createLineBuilder(e,l),x=0;const b=(t,e)=>{o&&(t.listMarker={text:e?g:"",width:u,indent:c,isFirstLineOfListItem:e}),h.push(t)};for(let t=0;t<m.length;t++){const e=m[t],i=e.text.length>0&&/^\s+$/.test(e.text),s=e.embeddedObjects.find(t=>t.isBlock);if(s){if(p.text.length>0){b(this.finalizeLineBuilder(p,n,!0,f),0===h.length)}b(this.createBlockObjectLine(s,e,n),0===h.length),p=this.createLineBuilder(e.startIndex+1,l),x=0;continue}if(p.width+e.width>f&&p.text.length>0){if(i){if(this.addSegmentToLine(p,e,x),x+=e.width,t+1<m.length){b(this.finalizeLineBuilder(p,n,!1,f),0===h.length);const e=m[t+1];p=this.createLineBuilder(e.startIndex,l),x=0}continue}b(this.finalizeLineBuilder(p,n,!1,f),0===h.length),p=this.createLineBuilder(e.startIndex,l),x=0}this.addSegmentToLine(p,e,x),x+=e.width}if(p.text.length>0||0===h.length){b(this.finalizeLineBuilder(p,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 s=0;for(;s<t.length;){const o=t[s],r=/\s/.test(o);if(o===h){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===h)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,d=0;const h=[],c=[],g=[];let u=null;for(let i=0;i<t.length;i++){const f=e+i,m=t[i],p=n.getFormattingAt(f),x=s.getFieldAt(f),b=o.getObjectAt(f);if(x){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(x,p);c.push({field:x,textIndex:f,x:a,width:t.width}),h.push({text:m,formatting:p,startIndex:f,endIndex:f+1}),a+=t.width,l=Math.max(l,t.height),d=Math.max(d,.8*p.fontSize)}else if(b)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"===b.position)g.push({object:b,textIndex:f,x:0,isBlock:!0}),h.push({text:m,formatting:p,startIndex:f,endIndex:f+1}),d=Math.max(d,.8*p.fontSize);else if("relative"===b.position)g.push({object:b,textIndex:f,x:a,isAnchor:!0}),h.push({text:m,formatting:p,startIndex:f,endIndex:f+1}),d=Math.max(d,.8*p.fontSize);else{const t=b.width+2;g.push({object:b,textIndex:f,x:a}),h.push({text:m,formatting:p,startIndex:f,endIndex:f+1}),a+=t,l=Math.max(l,b.height),d=Math.max(d,.8*p.fontSize)}else{if(""===m)continue;{const t=r.measureCharacter(m,p),e=r.getLineHeight(p);u&&this.formattingEquals(u.formatting,p)||(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:p,startIndex:f}),u.text+=m,a+=t,l=Math.max(l,e),d=Math.max(d,.8*p.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 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 d=0;d<t.length;d++){const c=t[d],g=s+d;if(c===h){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 F={width:1,color:"#cccccc",style:"solid"};class v 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 _ extends v{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}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,d=0,h=0,c=e,g=i;switch(this._fit){case"fill":break;case"contain":{const t=Math.min(e/n,i/s);c=n*t,g=s*t,d=(e-c)/2,h=(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,d=(e-n)/2,h=(i-s)/2;break;case"tile":return void this.drawTiledImage(t,e,i)}t.drawImage(this._image,o,r,a,l,d,h,c,g)}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 _({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 I{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 d=r.text[a];o+=this.getCharWidth(d,l,i,n,s),"justify"===t.alignment&&t.extraWordSpacing&&/\s/.test(d)&&(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,d=a.text[t],h=n.get(l);if(h){const t=h.width;if(e>=o&&e<o+t)return l+1;o+=t,r>0&&/\s/.test(d)&&(o+=r);continue}const c=this.getCharWidth(d,l,i,n,s);if(e>=o&&e<o+c)return e<o+c/2?l:l+1;o+=c,r>0&&/\s/.test(d)&&(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 P="Arial",T=14,R="#000000",M="#ffffff",k=4;class A extends v{constructor(t){super(t),this._editing=!1,this._flowedLines=[],this._flowedPage=null,this.type="textbox",this._content=t.content||"",this._fontFamily=t.fontFamily||P,this._fontSize=t.fontSize||T,this._color=t.color||R,this._backgroundColor=t.backgroundColor||M,this._border=function(t,e){const i=e?{...F,color:e}:{...F};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??k,this._flowingContent=new Z(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 I.getAlignmentOffset(e,n.width)+I.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-I.getAlignmentOffset(e,n.width);return I.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.getFormattingManager().getAllFormatting(),e=[];t.forEach((t,i)=>{e.push([i,{...t}])});const 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){const t=this._flowingContent.getFormattingManager();t.clear();for(const[i,n]of e.formattingRuns)t.applyFormatting(i,i+1,n)}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 A({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){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.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 O=4,z="#000000",E=1,j="Arial",D=12,L="#000000",B="#ffffff",H=20,W=20,N=100,U={width:1,color:"#000000",style:"solid"};function $(t){return t.top+t.bottom}class V 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??B,this._border=function(t){const e=U;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??O;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,O),this._verticalAlign=t.verticalAlign??"top",this._fontFamily=t.fontFamily??j,this._fontSize=t.fontSize??D,this._color=t.color??L,this._flowingContent=new Z,this._flowingContent.setDefaultFormatting({fontFamily:this._fontFamily,fontSize:this._fontSize,color:this._color}),this._flowingContent.insertEmbeddedObject=()=>{console.warn("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-$(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+=$(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,W),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,console.log("[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(console.log("[TableCell.handleKeyDown] Key:",t.key,"_editing:",this._editing,"flowingContent.hasFocus:",this._flowingContent.hasFocus()),!this._editing)return!1;if("Tab"===t.key)return!1;console.log("[TableCell.handleKeyDown] Delegating to FlowingTextContent.handleKeyDown");const e=this._flowingContent.handleKeyDown(t);return console.log("[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.getFormattingManager().getAllFormatting(),e=[];t.forEach((t,i)=>{e.push([i,{...t}])});const i=this._flowingContent.getSubstitutionFieldManager().getFieldsArray();return{id:this._id,rowSpan:this._rowSpan,colSpan:this._colSpan,backgroundColor:this._backgroundColor,border:this._border,padding:this._padding,verticalAlign:this._verticalAlign,content:this._flowingContent.getText(),fontFamily:this._fontFamily,fontSize:this._fontSize,color:this._color,formattingRuns:e.length>0?e:void 0,substitutionFields:i.length>0?i:void 0}}static fromData(t){const e=new V({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){const i=e._flowingContent.getFormattingManager(),n=new Map;for(const[e,i]of t.formattingRuns)n.set(e,i);i.setAllFormatting(n)}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 V.fromData(this.toData())}}class K 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??W,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 V(s);this.setupCellListeners(o),this._cells.push(o)}else for(let t=0;t<e;t++){const t=new V(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 V(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]||N;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]||N;o.setBounds({x:r,y:t,width:a,height:n})}}toData(){return{id:this._id,height:this._height,minHeight:this._minHeight,isHeader:this._isHeader,cells:this._cells.map(t=>t.toData())}}static fromData(t){const e=new K({id:t.id,height:t.height,minHeight:t.minHeight,isHeader:t.isHeader},t.cells.length);return e._cells=t.cells.map(t=>{const i=V.fromData(t);return e.setupCellListeners(i),i}),e}clone(){return K.fromData(this.toData())}}class G{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 X(){return`col_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}class q extends v{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??O,this._defaultBorderColor=t.defaultBorderColor??z,this._defaultBorderWidth=t.defaultBorderWidth??E,this._defaultFontFamily=t.defaultFontFamily??j,this._defaultFontSize=t.defaultFontSize??D,this._defaultColor=t.defaultColor??L;const e=t.columns??2;if(t.columnConfig&&t.columnConfig.length>0)this._columns=t.columnConfig.map(t=>({id:t.id||X(),width:t.width,minWidth:t.minWidth??H}));else if(t.columnWidths&&t.columnWidths.length>0)this._columns=t.columnWidths.map(t=>({id:X(),width:t,minWidth:H}));else for(let t=0;t<e;t++)this._columns.push({id:X(),width:N,minWidth:H});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 K(e,this._columns.length,n);this.setupRowListeners(t),this._rows.push(t)}else for(let t=0;t<i;t++){const t=new K({},this._columns.length,n);this.setupRowListeners(t),this._rows.push(t)}this.updateSizeFromLayout()}get objectType(){return"table"}set position(t){"block"!==t&&console.warn(`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],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 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??H;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??N,n={id:X(),width:i,minWidth:H};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);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 K(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);return this.shiftRowLoopIndices(t,-1),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 console.warn("[TableObject.createRowLoop] Invalid row range"),null;if(t>e)return console.warn("[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 console.warn("[TableObject.createRowLoop] Loop range overlaps with existing loop"),null;for(let i=t;i<=e;i++)if(this._rows[i]?.isHeader)return console.warn("[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);return 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 d=a.colSpan;for(let t=o;t<o+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+=s[e];a.setBounds({x:n[o],y:r[t],width:l,height:h})}}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,d=0,h=!0;for(;l<this._rows.length;){const t=h?r:e,n=!h;let s=n?i:0,c=l;const g=d;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,d+=i,c++}if(c=this.adjustSliceEndForMergedCells(l,c),c<this._rows.length){s=n?i:0,d=g;for(let t=l;t<c;t++)n&&this._rows[t].isHeader||(s+=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&&(s+=this._rows[c].calculatedHeight,d+=this._rows[c].calculatedHeight,c++)}((h?c>o:c>l)||c===this._rows.length)&&(a.push({startRow:l,endRow:c,isContinuation:n,height:s,yOffset:g}),h=!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 d=0;for(let t=r;t<r+l.colSpan&&t<this._columns.length;t++)d+=s[t];t.save(),t.translate(n[r],o);const h=l.getBounds();l.setBounds({x:n[r],y:o,width:d,height:i.calculatedHeight}),l.render(t),h&&l.setBounds(h),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 d=0;for(let t=e;t<e+l.colSpan&&t<this._columns.length;t++)d+=s[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],o);const c=l.getBounds();l.setBounds({x:n[e],y:o,width:d,height:h}),l.render(t),c&&l.setBounds(c),t.restore()}o+=r.calculatedHeight}}}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.emit("blur",{})}hasFocus(){return this._editing}handleKeyDown(t){if(console.log("[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=G.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=G.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=G.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=G.canMerge(this,e);return{canMerge:null===i,error:i||void 0}}canSplitCell(t,e){const i=G.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 d=`⟳ ${s.fieldPath}`,h=t.measureText(d);t.translate(-8-h.width-4,r+l/2),t.fillText(d,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],d=o[e.row],h=o[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,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 q(e);i._rows=[];for(const e of t.data.rows){const t=K.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=K.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 q.fromData(this.toData())}}class J{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 d=0;const h=t.rows;for(let t=0;t<h.length;t++)if(d+=h[t].calculatedHeight,Math.abs(o-d)<=4)return{type:"row",index:t,position:d};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),d=Math.max(a,Math.min(s,l)),h=o+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-s,d=e.rows[n];if(i){const t=Math.max(o+l,d.minHeight);d.height=t}else if(void 0!==r){const t=e.rows[n+1],i=r-t.minHeight,s=-(o-d.minHeight),a=Math.max(s,Math.min(i,l)),h=o+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: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 Y{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 _({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 A({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=e.flowingContent.getFormattingManager(),n=new Map;for(const[e,i]of t.data.formattingRuns)n.set(e,i);i.setAllFormatting(n)}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=>q.fromData(t)),this.initialized=!0)}static ensureInitialized(){this.initialized||this.initialize()}static reset(){this.registry.clear(),this.initialized=!1}}Y.registry=new Map,Y.initialized=!1;class Z 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 p,this.substitutionFields=new x,this.embeddedObjects=new b,this.repeatingSections=new w,this.hyperlinks=new y,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(h,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(h,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)+h+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(console.log("[FlowingTextContent.handleKeyDown] Key:",t.key,"_hasFocus:",this._hasFocus),!this._hasFocus)return console.log("[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=[],i=this.formatting.defaultFormatting;let n=null;for(let s=0;s<t.length;s++){const t=this.formatting.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:{fontFamily:t.fontFamily,fontSize:t.fontSize,fontWeight:t.fontWeight,fontStyle:t.fontStyle,color:t.color,backgroundColor:t.backgroundColor}}),n=t}}const s=this.paragraphFormatting.toJSON(),o=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})),r=this.repeatingSections.toJSON(),a=[];this.embeddedObjects.getObjects().forEach((t,e)=>{a.push({textIndex:e,object:t.toData()})});const l=this.hyperlinks.toJSON();return{text:t,formattingRuns:e.length>0?e:void 0,paragraphFormatting:s.length>0?s:void 0,substitutionFields:o.length>0?o:void 0,repeatingSections:r.length>0?r:void 0,embeddedObjects:a.length>0?a:void 0,hyperlinks:l.length>0?l:void 0}}static fromData(t){const e=new Z(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=Y.tryCreate(i.object);t?e.getEmbeddedObjectManager().insert(t,i.textIndex):console.warn(`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=Y.tryCreate(e.object);t?this.embeddedObjects.insert(t,e.textIndex):console.warn(`Failed to create embedded object of type: ${e.object.objectType}`)}t.hyperlinks&&t.hyperlinks.length>0&&this.hyperlinks.fromJSON(t.hyperlinks)}}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 tt{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 et 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 it 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 nt 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 st={USD:"USD",EUR:"EUR",GBP:"GBP",JPY:"JPY"};function ot(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 rt(t,e,i);case"currency":return function(t,e,i){const n=at(t);if(isNaN(n))return String(t);const s=e.currencyFormat||"USD";if("custom"===s){const t=e.currencySymbol||"$",s=e.currencyPosition||"before",o=rt(n,{decimalPlaces:e.decimalPlaces??2,useGrouping:e.useGrouping??!0},i);return"before"===s?`${t}${o}`:`${o}${t}`}const o={style:"currency",currency:st[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 rt(t,e,i){const n=at(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 at(t){if("number"==typeof t)return t;if("string"==typeof t){const e=t.replace(/[^0-9.-]/g,"");return parseFloat(e)}return NaN}class lt extends o{constructor(t){super(),this._pages=[],this._version="1.0.0",this._bodyFlowingContent=new Z,this._headerFlowingContent=new Z,this._footerFlowingContent=new Z,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 dt{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 ht=100,ct=90,gt=80,ut="#87CEEB",ft="#888888",mt="Page Break",pt="#6B46C1",xt=[4,4];class bt 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 dt,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=I.getAlignmentOffset(e.line,o),a=I.getXPositionForTextIndex(e.line,i,t),l=e.line.listMarker?.indent??0;let d=s.position.y;d+=this.getPageTextOffset(e.pageIndex);for(let t=0;t<e.lineIndex;t++)d+=e.flowedPage.lines[t].height;return{x:s.position.x+r+l+a,y:d,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=I.getAlignmentOffset(s.line,r),l=I.getXPositionForTextIndex(s.line,i,t),d=s.line.listMarker?.indent??0;let h=o.position.y;for(let t=0;t<s.lineIndex;t++)h+=s.flowedPage.lines[t].height;return{x:o.position.x+a+d+l,y:h,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=I.findLineAtY(o,s.y);if(a){const{line:o,lineIndex:l}=a,d=I.getAlignmentOffset(o,r),h=t.getRegionBounds(i);if(h){const i=h.y+a.lineY,n=h.x+d,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-d,g=I.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,d=o[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:s=!0,renderSelection:o=!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.getCursorPosition();if(r&&(e.save(),e.beginPath(),e.rect(a.x,a.y,a.width,a.height),e.clip()),o&&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();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;this.renderFlowedLine(n,e,{x:a.x,y:m},d,i,c,u,f),m+=n.height}}s&&h.hasFocus()&&h.isCursorVisible()&&this.renderRegionCursor(l,e,a,d,c),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),d=I.getAlignmentOffset(s,n),h=s.listMarker?.indent??0,c=i.x+d+h+I.getXPositionForTextIndex(s,t,e),g=i.x+d+h+I.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=I.getAlignmentOffset(r,n),a=r.listMarker?.indent??0,l=i.x+t+a+I.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=I.getAlignmentOffset(r,n),l=r.listMarker?.indent??0,d=i.x+a+l+I.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(d,o),e.lineTo(d,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?r.getCursorPosition():0,l=this.document.pages[0],d=l&&this.flowedPages.get(l.id)?.length||1,h=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,d,h),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 q||this._hitTestManager.register(i,{type:"embedded-object",category:"content",bounds:{x:r,y:a,width:n.width,height:n.height},priority:gt,data:{type:"embedded-object",object:n}}),e.save(),e.translate(r,a),n instanceof A){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 d=t.listMarker?.indent||0,h=n-d;let c=i.x+d+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);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],m=g.get(h);if(m){const n=o===h+1,a=s+1;c=this.renderSubstitutionField(m,e,{x:c,y:i.y},t,n,a,r);continue}const p=u.get(h);if(p)c=this.renderEmbeddedObject(p,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(h>=t.startIndex&&h<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=ut,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=ut,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=ut,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=ut;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,d=i.y+n;e.fillText(t.text,a,d),e.restore()}renderPageBreakIndicator(t,e,i,n){const s=e.y+i.height+8;if(t.save(),this.showControlCharacters){t.strokeStyle=ft,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(mt).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=ft,t.lineWidth=1,t.strokeRect(r,a,i,o),t.fillStyle=ft,t.textAlign="center",t.textBaseline="middle",t.fillText(mt,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 d=t.field.fieldType;a="pageNumber"===d?void 0!==o?t.field.displayFormat?t.field.displayFormat.replace(/%d/g,String(o)):String(o):"{{page}}":"pageCount"===d?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||l;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,m=f-c,p="pageNumber"===d||"pageCount"===d,x=p?"#d4ebff":"#e8e8e8",b=p?"#87CEEB":"#cccccc";return e.fillStyle=h.backgroundColor||x,e.fillRect(i.x,m,u,g),h.backgroundColor||(e.strokeStyle=b,e.lineWidth=1,e.strokeRect(i.x,m,u,g)),s&&(e.strokeStyle="#0066ff",e.lineWidth=2,e.setLineDash([4,2]),e.strokeRect(i.x-1,m-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,s,o,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=ut,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:gt,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,d=i.y;break;case"relative":{const t=a.relativeOffset;l=o+t.x,d=i.y+t.y;break}default:l=i.x}if(a.renderedPosition={x:l,y:d},a.renderedPageIndex=r,a instanceof q||this._hitTestManager.register(r,{type:"embedded-object",category:"content",bounds:{x:l,y:d,width:a.width,height:a.height},priority:gt,data:{type:"embedded-object",object:a}}),a instanceof A){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 q){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:d},t.renderedPageIndex=r,e.save(),e.translate(l,d),t.renderSlice(e,i,o.pageLayout),e.restore();const n=t.getRowsForSlice(i,o.pageLayout);this.renderTableCellText(t,n,e,r,l,d,i,o.pageLayout);let a=0;for(const t of n)a+=t.calculatedHeight;const h=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:d},a,h,o.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),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-d;if(t.needsPageSplit(i)){const o=n.size.height,a=t.calculatePageLayout(i,o);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(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: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(s)}}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 q||this.drawEmbeddedObjectHandles(e,a,{x:l,y:d}),"inline"===a.position?i.x+a.width+2:i.x}renderTableCellText(t,e,i,n,s,o,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:s+l[e],y:o+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:s+l[e],y:o+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:gt,data:{type:"embedded-object",object:t}})}updateResizeHandleTargets(t){this._hitTestManager.clearCategory("resize-handles"),console.log("[updateResizeHandleTargets] selectedObjects:",t.length);for(const e of t)if(e.resizable)if(e instanceof q)this.registerTableResizeHandles(e);else{const t=e.renderedPosition,i=e.renderedPageIndex;console.log("[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:ht,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:ht,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:ct,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 o=0;o<l.length;o++){if(a+=l[o].calculatedHeight,d){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:ct,data:{type:"table-divider",table:t,dividerType:"row",index:o}})}else{const r=e.yOffset,d=r+s-(h>0?e.headerHeight:0);if(o<h){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:ct,data:{type:"table-divider",table:t,dividerType:"row",index:o}});continue}if(a<r||a>d+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:ct,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 d=o.getRowsForSlice(r,s.pageLayout);this.renderTableCellText(o,d,t,e,a,l,r,s.pageLayout);let h=0;for(const t of d)h+=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},h,c,s.sliceIndex,g,u),this.registerTableSliceHitTarget(o,e,{x:a,y:l},h),o.selected&&this.drawEmbeddedObjectHandles(t,o,{x:a,y:l},{width:o.width,height:h},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],d=i.x,h=n+s;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;s+=g;const u=r.sliceIndex===r.pageLayout.slices.length-1?"last":"middle",f=r.pageLayout.slices[r.sliceIndex].yOffset,m=r.pageLayout.headerHeight;if(a.setRenderedSlice(e,{x:d,y:h},g,u,r.sliceIndex,f,m),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(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=this.getAlignmentOffset(s,i.width),r=s.listMarker?.indent??0;e.fillRect(i.x+o+r+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,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 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,d=a.text[t];let h;const c=n.get(l);if(c){if(h=c.width,e>=o&&e<o+h)return l+1;o+=h,r>0&&/\s/.test(d)&&(o+=r)}else{if(s.has(l)){h=s.get(l).object.width+2}else h=""!==d?"\t"===d?i.measureText(" ").width:i.measureText(d).width:0;if(e>=o&&e<o+h)return e<o+h/2?l:l+1;o+=h,r>0&&/\s/.test(d)&&(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 d=r.text[a];let h;const c=n.get(l);if(c)h=c.width;else if(s.has(l)){h=s.get(l).object.width+2}else h=""!==d?"\t"===d?i.measureText(" ").width:i.measureText(d).width:0;o+=h,"justify"===t.alignment&&t.extraWordSpacing&&/\s/.test(d)&&(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 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 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 d=e.lines[l],h=this.calculateCursorRelativeXForSection(n);return this.getTextIndexAtVisualX(d,h,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 I.getAlignmentOffset(i.line,o)+I.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 I.getAlignmentOffset(i.line,s)+I.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];return{body:t&&this.flowedPages.get(t.id)||[],header:this.headerFlowedPage,footer:this.footerFlowedPage}}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 d=null!==a,h=null!==l,c=t.startIndex<s.startIndex,g=t.endIndex>s.endIndex;i.save(),i.strokeStyle=pt,i.fillStyle=pt,i.lineWidth=1;const u=o.x+5,f=u+16;if(d){const t=a.y;i.setLineDash(xt),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(xt),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(xt),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(xt),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 m,p;if(m=d?a.y:n.y,p=h?l.y:g?n.y+n.height:m,p>m&&(i.beginPath(),i.moveTo(f,m),i.lineTo(f,p),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,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=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()}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 d,h;if(d=e?e.y:s.y,n)h=n.y;else{if(!l)continue;h=s.y+o.height}if(Math.abs(t.x-a)<=10&&t.y>=d&&t.y<=h)return i}return null}destroy(){this.removeAllListeners()}}class wt 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 J,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 tt,this.setupFlowingTextListeners(),this.initializeRegions()}initializeRegions(){const t=new et(this.document.bodyFlowingContent,t=>this.document.pages[t]||null);this.regionManager.setBodyRegion(t);const e=new it(this.document.headerFlowingContent,t=>this.document.pages[t]||null);this.regionManager.setHeaderRegion(e);const i=new nt(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()}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,d=l?.getRepeatingSections()??[];if(d.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(d,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 q||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 q){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;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))>=wt.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)>=wt.CELL_SELECTION_THRESHOLD))return void t.preventDefault();this.tableCellSelectionPending=!1,this.isSelectingTableCells=!0}if(this.isSelectingTableCells&&this.tableCellSelectionStart&&this.tableCellSelectionTable){const e=this.tableCellSelectionTable;if(e.renderedPosition){const t={x:i.x-e.renderedPosition.x,y:i.y-e.renderedPosition.y},n=e.getCellAtPoint(t);n&&(e.selectRange({start:this.tableCellSelectionStart,end:n}),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.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 q){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=this.getFlowingContentForActiveSection();return t&&t.clearSelection(),this.clearSelection(),void this.selectInlineElement(l.data.object)}const d=this.document.bodyFlowingContent;if(d){const t=d.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},d=this.flowingTextRenderer.getRepeatingSectionAtPoint(i,t,n,l,r,s[n]);if(d)return this.clearSelection(),this.selectedSectionId=d.id,this.render(),void this.emit("repeating-section-clicked",{section:d})}}}const h=this.contexts.get(e),c=this.document.pages.findIndex(t=>t.id===e);if(h&&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,h)){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=J.getCursorForHandle(s.handleInfo.type));const o=this.document.pages.findIndex(t=>t.id===e),r=this.flowingTextRenderer.hitTestManager.queryByType(o,t,"embedded-object");if(r&&"embedded-object"===r.data.type){if("relative"===r.data.object.position)return void(i.style.cursor="move")}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){console.log("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&&(console.log("Found embedded object to select:",i.id),i.selected=!0)}console.log("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(){console.log("clearSelection called, current selected elements:",Array.from(this.selectedElements)),this.selectedElements.forEach(t=>{console.log("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&&(console.log("Clearing selection on embedded object:",t),i.selected=!1)}}),this.selectedElements.clear(),this.selectedSectionId=null,console.log("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){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 q&&this._focusedControl===t.element||this.editingTextBox!==t.element&&(this.clearSelection(),this.selectInlineElement(t.element))}),this.flowingTextRenderer.on("substitution-field-clicked",t=>{console.log("[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})}}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 q){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 A&&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 q){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 q){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.setFocus(t),this.document.bodyFlowingContent.clearSelection(),this.clearSelection(),this.selectInlineElement({type:"embedded-object",object:t,textIndex:t.textIndex}),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 q&&this.flowingTextRenderer.updateTableDividerTargets(null),this._focusedControl&&(this._focusedControl.offCursorBlink(this.handleFocusedCursorBlink),this._focusedControl.blur()),this._focusedControl=t,t instanceof q&&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()}}wt.CELL_SELECTION_THRESHOLD=5,wt.RELATIVE_DRAG_THRESHOLD=3;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 Ct(t,e){return e-t}function St(t,e,i,n,s){return{x:t,y:s-e-n,width:i,height:n}}const Ft={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,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 _t(t,e,i,n,s,o,r){const a=St(e,i,n,s,r);t.drawRectangle({x:a.x,y:a.y,width:a.width,height:a.height,color:o})}function It(t,e,i,n,s,o,r,a){t.drawLine({start:{x:e,y:Ct(i,a)},end:{x:n,y:Ct(s,a)},color:o,thickness:r})}class Pt{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(),d={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)}if(i?.body&&i.body[n]&&await this.renderFlowedPage(a,i.body[n],d,r.height,n,t.pages.length),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)}}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=Ft[n];return a?a[r]:Ft.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){let r=i.y;const a=[];for(const l of e.lines){if(l.embeddedObjects)for(const t of l.embeddedObjects)t.isAnchor&&"relative"===t.object.position&&a.push({object:t.object,anchorX:i.x,anchorY:r});const e=this.getAlignmentOffset(l,i.width),d=i.x+e;let h=d;for(const e of l.runs){if(!e.text)continue;const i=this.filterToWinAnsi(e.text);if(!i)continue;const s=e.formatting||{},o=this.getFont(s),a=s.fontSize||14,d=vt(s.color||"#000000");if(s.backgroundColor){const e=vt(s.backgroundColor);_t(t,h,r,o.widthOfTextAtSize(i,a),l.height,e,n)}const c=r+l.baseline;if(t.drawText(i,{x:h,y:Ct(c,n),font:o,size:a,color:d}),h+=o.widthOfTextAtSize(i,a),l.extraWordSpacing&&i.includes(" ")){h+=(i.match(/ /g)||[]).length*l.extraWordSpacing}}for(const e of l.substitutionFields)this.renderSubstitutionField(t,e,d,r,l,n,s,o);for(const e of l.embeddedObjects){if(e.isAnchor)continue;let a=d+e.x;if(e.isBlock)switch(l.alignment){case"center":a=i.x+(i.width-e.object.width)/2;break;case"right":a=i.x+i.width-e.object.width;break;default:a=i.x}await this.renderEmbeddedObject(t,e.object,a,r,n,s,o)}r+=l.height}await this.renderRelativeObjects(t,a,n,s,o)}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 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),m=i+e.x,p=n+s.baseline;t.drawText(h,{x:m,y:Ct(p,o),font:g,size:u,color:f})}async renderEmbeddedObject(t,e,i,n,s,o,r){e instanceof _?await this.renderImage(t,e,i,n,s):e instanceof A?await this.renderTextBox(t,e,i,n,s,o,r):e instanceof q&&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,d=a+e.y;await this.renderEmbeddedObject(t,o,l,d,i,n,s)}}async renderImage(t,i,n,s,o){const r=t.doc,a=i.src;if(a.startsWith("data:"))try{const e=await this.embedImageFromDataUrl(r,a);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){console.warn("Failed to embed image:",t)}const l=St(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 d=0;d<o;d+=l)for(let h=0;h<s;h+=a){const c=Math.min(a,s-h),g=Math.min(l,o-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,s,o,r){if(e.backgroundColor){const o=vt(e.backgroundColor);_t(t,i,n,e.width,e.height,o,s)}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,s),"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,s),"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,s),"none"!==a.left.style&&a.left.width>0&&It(t,i,n,i,n+e.height,vt(a.left.color),a.left.width,s));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,s,o,r)}}}}async renderTable(t,e,i,n,s,o,r){const a=e.getColumnPositions(),l=e.getColumnWidths(),d=e.getRenderedSlice(o);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 s=i;s<i+n.colSpan;s++)t===e&&s===i||g.add(`${t},${s}`)}for(const{row:n,originalIndex:d}of h){for(let u=0;u<n.cells.length;u++){const f=n.cells[u],m=`${d},${u}`;if(g.has(m))continue;if(!f)continue;let p=0;for(let t=u;t<u+f.colSpan;t++)p+=l[t]||0;let x=n.calculatedHeight;if(f.rowSpan>1){x=0;for(let t=d;t<d+f.rowSpan&&t<e.rows.length;t++){h.some(e=>e.originalIndex===t)&&(x+=e.rows[t].calculatedHeight)}}const b=i+a[u];if(f.backgroundColor){_t(t,b,c,p,x,vt(f.backgroundColor),s)}this.renderCellBorders(t,f,b,c,p,x,s);const w=f.flowingContent;if(w){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=w.flowText(p-n,x-a,i);if(l.length>0){const i={x:b+e.left,y:c+e.top,width:p-n,height:x-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&&It(t,i,n,i+s,n,vt(a.top.color),a.top.width,r),"none"!==a.right.style&&a.right.width>0&&It(t,i+s,n,i+s,n+o,vt(a.right.color),a.right.width,r),"none"!==a.bottom.style&&a.bottom.width>0&&It(t,i,n+o,i+s,n+o,vt(a.bottom.color),a.bottom.width,r),"none"!==a.left.style&&a.left.width>0&&It(t,i,n,i,n+o,vt(a.left.color),a.left.width,r)}}class Tt 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 Rt extends o{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 Mt={maxTimeGap:500,maxCharacters:50};function kt(){return`${Date.now()}_${Math.random().toString(36).substr(2,9)}`}class At extends o{constructor(t,e,i,n=100){super(),this.undoStack=[],this.redoStack=[],this.maxHistory=100,this.isPerformingUndoRedo=!1,this.coalesceConfig=Mt,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,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: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 Ot{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 zt{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:kt(),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),d=this.captureObjectsInRange(t,e,n);i.deleteText(e,n,s);const h=this.captureState(t);this.recordMutation(t,{id:kt(),sourceId:this.getSourceId(t),type:"delete",timestamp:Date.now(),beforeState:o,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 s=this.captureState(t);i.insertTextAt(e,n);const o=this.captureState(t);this.recordMutation(t,{id:kt(),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:kt(),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:kt(),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: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 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:kt(),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:kt(),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:kt(),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 Et{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 q&&(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 _&&(a.originalImageProperties=this.wrapImageProperties(t)),t instanceof A&&(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 q&&(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 _){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 A){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 q?"table":t instanceof A?"textbox":t instanceof _?"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 s={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(s)}recordTableStructureMutation(t,e,i,n){this.manager.createBoundary();const s={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(s)}captureTableSnapshot(t){return t.toData()}}class jt{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:console.warn("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:console.warn("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.applyFormatting(i.position+n,i.position+n+1,e)})}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.applyFormatting(i.start+e,i.start+e+1,t)})}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=Y.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=Y.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 q))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 q))return;const i=t.data;"restoreFromData"in e&&"function"==typeof e.restoreFromData&&e.restoreFromData(i.afterSnapshot)}}class Dt{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 A){const e=t.flowingContent,i={type:"textbox",objectId:t.id};this.registerContent(e,i)}t instanceof q&&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 A&&this.unregisterContent(t.flowingContent),t instanceof q&&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 Lt="application/x-pceditor-content";class Bt{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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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 Ht extends o{constructor(){super(),this.cachedClipboardData=null,this.htmlConverter=new Bt}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[Lt]=new Blob([a],{type:Lt}),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(Lt)&&"html"!==e&&"text"!==e){const t=await i.getType(Lt),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),d=this.extractEmbeddedObjects(t,e,i),h=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:d.length>0?d:void 0,hyperlinks:h.length>0?h: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 Wt={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 Ut 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 $t{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 Ut("This PDF is encrypted and requires a password",t.PDFImportErrorCode.PASSWORD_REQUIRED):new Ut("Incorrect password for encrypted PDF",t.PDFImportErrorCode.INCORRECT_PASSWORD);throw new Ut("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 Ut("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],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],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{console.warn(`Failed to extract image: ${t}`)}}}}catch(t){console.warn("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 Vt{constructor(t){this.options={...Wt,...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 d=o[o.length-1],h=r.y-d.y>1.5*a,c=Math.abs(r.minX-d.minX);h||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),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?o++:d<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 Kt{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+=h,"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+=h,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 Gt{constructor(){this.parser=new $t,this.analyzer=new Vt,this.builder=new Kt}async import(e,i={},n){const s={...Wt,...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 Ut)throw e;throw new Ut("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 Ut("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 Ut(`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 Ut)throw e;throw new Ut("Failed to fetch PDF from URL",t.PDFImportErrorCode.INVALID_PDF,e)}}}class Xt 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 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 Yt(t){return Jt[t]}class Zt extends Xt{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=Yt(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,d=Math.ceil(a/e/n)*n+n;for(let s=Math.max(0,l);s<=d;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)}}t.BaseControl=Xt,t.BaseEmbeddedObject=v,t.BaseTextRegion=Q,t.BodyTextRegion=et,t.ClipboardManager=Ht,t.ContentAnalyzer=Vt,t.DEFAULT_IMPORT_OPTIONS=Wt,t.Document=lt,t.DocumentBuilder=Kt,t.EmbeddedObjectFactory=Y,t.EmbeddedObjectManager=b,t.EventEmitter=o,t.FlowingTextContent=Z,t.FooterTextRegion=nt,t.HeaderTextRegion=it,t.HorizontalRuler=class extends Zt{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=Yt("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=Yt(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,d=Math.ceil(a/e/n)*n+n;for(let s=Math.max(0,l);s<=d;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=Bt,t.ImageObject=_,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),this.document=new lt,this.document.updateSettings({pageSize:this.options.pageSize,pageOrientation:this.options.pageOrientation,units:this.options.units}),this.dataBinder=new yt,this.pdfGenerator=new Pt,this.clipboardManager=new Ht,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"}}initialize(){try{this.setupContainer(),this.canvasManager=new wt(this.container,this.document,this.options),this.layoutEngine=new Rt(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.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 Ot(()=>{const t=this._activeEditingSection,e=this.canvasManager?.getFocusedControl();if(e instanceof q&&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 zt(this.transactionManager),this.objectMutationObserver=new Et(this.transactionManager),this.observeAllEmbeddedObjects(),this.mutationUndo=new jt(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 Dt(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){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 Z?"body":this.canvasManager.isEditingTextBox()?"textbox":t instanceof q&&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(!this._isReady)throw new Error("Editor is not ready");this.document.clear(),this.document=new lt(t),this.canvasManager.setDocument(this.document),this._activeEditingSection="body",this.currentSelection={type:"none"},this.clearUndoHistory(),this.layoutEngine.destroy(),this.layoutEngine=new Rt(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(!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(!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(!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"){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(!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(!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 Gt;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 Ut("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&&console.warn(`Document version ${e.version} may not be fully compatible with this editor`)}selectElement(t){if(!this._isReady)throw new Error("Editor is not ready");this.canvasManager.selectElement(t)}clearSelection(){if(!this._isReady)throw new Error("Editor is not ready");this.canvasManager.clearSelection()}removeEmbeddedObject(t){if(!this._isReady)throw new Error("Editor is not ready");this.canvasManager.removeEmbeddedObject(t)}undo(){if(!this._isReady)return;this.transactionManager.undo()&&this.canvasManager.render(),this.emit("undo")}redo(){if(!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(){this._isReady&&this.canvasManager.zoomIn()}zoomOut(){this._isReady&&this.canvasManager.zoomOut()}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(){this._isReady&&this.canvasManager.fitToWidth()}render(){this._isReady&&this.canvasManager.render()}fitToPage(){this._isReady&&this.canvasManager.fitToPage()}setAutoFlow(t){if(!this._isReady)throw new Error("Editor is not ready");this.layoutEngine.setAutoFlow(t)}reflowDocument(){if(!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(!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(!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 q&&e.editing||this.canvasManager.clearSelection()}const e=this.canvasManager.getFocusedControl();if(console.log("[PCEditor.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 q&&e.editing&&(i=e.textIndex,n=e.id)),console.log("[PCEditor.handleKeyDown] Calling focusedControl.handleKeyDown");const o=e.handleKeyDown(t);if(console.log("[PCEditor.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 q&&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 q){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,d=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&&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<o.length){const t=o[h],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 Z||(!!this.canvasManager.isEditingTextBox()||!!(t instanceof q&&t.focusedCell))}getEditingFlowingContent(){const t=this.canvasManager.getFocusedControl();if(t instanceof Z)return t;const e=this.canvasManager.getEditingTextBox();if(e)return e.flowingContent;if(t instanceof q&&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){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){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(!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(!this._isReady)throw new Error("Editor is not ready");const e=this.getActiveFlowingContent();e&&e.setText(t)}setCursorPosition(t){if(!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(!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(!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(!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(!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(!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 A)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 q)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 _)return t}return null}getFocusedTable(){const t=this.canvasManager?.getFocusedControl();return t&&t instanceof q?t: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"){console.warn("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?ot(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 A)i+=this.substituteFieldsInContent(t.flowingContent,e);else if(t instanceof q)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 q&&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,d=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 d){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 d){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.document.bodyFlowingContent.createRepeatingSection(t,e,i);return n&&(this.canvasManager.render(),this.emit("repeating-section-added",{section:n})),n}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 q&&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=Y.tryCreate(t);return e||console.warn("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 _({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}}destroy(){this.disableTextInput(),this.canvasManager&&this.canvasManager.destroy(),this.layoutEngine&&this.layoutEngine.destroy(),this.document.clear(),this.removeAllListeners(),this._isReady=!1}},t.PDFImportError=Ut,t.PDFImporter=Gt,t.PDFParser=$t,t.Page=r,t.RegionManager=tt,t.RepeatingSectionManager=w,t.RulerControl=Zt,t.SubstitutionFieldManager=x,t.TableCell=V,t.TableObject=q,t.TableRow=K,t.TextBoxObject=A,t.TextFormattingManager=u,t.TextLayout=C,t.TextMeasurer=S,t.TextPositionCalculator=I,t.TextState=g,t.VerticalRuler=class extends Zt{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=Yt("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=Yt(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 d=Math.floor(a/e/n)*n-n,h=Math.ceil(l/e/n)*n+n;for(let s=Math.max(0,d);s*e<=this.pageHeightPx&&s<=h;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())}}});
|
|
2
|
+
//# sourceMappingURL=pc-editor.min.js.map
|