@silurus/ooxml 0.82.1 → 0.83.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +74 -5
  2. package/dist/assets/render-worker-4GSYWsM3.js +11 -0
  3. package/dist/assets/{render-worker-Cy-QsDge.js → render-worker-DwFpY197.js} +4 -4
  4. package/dist/{canvas-viewer-mechanics-CS_qbr6T.js → canvas-viewer-mechanics-h07vpVOQ.js} +42 -2
  5. package/dist/{comment-ui-runtime-C1RV_3iu.js → comment-ui-runtime-BelHJt73.js} +2 -2
  6. package/dist/{comment-ui-runtime-DgCZpPR0.js → comment-ui-runtime-DD5a3x3k.js} +2 -2
  7. package/dist/{comments-Cf9W7r3M.js → comments-AAaNnQTi.js} +7 -2
  8. package/dist/{document-pull-client-B1WOjA0z.js → document-pull-client-DSx36ZsB.js} +4519 -3952
  9. package/dist/docx-BF-WKW73.js +2784 -0
  10. package/dist/docx.mjs +6 -6
  11. package/dist/docx_parser_bg.wasm +0 -0
  12. package/dist/dom-interaction-boundary-CepOlXt6.js +217 -0
  13. package/dist/index.mjs +4 -4
  14. package/dist/line-distribute-D7A_wnJg.js +1003 -0
  15. package/dist/{line-metrics-B3syvDn2.js → line-metrics-Bpn7OeZD.js} +616 -616
  16. package/dist/node.mjs +308 -308
  17. package/dist/pptx-CA-Q09yW.js +3010 -0
  18. package/dist/pptx.mjs +5 -5
  19. package/dist/pptx_parser_bg.wasm +0 -0
  20. package/dist/{render-BC8p7vZQ.js → render-DtbFbO5c.js} +1 -1
  21. package/dist/{render-worker-host-BNnXCtAu.js → render-worker-host-D1jcACJV.js} +1 -1
  22. package/dist/{render-worker-host-DhnkTyjj.js → render-worker-host-DCLyw6UR.js} +1 -1
  23. package/dist/{resource-measurement-CsW4_eYt.js → resource-measurement-DuiFWzam.js} +3 -3
  24. package/dist/{session-Da7LEQUB.js → session-CxT-t0BX.js} +107 -94
  25. package/dist/{slide-pull-client-Bg9DusLX.js → slide-pull-client-B9rcJdO4.js} +1190 -937
  26. package/dist/types/docx.d.ts +103 -8
  27. package/dist/types/index.d.ts +195 -13
  28. package/dist/types/node.d.ts +2 -2
  29. package/dist/types/pptx.d.ts +100 -5
  30. package/dist/types/xlsx.d.ts +2 -2
  31. package/dist/{worksheet-pull-client-CYtwXP5D.js → worksheet-pull-client-DyFsDF4A.js} +32 -32
  32. package/dist/{xlsx-DMWeXT-c.js → xlsx-BibrHQ52.js} +476 -476
  33. package/dist/xlsx.mjs +5 -5
  34. package/dist/xlsx_parser_bg.wasm +0 -0
  35. package/package.json +3 -1
  36. package/dist/assets/render-worker-aHayzR7v.js +0 -11
  37. package/dist/docx-HoZXZUPA.js +0 -2162
  38. package/dist/dom-interaction-boundary-C8F6HO5x.js +0 -119
  39. package/dist/line-distribute-iXsUCIH-.js +0 -1003
  40. package/dist/pptx-DEUP4Yq5.js +0 -2432
  41. /package/dist/{comment-occurrence-C34fWs_F.js → comment-occurrence-X54si2ob.js} +0 -0
  42. /package/dist/{highlight-rect-MaCt0om0.js → highlight-rect-Hes0z_Mj.js} +0 -0
@@ -1,2162 +0,0 @@
1
- import { t as e } from "./chunk-DmhlhrBa.js";
2
- import { B as t, Ct as n, Et as r, Jt as i, R as a, Yt as o, a as s, it as c, mt as l, q as u, z as d } from "./line-metrics-B3syvDn2.js";
3
- import { C as f, E as p, S as m, T as h, _ as g, a as _, b as ee, c as v, d as y, f as te, g as ne, h as re, i as b, l as x, m as ie, n as ae, o as oe, p as se, r as ce, s as le, t as ue, u as de, v as fe, w as pe, x as me, y as S } from "./canvas-viewer-mechanics-CS_qbr6T.js";
4
- import { a as he, c as ge, i as _e, o as ve, r as ye, s as be, t as xe } from "./bounded-raw-part-cache-C6ro6Ezf.js";
5
- import { C, E as Se, S as w, T as Ce, _ as T, a as we, b as Te, c as Ee, d as De, f as Oe, g as ke, h as Ae, l as je, m as Me, n as Ne, o as Pe, p as Fe, s as Ie, t as Le, v as Re, w as ze, x as Be, y as E } from "./document-pull-client-B1WOjA0z.js";
6
- import { cn as Ve, ln as He } from "./plot-area-frame-DHV02PJU.js";
7
- import { a as D } from "./units-BzZ0gAxs.js";
8
- import { n as Ue } from "./renderer-module-contract-DLbb7zY0.js";
9
- import { a as We, i as O, n as Ge, t as Ke } from "./dom-interaction-boundary-C8F6HO5x.js";
10
- import { n as qe, t as k } from "./highlight-rect-MaCt0om0.js";
11
- import { o as A } from "./source-key-BklvnEyQ.js";
12
- import { i as Je, n as j, r as M, t as Ye } from "./comments-Cf9W7r3M.js";
13
- //#region packages/core/src/fonts/embedded.ts
14
- function Xe(e, t) {
15
- let n = Ze(t), r = e.slice(), i = Math.min(32, r.length);
16
- for (let e = 0; e < i; e++) r[e] ^= n[e % 16];
17
- return r;
18
- }
19
- function Ze(e) {
20
- let t = e.replace(/[{}\-\s]/g, "");
21
- if (t.length !== 32 || /[^0-9a-fA-F]/.test(t)) throw Error(`invalid fontKey GUID: ${e}`);
22
- let n = new Uint8Array(16);
23
- for (let e = 0; e < 16; e++) n[e] = parseInt(t.slice(e * 2, e * 2 + 2), 16);
24
- return n.reverse();
25
- }
26
- function Qe(e, t, n, r) {
27
- let i = 2166136261;
28
- for (let e = 0; e < r.length; e++) i ^= r[e], i = Math.imul(i, 16777619);
29
- return `${e}|${t}|${n}|${r.length}|${(i >>> 0).toString(16)}`;
30
- }
31
- async function $e(e, t = 30 * 1024 * 1024) {
32
- let n = ye();
33
- if (!n || typeof FontFace > "u") return [];
34
- let r = [], i = [], a = [];
35
- for (let o of e) try {
36
- if (o.bytes.length === 0 || o.bytes.length > t) {
37
- a.push(o.family);
38
- continue;
39
- }
40
- let e = o.odttf ? Xe(o.bytes, o.fontKey ?? "") : o.bytes, { face: s, isNew: c } = ge(`embedded:${Qe(o.family, o.weight, o.style, e)}`, n, () => {
41
- let t = e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength), r = new FontFace(o.family, t, {
42
- weight: o.weight,
43
- style: o.style
44
- });
45
- return n.add(r), r;
46
- });
47
- r.push(s), c && i.push(s);
48
- } catch {
49
- a.push(o.family);
50
- }
51
- return i.length > 0 && await ve(Promise.allSettled(i.map((e) => e.load())).then((e) => (e.forEach((e, t) => {
52
- e.status === "rejected" && a.push(i[t].family);
53
- }), n.ready))), a.length > 0 && console.warn(`[ooxml] failed to register embedded font(s): ${[...new Set(a)].join(", ")}; falling back to substitute fonts (text may shift or differ).`), r;
54
- }
55
- function et(e) {
56
- be(e);
57
- }
58
- //#endregion
59
- //#region packages/docx/src/worker.ts?worker&inline
60
- var N = "var e=(e,t)=>()=>(e&&(t=e(e=0)),t),t=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,r.unregister(this),e}free(){let e=this.__destroy_into_raw();_.__wbg_docxarchive_free(e,0)}acknowledge_document_chunk(e,t,n){let r=_.docxarchive_acknowledge_document_chunk(this.__wbg_ptr,e,t,n);if(r[1])throw f(r[0])}assert_healthy(){let e=_.docxarchive_assert_healthy(this.__wbg_ptr);if(e[1])throw f(e[0])}cancel_document_cursor(){_.docxarchive_cancel_document_cursor(this.__wbg_ptr)}close_document_session(){_.docxarchive_close_document_session(this.__wbg_ptr)}document_chunk_done(){let e=_.docxarchive_document_chunk_done(this.__wbg_ptr);if(e[2])throw f(e[1]);return e[0]!==0}document_cursor_resource_usage(){let e=_.docxarchive_document_cursor_resource_usage(this.__wbg_ptr);if(e[3])throw f(e[2]);var t=i(e[0],e[1]).slice();return _.__wbindgen_free(e[0],e[1]*1,1),t}extract_image(e){let t=d(e,_.__wbindgen_malloc,_.__wbindgen_realloc),n=g,r=_.docxarchive_extract_image(this.__wbg_ptr,t,n);if(r[3])throw f(r[2]);var a=i(r[0],r[1]).slice();return _.__wbindgen_free(r[0],r[1]*1,1),a}constructor(e,t,n,i){let a=ee(e,_.__wbindgen_malloc),o=g,s=_.docxarchive_new(a,o,!u(t),u(t)?BigInt(0):t,!u(n),u(n)?BigInt(0):n,!u(i),u(i)?BigInt(0):i);if(s[2])throw f(s[1]);return this.__wbg_ptr=s[0]>>>0,r.register(this,this.__wbg_ptr,this),this}open_document_cursor(e,t){let n=_.docxarchive_open_document_cursor(this.__wbg_ptr,e,t);if(n[1])throw f(n[0])}parse(){let e=_.docxarchive_parse(this.__wbg_ptr);if(e[3])throw f(e[2]);var t=i(e[0],e[1]).slice();return _.__wbindgen_free(e[0],e[1]*1,1),t}pull_document_chunk(e,t,n,r){let a=_.docxarchive_pull_document_chunk(this.__wbg_ptr,e,t,n,r);if(a[3])throw f(a[2]);var o=i(a[0],a[1]).slice();return _.__wbindgen_free(a[0],a[1]*1,1),o}resource_usage(){let e=_.docxarchive_resource_usage(this.__wbg_ptr);if(e[3])throw f(e[2]);var t=i(e[0],e[1]).slice();return _.__wbindgen_free(e[0],e[1]*1,1),t}to_markdown(){let e,t;try{let i=_.docxarchive_to_markdown(this.__wbg_ptr);var n=i[0],r=i[1];if(i[3])throw n=0,r=0,f(i[2]);return e=n,t=r,s(n,r)}finally{_.__wbindgen_free(e,t,1)}}};Symbol.dispose&&(t.prototype[Symbol.dispose]=t.prototype.free);function n(){return{__proto__:null,\"./docx_parser_bg.js\":{__proto__:null,__wbg___wbindgen_throw_6b64449b9b9ed33c:function(e,t){throw Error(s(e,t))},__wbg_error_a6fa202b58aa1cd3:function(e,t){let n,r;try{n=e,r=t,console.error(s(e,t))}finally{_.__wbindgen_free(n,r,1)}},__wbg_new_227d7c05414eb861:function(){return Error()},__wbg_stack_3b0d974bbf31e44f:function(e,t){let n=t.stack,r=d(n,_.__wbindgen_malloc,_.__wbindgen_realloc),i=g;o().setInt32(e+4,i,!0),o().setInt32(e+0,r,!0)},__wbindgen_cast_0000000000000001:function(e,t){return s(e,t)},__wbindgen_init_externref_table:function(){let e=_.__wbindgen_externrefs,t=e.grow(4);e.set(0,void 0),e.set(t+0,void 0),e.set(t+1,null),e.set(t+2,!0),e.set(t+3,!1)}}}}const r=typeof FinalizationRegistry>`u`?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>_.__wbg_docxarchive_free(e>>>0,1));function i(e,t){return e>>>=0,l().subarray(e/1,e/1+t)}let a=null;function o(){return(a===null||a.buffer.detached===!0||a.buffer.detached===void 0&&a.buffer!==_.memory.buffer)&&(a=new DataView(_.memory.buffer)),a}function s(e,t){return e>>>=0,te(e,t)}let c=null;function l(){return(c===null||c.byteLength===0)&&(c=new Uint8Array(_.memory.buffer)),c}function u(e){return e==null}function ee(e,t){let n=t(e.length*1,1)>>>0;return l().set(e,n/1),g=e.length,n}function d(e,t,n){if(n===void 0){let n=h.encode(e),r=t(n.length,1)>>>0;return l().subarray(r,r+n.length).set(n),g=n.length,r}let r=e.length,i=t(r,1)>>>0,a=l(),o=0;for(;o<r;o++){let t=e.charCodeAt(o);if(t>127)break;a[i+o]=t}if(o!==r){o!==0&&(e=e.slice(o)),i=n(i,r,r=o+e.length*3,1)>>>0;let t=l().subarray(i+o,i+r),a=h.encodeInto(e,t);o+=a.written,i=n(i,r,o,1)>>>0}return g=o,i}function f(e){let t=_.__wbindgen_externrefs.get(e);return _.__externref_table_dealloc(e),t}let p=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0});p.decode();let m=0;function te(e,t){return m+=t,m>=2146435072&&(p=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}),p.decode(),m=t),p.decode(l().subarray(e,e+t))}const h=new TextEncoder;`encodeInto`in h||(h.encodeInto=function(e,t){let n=h.encode(e);return t.set(n),{read:e.length,written:n.length}});let g=0,_;function v(e,t){return _=e.exports,a=null,c=null,_.__wbindgen_start(),_}async function y(e,t){if(typeof Response==`function`&&e instanceof Response){if(typeof WebAssembly.instantiateStreaming==`function`)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if(e.ok&&n(e.type)&&e.headers.get(`Content-Type`)!==`application/wasm`)console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\",t);else throw t}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}else{let n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}function n(e){switch(e){case`basic`:case`cors`:case`default`:return!0}return!1}}async function b(e){if(_!==void 0)return _;e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn(`using deprecated parameters for the initialization function; pass a single object instead`));let t=n();(typeof e==`string`||typeof Request==`function`&&e instanceof Request||typeof URL==`function`&&e instanceof URL)&&(e=fetch(e));let{instance:r,module:i}=await y(await e,t);return v(r,i)}async function ne(e){return _=void 0,a=null,c=null,b(e)}var x=class e extends Error{code;constructor(t,n){super(n),this.name=`OoxmlError`,this.code=t,Object.setPrototypeOf(this,e.prototype)}},S=class e extends Error{code=`ooxml-resource-limit`;details;constructor(t,n){super(t),this.name=`OoxmlResourceLimitError`;let r=n.violation,i=Object.freeze({format:r.format,operation:r.operation,resource:r.resource,metric:r.metric,...r.part===void 0?{}:{part:r.part},limit:r.limit,observed:r.observed,configurable:r.configurable,usage:Object.freeze({archiveEntryCount:r.usage.archiveEntryCount,declaredInflatedBytes:r.usage.declaredInflatedBytes,...r.usage.largestInflatedEntryBytes===void 0?{}:{largestInflatedEntryBytes:r.usage.largestInflatedEntryBytes},distinctInflatedBytes:r.usage.distinctInflatedBytes,operationInflatedBytes:r.usage.operationInflatedBytes})});this.details=Object.freeze({stage:n.stage,violation:i}),Object.setPrototypeOf(this,e.prototype)}},C,w,re=e((()=>{C=1<<25,C*4,w=class e extends RangeError{code=`ooxml-decoded-image-limit`;constructor(t,n,r){super(`OOXML decoded image limit exceeded: ${t} ${r} > ${n}`),this.metric=t,this.limit=n,this.observed=r,this.name=`OoxmlDecodedImageLimitError`,Object.setPrototypeOf(this,e.prototype)}}}));function ie(e){if(!e.startsWith(`data:`))return null;let t=e.indexOf(`,`);if(t===-1)return null;let n=atob(e.slice(t+1)),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r.buffer}var ae=class{state=`uninitialized`;generationValue=0;readiness;poisonListeners=new Set;constructor(e,t,n){this.initialize=e,this.reinitialize=t,this.normalizeFailure=n}get generation(){return this.generationValue}get poisoned(){return this.state===`poisoned`}onPoison(e){return this.poisonListeners.add(e),()=>this.poisonListeners.delete(e)}async ensureReady(){if(this.state!==`ready`){if(!this.readiness){let e=this.state===`uninitialized`?this.initialize:this.reinitialize;this.readiness=Promise.resolve().then(e).then(()=>{this.generationValue+=1,this.state=`ready`,this.readiness=void 0},e=>{throw this.readiness=void 0,e})}await this.readiness}}run(e){try{return e()}catch(e){let t=this.normalizeFailure(e);throw t?(this.poison(t),t):e}}tryRunReady(e){if(this.state!==`ready`)return{current:!1};let t=this.generationValue,n=this.run(e);return this.state!==`ready`||t!==this.generationValue?{current:!1}:{current:!0,generation:t,value:n}}poison(e){this.state=`poisoned`,this.readiness=void 0;for(let t of this.poisonListeners)t(e)}assertCurrent(e){if(this.state!==`ready`||e!==this.generationValue)throw Error(`WASM archive session belongs to a discarded runtime generation`)}},T=class e extends Error{code=`parser-crashed`;constructor(t){super(t),this.name=`WasmTrapError`,Object.setPrototypeOf(this,e.prototype)}};function E(e){let t=globalThis.WebAssembly?.RuntimeError;return t&&e instanceof t||e instanceof RangeError?!0:e instanceof Error?e.name===`RuntimeError`||e.name===`CompileError`||e.name===`LinkError`||e.name===`InternalError`||e.name===`OOMError`:!1}function oe(e){try{if((typeof e!=`object`||!e)&&typeof e!=`function`)return;let t=Reflect.get(e,`__destroy_into_raw`);typeof t==`function`&&Reflect.apply(t,e,[])}catch{}}function se(e,t){return e({module_or_path:t})}var ce=class{runtime;wasmInput=null;currentArchive=null;constructor(e,t={}){this.init=e,this.options=t,this.runtime=new ae(()=>this.invokeConfigured(this.init),()=>this.invokeConfigured(this.options.reinit??this.init),le),this.runtime.onPoison(()=>this.dropPoisonedArchive())}setWasmInput(e){this.wasmInput=e,this.runtime.ensureReady().catch(()=>void 0)}setWasmUrl(e){this.setWasmInput(e)}get archive(){return this.currentArchive}setArchive(e){this.freeArchive(),this.currentArchive=e}disposeArchive(){this.freeArchive()}get poisoned(){return this.runtime.poisoned}async ensureReady(){await this.runtime.ensureReady()}run(e){return this.runtime.run(e)}poison(){this.runtime.poison(new T(`WASM parser was recycled`))}invokeConfigured(e){return this.wasmInput===null?Promise.reject(Error(`WasmParserHost: setWasmInput was never called`)):se(e,this.wasmInput)}freeArchive(){this.currentArchive!==null&&this.options.freeArchive&&this.options.freeArchive(this.currentArchive),this.currentArchive=null}dropPoisonedArchive(){let e=this.currentArchive;this.currentArchive=null,oe(e)}};function le(e){return E(e)?new T(`WASM parser trapped and was recycled: ${e instanceof Error?e.message:String(e)}`):null}function D(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function O(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return D(t.requiredBytes)&&D(t.offeredBytes)&&t.requiredBytes>t.offeredBytes}var k=class e extends RangeError{code=`ooxml-insufficient-credit`;requiredBytes;offeredBytes;constructor(t){super(`Pull unit requires ${t.requiredBytes} bytes but credit is ${t.offeredBytes}`),this.name=`PullSessionInsufficientCreditError`,this.requiredBytes=t.requiredBytes,this.offeredBytes=t.offeredBytes,Object.setPrototypeOf(this,e.prototype)}};function A(e){if(e instanceof k)return e;let t=e instanceof Error?e.message:String(e);if(!t.startsWith(`OOXML_INSUFFICIENT_CREDIT:`))return;let n;try{n=JSON.parse(t.slice(26))}catch{return}if(!n||typeof n!=`object`||Array.isArray(n))return;let r=n;if(!(r.code!==`ooxml-insufficient-credit`||!O(r)))return new k(r)}function ue(e,t,n){let r=A(e);if(!(!r||r.offeredBytes!==t||r.requiredBytes>n))return r}re();const j=`OOXML_RESOURCE_LIMIT:`;function M(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function N(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return M(t.archiveEntryCount)&&M(t.declaredInflatedBytes)&&(t.largestInflatedEntryBytes===void 0||M(t.largestInflatedEntryBytes))&&M(t.distinctInflatedBytes)&&M(t.operationInflatedBytes)}function P(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw TypeError(`OOXML resource usage checkpoint is not valid JSON`)}if(!N(t))throw TypeError(`OOXML resource usage checkpoint is invalid`);return t}function F(e){return e===`docx`||e===`xlsx`||e===`pptx`}function I(e){return e===`container`||e===`decompression`||e===`parsing`||e===`serialization`||e===`layout`||e===`rendering`||e===`worker`}function L(e,t){return typeof e==`string`&&e.length>0&&e.length<=t&&!/[\\u0000-\\u001f\\u007f]/u.test(e)}function R(e){return L(e,128)&&/^[a-z0-9][a-z0-9-]*$/u.test(e)}function z(e){return!L(e,4096)||e.startsWith(`/`)||e.startsWith(`\\\\`)||e.includes(`\\\\`)||e.includes(`?`)||e.includes(`#`)||e.includes(`://`)||/^[a-z]:/iu.test(e)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}const B=new Map([[`archive-entry:declared-inflated-bytes`,{stage:`container`,part:`required`}],[`archive-entry:actual-inflated-bytes`,{stage:`decompression`,part:`required`}],[`archive:entry-count`,{stage:`container`,part:`forbidden`}],[`archive:central-directory-bytes`,{stage:`container`,part:`forbidden`,configurable:!1}],[`archive:distinct-inflated-bytes`,{stage:`decompression`,part:`required`}],[`xml-event:bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`xml-context:bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`xml-tree:depth`,{stage:`parsing`,part:`optional`,configurable:!1}],[`worksheet-row:projected-bytes`,{stage:`parsing`,part:`optional`,configurable:!1}],[`worksheet-shell:projected-bytes`,{stage:`parsing`,part:`optional`,configurable:!1}]]),V=new Set([...B.keys()].map(e=>e.slice(0,e.indexOf(`:`)))),H=new Set([...B.keys()].map(e=>e.slice(e.indexOf(`:`)+1)));function de(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return!F(t.format)||!L(t.operation,256)||!R(t.resource)||!R(t.metric)||!M(t.limit)||!M(t.observed)||typeof t.configurable!=`boolean`||!N(t.usage)?!1:!(`part`in t)||z(t.part)}function U(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;if(!I(t.stage)||!de(t.violation))return!1;let n=t.violation,r=B.get(`${n.resource}:${n.metric}`);return r?t.stage!==r.stage||r.configurable===!1&&n.configurable!==!1?!1:r.part===`required`?n.part!==void 0:r.part===`forbidden`?n.part===void 0:!0:!(V.has(n.resource)&&H.has(n.metric))}function fe(e){return{archiveEntryCount:e.archiveEntryCount,declaredInflatedBytes:e.declaredInflatedBytes,...e.largestInflatedEntryBytes===void 0?{}:{largestInflatedEntryBytes:e.largestInflatedEntryBytes},distinctInflatedBytes:e.distinctInflatedBytes,operationInflatedBytes:e.operationInflatedBytes}}function pe(e){if(!U(e))return;let t=e.violation,n={stage:e.stage,violation:{format:t.format,operation:t.operation,resource:t.resource,metric:t.metric,...t.part===void 0?{}:{part:t.part},limit:t.limit,observed:t.observed,configurable:t.configurable,usage:fe(t.usage)}};return U(n)?n:void 0}function W(e){let t=e.violation;return`OOXML resource limit exceeded${t.part?` for ${t.part}`:``}: ${t.metric} ${t.observed} > ${t.limit}`}function me(e){let t=e instanceof Error?e.message:String(e);if(!t.startsWith(j))return;let n;try{n=JSON.parse(t.slice(21))}catch{return}if(!n||typeof n!=`object`)return;let r=n;if(!(r.code!==`ooxml-resource-limit`||!U(r.details)))return new S(W(r.details),r.details)}function he(e){if(e instanceof w)return{message:e.message,errorName:e.name,code:e.code,decodedImage:{metric:e.metric,limit:e.limit,observed:e.observed}};let t=A(e);if(t)return{message:t.message,errorName:t.name,code:t.code,insufficientCredit:{requiredBytes:t.requiredBytes,offeredBytes:t.offeredBytes}};let n=e instanceof x||e instanceof S?e:me(e);if(n instanceof S){let e=pe(n.details);return e?{message:typeof n.message==`string`?n.message:W(e),errorName:`OoxmlResourceLimitError`,code:`ooxml-resource-limit`,resourceLimit:e}:{message:`Invalid OOXML resource-limit error payload`,errorName:`Error`}}if(n instanceof x)return{message:typeof n.message==`string`?n.message:String(n.message),errorName:L(n.name,128)?n.name:`OoxmlError`,...R(n.code)?{code:n.code}:{}};let r=e instanceof Error?e.message:String(e);if(typeof r==`string`&&r.startsWith(j))return{message:`Invalid OOXML resource-limit payload`,errorName:`Error`};let i=e instanceof Error?e:Error(r),a=i;return{message:typeof i.message==`string`?i.message:String(i.message),errorName:L(i.name,128)?i.name:`Error`,...typeof a.code==`string`?{code:a.code}:{}}}function G(e){try{return he(e)}catch{return{message:`Worker operation failed with an unreadable error`,errorName:`Error`}}}function ge(e){return e.byteOffset===0&&e.byteLength===e.buffer.byteLength&&e.buffer instanceof ArrayBuffer?e.buffer:e.slice().buffer}Object.freeze({maxArchiveEntryBytes:134217728,maxTotalInflatedBytes:268435456,maxArchiveEntries:4096});function _e(e){return[e.maxArchiveEntryBytes===null?0n:BigInt(e.maxArchiveEntryBytes),e.maxTotalInflatedBytes===null?0n:BigInt(e.maxTotalInflatedBytes),e.maxArchiveEntries===null?0n:BigInt(e.maxArchiveEntries)]}const K=`ooxml-pull-v1`;function q(e,t){if(!Number.isSafeInteger(e)||e<=0)throw RangeError(`${t} must be a positive safe integer`)}function ve(e){if(!(typeof e==`string`&&e.length>0||typeof e==`number`&&Number.isSafeInteger(e)&&e>0))throw RangeError(`session id must be a non-empty string or positive safe integer`)}var J=class{owner;queue=Promise.resolve();leases=new Map;retainedBytes=0;retainedCount=0;maxRetainedBytes;maxRetainedCount;cleanups=new Set;pendingFatalCleanups=[];poisonRunning=!1;fatal;constructor(e){this.maxRetainedBytes=e?.maxRetainedBytes??64*1024*1024,this.maxRetainedCount=e?.maxRetainedCount??256,q(this.maxRetainedBytes,`max retained lease bytes`),q(this.maxRetainedCount,`max retained lease count`)}enqueue(e){let t=this.queue.then(e,e);return this.queue=t.then(()=>void 0,()=>void 0),t}acquire(e){return this.owner===void 0?(this.owner=e,!0):this.owner===e}release(e){this.owner===e&&(this.owner=void 0)}retainLease(e,t,n){if(!Number.isSafeInteger(n)||n<0)throw RangeError(`retained lease bytes are invalid`);let r=this.leases.get(e)??new Map;if(r.has(t))throw Error(`driver returned a duplicate lease id`);if(this.retainedCount+1>this.maxRetainedCount)throw RangeError(`retained lease count exceeds limit`);if(this.retainedBytes+n>this.maxRetainedBytes)throw RangeError(`retained lease bytes exceed limit`);r.set(t,n),this.leases.set(e,r),this.retainedCount++,this.retainedBytes+=n}releaseLease(e,t){let n=this.leases.get(e),r=n?.get(t);r!==void 0&&(n?.delete(t),n?.size===0&&this.leases.delete(e),this.retainedCount--,this.retainedBytes-=r)}registerCleanup(e){return this.fatal?(this.poisonRunning?this.pendingFatalCleanups.push(e):this.enqueue(e).catch(()=>void 0),()=>void 0):(this.cleanups.add(e),()=>this.cleanups.delete(e))}get fatalError(){return this.fatal}get registeredHostCount(){return this.cleanups.size}async poison(e){if(this.fatal??=e,this.poisonRunning)return this.fatal;this.poisonRunning=!0,this.pendingFatalCleanups.push(...this.cleanups);try{let e;for(;(e=this.pendingFatalCleanups.shift())!==void 0;)await e().catch(()=>void 0)}finally{this.poisonRunning=!1}return this.fatal}},ye=class{options;coordinator;coordinatorOwner=Symbol(`pull-session-host`);unregisterCleanup;sequence=0;unacked;leases=new Map;activeDriverLeases=new Set;nextWireLeaseId;cancelRequested=!1;cancelComplete=!1;closeRequested=!1;closeComplete=!1;driverCancelComplete=!1;driverCloseComplete=!1;completed=!1;constructor(e){ve(e.sessionId),q(e.operationId,`operation id`),q(e.generation,`generation`),q(e.maxByteCredit,`max byte credit`),e.wireLeaseIdStart!==void 0&&q(e.wireLeaseIdStart,`wire lease id start`),this.options=e,this.coordinator=e.coordinator,this.nextWireLeaseId=e.wireLeaseIdStart??1,this.unregisterCleanup=this.coordinator.registerCleanup(()=>this.forceFatalCleanup())}dispatch(e,t){return this.coordinator.enqueue(async()=>{let n=await this.execute(e);try{t(n.response,n.transfer)}catch(e){throw await this.rollbackFailedPost(n),e}})}async rollbackFailedPost(e){let t=e.response;if(t.kind===`chunk`){let n=t.leaseId===void 0?void 0:this.leases.get(t.leaseId);try{await this.options.driver.disposeInvalidChunk?.({payload:t.payload,byteLength:t.byteLength,done:t.done,leaseId:n?.driverLeaseId,retainedBytes:n?.retainedBytes,transfer:e.transfer})}catch{}}this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);for(let[e,t]of[...this.leases])try{await this.options.driver.releaseLease?.(t.driverLeaseId)}catch{}finally{this.leases.delete(e),this.activeDriverLeases.delete(t.driverLeaseId),this.coordinator.releaseLease(this.coordinatorOwner,e)}if(this.cancelRequested=!0,!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch{}this.unregisterCleanup()}async execute(e){try{if(this.isStaleLifecycle(e)){let t=e.kind===`cancel`?`cancel`:`close`;return this.sameOperationIdentity(e)?{response:this.accepted(e,t,!0)}:{response:this.errorResponse(e,{message:`stale lifecycle targets another session or operation`,errorName:`PullSessionProtocolError`,code:`ooxml-stale-lifecycle`})}}this.validateCommandIdentity(e);let t=this.coordinator.fatalError;if(t)return e.kind===`pull`?{response:this.errorResponse(e,t)}:(e.kind===`cancel`?await this.cancel():e.kind===`close`?await this.close():e.kind===`release`&&await this.release(e.leaseId),{response:this.accepted(e,e.kind)});switch(e.kind){case`pull`:return await this.pull(e);case`ack`:return await this.ack(e.sequence),{response:this.accepted(e,`ack`)};case`release`:return await this.release(e.leaseId),{response:this.accepted(e,`release`)};case`cancel`:return await this.cancel(),{response:this.accepted(e,`cancel`)};case`close`:return await this.close(),{response:this.accepted(e,`close`)}}}catch(t){let n=G(t);return n.code===`ooxml-resource-limit`&&(n=await this.coordinator.poison(n)),{response:this.errorResponse(e,n)}}}async pull(e){if(this.closeRequested||this.cancelRequested||this.completed)throw Error(`pull session is closed`);if(this.unacked)throw Error(`previous chunk is not acknowledged`);if(!Number.isSafeInteger(e.sequence)||e.sequence<0||e.sequence!==this.sequence)throw Error(`pull command sequence mismatch`);if(this.validateHostCredit(e.byteCredit),!this.coordinator.acquire(this.coordinatorOwner))throw Error(`another operation has an unacknowledged package chunk`);let t;try{t=await this.options.driver.pull(e.byteCredit)}catch(e){throw this.coordinator.release(this.coordinatorOwner),e}let n=!1,r=!1,i,a;try{let o=this.options.driver.measureChunk(t),s=this.arrayBufferTransferBytes(t.transfer);if(o<s)throw RangeError(`measured chunk bytes are below ArrayBuffer transfer bytes`);if(a=Math.max(o,s),t.leaseId!==void 0){if(q(t.leaseId,`lease id`),t.retainedBytes===void 0)throw Error(`retained lease bytes are required`);if(this.activeDriverLeases.has(t.leaseId))throw r=!0,Error(`driver returned an active duplicate lease id`);i=this.allocateWireLeaseId(),this.coordinator.retainLease(this.coordinatorOwner,i,t.retainedBytes),this.leases.set(i,{driverLeaseId:t.leaseId,retainedBytes:t.retainedBytes}),this.activeDriverLeases.add(t.leaseId),n=!0}else if(t.retainedBytes!==void 0)throw Error(`retained lease bytes require a lease id`);if(!Number.isSafeInteger(a)||a<0)throw RangeError(`host chunk byte length must be a non-negative safe integer`);if(a>e.byteCredit)throw RangeError(`host chunk exceeds byte credit`)}catch(e){let a;try{await this.options.driver.disposeInvalidChunk?.(t)}catch(e){a=e}if(n&&i!==void 0)try{await this.release(i)}catch(e){a??=e}else if(t.leaseId!==void 0&&!r)try{await this.options.driver.releaseLease?.(t.leaseId)}catch(e){a??=e}if(r)try{await this.cancel()}catch(e){a??=e}throw this.coordinator.release(this.coordinatorOwner),a||e}return this.unacked={sequence:this.sequence,done:t.done},{response:{kind:`chunk`,protocol:K,...this.identity(),requestId:e.requestId,sequence:this.sequence,byteLength:a,done:t.done,payload:t.payload,leaseId:i,usage:this.resourceUsage()},transfer:t.transfer}}async ack(e){if(!Number.isSafeInteger(e)||e<0)throw RangeError(`invalid ack sequence`);if(e<this.sequence)return;if(!this.unacked||e!==this.sequence)throw Error(`ack sequence mismatch`);let t=this.unacked.done;await this.options.driver.acknowledge?.(e),this.unacked=void 0,this.coordinator.release(this.coordinatorOwner),this.sequence++,t&&(this.completed=!0,this.maybeUnregisterCompleted())}async release(e){q(e,`wire lease id`);let t=this.leases.get(e);t&&(await this.options.driver.releaseLease?.(t.driverLeaseId),this.leases.delete(e),this.activeDriverLeases.delete(t.driverLeaseId),this.coordinator.releaseLease(this.coordinatorOwner,e),this.maybeUnregisterCompleted())}async cancel(){if(this.cancelComplete)return;this.cancelRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;try{await this.releaseAllLeases()}catch(t){e=t}if(!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch(t){e??=t}if(e)throw e;this.cancelComplete=!0,this.unregisterCleanup()}async close(){if(this.closeComplete)return;this.closeRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;try{await this.releaseAllLeases()}catch(t){e=t}if(!this.driverCloseComplete)try{await this.options.driver.close?.(),this.driverCloseComplete=!0}catch(t){e??=t}if(e)throw e;this.closeComplete=!0,this.unregisterCleanup()}async releaseAllLeases(){let e;for(let t of[...this.leases.keys()])try{await this.release(t)}catch(t){e??=t}if(e)throw e}validateCommandIdentity(e){if(e.protocol!==`ooxml-pull-v1`||e.sessionId!==this.options.sessionId||e.operationId!==this.options.operationId||e.generation!==this.options.generation||!Number.isSafeInteger(e.requestId)||e.requestId<=0)throw Error(`stale or mismatched pull session command`)}validateHostCredit(e){if(q(e,`byte credit`),e>this.options.maxByteCredit)throw RangeError(`byte credit exceeds host maximum`)}accepted(e,t,n=!1){return{kind:`accepted`,protocol:K,...n?{sessionId:e.sessionId,operationId:e.operationId,generation:e.generation}:this.identity(),requestId:e.requestId,command:t,usage:this.resourceUsage()}}identity(){return{sessionId:this.options.sessionId,operationId:this.options.operationId,generation:this.options.generation}}isStaleLifecycle(e){return(e.kind===`cancel`||e.kind===`close`)&&e.protocol===`ooxml-pull-v1`&&Number.isSafeInteger(e.requestId)&&e.requestId>0&&Number.isSafeInteger(e.generation)&&e.generation>0&&e.generation<this.options.generation}sameOperationIdentity(e){return e.sessionId===this.options.sessionId&&e.operationId===this.options.operationId}errorResponse(e,t){return{kind:`error`,protocol:K,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:t,usage:this.errorResourceUsage()}}async forceFatalCleanup(){this.cancelRequested=!0,this.unacked=void 0,this.coordinator.release(this.coordinatorOwner);let e;for(let t of[...this.leases.keys()])try{await this.release(t)}catch(t){e??=t}if(!this.driverCancelComplete)try{await this.options.driver.cancel?.(),this.driverCancelComplete=!0}catch(t){e??=t}if(e)throw e;this.unregisterCleanup()}allocateWireLeaseId(){if(!Number.isSafeInteger(this.nextWireLeaseId)||this.nextWireLeaseId<=0)throw RangeError(`wire lease id space exhausted`);return this.nextWireLeaseId++}arrayBufferTransferBytes(e){let t=0;for(let n of e??[])if(n instanceof ArrayBuffer&&(t+=n.byteLength,!Number.isSafeInteger(t)))throw RangeError(`ArrayBuffer transfer bytes overflow`);return t}maybeUnregisterCompleted(){this.completed&&this.leases.size===0&&this.unregisterCleanup()}resourceUsage(){return this.options.driver.resourceUsage?.()}errorResourceUsage(){try{return this.resourceUsage()}catch{return}}};const Y=67108864;var be=class{coordinator=new J;host=null;identity=null;constructor(e,t=e=>e(this.requireArchive())){this.archive=e,this.executeArchive=t}open(e){if(this.host)throw Error(`a DOCX document pull session is already active`);this.executeArchive(t=>{t.open_document_cursor(e.operationId,e.generation)});let t=0;this.identity=e,this.host=new ye({...e,maxByteCredit:Y,coordinator:this.coordinator,driver:{pull:n=>{let r;try{r=this.executeArchive(r=>r.pull_document_chunk(t,e.operationId,e.generation,n))}catch(e){throw ue(e,n,Y)||e}let i=ge(r);return{payload:i,byteLength:i.byteLength,done:this.executeArchive(e=>e.document_chunk_done()),transfer:[i]}},measureChunk:({payload:e})=>e.byteLength,acknowledge:n=>{if(n!==t)throw Error(`DOCX document acknowledgement sequence mismatch`);this.executeArchive(n=>n.acknowledge_document_chunk(t,e.operationId,e.generation)),t+=1},cancel:()=>this.executeArchive(e=>e.cancel_document_cursor()),close:()=>this.executeArchive(e=>e.close_document_session()),resourceUsage:()=>{let e=this.executeArchive(e=>e.document_cursor_resource_usage?.());return e?P(e):void 0}}})}dispatch(e,t){return!this.host||!this.identity?(t({protocol:K,kind:`error`,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:G(Error(`DOCX document pull session is not open`))}),Promise.resolve()):this.host.dispatch(e,t)}async reset(){if(this.host)try{this.archive()&&this.executeArchive(e=>e.close_document_session())}finally{this.host=null,this.identity=null,this.coordinator=new J}}requireArchive(){let e=this.archive();if(!e)throw Error(`No docx loaded`);return e}};function xe(e){return!!e&&typeof e==`object`&&e.protocol===`ooxml-pull-v1`}const X=new ce(b,{freeArchive:e=>e.free(),reinit:ne}),Z=new be(()=>X.archive,e=>X.run(()=>{let t=X.archive;if(!t)throw Error(`No docx loaded`);return e(t)}));let Q=0;const $=(e,t)=>self.postMessage(e,t);self.onmessage=async e=>{let n=e.data;if(xe(n)){try{await Z.dispatch(n,$)}catch(e){$({protocol:K,kind:`error`,sessionId:n.sessionId,operationId:n.operationId,generation:n.generation,requestId:n.requestId,error:G(e)})}return}if(n.type===`init`){X.setWasmInput(ie(n.wasmUrl)??n.wasmUrl);return}let r=n.id;try{if(await X.ensureReady(),n.type!==`parse`&&X.archive){let e=X.archive;X.run(()=>e.assert_healthy())}if(n.type===`parse`){await Z.reset();let[e,i,a]=_e(n.resourcePolicy),o=new Uint8Array(n.data);X.run(()=>{let n=new t(o,e,i,a);X.setArchive(n)}),Q+=1;let s={sessionId:Q,operationId:Q,generation:Q};Z.open(s),$({type:`documentSessionOpened`,id:r,...s});return}let e=X.archive;if(n.type===`extractImage`){if(!e)throw Error(`No docx loaded`);let t=X.run(()=>e.extract_image(n.path).buffer),i={type:`imageExtracted`,id:r,bytes:t};self.postMessage(i,[t]);return}if(n.type===`resourceUsage`){if(!e)throw Error(`No docx loaded`);$({type:`resourceUsage`,id:r,usage:P(X.run(()=>e.resource_usage()))});return}if(n.type===`toMarkdown`){if(!e)throw Error(`No docx loaded`);$({type:`markdownRendered`,id:r,markdown:X.run(()=>e.to_markdown())});return}}catch(e){$({type:`error`,id:r,...G(e)})}};", tt = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", N], { type: "text/javascript;charset=utf-8" });
61
- function nt(e) {
62
- let t;
63
- try {
64
- if (t = tt && (self.URL || self.webkitURL).createObjectURL(tt), !t) throw "";
65
- let n = new Worker(t, {
66
- type: "module",
67
- name: e?.name
68
- });
69
- return n.addEventListener("error", () => {
70
- (self.URL || self.webkitURL).revokeObjectURL(t);
71
- }), n;
72
- } catch {
73
- return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(N), {
74
- type: "module",
75
- name: e?.name
76
- });
77
- }
78
- }
79
- //#endregion
80
- //#region packages/docx/src/wasm/docx_parser_bg.wasm?url
81
- var rt = new URL("docx_parser_bg.wasm", import.meta.url).href;
82
- //#endregion
83
- //#region packages/docx/src/bookmark-nav.ts
84
- function it(e) {
85
- let t = /* @__PURE__ */ new Map();
86
- for (let n of e.pages) for (let e of n.bookmarkStarts) e.name !== "" && !t.has(e.name) && t.set(e.name, n.pageIndex);
87
- return t;
88
- }
89
- //#endregion
90
- //#region packages/docx/src/embedded-fonts.ts
91
- async function at(e, t) {
92
- let n = e.embeddedFonts;
93
- if (!n || n.length === 0) return [];
94
- let r = (await Promise.all(n.map(async (e) => {
95
- try {
96
- let n = await t(e.partPath);
97
- return {
98
- family: e.fontName,
99
- bytes: n,
100
- odttf: e.partPath.toLowerCase().endsWith(".odttf"),
101
- fontKey: e.fontKey,
102
- weight: ot(e.style),
103
- style: st(e.style)
104
- };
105
- } catch {
106
- return null;
107
- }
108
- }))).filter((e) => e !== null);
109
- return r.length === 0 ? [] : $e(r);
110
- }
111
- function ot(e) {
112
- return e === "bold" || e === "boldItalic" ? "bold" : "normal";
113
- }
114
- function st(e) {
115
- return e === "italic" || e === "boldItalic" ? "italic" : "normal";
116
- }
117
- //#endregion
118
- //#region packages/docx/src/element-context.ts
119
- var P = de, ct = 16384;
120
- function lt(e, t) {
121
- let n = Math.min(e.length, t);
122
- if (n > 0 && n < e.length) {
123
- let t = e.charCodeAt(n - 1), r = e.charCodeAt(n);
124
- t >= 55296 && t <= 56319 && r >= 56320 && r <= 57343 && n--;
125
- }
126
- return e.slice(0, n);
127
- }
128
- function ut(e, t) {
129
- let n = [], r = 0, i = !1;
130
- for (let a of e) {
131
- if (a.length === 0) continue;
132
- if (r > 0) {
133
- if (r >= t) {
134
- i = !0;
135
- break;
136
- }
137
- n.push("\n"), r++;
138
- }
139
- let e = lt(a, Math.max(0, t - r));
140
- if (n.push(e), r += e.length, e.length < a.length) {
141
- i = !0;
142
- break;
143
- }
144
- }
145
- let a = n.join("");
146
- return {
147
- ...a.length === 0 ? {} : { text: a },
148
- truncated: i
149
- };
150
- }
151
- function* F(e) {
152
- if (e.kind === "paragraph") {
153
- for (let t of e.lines) {
154
- let e = t.placements.flatMap((e) => e.kind === "text" ? [e.text] : []).join("");
155
- e && (yield e);
156
- }
157
- return;
158
- }
159
- if (e.kind === "table") {
160
- for (let t of e.rows) for (let e of t.cells) for (let t of e.blocks) yield* F(t.layout);
161
- return;
162
- }
163
- if (e.kind === "note" || e.kind === "textbox") for (let t of e.story.blocks) yield* F(t);
164
- }
165
- function* dt(e) {
166
- for (let t of e.drawing.commands) (t.kind === "text" || t.kind === "watermark-text") && (yield t.text);
167
- for (let t of e.textBoxes) yield* F(t);
168
- }
169
- function ft(e) {
170
- let t = e ?? ct;
171
- if (!Number.isFinite(t) || t < 0) throw RangeError("maxTextCharacters must be a finite non-negative number.");
172
- return Math.min(P, Math.floor(t));
173
- }
174
- function pt(e) {
175
- return {
176
- story: e.story,
177
- storyInstance: e.storyInstance,
178
- path: [...e.path]
179
- };
180
- }
181
- function mt(e) {
182
- return "drawing" in e ? e.drawing.inkBounds : e.placement.bounds;
183
- }
184
- function ht(e) {
185
- let t = mt(e), n = [
186
- E(e.pointToPage, t),
187
- E(e.pointToPage, {
188
- xPt: t.xPt + t.widthPt,
189
- yPt: t.yPt
190
- }),
191
- E(e.pointToPage, {
192
- xPt: t.xPt,
193
- yPt: t.yPt + t.heightPt
194
- }),
195
- E(e.pointToPage, {
196
- xPt: t.xPt + t.widthPt,
197
- yPt: t.yPt + t.heightPt
198
- })
199
- ], r = Math.min(...n.map((e) => e.xPt)), i = Math.min(...n.map((e) => e.yPt)), a = Math.max(...n.map((e) => e.xPt)), o = Math.max(...n.map((e) => e.yPt));
200
- return {
201
- xPt: r,
202
- yPt: i,
203
- widthPt: a - r,
204
- heightPt: o - i
205
- };
206
- }
207
- function I(e, t) {
208
- return t.xPt >= e.xPt && t.xPt <= e.xPt + e.widthPt && t.yPt >= e.yPt && t.yPt <= e.yPt + e.heightPt;
209
- }
210
- function gt(e, t) {
211
- let n = !1;
212
- for (let r = 0, i = t.length - 1; r < t.length; i = r++) {
213
- let a = t[r], o = t[i];
214
- a.yPt > e.yPt != o.yPt > e.yPt && e.xPt < (o.xPt - a.xPt) * (e.yPt - a.yPt) / (o.yPt - a.yPt) + a.xPt && (n = !n);
215
- }
216
- return n;
217
- }
218
- function _t(e, t) {
219
- return I(e.inkBounds, t) ? e.clip ? e.clip.kind === "rect" ? I(e.clip.rect, t) : gt(t, e.clip.points) : !0 : !1;
220
- }
221
- function vt(e, t, n) {
222
- for (let n of e.clips) {
223
- let e = Re(n.pointToPage, t);
224
- if (!e || !I(n.bounds, e)) return !1;
225
- }
226
- return "drawing" in e ? _t(e.drawing, n) : I(e.placement.bounds, n);
227
- }
228
- function L(e, t) {
229
- return e.commands.find((e) => e.kind === "resource" && e.resourceKind === t);
230
- }
231
- function yt(e) {
232
- return L(e, "chart") ? "chart" : e.commands.some((e) => e.kind === "drawingml-shape" || e.kind === "drawingml-image-fill" || e.kind === "fill-rect" || e.kind === "stroke-rect" || e.kind === "text" || e.kind === "watermark-text") ? "shape" : L(e, "image") ? "image" : null;
233
- }
234
- function bt(e, t, n, r, i, a) {
235
- let o = "drawing" in e ? yt(e.drawing) : e.placement.resourceKind;
236
- if (!o) return null;
237
- let s, c = !1, l, u;
238
- if (o === "chart") {
239
- let t = "drawing" in e ? L(e.drawing, "chart").resourceKey : e.placement.resourceKey, n = i.resolve(t, "chart"), r = y(n.model, a);
240
- s = r.text, c = r.truncated, u = n.model.series.length;
241
- } else if (o === "image") {
242
- let t = "drawing" in e ? L(e.drawing, "image").resourceKey : e.placement.resourceKey, n = i.descriptors.find((e) => e.resourceKey === t && e.kind === "image" && "mimeType" in e);
243
- if (!n) throw Error(`Unknown image paint resource: ${t}`);
244
- l = n.mimeType;
245
- } else {
246
- let t = ut(dt(e), a);
247
- s = t.text, c = t.truncated;
248
- }
249
- return {
250
- format: "docx",
251
- kind: "element",
252
- pageIndex: t,
253
- elementIndex: n,
254
- elementType: o,
255
- point: { ...r },
256
- bounds: ht(e),
257
- source: pt("drawing" in e ? e.drawing.source : e.source),
258
- ...s === void 0 ? {} : { text: s },
259
- ...l === void 0 ? {} : { mimeType: l },
260
- ...u === void 0 ? {} : { seriesCount: u },
261
- truncated: c,
262
- truncationReasons: c ? ["text"] : [],
263
- textCharacters: s?.length ?? 0,
264
- maxTextCharacters: a
265
- };
266
- }
267
- function xt(e, t, n, r, i = {}) {
268
- if (!Number.isFinite(n.xPt) || !Number.isFinite(n.yPt)) throw RangeError("DOCX hit-test point must contain finite page coordinates.");
269
- let a = ft(i.maxTextCharacters), o = ke(e, t);
270
- for (let e = o.length - 1; e >= 0; e--) {
271
- let i = o[e], s = Re(i.pointToPage, n);
272
- if (!s || !vt(i, n, s)) continue;
273
- let c = bt(i, t, e, n, r, a);
274
- if (c) return c;
275
- }
276
- return null;
277
- }
278
- function St(e, t, n, r) {
279
- return xt(Te(e, {
280
- currentDate: r.currentDate,
281
- defaultCurrentDateMs: r.defaultCurrentDateMs
282
- }, t).layout, t, n, ze(e), r);
283
- }
284
- function R(e, t) {
285
- let n = ft(t), r = e.text === void 0 ? void 0 : lt(e.text, n), i = e.truncated || e.text !== void 0 && r.length < e.text.length;
286
- return {
287
- ...structuredClone(e),
288
- ...r === void 0 ? {} : { text: r },
289
- truncated: i,
290
- truncationReasons: i ? ["text"] : [],
291
- textCharacters: r?.length ?? 0,
292
- maxTextCharacters: n
293
- };
294
- }
295
- //#endregion
296
- //#region packages/docx/src/revisions.ts
297
- function z(e) {
298
- let t = Je(e.id);
299
- return t === void 0 ? void 0 : `${e.kind}\u0000${t}`;
300
- }
301
- function B(e) {
302
- return Object.freeze({
303
- ...e,
304
- path: Object.freeze([...e.path])
305
- });
306
- }
307
- function V(e, t) {
308
- return e !== void 0 && e.story === t.story && e.storyInstance === t.storyInstance && e.path.length === t.path.length && e.path.every((e, n) => e === t.path[n]);
309
- }
310
- function H(e, t) {
311
- let n = 0, r = e.length;
312
- for (; n < r;) {
313
- let i = n + Math.floor((r - n) / 2);
314
- e[i] < t ? n = i + 1 : r = i;
315
- }
316
- return n;
317
- }
318
- function Ct(e, t) {
319
- let n = Array(e.length), r;
320
- for (let i = e.length - 1; i >= 0; --i) {
321
- n[i] = r;
322
- let a = e[i], o = t.get(A(a.source))?.[0];
323
- o !== void 0 && (r = Object.freeze({
324
- source: B(a.source),
325
- sourceRunIndex: o
326
- }));
327
- }
328
- let i = Array(e.length), a;
329
- for (let n = 0; n < e.length; n += 1) {
330
- i[n] = a;
331
- let r = e[n], o = t.get(A(r.source))?.at(-1);
332
- o !== void 0 && (a = Object.freeze({
333
- source: B(r.source),
334
- sourceRunIndex: o
335
- }));
336
- }
337
- return {
338
- following: n,
339
- preceding: i
340
- };
341
- }
342
- function wt(e, t, n, r, i, a) {
343
- let o = r[e], s = i.get(A(o.source)) ?? [], c = s[H(s, n)], l = s[H(s, t) - 1], u = c ?? l;
344
- return u === void 0 ? a.following[e] ?? a.preceding[e] : Object.freeze({
345
- source: B(o.source),
346
- sourceRunIndex: u
347
- });
348
- }
349
- function Tt(e, t, n = /* @__PURE__ */ new Map()) {
350
- let r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Set();
351
- e.forEach((e, t) => {
352
- let n = z(e);
353
- n === void 0 || i.has(n) || (r.has(n) ? (r.delete(n), i.add(n)) : r.set(n, t));
354
- });
355
- let a = t.blocks.sources.flatMap((e) => {
356
- if (e.story !== "body") return [];
357
- let n = t.blocks.resolve(e);
358
- return n.type === "paragraph" ? [{
359
- source: e,
360
- runs: n.runs
361
- }] : [];
362
- }), o = new Map([...n].map(([e, t]) => [e, Object.freeze([...t].sort((e, t) => e - t))])), s = Ct(a, o), c = [];
363
- for (let [e, t] of a.entries()) {
364
- let n = 0;
365
- for (; n < t.runs.length;) {
366
- let i = t.runs[n], l = i.revision?.kind ? z({
367
- kind: i.revision.kind,
368
- id: i.revision.id
369
- }) : void 0, u = l === void 0 ? void 0 : r.get(l);
370
- if (u === void 0) {
371
- n += 1;
372
- continue;
373
- }
374
- let d = n;
375
- for (n += 1; n < t.runs.length;) {
376
- let e = t.runs[n].revision;
377
- if (!e?.kind || z({
378
- kind: e.kind,
379
- id: e.id
380
- }) !== l) break;
381
- n += 1;
382
- }
383
- let f = n, p = o.get(A(t.source)) ?? [], m = (p[H(p, d)] ?? f) < f ? void 0 : wt(e, d, f, a, o, s);
384
- c.push(Object.freeze({
385
- revisionIndex: u,
386
- source: B(t.source),
387
- startRunIndex: d,
388
- endRunIndex: f,
389
- ...m === void 0 ? {} : { geometryFallback: m }
390
- }));
391
- }
392
- }
393
- return c;
394
- }
395
- function Et(e, t, n = /* @__PURE__ */ new Map()) {
396
- return (e?.length ?? 0) === 0 ? [] : Tt(e ?? [], t, n);
397
- }
398
- function U(e, t) {
399
- let n = t.filter((t) => t.sourceRunIndex !== void 0 && V(t.source, e.source) && t.sourceRunIndex >= e.startRunIndex && t.sourceRunIndex < e.endRunIndex);
400
- if (n.length > 0) return n;
401
- let r = e.geometryFallback;
402
- return r === void 0 ? [] : t.filter((e) => e.sourceRunIndex === r.sourceRunIndex && V(e.source, r.source));
403
- }
404
- //#endregion
405
- //#region packages/docx/src/document.ts
406
- var W = Object.freeze({
407
- comments: Object.freeze([]),
408
- revisions: Object.freeze([])
409
- });
410
- function G(e, t) {
411
- return Ce({
412
- comments: e,
413
- revisions: t
414
- }, "DOCX review metadata");
415
- }
416
- var K = class e {
417
- _metrics = null;
418
- _document = null;
419
- _source = null;
420
- _meta = null;
421
- _review = W;
422
- _bookmarkPages = null;
423
- _commentAnchorRanges = null;
424
- _revisionAnchorRanges = null;
425
- _reviewTextRunSourceIndex = null;
426
- _mode = "main";
427
- _threeD;
428
- _regionMap;
429
- _chartEx;
430
- _worker;
431
- _bridge;
432
- _rawParts = new xe({
433
- maxEntries: 64,
434
- maxBytes: u
435
- });
436
- _embeddedFontFaces = [];
437
- _googleFontFaces = [];
438
- _localMetricFontFaces = [];
439
- _fetchImage = (e, t) => this.getImage(e, t);
440
- constructor(e, t, n, r) {
441
- this._worker = e, this._mode = t, Be(this, n), this._bridge = new f(this._worker, {
442
- correlate: (e) => "protocol" in e && e.protocol === "ooxml-pull-v1" ? e.requestId : "id" in e ? e.id : void 0,
443
- toError: (e) => {
444
- if (!("protocol" in e || e.type !== "error")) return Object.assign(c(e), {
445
- ...e.reason === void 0 ? {} : { reason: e.reason },
446
- ...e.outgoingColumnIndex === void 0 ? {} : { outgoingColumnIndex: e.outgoingColumnIndex },
447
- ...e.outgoingColumnCount === void 0 ? {} : { outgoingColumnCount: e.outgoingColumnCount },
448
- ...e.incomingColumnCount === void 0 ? {} : { incomingColumnCount: e.incomingColumnCount }
449
- });
450
- }
451
- });
452
- let i = new URL(r ?? rt, location.href).href;
453
- this._bridge.post({
454
- type: "init",
455
- wasmUrl: i
456
- });
457
- }
458
- static async load(n, r = {}) {
459
- let i = t(r), o = Date.now(), s = r.mode ?? "main", c = new a({
460
- enabled: !0,
461
- format: "docx",
462
- mode: s,
463
- policy: i.policy,
464
- onMetrics: i.onResourceMetrics,
465
- emitToConsole: i.debug
466
- });
467
- try {
468
- if (s === "worker" && (typeof Worker > "u" || typeof OffscreenCanvas > "u")) throw Error("mode: 'worker' requires Worker and OffscreenCanvas support");
469
- let t;
470
- if (typeof n == "string") {
471
- let e = await fetch(n);
472
- if (!e.ok) throw Error(`Failed to fetch: ${e.status} ${e.statusText}`);
473
- t = await e.arrayBuffer();
474
- } else t = n;
475
- t = p(await h(t, r.password)), c.setSourceBytes(t.byteLength), c.checkpoint("container ready");
476
- let a = s === "worker" ? (await import("./render-worker-host-DhnkTyjj.js")).createRenderWorker() : new nt(), l = s === "worker" ? Ue(r) : void 0, u;
477
- try {
478
- if (u = new e(a, s, o, r.wasmUrl), u._metrics = c, await u._parse(t, i.policy, s === "worker" ? !!r.useGoogleFonts : !1, r.workerTimeoutMs, (e) => c.observeUsage(e), l), s === "worker" && u._mode === "main" && (c.setMode("main"), console.warn("[ooxml] mode: 'worker' fell back to main-thread rendering because this document requires DOM OpenType vertical glyph selection.")), r.math && u._mode === "worker" && !l?.math && console.warn("[ooxml] a custom math renderer cannot cross the worker boundary; equations will be skipped in mode: 'worker'. Use the math renderer from @silurus/ooxml/math."), r.threeD && u._mode === "worker" && !l?.threeD && console.warn("[ooxml] a custom 3-D chart renderer cannot cross the worker boundary; charts use their 2-D family fallback in mode: 'worker'. Use the renderer from @silurus/ooxml/three-d."), u._threeD = u._mode === "worker" ? void 0 : r.threeD, r.regionMap && u._mode === "worker" && !l?.regionMap && console.warn("[ooxml] a custom Region Map renderer cannot cross the worker boundary; geospatial charts use the unsupported-chart placeholder in mode: 'worker'. Use the renderer from @silurus/ooxml/region-map."), u._regionMap = u._mode === "worker" ? void 0 : r.regionMap, r.chartEx && u._mode === "worker" && !l?.chartEx && console.warn("[ooxml] a custom ChartEx renderer cannot cross the worker boundary; ChartEx charts use the unsupported-chart placeholder in mode: 'worker'. Use the renderer from @silurus/ooxml/chart-ex."), u._chartEx = u._mode === "worker" ? void 0 : r.chartEx, u._mode === "main" && r.useGoogleFonts && u._document && (u._googleFontFaces = await _e(Fe(u._document), Oe)), u._mode === "main" && u._document?.embeddedFonts?.length) {
479
- let e = u;
480
- u._embeddedFontFaces = await at(u._document, (t) => e.getFontBytes(t));
481
- }
482
- let n;
483
- u._mode === "main" && u._document && (n = await De(u._document), u._localMetricFontFaces = n.faces);
484
- let d;
485
- if (u._mode === "main" && r.math && u._document && Pe(u._document) && (d = await Ie(u._document, r.math)), u._mode === "main" && u._document && u._source) {
486
- let e = w(u);
487
- e.services = je(u._source, {
488
- localMetrics: n?.metrics,
489
- useGoogleFonts: !!r.useGoogleFonts,
490
- embeddedFaces: u._embeddedFontFaces,
491
- googleFaces: u._googleFontFaces,
492
- mathResources: d?.records,
493
- mathDrawables: d?.drawables
494
- });
495
- let t = e.services;
496
- we(u._source, t, e.defaultCurrentDateMs).layoutVariants.defaultLayout;
497
- }
498
- return await u._resourceUsage(r.workerTimeoutMs ?? 1e3).then((e) => c.observeUsage(e), () => void 0), c.checkpoint("model and layout ready"), c.succeed({ pages: u.pageCount }), u;
499
- } catch (e) {
500
- let t = u;
501
- throw m(a, t ? () => t.destroy() : void 0), e;
502
- }
503
- } catch (e) {
504
- throw c.fail(e), e;
505
- }
506
- }
507
- async _parse(e, t, n = !1, r, i, a) {
508
- let o = await this._bridge.request((r) => this._mode === "worker" ? {
509
- type: "parse",
510
- id: r,
511
- data: e,
512
- resourcePolicy: t,
513
- useGoogleFonts: n,
514
- defaultCurrentDateMs: w(this).defaultCurrentDateMs,
515
- renderers: a
516
- } : {
517
- type: "parse",
518
- id: r,
519
- data: e,
520
- resourcePolicy: t
521
- }, [e], { timeoutMs: r });
522
- if ("protocol" in o) throw Error("DOCX parse open returned a pull-protocol response");
523
- if (this._mode === "worker") if ("usage" in o && o.usage && i?.(o.usage), o.type === "mainThreadVerticalFallback") {
524
- let e = await Ne(this._bridge.transport(Le), o, {
525
- timeoutMs: r,
526
- onUsage: i
527
- });
528
- this._source = e.source, this._document = e.document, this._meta = null, this._mode = "main";
529
- } else this._meta = o.meta;
530
- else {
531
- let e = o, t = await Ne(this._bridge.transport(Le), e, {
532
- timeoutMs: r,
533
- onUsage: i
534
- });
535
- this._source = t.source, this._document = t.document;
536
- }
537
- this._review = G(this._meta?.comments ?? this._document?.comments ?? [], this._meta?.revisions ?? this._document?.revisions ?? []);
538
- }
539
- destroy() {
540
- this._bridge.terminate(), this._document = null, this._source = null, this._meta = null, this._review = W, w(this).services = null, this._bookmarkPages = null, this._commentAnchorRanges = null, this._revisionAnchorRanges = null, this._reviewTextRunSourceIndex = null, this._rawParts.clear(), this._embeddedFontFaces.length > 0 && (et(this._embeddedFontFaces), this._embeddedFontFaces = []), this._googleFontFaces.length > 0 && (he(this._googleFontFaces), this._googleFontFaces = []), this._localMetricFontFaces.length > 0 && (Se(this._localMetricFontFaces), this._localMetricFontFaces = []), r(this._fetchImage), n(this._fetchImage);
541
- }
542
- async getImage(e, t) {
543
- return this._rawParts.get(e, t, () => this._bridge.request((t) => ({
544
- type: "extractImage",
545
- id: t,
546
- path: e
547
- })).then((e) => {
548
- let n = e.bytes;
549
- return new Blob([n], { type: t });
550
- }));
551
- }
552
- async getFontBytes(e) {
553
- let t = (await this._bridge.request((t) => ({
554
- type: "extractImage",
555
- id: t,
556
- path: e
557
- }))).bytes;
558
- return new Uint8Array(t);
559
- }
560
- async _resourceUsage(e) {
561
- return (await this._bridge.request((e) => ({
562
- type: "resourceUsage",
563
- id: e
564
- }), void 0, { timeoutMs: e })).usage;
565
- }
566
- async getResourceMetrics() {
567
- let e = this._metrics;
568
- if (!e) throw Error("Document not loaded");
569
- return d(e, (e) => this._resourceUsage(e));
570
- }
571
- async toMarkdown() {
572
- return (await this._bridge.request((e) => ({
573
- type: "toMarkdown",
574
- id: e
575
- }))).markdown;
576
- }
577
- get pageCount() {
578
- return this._meta ? this._meta.pageCount : this._document ? this._getLayout()?.pages.length ?? 0 : 0;
579
- }
580
- get mode() {
581
- return this._mode;
582
- }
583
- get document() {
584
- if (this._meta && !this._document) throw Error("the raw document model stays in the worker in mode: 'worker'; use mode: 'main' if you need direct model access");
585
- if (!this._document) throw Error("Document not loaded");
586
- return this._document;
587
- }
588
- get comments() {
589
- return this._reviewSnapshot().comments;
590
- }
591
- get revisions() {
592
- return this._reviewSnapshot().revisions;
593
- }
594
- commentAnchorRanges() {
595
- if (this._meta) return this._meta.commentAnchorRanges ?? [];
596
- if (!this._document || !this._source) return [];
597
- let e = w(this).services;
598
- if (!e) throw Error("Document layout services are not initialized");
599
- let t = C(e)?.defaultLayout;
600
- if (!t) throw Error("Document layout variant store is not initialized");
601
- return this._reviewTextRunSourceIndex ??= T(t), this._commentAnchorRanges ??= Ye(this._reviewSnapshot().comments, this._source, this._reviewTextRunSourceIndex), this._commentAnchorRanges;
602
- }
603
- revisionAnchorRanges() {
604
- if (this._meta) return this._meta.revisionAnchorRanges ?? [];
605
- if (!this._document || !this._source) return [];
606
- let e = w(this).services;
607
- if (!e) throw Error("Document layout services are not initialized");
608
- let t = C(e)?.defaultLayout;
609
- if (!t) throw Error("Document layout variant store is not initialized");
610
- return this._reviewTextRunSourceIndex ??= T(t), this._revisionAnchorRanges ??= Et(this._reviewSnapshot().revisions, this._source, this._reviewTextRunSourceIndex), this._revisionAnchorRanges;
611
- }
612
- _reviewSnapshot() {
613
- return this._review ||= G(this._meta?.comments ?? this._document?.comments ?? [], this._meta?.revisions ?? this._document?.revisions ?? []), this._review;
614
- }
615
- get footnotes() {
616
- return this._meta?.footnotes ?? this._document?.footnotes ?? [];
617
- }
618
- get endnotes() {
619
- return this._meta?.endnotes ?? this._document?.endnotes ?? [];
620
- }
621
- _getLayout() {
622
- if (!this._document) return null;
623
- let e = w(this).services;
624
- if (!e) throw Error("Document layout services are not initialized");
625
- let t = C(e);
626
- if (!t) throw Error("Document layout variant store is not initialized");
627
- return t.defaultLayout;
628
- }
629
- _getBookmarkPages() {
630
- if (this._bookmarkPages) return this._bookmarkPages;
631
- if (this._meta) return this._bookmarkPages = new Map(this._meta.bookmarkPages), this._bookmarkPages;
632
- let e = this._getLayout();
633
- return e ? (this._bookmarkPages = it(e), this._bookmarkPages) : null;
634
- }
635
- getBookmarkPage(e) {
636
- return this._getBookmarkPages()?.get(e);
637
- }
638
- pageSize(e) {
639
- if (this._meta) {
640
- let t = this._meta.pageSizes, n = t[Math.max(0, Math.min(e, t.length - 1))];
641
- return n ? {
642
- widthPt: n.widthPt,
643
- heightPt: n.heightPt
644
- } : {
645
- widthPt: 0,
646
- heightPt: 0
647
- };
648
- }
649
- if (!this._document) return {
650
- widthPt: 0,
651
- heightPt: 0
652
- };
653
- let t = this._getLayout();
654
- if (!t || t.pages.length === 0) return {
655
- widthPt: 0,
656
- heightPt: 0
657
- };
658
- let n = Math.max(0, Math.min(e, t.pages.length - 1)), r = t.pages[n].geometry;
659
- return {
660
- widthPt: r.widthPt,
661
- heightPt: r.heightPt
662
- };
663
- }
664
- renderPage(e, t, n = {}) {
665
- if (this._mode === "worker") throw Error("renderPage(canvas) is unavailable in mode: 'worker'; use renderPageToBitmap() and paint it via an ImageBitmapRenderingContext");
666
- if (!this._source) throw Error("Document not loaded");
667
- return Ee(this._source, e, t, {
668
- ...n,
669
- fetchImage: this._fetchImage,
670
- layoutServices: w(this).services ?? void 0,
671
- defaultCurrentDateMs: w(this).defaultCurrentDateMs,
672
- threeD: this._threeD,
673
- regionMap: this._regionMap,
674
- chartEx: this._chartEx
675
- });
676
- }
677
- async renderPageToBitmap(e, t = {}) {
678
- let { onTextRun: n, ...r } = t, i = {
679
- ...r,
680
- dpr: r.dpr ?? l()
681
- };
682
- if (this._mode === "worker") {
683
- let t = await this._bridge.request((t) => ({
684
- type: "renderPage",
685
- id: t,
686
- pageIndex: e,
687
- opts: i
688
- }));
689
- if (n) for (let e of t.runs) n(e);
690
- return t.bitmap;
691
- }
692
- let a = new OffscreenCanvas(1, 1);
693
- return await this.renderPage(a, e, {
694
- ...i,
695
- onTextRun: n
696
- }), a.transferToImageBitmap();
697
- }
698
- async collectPageRuns(e, t = {}) {
699
- let n = { ...t };
700
- if (this._mode === "worker") return (await this._bridge.request((t) => ({
701
- type: "collectRuns",
702
- id: t,
703
- pageIndex: e,
704
- opts: n
705
- }))).runs;
706
- let r = w(this), i = r.services;
707
- if (!i) throw Error("Document layout services are not initialized");
708
- return Ae(i, e, {
709
- currentDate: n.currentDate,
710
- defaultCurrentDateMs: r.defaultCurrentDateMs,
711
- width: n.width
712
- });
713
- }
714
- async getCommentThreads(e, t = {}) {
715
- let { includeResolved: n, width: r, currentDate: i } = t, a = await this.collectPageRuns(e, {
716
- width: r,
717
- currentDate: i
718
- });
719
- return M(this.comments, this.commentAnchorRanges(), a, { includeResolved: n });
720
- }
721
- async getElementContextAt(e, t, n = {}) {
722
- if (this._mode === "worker") return (await this._bridge.request((r) => ({
723
- type: "hitTestElement",
724
- id: r,
725
- pageIndex: e,
726
- point: t,
727
- opts: n
728
- }))).context;
729
- let r = w(this), i = r.services;
730
- if (!i) throw Error("Document layout services are not initialized");
731
- return St(i, e, t, {
732
- ...n,
733
- defaultCurrentDateMs: r.defaultCurrentDateMs
734
- });
735
- }
736
- };
737
- //#endregion
738
- //#region packages/docx/src/tate-chu-yoko-overlay.ts
739
- function Dt(e, t) {
740
- if (!e.eastAsianVert) return 1;
741
- let n = t(e.text);
742
- return !(n > 0) || e.w >= n ? 1 : e.w / n;
743
- }
744
- //#endregion
745
- //#region packages/docx/src/text-layer.ts
746
- function q(e, t, n) {
747
- e.dataset ? n === void 0 ? delete e.dataset[t] : e.dataset[t] = n : n !== void 0 && e.setAttribute?.(`data-${t.replace(/[A-Z]/g, (e) => `-${e.toLowerCase()}`)}`, n);
748
- }
749
- function J(e, t, n, r, i, a, o) {
750
- e.innerHTML = "", q(e, "ooxmlSelectionSurface", "docx"), q(e, "pageIndex", o === void 0 ? void 0 : String(o));
751
- let s = e.ownerDocument ?? document;
752
- for (let [o, c] of t.entries()) {
753
- let t = s.createElement("span");
754
- q(t, "ooxmlSelectionRun", "docx"), q(t, "runIndex", String(o)), c.paragraphId !== void 0 && q(t, "paragraphId", c.paragraphId), c.source !== void 0 && (q(t, "sourceStory", c.source.story), q(t, "sourceStoryInstance", c.source.storyInstance), q(t, "sourcePath", JSON.stringify(c.source.path))), t.textContent = c.text;
755
- let l = c.transform ?? "";
756
- if (a && c.eastAsianVert) {
757
- let e = Dt(c, a(c.font));
758
- e !== 1 && (l = `${l ? `${l} ` : ""}scaleX(${e})`);
759
- }
760
- let u = l ? `transform:${l};transform-origin:top left;` : "", d = i ? c.hyperlink : void 0, f = d ? "pointer" : "text", p = c.letterSpacingPx === void 0 ? "0" : `${c.letterSpacingPx}px`;
761
- t.style.cssText = `position:absolute;left:${k(c.x, n)};top:${k(c.y, r)};font:${c.font};line-height:${c.h}px;letter-spacing:${p};` + u + `white-space:pre;color:transparent;cursor:${f};pointer-events:all;`, d && i && (t.title = d.kind === "external" ? d.url : d.ref, t.addEventListener("click", (e) => {
762
- e.preventDefault(), i(d);
763
- })), e.appendChild(t);
764
- }
765
- }
766
- function Y(e, t, n, r, i, a, o = {}) {
767
- e.innerHTML = "";
768
- let s = o.match ?? "rgba(255, 214, 0, 0.42)", c = o.active ?? "rgba(255, 140, 0, 0.55)";
769
- for (let o of n) {
770
- let n = o.active ? c : s;
771
- for (let s of o.slices) {
772
- let o = t[s.runIndex];
773
- if (!o) continue;
774
- let c = a(o.font), l = qe(o.text, s.start, s.end, c), u = o.letterSpacingPx ?? 0, d = Math.max(0, Math.min(s.start, o.text.length)), f = Math.max(d, Math.min(s.end, o.text.length)), p = [...o.text.slice(0, d)].length, m = [...o.text.slice(d, f)].length, h = l.x + p * u, g = l.width + Math.max(0, m - 1) * u, _ = Dt(o, c), ee = h * _, v = g * _;
775
- if (v <= 0) continue;
776
- let y = document.createElement("div"), te = o.transform ? `transform:${o.transform};transform-origin:top left;` : "";
777
- y.style.cssText = `position:absolute;left:${k(o.x + ee, r)};top:${k(o.y, i)};width:${k(v, r)};height:${k(o.h, i)};` + te + `background:${n};pointer-events:none;`, e.appendChild(y);
778
- }
779
- }
780
- }
781
- //#endregion
782
- //#region packages/docx/src/find.ts
783
- var Ot = class {
784
- _pageRuns = /* @__PURE__ */ new Map();
785
- _matches = [];
786
- _active = -1;
787
- _generation = 0;
788
- _runsRevision = 0;
789
- constructor(e, t) {
790
- this._pageCount = e, this._collectPageRuns = t;
791
- }
792
- invalidate() {
793
- this._generation++, this._runsRevision++, this._pageRuns.clear(), this._matches = [], this._active = -1;
794
- }
795
- pageRuns(e) {
796
- return this._pageRuns.get(e);
797
- }
798
- setPageRuns(e, t) {
799
- this._runsRevision++, this._pageRuns.set(e, t);
800
- }
801
- _matchAt(e) {
802
- return this._matches[e];
803
- }
804
- pageHighlights(e) {
805
- let t = [];
806
- for (let n = 0; n < this._matches.length; n++) {
807
- let r = this._matches[n];
808
- r.page === e && t.push({
809
- slices: r.slices,
810
- active: n === this._active
811
- });
812
- }
813
- return t;
814
- }
815
- activePage() {
816
- let e = this._matchAt(this._active);
817
- return e ? e.page : null;
818
- }
819
- matches() {
820
- return this._matches.map((e, t) => ({
821
- matchIndex: t,
822
- text: e.text,
823
- location: { page: e.page }
824
- }));
825
- }
826
- async find(e, t = {}) {
827
- let n = ++this._generation;
828
- if (e.length === 0) return this._runsRevision++, this._pageRuns.clear(), this._matches = [], this._active = -1, [];
829
- let r = this._runsRevision, i = new Map(this._pageRuns), a = this._pageCount();
830
- for (let e = 0; e < a; e++) {
831
- let t = i.get(e);
832
- if (!t) {
833
- try {
834
- t = await this._collectPageRuns(e);
835
- } catch (e) {
836
- if (n !== this._generation) return [];
837
- throw e;
838
- }
839
- if (n !== this._generation) return [];
840
- i.set(e, t);
841
- }
842
- }
843
- if (n !== this._generation) return [];
844
- let o = r === this._runsRevision ? i : new Map([...i, ...this._pageRuns]), s = [];
845
- for (let n = 0; n < a; n++) {
846
- let r = o.get(n) ?? [], i = ie(r);
847
- for (let a of re(i, e, t)) {
848
- let e = a.slices.map((e) => r[e.runIndex].text.slice(e.start, e.end)).join("");
849
- s.push({
850
- page: n,
851
- text: e,
852
- slices: a.slices
853
- });
854
- }
855
- }
856
- return this._runsRevision++, this._pageRuns = o, this._matches = s, this._active = -1, this.matches();
857
- }
858
- next() {
859
- return this._active = te(this._active, this._matches.length), this._activePublic();
860
- }
861
- prev() {
862
- return this._active = se(this._active, this._matches.length), this._activePublic();
863
- }
864
- _activePublic() {
865
- let e = this._matchAt(this._active);
866
- return e ? {
867
- matchIndex: this._active,
868
- text: e.text,
869
- location: { page: e.page }
870
- } : null;
871
- }
872
- };
873
- //#endregion
874
- //#region packages/docx/src/selection-context.ts
875
- function kt(e, t, n, r, i = {}) {
876
- let a = e.find((e) => e.id === n && e.parentId === void 0);
877
- if (!a) return null;
878
- let o = new Map(e.map((e) => [e.id, e])), s = e.filter((e) => {
879
- if (e.parentId === void 0) return !1;
880
- let t = e, n = /* @__PURE__ */ new Set();
881
- for (; t.parentId !== void 0 && !n.has(t.id);) {
882
- n.add(t.id);
883
- let e = o.get(t.parentId);
884
- if (!e) return !1;
885
- if (e.id === a.id) return !0;
886
- t = e;
887
- }
888
- return !1;
889
- }), c = Ge({
890
- id: a.id,
891
- author: a.author,
892
- date: a.date,
893
- text: a.paragraphs?.join("\n") ?? a.text,
894
- status: a.resolved ? "resolved" : "active"
895
- }, s.map((e) => ({
896
- id: e.id,
897
- author: e.author,
898
- date: e.date,
899
- text: e.paragraphs?.join("\n") ?? e.text,
900
- status: e.resolved ? "resolved" : "active"
901
- })), i.maxTextCharacters), l = t.find((e) => e.commentId === n)?.source;
902
- return Object.freeze({
903
- format: "docx",
904
- kind: "comment",
905
- pageIndex: r,
906
- commentId: n,
907
- ...l ? { source: Object.freeze({
908
- ...l,
909
- path: Object.freeze([...l.path])
910
- }) } : {},
911
- thread: c.thread,
912
- truncated: c.truncated,
913
- truncationReasons: c.truncated ? ["text"] : [],
914
- textCharacters: c.textCharacters,
915
- maxTextCharacters: c.maxTextCharacters
916
- });
917
- }
918
- function At(e) {
919
- if (e === void 0 || !/^\d+$/.test(e)) return null;
920
- let t = Number(e);
921
- return Number.isSafeInteger(t) ? t : null;
922
- }
923
- function jt(e) {
924
- for (let t = e; t; t = t.parentElement) {
925
- let e = At(t.dataset.pageIndex);
926
- if (e !== null) return e;
927
- }
928
- return null;
929
- }
930
- var Mt = new Set([
931
- "body",
932
- "header",
933
- "footer",
934
- "footnote",
935
- "endnote",
936
- "textbox"
937
- ]);
938
- function Nt(e) {
939
- let t = e.dataset.sourceStory, n = e.dataset.sourceStoryInstance, r = e.dataset.sourcePath;
940
- if (!t || !Mt.has(t) || !n || !r) return null;
941
- try {
942
- let e = JSON.parse(r);
943
- return !Array.isArray(e) || e.length === 0 || e.length > 32 || !e.every((e) => Number.isSafeInteger(e) && e >= 0) ? null : {
944
- story: t,
945
- storyInstance: n,
946
- path: [...e]
947
- };
948
- } catch {
949
- return null;
950
- }
951
- }
952
- function X(e, t, n = {}) {
953
- let r = le(e, t, (e) => {
954
- let t = jt(e), n = At(e.dataset.runIndex);
955
- return t === null || n === null ? null : {
956
- pageIndex: t,
957
- runIndex: n,
958
- ...e.dataset.paragraphId === void 0 ? {} : { paragraphId: e.dataset.paragraphId },
959
- ...Nt(e) === null ? {} : { source: Nt(e) }
960
- };
961
- }, {
962
- maxChars: n.maxTextCharacters,
963
- maxLocators: n.maxRunLocators
964
- });
965
- if (!r) return null;
966
- let i = [...r.locators].sort((e, t) => e.pageIndex - t.pageIndex || e.runIndex - t.runIndex);
967
- return {
968
- format: "docx",
969
- kind: "text",
970
- text: r.text,
971
- pageIndexes: [...new Set(i.map((e) => e.pageIndex))],
972
- paragraphIds: [...new Set(i.flatMap((e) => e.paragraphId ? [e.paragraphId] : []))],
973
- runs: i,
974
- truncated: r.truncated,
975
- truncationReasons: r.truncationReasons,
976
- textCharacters: r.textCharacters,
977
- maxTextCharacters: r.maxTextCharacters,
978
- maxRunLocators: r.maxLocators
979
- };
980
- }
981
- //#endregion
982
- //#region packages/docx/src/focused-view-runtime.ts
983
- function Z(e, t, n, r, i) {
984
- return r === "worker" ? e.renderPageToBitmap(n, i) : e.renderPage(t, n, i);
985
- }
986
- //#endregion
987
- //#region packages/docx/src/viewer.ts
988
- var Pt = Symbol("DocxViewer.borrowedDocument"), Q = class e {
989
- _documentOwner;
990
- get _doc() {
991
- return this._documentOwner.current;
992
- }
993
- _borrowed;
994
- _hostWindow;
995
- _currentPage = 0;
996
- _scale = null;
997
- _canvas;
998
- _wrapper;
999
- _canvasMount;
1000
- _textLayer = null;
1001
- _highlightLayer = null;
1002
- _elementLayer = null;
1003
- _find;
1004
- _measureCtx = null;
1005
- _opts;
1006
- _mode;
1007
- _renderDispatcher;
1008
- _errorRouter;
1009
- _destroyed = !1;
1010
- _selectionChangeListener = null;
1011
- _selectionContextKey = "null";
1012
- _elementContext = null;
1013
- _elementHitGeneration = 0;
1014
- _elementClickListener = null;
1015
- _contextMenuListener = null;
1016
- static fromDocument(t, n, r = {}) {
1017
- return new e(t, {
1018
- ...r,
1019
- [Pt]: n
1020
- });
1021
- }
1022
- constructor(e, t = {}) {
1023
- this._canvas = e, this._opts = t;
1024
- let n = t[Pt];
1025
- this._borrowed = n !== void 0, this._mode = x("DocxViewer", t.mode, n), this._documentOwner = new _("DocxViewer", n ?? null, !1);
1026
- let r = e.ownerDocument?.defaultView ?? (typeof window < "u" ? window : null);
1027
- if (!r) throw Error("DocxViewer requires a canvas with an active Window");
1028
- this._hostWindow = r, this._canvasMount = new ue(e, {
1029
- wrapperCssText: "position:relative;display:inline-block;vertical-align:top;",
1030
- forceDisplayBlock: !0
1031
- }), this._wrapper = this._canvasMount.wrapper, this._renderDispatcher = new b(e, this._mode === "worker"), this._errorRouter = new ce("DocxViewer", t.onError);
1032
- let i = new ae(this._wrapper, t.enableTextSelection === !0, t.enableElementSelection === !0);
1033
- this._textLayer = i.textLayer, this._highlightLayer = i.highlightLayer, this._elementLayer = i.elementLayer, this._textLayer && (t.onSelectionContextChange || t.enableElementSelection) && (this._selectionChangeListener = () => this._emitSelectionContextChange(), this._wrapper.ownerDocument.addEventListener("selectionchange", this._selectionChangeListener)), t.enableElementSelection && (this._elementClickListener = (e) => {
1034
- this._onElementClick(e).catch((e) => this._reportRenderError(e));
1035
- }, this._wrapper.addEventListener("click", this._elementClickListener)), t.onContextMenu && (this._contextMenuListener = (e) => this._onContextMenu(e), this._wrapper.addEventListener("contextmenu", this._contextMenuListener)), this._find = new Ot(() => this.pageCount, (e) => this._collectPageRuns(e));
1036
- }
1037
- async load(e) {
1038
- if (this._destroyed) throw Error("DocxViewer is destroyed");
1039
- if (this._borrowed) throw Error("DocxViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.");
1040
- let t = !1;
1041
- try {
1042
- if (!await this._documentOwner.replace(() => K.load(e, {
1043
- password: this._opts.password,
1044
- useGoogleFonts: this._opts.useGoogleFonts,
1045
- maxZipEntryBytes: this._opts.maxZipEntryBytes,
1046
- resourceLimits: this._opts.resourceLimits,
1047
- debug: this._opts.debug,
1048
- onResourceMetrics: this._opts.onResourceMetrics,
1049
- workerTimeoutMs: this._opts.workerTimeoutMs,
1050
- wasmUrl: this._opts.wasmUrl,
1051
- math: this._opts.math,
1052
- threeD: this._opts.threeD,
1053
- regionMap: this._opts.regionMap,
1054
- chartEx: this._opts.chartEx,
1055
- mode: this._mode
1056
- }), () => {
1057
- this._invalidateElementContext(!1), t = !0, this._renderDispatcher.begin(), this._find.invalidate();
1058
- })) return;
1059
- if (this._destroyed) throw Error("DocxViewer is destroyed");
1060
- this._currentPage = 0, this._find.invalidate(), await this._render();
1061
- } catch (e) {
1062
- throw this._destroyed ? Error("DocxViewer is destroyed") : e instanceof Error ? e : Error(String(e));
1063
- }
1064
- t && !this._destroyed && this._emitSelectionContextChange();
1065
- }
1066
- get pageCount() {
1067
- return this._doc?.pageCount ?? 0;
1068
- }
1069
- get currentPage() {
1070
- return this._currentPage;
1071
- }
1072
- get canvasElement() {
1073
- return this._canvas;
1074
- }
1075
- async goToPage(e) {
1076
- if (!this._doc) return;
1077
- let t = Math.max(0, Math.min(e, this.pageCount - 1)), n = t !== this._currentPage;
1078
- n && this._invalidateElementContext(!1), this._currentPage = t, await this._render(), n && !this._destroyed && this._emitSelectionContextChange();
1079
- }
1080
- async nextPage() {
1081
- await this.goToPage(this._currentPage + 1);
1082
- }
1083
- async prevPage() {
1084
- await this.goToPage(this._currentPage - 1);
1085
- }
1086
- _naturalWidthPx() {
1087
- return !this._doc || this._doc.pageCount === 0 ? 0 : this._doc.pageSize(this._currentPage).widthPt * D;
1088
- }
1089
- _renderWidth() {
1090
- if (this._scale === null) return this._opts.width;
1091
- let e = this._naturalWidthPx();
1092
- return e <= 0 ? this._opts.width : Math.round(e * this._scale);
1093
- }
1094
- getScale() {
1095
- if (this._scale !== null) return this._scale;
1096
- let e = this._naturalWidthPx();
1097
- return e <= 0 ? 1 : this._opts.width && this._opts.width > 0 ? this._opts.width / e : 1;
1098
- }
1099
- _zoomMin() {
1100
- return this._opts.zoomMin ?? .1;
1101
- }
1102
- _zoomMax() {
1103
- return this._opts.zoomMax ?? 4;
1104
- }
1105
- async setScale(e) {
1106
- let t = ne(e, this._zoomMin(), this._zoomMax()), n = t !== this.getScale();
1107
- this._scale = t, await this._render(), n && this._opts.onScaleChange?.(t);
1108
- }
1109
- async zoomIn() {
1110
- await this.setScale(fe(this.getScale()));
1111
- }
1112
- async zoomOut() {
1113
- await this.setScale(S(this.getScale()));
1114
- }
1115
- async fitWidth() {
1116
- await this._fit("width");
1117
- }
1118
- async fitPage() {
1119
- await this._fit("page");
1120
- }
1121
- async _fit(e) {
1122
- if (!this._doc || this._doc.pageCount === 0) return;
1123
- let t = this._doc.pageSize(this._currentPage), n = this._fitContainer();
1124
- if (!n) return;
1125
- let r = g({
1126
- contentWidth: t.widthPt * D,
1127
- contentHeight: t.heightPt * D,
1128
- containerWidth: n.clientWidth,
1129
- containerHeight: n.clientHeight
1130
- }, e);
1131
- r <= 0 || await this.setScale(r);
1132
- }
1133
- _fitContainer() {
1134
- return this._opts.container ?? this._wrapper.parentElement ?? null;
1135
- }
1136
- async findText(e, t = {}) {
1137
- if (!this._doc) return [];
1138
- let n = await this._find.find(e, t);
1139
- return this._redrawHighlights(), n;
1140
- }
1141
- async findNext() {
1142
- return this._activateMatch(this._find.next());
1143
- }
1144
- async findPrev() {
1145
- return this._activateMatch(this._find.prev());
1146
- }
1147
- clearFind() {
1148
- this._find.invalidate(), this._redrawHighlights();
1149
- }
1150
- async _activateMatch(e) {
1151
- return e ? (e.location.page === this._currentPage ? this._redrawHighlights() : await this.goToPage(e.location.page), e) : (this._redrawHighlights(), null);
1152
- }
1153
- _redrawHighlights() {
1154
- let e = this._find.pageRuns(this._currentPage) ?? [];
1155
- this._buildHighlightLayer(e);
1156
- }
1157
- async getResourceMetrics() {
1158
- if (!this._doc) throw Error("Document not loaded");
1159
- return await this._doc.getResourceMetrics();
1160
- }
1161
- getSelectionContext(e = {}) {
1162
- if (this._destroyed) throw Error("DocxViewer is destroyed");
1163
- return (this._textLayer ? X(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null, e) : null) ?? (this._elementContext ? R(this._elementContext, e.maxTextCharacters) : null);
1164
- }
1165
- _emitSelectionContextChange() {
1166
- let e = this.getSelectionContext();
1167
- e?.kind === "text" && (this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutline());
1168
- let t = JSON.stringify(e);
1169
- t !== this._selectionContextKey && (this._selectionContextKey = t, this._opts.onSelectionContextChange?.(e ? structuredClone(e) : null));
1170
- }
1171
- _setElementContext(e) {
1172
- this._elementContext = e ? structuredClone(e) : null, this._redrawElementOutline(), this._emitSelectionContextChange();
1173
- }
1174
- _invalidateElementContext(e = !0) {
1175
- this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutline(), e && this._emitSelectionContextChange();
1176
- }
1177
- _redrawElementOutline() {
1178
- let e = this._elementContext, t = this._doc;
1179
- if (!e || !t || e.pageIndex !== this._currentPage) {
1180
- v(this._elementLayer, null);
1181
- return;
1182
- }
1183
- let n = t.pageSize(e.pageIndex);
1184
- v(this._elementLayer, {
1185
- x: e.bounds.xPt / n.widthPt,
1186
- y: e.bounds.yPt / n.heightPt,
1187
- width: e.bounds.widthPt / n.widthPt,
1188
- height: e.bounds.heightPt / n.heightPt
1189
- });
1190
- }
1191
- async _onElementClick(e) {
1192
- this._destroyed || e.defaultPrevented || e.button !== 0 || await this._resolveContextAt(e);
1193
- }
1194
- _onContextMenu(e) {
1195
- let t;
1196
- this._opts.onContextMenu?.({
1197
- originalEvent: e,
1198
- getContext: () => t ??= this._resolveContextAt(e)
1199
- });
1200
- }
1201
- async _resolveContextAt(e) {
1202
- let t = this._doc;
1203
- if (this._destroyed || !t) return null;
1204
- if (this._textLayer && X(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null)) return this._emitSelectionContextChange(), this._destroyed ? null : this.getSelectionContext();
1205
- if (!this._opts.enableElementSelection) return this.getSelectionContext();
1206
- let n = this._canvas.getBoundingClientRect();
1207
- if (n.width <= 0 || n.height <= 0) return this._invalidateElementContext(), null;
1208
- let r = e.clientX - n.left, i = e.clientY - n.top;
1209
- if (r < 0 || i < 0 || r > n.width || i > n.height) return this._invalidateElementContext(), null;
1210
- let a = ++this._elementHitGeneration, o = this._currentPage, s = t.pageSize(o), c;
1211
- try {
1212
- c = await t.getElementContextAt(o, {
1213
- xPt: r / n.width * s.widthPt,
1214
- yPt: i / n.height * s.heightPt
1215
- }, {
1216
- currentDate: this._opts.currentDate,
1217
- maxTextCharacters: P
1218
- });
1219
- } catch (e) {
1220
- if (this._destroyed || a !== this._elementHitGeneration || o !== this._currentPage || t !== this._doc) return null;
1221
- throw e;
1222
- }
1223
- return this._destroyed || a !== this._elementHitGeneration || o !== this._currentPage || t !== this._doc ? null : (this._setElementContext(c), this._destroyed ? null : this.getSelectionContext());
1224
- }
1225
- destroy() {
1226
- this._destroyed || (this._destroyed = !0, this._errorRouter.close(), this._renderDispatcher.destroy(), Me(this._canvas), this._documentOwner.close(), this._find.invalidate(), this._selectionChangeListener &&= (this._wrapper.ownerDocument.removeEventListener("selectionchange", this._selectionChangeListener), null), this._elementHitGeneration++, this._elementClickListener &&= (this._wrapper.removeEventListener("click", this._elementClickListener), null), this._contextMenuListener &&= (this._wrapper.removeEventListener("contextmenu", this._contextMenuListener), null), this._elementContext = null, this._canvasMount.restore());
1227
- }
1228
- async _render() {
1229
- let e = this._renderDispatcher.begin();
1230
- try {
1231
- await this._renderPage(e);
1232
- } catch (t) {
1233
- if (!this._renderDispatcher.isCurrent(e)) return;
1234
- throw t;
1235
- }
1236
- }
1237
- _reportRenderError(e) {
1238
- this._errorRouter.report(e);
1239
- }
1240
- async _renderPage(e) {
1241
- if (!this._doc) return;
1242
- let t = this._mode === "worker", n = this._renderWidth(), r = [], i = (e) => r.push(e), a = this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1), o = {
1243
- width: n,
1244
- dpr: this._opts.dpr,
1245
- defaultTextColor: this._opts.defaultTextColor,
1246
- currentDate: this._opts.currentDate,
1247
- onTextRun: i
1248
- };
1249
- if (t) {
1250
- let t = await Z(this._doc, this._canvas, this._currentPage, "worker", o);
1251
- if (!this._renderDispatcher.commitBitmap(e, t, {
1252
- cssWidth: Math.round(t.width / a),
1253
- cssHeight: Math.round(t.height / a)
1254
- })) return;
1255
- } else if (await Z(this._doc, this._canvas, this._currentPage, "main", o), !this._renderDispatcher.isCurrent(e)) return;
1256
- this._textLayer && this._buildTextLayer(this._textLayer, r), this._find.setPageRuns(this._currentPage, r), this._buildHighlightLayer(r), this._opts.onPageChange?.(this._currentPage, this.pageCount);
1257
- }
1258
- _buildHighlightLayer(e) {
1259
- let t = this._highlightLayer;
1260
- if (!t) return;
1261
- let { width: n, height: r } = this._canvasCssPx();
1262
- Y(t, e, this._find.pageHighlights(this._currentPage), n, r, (e) => this._measureForFont(e), this._opts.findHighlightColors);
1263
- }
1264
- _canvasCssPx() {
1265
- return {
1266
- width: parseFloat(this._canvas.style.width) || this._canvas.width,
1267
- height: parseFloat(this._canvas.style.height) || this._canvas.height
1268
- };
1269
- }
1270
- _measureForFont(e) {
1271
- this._measureCtx ||= document.createElement("canvas").getContext("2d");
1272
- let t = this._measureCtx;
1273
- return t ? (t.font = e, (e) => t.measureText(e).width) : (e) => e.length;
1274
- }
1275
- async _collectPageRuns(e) {
1276
- return this._doc ? this._doc.collectPageRuns(e, {
1277
- width: this._renderWidth(),
1278
- currentDate: this._opts.currentDate
1279
- }) : [];
1280
- }
1281
- _buildTextLayer(e, t) {
1282
- let { width: n, height: r } = this._canvasCssPx();
1283
- J(e, t, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), this._currentPage);
1284
- }
1285
- _hyperlinkHandler() {
1286
- return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
1287
- if (e.kind === "external") {
1288
- s(e.url, void 0, this._hostWindow);
1289
- return;
1290
- }
1291
- let t = this._doc?.getBookmarkPage(e.ref);
1292
- t !== void 0 && this.goToPage(t).catch((e) => this._reportRenderError(e));
1293
- });
1294
- }
1295
- }, Ft = 150, It = "0 1px 3px rgba(0,0,0,0.2)", $ = 12, Lt = 13, Rt = Symbol("DocxScrollViewer.borrowedDocument"), zt;
1296
- function Bt() {
1297
- return zt ??= import("./comment-ui-runtime-DgCZpPR0.js");
1298
- }
1299
- var Vt = class e {
1300
- _documentOwner;
1301
- get _doc() {
1302
- return this._documentOwner.current;
1303
- }
1304
- _borrowed;
1305
- _opts;
1306
- _container;
1307
- _wrapper;
1308
- _scrollHost;
1309
- _spacer;
1310
- _mode;
1311
- _scale = 1;
1312
- _scaleEstablished = !1;
1313
- _pendingScale = null;
1314
- _slots = /* @__PURE__ */ new Map();
1315
- _free = [];
1316
- _heights = [];
1317
- _scrollGeometry = {
1318
- offsets: [],
1319
- totalHeight: 0
1320
- };
1321
- _lastRange = null;
1322
- _lastTopIndex = -1;
1323
- _scrollListener = null;
1324
- _selectionChangeListener = null;
1325
- _selectionContextKey = "null";
1326
- _elementClickListener = null;
1327
- _contextMenuListener = null;
1328
- _commentOutsidePointerListener = null;
1329
- _elementContext = null;
1330
- _activeCommentId = null;
1331
- _activeCommentPage = null;
1332
- _commentUi = null;
1333
- _commentPageById = /* @__PURE__ */ new Map();
1334
- _commentRunsByPage = /* @__PURE__ */ new Map();
1335
- _commentIndexedPages = /* @__PURE__ */ new Set();
1336
- _commentScanFrontier = 0;
1337
- _commentNavigationGeneration = 0;
1338
- _commentAnchorRangesForMargin = null;
1339
- _commentAnchorIds = /* @__PURE__ */ new Set();
1340
- _commentGeometryScheduled = !1;
1341
- _commentGeometryFrame = null;
1342
- _pendingCommentGeometry = /* @__PURE__ */ new Map();
1343
- _elementHitGeneration = 0;
1344
- _destroyed = !1;
1345
- _measureCtx;
1346
- _bitmapInFlight = /* @__PURE__ */ new Set();
1347
- _renderEpoch = 0;
1348
- _settleTimer = null;
1349
- _wheelListener = null;
1350
- _pendingZoomAnchor = null;
1351
- _resizeObserver = null;
1352
- _prevBase = 0;
1353
- _lastFitWidth = 0;
1354
- _pageShadow;
1355
- _find = new Ot(() => this.pageCount, (e) => this._collectPageRuns(e));
1356
- _findActive = !1;
1357
- static fromDocument(t, n, r = {}) {
1358
- return new e(t, {
1359
- ...r,
1360
- [Rt]: n
1361
- });
1362
- }
1363
- constructor(e, t = {}) {
1364
- if (e.tagName === "CANVAS") throw Error("DocxScrollViewer takes a container element (e.g. a <div>), not a <canvas> — the viewer creates and manages its own canvases. Pass a block container; for the single-page canvas API use DocxViewer.");
1365
- this._container = e, this._opts = t, this._pageShadow = t.pageShadow ?? It;
1366
- let n = t[Rt];
1367
- this._borrowed = n !== void 0, n ? (this._documentOwner = new _("DocxScrollViewer", n, !1), this._mode = x("DocxScrollViewer", t.mode, n)) : (this._documentOwner = new _("DocxScrollViewer"), this._mode = x("DocxScrollViewer", t.mode, void 0)), this._wrapper = document.createElement("div"), this._wrapper.style.cssText = "position:relative;width:100%;height:100%;overflow:hidden;", this._scrollHost = document.createElement("div"), this._scrollHost.style.cssText = "position:absolute;inset:0;overflow:auto;", this._scrollHost.style.scrollbarGutter = "stable", t.background && (this._scrollHost.style.background = t.background), this._spacer = document.createElement("div"), this._spacer.style.cssText = "position:absolute;top:0;left:0;width:1px;height:0;pointer-events:none;", this._scrollHost.appendChild(this._spacer), this._wrapper.appendChild(this._scrollHost), this._container.appendChild(this._wrapper), this._commentsEnabled() && Bt().then((e) => {
1368
- if (!this._destroyed) {
1369
- this._commentUi = e;
1370
- for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
1371
- }
1372
- }).catch((e) => this._reportRenderError(e)), t.enableTextSelection && (t.onSelectionContextChange || t.enableElementSelection) && (this._selectionChangeListener = () => this._emitSelectionContextChange(), this._wrapper.ownerDocument.addEventListener("selectionchange", this._selectionChangeListener)), t.enableElementSelection && (this._elementClickListener = (e) => {
1373
- this._onElementClick(e).catch((e) => this._reportRenderError(e));
1374
- }, this._scrollHost.addEventListener("click", this._elementClickListener)), t.onContextMenu && (this._contextMenuListener = (e) => this._onContextMenu(e), this._scrollHost.addEventListener("contextmenu", this._contextMenuListener)), this._scrollListener = () => this._onScroll(), this._scrollHost.addEventListener("scroll", this._scrollListener), t.comments && (this._commentOutsidePointerListener = (e) => {
1375
- if (!Ke(e, this._wrapper, "ooxmlCommentId") && this._activeCommentId !== null) {
1376
- this._activeCommentId = null, this._activeCommentPage = null;
1377
- for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
1378
- this._emitSelectionContextChange();
1379
- }
1380
- }, this._wrapper.ownerDocument.addEventListener("pointerdown", this._commentOutsidePointerListener)), this._opts.enableZoom !== !1 && (this._wheelListener = (e) => {
1381
- if (!(e.ctrlKey || e.metaKey) || (e.preventDefault(), e.deltaY === 0)) return;
1382
- let t = this._scrollHost.getBoundingClientRect(), n = e.clientX - t.left, r = e.clientY - t.top;
1383
- this._pendingZoomAnchor = Number.isFinite(n) && Number.isFinite(r) ? {
1384
- x: n,
1385
- y: r
1386
- } : null, this.setScale(me(this._scale, e.deltaY));
1387
- }, this._scrollHost.addEventListener("wheel", this._wheelListener, { passive: !1 })), typeof ResizeObserver < "u" && (this._resizeObserver = new ResizeObserver(() => this._onResize()), this._resizeObserver.observe(this._container)), this._borrowed && this.relayout();
1388
- }
1389
- async load(e) {
1390
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
1391
- if (this._borrowed) throw Error("DocxScrollViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.");
1392
- let t = !1;
1393
- try {
1394
- if (!await this._documentOwner.replace(() => K.load(e, {
1395
- password: this._opts.password,
1396
- useGoogleFonts: this._opts.useGoogleFonts,
1397
- maxZipEntryBytes: this._opts.maxZipEntryBytes,
1398
- resourceLimits: this._opts.resourceLimits,
1399
- debug: this._opts.debug,
1400
- onResourceMetrics: this._opts.onResourceMetrics,
1401
- workerTimeoutMs: this._opts.workerTimeoutMs,
1402
- wasmUrl: this._opts.wasmUrl,
1403
- math: this._opts.math,
1404
- threeD: this._opts.threeD,
1405
- regionMap: this._opts.regionMap,
1406
- chartEx: this._opts.chartEx,
1407
- mode: this._mode
1408
- }), (e) => {
1409
- if (this._invalidateElementContext(!1), t = !0, this._find.invalidate(), this._findActive = !1, this._activeCommentId = null, this._activeCommentPage = null, this._resetCommentNavigation(), e) {
1410
- for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
1411
- this._lastTopIndex = -1;
1412
- }
1413
- })) return;
1414
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
1415
- this._find.invalidate(), this._findActive = !1, this._activeCommentId = null, this._activeCommentPage = null, this._resetCommentNavigation();
1416
- let n = [];
1417
- this._relayout(n), await Promise.all(n);
1418
- } catch (e) {
1419
- throw this._destroyed ? Error("DocxScrollViewer is destroyed") : e instanceof Error ? e : Error(String(e));
1420
- }
1421
- t && !this._destroyed && this._emitSelectionContextChange();
1422
- }
1423
- get pageCount() {
1424
- return this._doc?.pageCount ?? 0;
1425
- }
1426
- _pageWidthPx(e) {
1427
- return this._doc.pageSize(e).widthPt * D * this._scale;
1428
- }
1429
- _pageHeightPx(e) {
1430
- return this._doc.pageSize(e).heightPt * D * this._scale;
1431
- }
1432
- _fitWidthPx() {
1433
- if (this._opts.width && this._opts.width > 0) return this._opts.width;
1434
- let e = this._scrollHost.clientWidth || this._container.clientWidth;
1435
- if (e <= 0) return 0;
1436
- let { left: t, right: n } = this._padH(), r = e - t - n;
1437
- if (r <= 0) return 0;
1438
- let i = this._doc?.pageSize(0).widthPt ? this._doc.pageSize(0).widthPt * D : 0, a = this._hasCommentMargin() && i > 0 ? r * i / (i + $ + 280) : r;
1439
- return a > 0 ? a : 0;
1440
- }
1441
- _hasCommentMargin() {
1442
- return this._hasDisplayableComments() && this._commentsOptions()?.cards !== !1;
1443
- }
1444
- _hasDisplayableComments() {
1445
- if (!this._commentsEnabled()) return !1;
1446
- let e = this._doc;
1447
- if (!e) return !1;
1448
- let t = e.commentAnchorRanges();
1449
- if (this._commentAnchorRangesForMargin !== t && (this._commentAnchorRangesForMargin = t, this._commentAnchorIds = new Set(t.map((e) => e.commentId))), this._commentAnchorIds.size === 0) return !1;
1450
- let n = this._commentsOptions()?.includeResolved === !0;
1451
- return e.comments.some((e) => this._commentAnchorIds.has(e.id) && e.parentId === void 0 && (n || e.resolved !== !0));
1452
- }
1453
- _commentMarginExtent() {
1454
- return this._hasCommentMargin() ? ($ + 280) * this._commentZoom() : 0;
1455
- }
1456
- _commentZoom() {
1457
- return this._scaleEstablished ? this._scale : 1;
1458
- }
1459
- _commentsEnabled() {
1460
- return this._opts.comments === !0 || typeof this._opts.comments == "object";
1461
- }
1462
- _commentsOptions() {
1463
- return typeof this._opts.comments == "object" ? this._opts.comments : void 0;
1464
- }
1465
- _commentSide() {
1466
- let e = this._commentsOptions()?.side;
1467
- return e === "left" || e === "right" ? e : (this._container.ownerDocument.defaultView?.getComputedStyle?.(this._container).direction || this._container.dir || this._container.style.direction) === "rtl" ? "left" : "right";
1468
- }
1469
- _syncCommentMarginGeometry(e) {
1470
- if (!e) return;
1471
- let t = this._commentZoom(), n = `calc(100% + ${$ * t}px)`;
1472
- e.style.left = this._commentSide() === "right" ? n : "", e.style.right = this._commentSide() === "left" ? n : "", e.style.width = `${280 * t}px`, e.style.fontSize = `${Lt}px`, e.dataset.ooxmlCommentZoom = String(t);
1473
- }
1474
- _baseScale() {
1475
- if (!this._doc || this._doc.pageCount === 0) return 0;
1476
- let e = this._fitWidthPx();
1477
- if (e <= 0) return 0;
1478
- let t = this._doc.pageSize(0).widthPt;
1479
- return t <= 0 ? 0 : e / (t * D);
1480
- }
1481
- relayout() {
1482
- this._relayout();
1483
- }
1484
- _relayout(e) {
1485
- if (this._doc) {
1486
- if (!this._scaleEstablished) {
1487
- let e = this._baseScale();
1488
- if (e > 0) {
1489
- if (this._scale = e, this._prevBase = e, this._lastFitWidth = this._fitWidthPx(), this._scaleEstablished = !0, this._pendingScale !== null) {
1490
- let e = this._pendingScale;
1491
- this._pendingScale = null, e !== this._scale && (this._scale = e, this._opts.onScaleChange?.(e));
1492
- }
1493
- } else return;
1494
- }
1495
- this._recomputeHeights(), this._syncSpacer(), this._mountVisible(e);
1496
- for (let [e, t] of this._slots) t.renderedPage === e && t.renderedScale >= 0 && this._redrawSlotComments(e, t);
1497
- }
1498
- }
1499
- _recomputeHeights() {
1500
- let e = this._doc.pageCount, t = Array(e);
1501
- for (let n = 0; n < e; n++) t[n] = this._pageHeightPx(n);
1502
- this._heights = t, this._scrollGeometry = We(t, this._gap(), this._pad());
1503
- }
1504
- _gap() {
1505
- return this._opts.gap ?? 16;
1506
- }
1507
- _overscan() {
1508
- return this._opts.overscan ?? 1;
1509
- }
1510
- _pad() {
1511
- let e = this._gap();
1512
- return {
1513
- leading: this._opts.paddingTop ?? e,
1514
- trailing: this._opts.paddingBottom ?? e
1515
- };
1516
- }
1517
- _padH() {
1518
- let e = this._gap();
1519
- return {
1520
- left: this._opts.paddingLeft ?? e,
1521
- right: this._opts.paddingRight ?? e
1522
- };
1523
- }
1524
- _pageIndexAtOffset(e, t) {
1525
- let { offsets: n } = e, r = 0, i = n.length - 1, a = 0;
1526
- for (; r <= i;) {
1527
- let e = r + i >> 1;
1528
- n[e] <= t ? (a = e, r = e + 1) : i = e - 1;
1529
- }
1530
- return a;
1531
- }
1532
- _range() {
1533
- return O(this._scrollGeometry, this._scrollHost.scrollTop, this._scrollHost.clientHeight, this._overscan());
1534
- }
1535
- _syncSpacer() {
1536
- let e = this._range();
1537
- this._lastRange = e, this._spacer.style.height = `${e.totalHeight}px`, this._syncSpacerWidth();
1538
- }
1539
- _syncSpacerWidth() {
1540
- let { left: e, right: t } = this._padH(), n = 0;
1541
- for (let e = 0; e < this._heights.length; e++) {
1542
- let t = this._pageWidthPx(e);
1543
- t > n && (n = t);
1544
- }
1545
- this._spacer.style.width = `${n + this._commentMarginExtent() + e + t}px`;
1546
- }
1547
- _onScroll() {
1548
- !this._doc || !this._scaleEstablished || this._mountVisible(void 0, !1);
1549
- }
1550
- _mountVisible(e, t = !0) {
1551
- if (!this._doc || this._doc.pageCount === 0) return;
1552
- let n = this._range();
1553
- this._lastRange = n;
1554
- for (let [e, t] of [...this._slots]) (e < n.start || e > n.end) && this._recycleSlot(e, t);
1555
- for (let r = n.start; r <= n.end; r++) if (this._slots.has(r)) t && this._positionSlot(this._slots.get(r), r, n);
1556
- else {
1557
- let t = this._acquireSlot();
1558
- this._positionSlot(t, r, n), this._slots.set(r, t);
1559
- let i = this._renderSlot(r, t, e === void 0);
1560
- e && i && e.push(i);
1561
- }
1562
- n.topIndex !== this._lastTopIndex && (this._lastTopIndex = n.topIndex, this._opts.onVisiblePageChange?.(n.topIndex, this._doc.pageCount));
1563
- }
1564
- _applyPageShadow(e) {
1565
- this._pageShadow !== !1 && (e.style.boxShadow = this._pageShadow);
1566
- }
1567
- _acquireSlot() {
1568
- let e = this._free.pop();
1569
- if (e) return this._scrollHost.appendChild(e.wrapper), e;
1570
- let t = document.createElement("div");
1571
- t.style.cssText = "position:absolute;";
1572
- let n = document.createElement("canvas");
1573
- n.style.cssText = "display:block;background:#fff;", this._applyPageShadow(n), t.appendChild(n);
1574
- let r = null;
1575
- this._opts.enableTextSelection && (r = document.createElement("div"), r.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;user-select:text;-webkit-user-select:text;", t.appendChild(r));
1576
- let i = document.createElement("div");
1577
- i.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;", t.appendChild(i);
1578
- let a = null, o = null, s = null;
1579
- this._hasDisplayableComments() && (a = document.createElement("div"), a.style.cssText = "position:absolute;inset:0;overflow:hidden;pointer-events:none;", t.appendChild(a), this._hasCommentMargin() && (o = document.createElement("div"), o.style.cssText = "position:absolute;top:0;height:100%;box-sizing:border-box;overflow-x:hidden;overflow-y:auto;pointer-events:auto;", this._syncCommentMarginGeometry(o), this._commentsOptions()?.connectors !== void 0 && (s = document.createElement("div"), s.style.cssText = "position:absolute;top:0;left:0;overflow:visible;pointer-events:none;", t.appendChild(s)), t.appendChild(o)));
1580
- let c = oe(t, this._opts.enableElementSelection === !0);
1581
- return this._scrollHost.appendChild(t), {
1582
- wrapper: t,
1583
- canvas: n,
1584
- textLayer: r,
1585
- highlightLayer: i,
1586
- elementLayer: c,
1587
- commentTintLayer: a,
1588
- commentMargin: o,
1589
- commentDecorationLayer: s,
1590
- commentRuns: Object.freeze([]),
1591
- commentGeometry: null,
1592
- renderedPage: -1,
1593
- renderedScale: -1,
1594
- dispatcher: new b(n, this._mode === "worker")
1595
- };
1596
- }
1597
- _recycleSlot(e, t) {
1598
- this._slots.delete(e), t.dispatcher.destroy(), this._destroyed || (t.dispatcher = new b(t.canvas, this._mode === "worker")), t.textLayer && (t.textLayer.innerHTML = "", t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = ""), t.highlightLayer.innerHTML = "", t.highlightLayer.style.transform = "", t.highlightLayer.style.transformOrigin = "", t.commentTintLayer && (t.commentTintLayer.replaceChildren(), t.commentTintLayer.style.transform = "", t.commentTintLayer.style.transformOrigin = "", t.commentTintLayer.style.visibility = ""), t.commentMargin && (this._commentUi?.disposeReadOnlyCommentMargin(t.commentMargin), this._commentUi || t.commentMargin.replaceChildren(), t.commentMargin.style.visibility = ""), t.commentDecorationLayer && (this._commentUi?.disposeReadOnlyCommentDecoration(t.commentDecorationLayer), this._commentUi || t.commentDecorationLayer.replaceChildren()), t.commentRuns = Object.freeze([]), t.commentGeometry = null, v(t.elementLayer, null), t.renderedPage = -1, t.renderedScale = -1, t.wrapper.remove(), this._free.push(t);
1599
- }
1600
- _positionSlot(e, t, n) {
1601
- e.wrapper.style.top = `${n.offsets[t]}px`;
1602
- let r = this._pageWidthPx(t), i = this._pageHeightPx(t);
1603
- if (e.wrapper.style.width = `${r}px`, e.wrapper.style.height = `${i}px`, this._syncCommentMarginGeometry(e.commentMargin), e.commentDecorationLayer) {
1604
- let t = this._commentMarginExtent();
1605
- e.commentDecorationLayer.style.left = this._commentSide() === "left" ? `${-t}px` : "0px", e.commentDecorationLayer.style.width = `${r + t}px`, e.commentDecorationLayer.style.height = `${i}px`;
1606
- }
1607
- this._redrawElementOutlineForSlot(t, e);
1608
- let { left: a } = this._padH(), o = this._scrollHost.clientWidth, s = this._commentMarginExtent(), c = r + s, l = Math.max(a, (o - c) / 2);
1609
- e.wrapper.style.left = `${l + (this._commentSide() === "left" ? s : 0)}px`;
1610
- }
1611
- _dpr() {
1612
- return this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1);
1613
- }
1614
- _renderSlot(e, t, n = !0) {
1615
- if (!this._doc || t.renderedPage === e) return null;
1616
- t.renderedPage = e;
1617
- let r = this._dpr(), i = this._pageWidthPx(e), a = this._renderEpoch, o = this._scale, s = t.dispatcher, c = s.begin();
1618
- if (this._mode === "worker") return this._renderSlotBitmap(e, t, i, r, o, s, c, n);
1619
- let l = [], u = !!this._opts.enableTextSelection && !!t.textLayer, d = u || this._findActive || !!t.commentTintLayer, f = d ? (e) => l.push(e) : void 0, p;
1620
- try {
1621
- p = Z(this._doc, t.canvas, e, "main", {
1622
- width: i,
1623
- dpr: r,
1624
- defaultTextColor: this._opts.defaultTextColor,
1625
- currentDate: this._opts.currentDate,
1626
- onTextRun: f
1627
- });
1628
- } catch (e) {
1629
- return n ? (this._reportRenderError(e), Promise.resolve()) : Promise.reject(e);
1630
- }
1631
- return p.then(() => {
1632
- if (!(!s.isCurrent(c) || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e)) {
1633
- if (t.renderedScale = o, u && t.textLayer) {
1634
- let { width: n, height: r } = this._canvasCssPx(t.canvas);
1635
- J(t.textLayer, l, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
1636
- }
1637
- d && this._refreshFindRuns(e, l), this._commitCommentRuns(e, t, l), this._redrawSlotHighlights(e, t);
1638
- }
1639
- }).catch((r) => {
1640
- if (s.isCurrent(c) && a === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e) if (n) this._reportRenderError(r);
1641
- else throw r;
1642
- });
1643
- }
1644
- _hyperlinkHandler() {
1645
- return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
1646
- if (e.kind === "external") {
1647
- s(e.url);
1648
- return;
1649
- }
1650
- let t = this._doc?.getBookmarkPage(e.ref);
1651
- t !== void 0 && this.scrollToPage(t);
1652
- });
1653
- }
1654
- _measureForFont(e) {
1655
- this._measureCtx === void 0 && (this._measureCtx = document.createElement("canvas").getContext("2d"));
1656
- let t = this._measureCtx;
1657
- return !t || typeof t.measureText != "function" ? (e) => e.length : (t.font = e, (e) => t.measureText(e).width);
1658
- }
1659
- _canvasCssPx(e) {
1660
- return {
1661
- width: parseFloat(e.style.width) || e.width,
1662
- height: parseFloat(e.style.height) || e.height
1663
- };
1664
- }
1665
- _reportRenderError(e) {
1666
- if (this._destroyed) return;
1667
- let t = e instanceof Error ? e : Error(String(e));
1668
- this._opts.onError ? this._opts.onError(t) : console.error("[ooxml] DocxScrollViewer render failed:", t);
1669
- }
1670
- async _renderSlotBitmap(e, t, n, r, i, a = t.dispatcher, o = a.begin(), s = !0) {
1671
- if (this._bitmapInFlight.has(e) || this._slots.get(e) !== t) return;
1672
- let c = this._renderEpoch;
1673
- this._bitmapInFlight.add(e);
1674
- let l = !1, u = !!this._opts.enableTextSelection && !!t.textLayer, d = u || this._findActive || !!t.commentTintLayer, f = [];
1675
- try {
1676
- let s = await Z(this._doc, t.canvas, e, "worker", {
1677
- width: n,
1678
- dpr: r,
1679
- defaultTextColor: this._opts.defaultTextColor,
1680
- currentDate: this._opts.currentDate,
1681
- onTextRun: d ? (e) => f.push(e) : void 0
1682
- });
1683
- if (!a.isCurrent(o) || c !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) {
1684
- s.close();
1685
- return;
1686
- }
1687
- if (!a.commitBitmap(o, s, {
1688
- cssWidth: Math.round(s.width / r),
1689
- cssHeight: Math.round(s.height / r)
1690
- })) return;
1691
- if (t.renderedScale = i, t.textLayer && (t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = "", u)) {
1692
- let { width: n, height: r } = this._canvasCssPx(t.canvas);
1693
- J(t.textLayer, f, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
1694
- }
1695
- d && this._refreshFindRuns(e, f), this._commitCommentRuns(e, t, f), this._redrawSlotHighlights(e, t), l = !0;
1696
- } catch (n) {
1697
- if (a.isCurrent(o) && c === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e) if (s) this._reportRenderError(n);
1698
- else throw n;
1699
- } finally {
1700
- this._bitmapInFlight.delete(e);
1701
- let n = this._slots.get(e);
1702
- !l && n && (n !== t || c !== this._renderEpoch || !a.isCurrent(o)) && !this._bitmapInFlight.has(e) && !this._destroyed && this._renderSlotBitmap(e, n, this._pageWidthPx(e), this._dpr(), this._scale);
1703
- }
1704
- }
1705
- setScale(e) {
1706
- let t = this._opts.zoomMin ?? .1, n = this._opts.zoomMax ?? 4, r = Math.min(n, Math.max(t, e)), i = this._pendingZoomAnchor;
1707
- if (this._pendingZoomAnchor = null, !this._doc || this._doc.pageCount === 0 || !this._scaleEstablished) {
1708
- this._pendingScale = r;
1709
- return;
1710
- }
1711
- if (r === this._scale) return;
1712
- let a = this._scale, o = i ? i.y : 0, s = this._range(), c = this._scrollHost.scrollTop, l = c + o, u = this._pageIndexAtOffset(s, l), d = this._heights[u] || 0, f = d > 0 ? (l - s.offsets[u]) / d : 0;
1713
- f = Math.min(1, Math.max(0, f));
1714
- let p = this._padH().left, m = this._scrollHost.scrollLeft || 0;
1715
- this._renderEpoch++, this._scale = r, this._recomputeHeights();
1716
- let h = O(this._scrollGeometry, 0, this._scrollHost.clientHeight, this._overscan());
1717
- this._spacer.style.height = `${h.totalHeight}px`, this._syncSpacerWidth();
1718
- let g = Math.max(0, h.totalHeight - this._scrollHost.clientHeight), _ = (h.offsets[u] ?? 0) + f * (this._heights[u] || 0), v = l < (s.offsets[0] ?? 0) ? c : _ - o;
1719
- if (this._scrollHost.scrollTop = Math.min(g, Math.max(0, v)), i) {
1720
- let e = Math.max(0, (this._spacer.offsetWidth || 0) - this._scrollHost.clientWidth);
1721
- this._scrollHost.scrollLeft = ee(m, i.x - p, a, r, { maxScroll: e });
1722
- }
1723
- this._previewVisible(), this._scheduleSettle(), this._opts.onScaleChange?.(r);
1724
- }
1725
- getScale() {
1726
- return this._scaleEstablished ? this._scale : this._pendingScale ?? 1;
1727
- }
1728
- zoomIn() {
1729
- this.setScale(fe(this.getScale()));
1730
- }
1731
- zoomOut() {
1732
- this.setScale(S(this.getScale()));
1733
- }
1734
- fitWidth() {
1735
- this._fit("width");
1736
- }
1737
- fitPage() {
1738
- this._fit("page");
1739
- }
1740
- _fit(e) {
1741
- if (!this._doc || this._doc.pageCount === 0) return;
1742
- let t = this._doc.pageSize(0), n = g({
1743
- contentWidth: t.widthPt * D,
1744
- contentHeight: t.heightPt * D,
1745
- containerWidth: this._fitWidthPx(),
1746
- containerHeight: this._scrollHost.clientHeight
1747
- }, e);
1748
- n <= 0 || this.setScale(n);
1749
- }
1750
- _previewVisible() {
1751
- if (!this._doc || this._doc.pageCount === 0) return;
1752
- let e = this._range();
1753
- this._lastRange = e;
1754
- for (let [t, n] of [...this._slots]) (t < e.start || t > e.end) && this._recycleSlot(t, n);
1755
- for (let t = e.start; t <= e.end; t++) {
1756
- let n = this._slots.get(t);
1757
- if (n) this._previewSlot(n, t, e);
1758
- else {
1759
- let n = this._acquireSlot();
1760
- this._positionSlot(n, t, e), this._slots.set(t, n), this._renderSlot(t, n);
1761
- }
1762
- }
1763
- e.topIndex !== this._lastTopIndex && (this._lastTopIndex = e.topIndex, this._opts.onVisiblePageChange?.(e.topIndex, this._doc.pageCount));
1764
- }
1765
- _previewSlot(e, t, n) {
1766
- if (this._positionSlot(e, t, n), e.canvas.style.width = `${this._pageWidthPx(t)}px`, e.canvas.style.height = `${this._pageHeightPx(t)}px`, e.renderedScale > 0) {
1767
- let t = this._scale / e.renderedScale;
1768
- e.textLayer && (e.textLayer.style.transformOrigin = "0 0", e.textLayer.style.transform = `scale(${t})`), e.commentMargin && this._commentUi?.previewReadOnlyCommentMargin(e.commentMargin, t);
1769
- for (let n of e.commentTintLayer?.children ?? []) n.dataset.ooxmlCommentMarker !== void 0 && (n.style.transform = `translate(-50%,-50%) scale(${t})`);
1770
- e.commentTintLayer && (e.commentTintLayer.style.visibility = ""), e.commentMargin && (e.commentMargin.style.visibility = ""), e.commentDecorationLayer && (e.commentDecorationLayer.style.visibility = "");
1771
- return;
1772
- }
1773
- e.commentTintLayer && (e.commentTintLayer.style.visibility = "hidden"), e.commentMargin && (e.commentMargin.style.visibility = "hidden"), e.commentDecorationLayer && (e.commentDecorationLayer.style.visibility = "hidden");
1774
- }
1775
- _scheduleSettle() {
1776
- this._settleTimer !== null && clearTimeout(this._settleTimer), this._settleTimer = setTimeout(() => {
1777
- this._settleTimer = null, this._settleRender();
1778
- }, Ft);
1779
- }
1780
- _settleRender() {
1781
- if (!(this._destroyed || !this._doc || this._doc.pageCount === 0)) for (let [e, t] of [...this._slots]) t.renderedScale !== this._scale && this._settleSlot(e, t);
1782
- }
1783
- _settleSlot(e, t) {
1784
- if (!this._doc) return;
1785
- let n = this._dpr(), r = this._pageWidthPx(e), i = this._scale, a = this._renderEpoch;
1786
- if (this._mode === "worker") {
1787
- this._renderSlotBitmap(e, t, r, n, i);
1788
- return;
1789
- }
1790
- let o = document.createElement("canvas");
1791
- o.style.cssText = "display:block;background:#fff;", this._applyPageShadow(o);
1792
- let s = new b(o, !1), c = s.begin(), l = [], u = !!this._opts.enableTextSelection && !!t.textLayer, d = u || this._findActive || !!t.commentTintLayer, f = d ? (e) => l.push(e) : void 0;
1793
- Z(this._doc, o, e, "main", {
1794
- width: r,
1795
- dpr: n,
1796
- defaultTextColor: this._opts.defaultTextColor,
1797
- currentDate: this._opts.currentDate,
1798
- onTextRun: f
1799
- }).then(() => {
1800
- if (!s.isCurrent(c) || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) {
1801
- s.destroy();
1802
- return;
1803
- }
1804
- let n = t.canvas;
1805
- if (t.dispatcher.destroy(), t.wrapper.insertBefore(o, n), n.remove(), t.canvas = o, t.dispatcher = s, t.renderedScale = i, t.textLayer && (t.textLayer.style.transform = "", t.textLayer.style.transformOrigin = "", u)) {
1806
- let { width: n, height: r } = this._canvasCssPx(o);
1807
- J(t.textLayer, l, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
1808
- }
1809
- d && this._refreshFindRuns(e, l), this._commitCommentRuns(e, t, l), this._redrawSlotHighlights(e, t);
1810
- }).catch((n) => {
1811
- s.isCurrent(c) && a === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e && this._reportRenderError(n), s.destroy();
1812
- });
1813
- }
1814
- scrollToPage(e, t) {
1815
- if (!this._doc || this._doc.pageCount === 0 || !this._scaleEstablished) return;
1816
- let n = Math.max(0, Math.min(e, this._doc.pageCount - 1)), r = O(this._scrollGeometry, 0, this._scrollHost.clientHeight, this._overscan()), i = r.offsets[n] ?? 0, a = Math.max(0, r.totalHeight - this._scrollHost.clientHeight), o = Math.min(a, Math.max(0, i)), s = this._scrollHost;
1817
- typeof s.scrollTo == "function" ? s.scrollTo({
1818
- top: o,
1819
- behavior: t?.behavior ?? "auto"
1820
- }) : this._scrollHost.scrollTop = o, this._mountVisible();
1821
- }
1822
- _scrollToPageTarget(e, t, n) {
1823
- let r = O(this._scrollGeometry, 0, this._scrollHost.clientHeight, this._overscan()), i = this._pageWidthPx(e), a = this._commentMarginExtent(), { left: o } = this._padH(), s = Math.max(o, (this._scrollHost.clientWidth - i - a) / 2) + (this._commentSide() === "left" ? a : 0), c = Math.max(0, r.totalHeight - this._scrollHost.clientHeight), l = this._spacer.offsetWidth || Number.parseFloat(this._spacer.style.width) || 0, u = Math.max(0, l - this._scrollHost.clientWidth), d = Math.min(c, Math.max(0, (r.offsets[e] ?? 0) + t.y + t.h / 2 - this._scrollHost.clientHeight / 2)), f = Math.min(u, Math.max(0, s + t.x + t.w / 2 - this._scrollHost.clientWidth / 2)), p = this._scrollHost;
1824
- typeof p.scrollTo == "function" ? p.scrollTo({
1825
- top: d,
1826
- left: f,
1827
- behavior: n?.behavior ?? "auto"
1828
- }) : (this._scrollHost.scrollTop = d, this._scrollHost.scrollLeft = f), this._mountVisible();
1829
- }
1830
- _resetCommentNavigation() {
1831
- this._commentNavigationGeneration++, this._commentPageById.clear(), this._commentRunsByPage.clear(), this._commentIndexedPages.clear(), this._commentScanFrontier = 0;
1832
- }
1833
- _advanceCommentScanFrontier() {
1834
- for (; this._commentIndexedPages.has(this._commentScanFrontier);) this._commentScanFrontier++;
1835
- }
1836
- _indexCommentPages(e, t, n) {
1837
- if (!this._commentIndexedPages.has(e)) {
1838
- for (let r of n) this._commentPageById.has(r.commentId) || j(r, t).length > 0 && this._commentPageById.set(r.commentId, e);
1839
- this._commentIndexedPages.add(e), this._advanceCommentScanFrontier();
1840
- }
1841
- }
1842
- async _commentRunsForPage(e, t) {
1843
- for (; !this._destroyed && this._doc === t;) {
1844
- let n = this._scale, r = this._commentRunsByPage.get(e);
1845
- (!r || r.scale !== n) && (r = {
1846
- scale: n,
1847
- runs: t.collectPageRuns(e, {
1848
- width: this._pageWidthPx(e),
1849
- currentDate: this._opts.currentDate
1850
- })
1851
- }, this._commentRunsByPage.set(e, r));
1852
- try {
1853
- let e = await r.runs;
1854
- if (this._destroyed || this._doc !== t) return null;
1855
- if (this._scale !== n) continue;
1856
- return e;
1857
- } catch (t) {
1858
- throw this._commentRunsByPage.get(e) === r && this._commentRunsByPage.delete(e), t;
1859
- }
1860
- }
1861
- return null;
1862
- }
1863
- async goToComment(e, t) {
1864
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
1865
- let n = this._doc;
1866
- if (!n || !n.comments.some((t) => t.id === e && t.parentId === void 0)) return !1;
1867
- let r = ++this._commentNavigationGeneration, i = n.commentAnchorRanges().filter((t) => t.commentId === e);
1868
- if (i.length === 0) return !1;
1869
- let a = t?.pageIndex;
1870
- if (a !== void 0 && (!Number.isInteger(a) || a < 0 || a >= n.pageCount)) return !1;
1871
- let o = a ?? this._commentPageById.get(e), s;
1872
- if (a === void 0 && o === void 0) {
1873
- let t = n.commentAnchorRanges();
1874
- for (; o === void 0 && this._commentScanFrontier < n.pageCount;) {
1875
- let i = this._commentScanFrontier, a = await this._commentRunsForPage(i, n);
1876
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
1877
- if (this._doc !== n || r !== this._commentNavigationGeneration || !a) return !1;
1878
- this._indexCommentPages(i, a, t), o = this._commentPageById.get(e);
1879
- }
1880
- }
1881
- if (o === void 0) return !1;
1882
- let c = await this._commentRunsForPage(o, n);
1883
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
1884
- if (this._doc !== n || r !== this._commentNavigationGeneration || !c || (s = i.flatMap((e) => j(e, c))[0], !s)) return !1;
1885
- this._activeCommentId = e, this._activeCommentPage = o, this._elementContext = null, this._scrollToPageTarget(o, s, t);
1886
- for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
1887
- return this._emitSelectionContextChange(), !0;
1888
- }
1889
- async findText(e, t = {}) {
1890
- if (!this._doc) return [];
1891
- this._findActive = e.length > 0;
1892
- let n = await this._find.find(e, t);
1893
- return this._redrawHighlights(), n;
1894
- }
1895
- async findNext() {
1896
- return this._activateMatch(this._find.next());
1897
- }
1898
- async findPrev() {
1899
- return this._activateMatch(this._find.prev());
1900
- }
1901
- clearFind() {
1902
- this._findActive = !1, this._find.invalidate(), this._redrawHighlights();
1903
- }
1904
- async _activateMatch(e) {
1905
- return e && this.scrollToPage(e.location.page), this._redrawHighlights(), e;
1906
- }
1907
- async _collectPageRuns(e) {
1908
- return this._doc ? this._doc.collectPageRuns(e, {
1909
- width: this._pageWidthPx(e),
1910
- currentDate: this._opts.currentDate
1911
- }) : [];
1912
- }
1913
- _redrawHighlights() {
1914
- for (let [e, t] of this._slots) this._redrawSlotHighlights(e, t);
1915
- }
1916
- _refreshFindRuns(e, t) {
1917
- this._findActive && this._find.setPageRuns(e, t);
1918
- }
1919
- _commitCommentRuns(e, t, n) {
1920
- t.commentTintLayer && (t.commentRuns = Object.freeze([...n]), this._commentRunsByPage.set(e, {
1921
- scale: this._scale,
1922
- runs: Promise.resolve(t.commentRuns)
1923
- }), this._doc && e === this._commentScanFrontier && this._indexCommentPages(e, t.commentRuns, this._doc.commentAnchorRanges()), t.commentTintLayer.style.transform = "", t.commentTintLayer.style.transformOrigin = "", this._redrawSlotComments(e, t), t.commentTintLayer.style.visibility = "", t.commentMargin && (t.commentMargin.style.visibility = ""), t.commentDecorationLayer && (t.commentDecorationLayer.style.visibility = ""));
1924
- }
1925
- _redrawSlotComments(e, t) {
1926
- if (!this._doc || !t.commentTintLayer) return;
1927
- let n = this._commentUi;
1928
- if (!n) {
1929
- t.commentTintLayer.replaceChildren(), t.commentMargin?.replaceChildren(), t.commentDecorationLayer?.replaceChildren(), t.commentGeometry = null;
1930
- return;
1931
- }
1932
- t.commentGeometry = n.buildDocxCommentMargin(t.commentTintLayer, t.commentMargin, t.commentRuns, {
1933
- comments: this._doc.comments,
1934
- anchors: this._doc.commentAnchorRanges()
1935
- }, this._pageWidthPx(e), this._pageHeightPx(e), this._activeCommentId, (t, n) => {
1936
- let r = n ? t : this._activeCommentId === t ? null : this._activeCommentId;
1937
- if (r !== this._activeCommentId) {
1938
- this._activeCommentId = r, this._activeCommentPage = r ? e : null, this._elementContext = null;
1939
- for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
1940
- this._emitSelectionContextChange();
1941
- }
1942
- }, this._commentZoom(), 280, this._commentsOptions()?.markers !== !1, this._commentsOptions()?.includeResolved === !0, t.commentDecorationLayer ? () => this._scheduleCommentGeometry(e, t, !1) : void 0, t.commentDecorationLayer ? () => this._scheduleCommentGeometry(e, t, !0) : void 0), this._redrawSlotCommentConnectors(e, t);
1943
- }
1944
- _redrawSlotCommentConnectors(e, t) {
1945
- let n = t.commentDecorationLayer, r = t.commentMargin, i = t.commentGeometry, a = this._commentsOptions()?.connectors;
1946
- if (!n || !r || !i || !a) return;
1947
- let o = this._pageWidthPx(e), s = this._pageHeightPx(e), c = this._commentSide(), l = this._commentMarginExtent(), u = this._commentUi;
1948
- u && u.buildReadOnlyCommentDecoration(n, Object.freeze({
1949
- surfaceBounds: Object.freeze({
1950
- x: c === "left" ? -l : 0,
1951
- y: 0,
1952
- width: o + l,
1953
- height: s
1954
- }),
1955
- contentBounds: Object.freeze({
1956
- x: 0,
1957
- y: 0,
1958
- width: o,
1959
- height: s
1960
- }),
1961
- side: c,
1962
- threads: u.projectReadOnlyCommentMarginScroll(i, r.scrollTop)
1963
- }), {
1964
- route: a.route ?? "bezier",
1965
- stroke: a.stroke ?? "solid",
1966
- color: a.color,
1967
- activeColor: a.activeColor
1968
- });
1969
- }
1970
- _scheduleCommentGeometry(e, t, n = !1) {
1971
- let r = this._pendingCommentGeometry.get(e);
1972
- if (this._pendingCommentGeometry.set(e, {
1973
- slot: t,
1974
- connectorsOnly: r?.slot === t ? r.connectorsOnly && n : n
1975
- }), this._commentGeometryScheduled) return;
1976
- this._commentGeometryScheduled = !0;
1977
- let i = () => {
1978
- this._commentGeometryScheduled = !1, this._commentGeometryFrame = null;
1979
- let e = [...this._pendingCommentGeometry];
1980
- if (this._pendingCommentGeometry.clear(), !this._destroyed) for (let [t, n] of e) {
1981
- let { slot: e, connectorsOnly: r } = n;
1982
- this._slots.get(t) === e && e.renderedScale === this._scale && (r ? this._redrawSlotCommentConnectors(t, e) : this._redrawSlotComments(t, e));
1983
- }
1984
- }, a = this._wrapper.ownerDocument.defaultView;
1985
- a?.requestAnimationFrame ? this._commentGeometryFrame = a.requestAnimationFrame(i) : queueMicrotask(i);
1986
- }
1987
- _redrawSlotHighlights(e, t) {
1988
- if (!this._findActive) {
1989
- t.highlightLayer.innerHTML = "";
1990
- return;
1991
- }
1992
- let n = this._find.pageRuns(e);
1993
- if (!n) {
1994
- t.highlightLayer.innerHTML = "";
1995
- return;
1996
- }
1997
- Y(t.highlightLayer, n, this._find.pageHighlights(e), this._pageWidthPx(e), this._pageHeightPx(e), (e) => this._measureForFont(e), this._opts.findHighlightColors);
1998
- }
1999
- _onResize() {
2000
- if (!this._doc || this._doc.pageCount === 0) return;
2001
- if (!this._scaleEstablished) {
2002
- this.relayout();
2003
- return;
2004
- }
2005
- if (this._opts.refitOnResize === !1) {
2006
- this._lastFitWidth = this._fitWidthPx(), this._mountVisible();
2007
- return;
2008
- }
2009
- let e = this._baseScale();
2010
- if (e <= 0) return;
2011
- let t = this._fitWidthPx();
2012
- if (t === this._lastFitWidth) {
2013
- this._mountVisible();
2014
- return;
2015
- }
2016
- this._lastFitWidth = t;
2017
- let n = this._prevBase > 0 ? this._scale / this._prevBase : 1;
2018
- this._prevBase = e, this.setScale(e * n), this._mountVisible();
2019
- }
2020
- get topVisiblePage() {
2021
- return this._lastRange?.topIndex ?? 0;
2022
- }
2023
- mountedPageIndicesForTest() {
2024
- return [...this._slots.keys()];
2025
- }
2026
- scaleForTest() {
2027
- return this._scale;
2028
- }
2029
- baseScaleForTest() {
2030
- return this._baseScale();
2031
- }
2032
- renderEpochForTest() {
2033
- return this._renderEpoch;
2034
- }
2035
- resizeForTest() {
2036
- this._onResize();
2037
- }
2038
- contentAtViewportYForTest(e) {
2039
- let t = this._range(), n = this._scrollHost.scrollTop + e, r = this._pageIndexAtOffset(t, n), i = this._heights[r] || 0;
2040
- return {
2041
- page: r,
2042
- frac: i > 0 ? Math.min(1, Math.max(0, (n - t.offsets[r]) / i)) : 0
2043
- };
2044
- }
2045
- viewportYOfForTest(e, t) {
2046
- return (this._range().offsets[e] ?? 0) + t * (this._heights[e] || 0) - this._scrollHost.scrollTop;
2047
- }
2048
- async getResourceMetrics() {
2049
- if (!this._doc) throw Error("Document not loaded");
2050
- return await this._doc.getResourceMetrics();
2051
- }
2052
- getSelectionContext(e = {}) {
2053
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2054
- return (this._doc && this._activeCommentId !== null && this._activeCommentPage !== null ? kt(this._doc.comments, this._doc.commentAnchorRanges(), this._activeCommentId, this._activeCommentPage, e) : null) || ((this._opts.enableTextSelection ? X(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null, e) : null) ?? (this._elementContext ? R(this._elementContext, e.maxTextCharacters) : null));
2055
- }
2056
- _emitSelectionContextChange() {
2057
- let e = this.getSelectionContext();
2058
- e?.kind === "text" && (this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutlines());
2059
- let t = JSON.stringify(e);
2060
- t !== this._selectionContextKey && (this._selectionContextKey = t, this._opts.onSelectionContextChange?.(e ? structuredClone(e) : null));
2061
- }
2062
- _setElementContext(e) {
2063
- this._elementContext = e ? structuredClone(e) : null, this._redrawElementOutlines(), this._emitSelectionContextChange();
2064
- }
2065
- _invalidateElementContext(e = !0) {
2066
- this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutlines(), e && this._emitSelectionContextChange();
2067
- }
2068
- _redrawElementOutlines() {
2069
- for (let [e, t] of this._slots) this._redrawElementOutlineForSlot(e, t);
2070
- }
2071
- _redrawElementOutlineForSlot(e, t) {
2072
- let n = this._elementContext, r = this._doc;
2073
- if (!n || !r || n.pageIndex !== e) {
2074
- v(t.elementLayer, null);
2075
- return;
2076
- }
2077
- let i = r.pageSize(e);
2078
- v(t.elementLayer, {
2079
- x: n.bounds.xPt / i.widthPt,
2080
- y: n.bounds.yPt / i.heightPt,
2081
- width: n.bounds.widthPt / i.widthPt,
2082
- height: n.bounds.heightPt / i.heightPt
2083
- });
2084
- }
2085
- async _onElementClick(e) {
2086
- this._destroyed || e.defaultPrevented || e.button !== 0 || await this._resolveContextAt(e);
2087
- }
2088
- _onContextMenu(e) {
2089
- let t;
2090
- this._opts.onContextMenu?.({
2091
- originalEvent: e,
2092
- getContext: () => t ??= this._resolveContextAt(e)
2093
- });
2094
- }
2095
- async _resolveContextAt(e) {
2096
- let t = this._doc;
2097
- if (this._destroyed || !t) return null;
2098
- if (this._opts.enableTextSelection && X(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null)) return this._emitSelectionContextChange(), this._destroyed ? null : this.getSelectionContext();
2099
- if (!this._opts.enableElementSelection) return this.getSelectionContext();
2100
- let n = e.target, r = [...this._slots].find(([, e]) => n !== null && e.wrapper.contains(n));
2101
- if (!r) return this._invalidateElementContext(), null;
2102
- let [i, a] = r, o = a.canvas.getBoundingClientRect();
2103
- if (o.width <= 0 || o.height <= 0) return this._invalidateElementContext(), null;
2104
- let s = e.clientX - o.left, c = e.clientY - o.top;
2105
- if (s < 0 || c < 0 || s > o.width || c > o.height) return this._invalidateElementContext(), null;
2106
- let l = ++this._elementHitGeneration, u = t.pageSize(i), d;
2107
- try {
2108
- d = await t.getElementContextAt(i, {
2109
- xPt: s / o.width * u.widthPt,
2110
- yPt: c / o.height * u.heightPt
2111
- }, {
2112
- currentDate: this._opts.currentDate,
2113
- maxTextCharacters: P
2114
- });
2115
- } catch (e) {
2116
- if (this._destroyed || l !== this._elementHitGeneration || t !== this._doc) return null;
2117
- throw e;
2118
- }
2119
- return this._destroyed || l !== this._elementHitGeneration || t !== this._doc ? null : (this._setElementContext(d), this._destroyed ? null : this.getSelectionContext());
2120
- }
2121
- destroy() {
2122
- if (!this._destroyed) {
2123
- this._destroyed = !0, this._resetCommentNavigation(), this._find.invalidate(), this._findActive = !1, this._selectionChangeListener &&= (this._wrapper.ownerDocument.removeEventListener("selectionchange", this._selectionChangeListener), null), this._elementHitGeneration++, this._elementClickListener &&= (this._scrollHost.removeEventListener("click", this._elementClickListener), null), this._contextMenuListener &&= (this._scrollHost.removeEventListener("contextmenu", this._contextMenuListener), null), this._commentOutsidePointerListener &&= (this._wrapper.ownerDocument.removeEventListener("pointerdown", this._commentOutsidePointerListener), null), this._commentGeometryFrame !== null && (this._wrapper.ownerDocument.defaultView?.cancelAnimationFrame?.(this._commentGeometryFrame), this._commentGeometryFrame = null), this._commentGeometryScheduled = !1, this._pendingCommentGeometry.clear(), this._elementContext = null, this._scrollListener &&= (this._scrollHost.removeEventListener("scroll", this._scrollListener), null), this._wheelListener &&= (this._scrollHost.removeEventListener("wheel", this._wheelListener), null), this._resizeObserver?.disconnect(), this._resizeObserver = null, this._settleTimer !== null && (clearTimeout(this._settleTimer), this._settleTimer = null);
2124
- for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
2125
- this._free.length = 0, this._documentOwner.close(), this._wrapper.remove();
2126
- }
2127
- }
2128
- };
2129
- //#endregion
2130
- //#region packages/docx/src/types.ts
2131
- function Ht(e) {
2132
- let t = [];
2133
- for (let n of e.content) {
2134
- if (n.type !== "paragraph") continue;
2135
- let e = "";
2136
- for (let t of n.runs) t.type === "text" && !t.noteRef && (e += t.text);
2137
- e = e.trim(), e && t.push(e);
2138
- }
2139
- return t.join(" ");
2140
- }
2141
- //#endregion
2142
- //#region src/docx.ts
2143
- var Ut = /* @__PURE__ */ e({
2144
- DocxDocument: () => K,
2145
- DocxScrollViewer: () => Vt,
2146
- DocxViewer: () => Q,
2147
- OoxmlDecodedImageLimitError: () => Ve,
2148
- OoxmlError: () => i,
2149
- OoxmlResourceLimitError: () => o,
2150
- autoResize: () => pe,
2151
- buildDocxHighlightLayer: () => Y,
2152
- buildDocxTextLayer: () => J,
2153
- isOoxmlDecodedImageLimitError: () => He,
2154
- noteText: () => Ht,
2155
- openExternalHyperlink: () => s,
2156
- readDocxTextSelectionContext: () => X,
2157
- resolveCommentAnchorRuns: () => j,
2158
- resolveDocxCommentThreads: () => M,
2159
- resolveRevisionAnchorRuns: () => U
2160
- });
2161
- //#endregion
2162
- export { X as a, K as c, Q as i, U as l, Ht as n, Y as o, Vt as r, J as s, Ut as t };