@silurus/ooxml 0.87.0 → 0.89.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/README.md +118 -23
  2. package/THIRD_PARTY_NOTICES.md +7 -6
  3. package/dist/abort-VrnK7mdP.js +10 -0
  4. package/dist/assets/render-worker-CUOU6mL2.js +16 -0
  5. package/dist/assets/render-worker-DOqrFhSU.js +15 -0
  6. package/dist/assets/render-worker-DvWUdZUN.js +35 -0
  7. package/dist/bounded-raw-part-cache-B7JoC1CD.js +64586 -0
  8. package/dist/bundled-asset-url-E2nXURF9.js +15 -0
  9. package/dist/canvas-viewer-mechanics-DfQqRKkD.js +675 -0
  10. package/dist/cfb-guard-9QTRTg7f.js +528 -0
  11. package/dist/chart-ex.mjs +708 -739
  12. package/dist/comment-overlay-controller-B5_zGgG5.js +994 -0
  13. package/dist/comment-ui-runtime-B7ZvovcS.js +2 -0
  14. package/dist/{comment-ui-runtime-DcJOYlw-.js → comment-ui-runtime-D_sb2K6s.js} +5 -5
  15. package/dist/{comment-ui-runtime-BfE7MJZn.js → comment-ui-runtime-Jy-3goA9.js} +5 -5
  16. package/dist/delimited-text-worker-host-CikWU6_m.js +27 -0
  17. package/dist/document-model-source-BKNrXjAL.js +249 -0
  18. package/dist/document-pull-client-CxONDGbk.js +37833 -0
  19. package/dist/document-pull-worker-AMyXYpPq.js +104 -0
  20. package/dist/docx-D91ER1_S.js +495 -0
  21. package/dist/docx-DhDnKEI6.js +3563 -0
  22. package/dist/docx-model-source-CdrSt3hF.js +98 -0
  23. package/dist/docx-source-worker.mjs +455 -0
  24. package/dist/docx.mjs +7 -7
  25. package/dist/docx_parser_bg.wasm +0 -0
  26. package/dist/drawingml-shape-ChcGZNd8.js +310 -0
  27. package/dist/duotone-ekYik4ix.js +126 -0
  28. package/dist/emf-UT6I8rVi.js +1790 -0
  29. package/dist/font-preload-demand-CdJZUMCT.js +2058 -0
  30. package/dist/grid-geometry-uQOgViJU.js +384 -0
  31. package/dist/host-layout-DVMw8hDY.js +56 -0
  32. package/dist/host-layout-measure-CCEgaC_v.js +7 -0
  33. package/dist/in-process-pull-transport-DuXcPZng.js +29 -0
  34. package/dist/index.mjs +4 -4
  35. package/dist/internal-companion.mjs +12 -0
  36. package/dist/line-distribute-CPOV6csk.js +2716 -0
  37. package/dist/math.mjs +2 -2
  38. package/dist/mathjax-stix2.js +10 -10
  39. package/dist/model-source-DJGzDtGb.js +61 -0
  40. package/dist/model-source-kz_NkZqT.js +179 -0
  41. package/dist/model-source-session-Bu9CHFHc.js +71 -0
  42. package/dist/model-source-session-CDuijwv1.js +85 -0
  43. package/dist/model-source-session-sKpNiIJI.js +58 -0
  44. package/dist/node.mjs +7 -1327
  45. package/dist/{pixel-budget-Dgjw269h.js → pixel-budget-BpTYrepD.js} +13 -10
  46. package/dist/plot-area-frame-CaJFvZ7p.js +8502 -0
  47. package/dist/pptx-CDP9dZHe.js +2936 -0
  48. package/dist/pptx-C_uxLVKB.js +183 -0
  49. package/dist/pptx-model-source-O7LhpOjz.js +37 -0
  50. package/dist/pptx-source-worker.mjs +446 -0
  51. package/dist/pptx.mjs +8 -7
  52. package/dist/pptx_parser_bg.wasm +0 -0
  53. package/dist/presentation-model-source-tmROzteR.js +77 -0
  54. package/dist/raster-target-YQ4G6rxo.js +42 -0
  55. package/dist/region-map.mjs +114 -150
  56. package/dist/{render-8Zo7dnds.js → render-CJVglUHl.js} +3 -3
  57. package/dist/{render-worker-host-BfbnEChF.js → render-worker-host-BseIaVvm.js} +1 -1
  58. package/dist/{render-worker-host-DNL9dWRh.js → render-worker-host-CyxPU4JU.js} +1 -1
  59. package/dist/{render-worker-host-IkHrYOci.js → render-worker-host-aF6aWkC0.js} +1 -1
  60. package/dist/renderer-CkGLj0CC.js +5170 -0
  61. package/dist/renderer-Czw1cCC7.js +5823 -0
  62. package/dist/resource-measurement-mXw-WjMF.js +771 -0
  63. package/dist/session-Csv9maad.js +656 -0
  64. package/dist/slide-pull-client-DRZYwBTu.js +6515 -0
  65. package/dist/three-d-BK5siJgJ.js +878 -0
  66. package/dist/three-d.mjs +871 -764
  67. package/dist/{raster-target-ojDdQizC.js → tiff-contract-C6M3QcPp.js} +1 -42
  68. package/dist/tiff.mjs +401 -248
  69. package/dist/types/chart-ex.d.ts +289 -4
  70. package/dist/types/docx.d.ts +473 -98
  71. package/dist/types/index.d.ts +674 -303
  72. package/dist/types/internal-companion.d.ts +11 -0
  73. package/dist/types/math.d.ts +1 -1
  74. package/dist/types/node.d.ts +530 -11
  75. package/dist/types/pptx.d.ts +410 -97
  76. package/dist/types/region-map.d.ts +289 -4
  77. package/dist/types/three-d.d.ts +289 -4
  78. package/dist/types/tiff.d.ts +1 -1
  79. package/dist/types/xlsx.d.ts +483 -134
  80. package/dist/wasm-loader-rlgHmcSv.js +35 -0
  81. package/dist/wasm-runtime-generation-DX4y0Ecl.js +97 -0
  82. package/dist/workbook-model-source-BTC4ISTS.js +94 -0
  83. package/dist/worker-source-I1cIYBel.js +22 -0
  84. package/dist/worker-source-SbudzjYL.js +22 -0
  85. package/dist/worker-source-UAi3GNcM.js +22 -0
  86. package/dist/worksheet-pull-client-CkHgbtyM.js +579 -0
  87. package/dist/xlsx-CpSDPAEU.js +5809 -0
  88. package/dist/xlsx-D5569TPf.js +534 -0
  89. package/dist/xlsx-model-source-DPSkjFic.js +309 -0
  90. package/dist/xlsx-source-worker.mjs +525 -0
  91. package/dist/xlsx.mjs +8 -7
  92. package/dist/xlsx_parser_bg.wasm +0 -0
  93. package/package.json +42 -16
  94. package/dist/assets/render-worker-CeK_iqK3.js +0 -10
  95. package/dist/assets/render-worker-DusrDhPk.js +0 -11
  96. package/dist/assets/render-worker-n2ZG0lrQ.js +0 -31
  97. package/dist/bounded-raw-part-cache-Cg1BsSZQ.js +0 -119
  98. package/dist/canvas-viewer-mechanics-Cpk0YFvM.js +0 -1384
  99. package/dist/cjk-fallback-bLI3z70h.js +0 -46
  100. package/dist/comment-occurrence-C8Y2uoVr.js +0 -6
  101. package/dist/comment-ui-runtime-BsK8pmUT.js +0 -2
  102. package/dist/comments-Diid5ujN.js +0 -246
  103. package/dist/delimited-text-worker-host-BVY-Ecni.js +0 -27
  104. package/dist/document-pull-client-yKxI8aDH.js +0 -27251
  105. package/dist/docx-BkSRiy07.js +0 -2995
  106. package/dist/dom-interaction-boundary-CBUQJsIM.js +0 -223
  107. package/dist/highlight-rect-C5hkRqUr.js +0 -13
  108. package/dist/hyperlink-ArrU3ArU.js +0 -36447
  109. package/dist/line-distribute-Dtudnqhs.js +0 -1023
  110. package/dist/line-metrics-B60C86uh.js +0 -60
  111. package/dist/plot-area-frame-D5hEOgkJ.js +0 -2903
  112. package/dist/pptx-62MmVbYB.js +0 -3063
  113. package/dist/renderer-XFSCOT6m.js +0 -5857
  114. package/dist/resource-measurement-CJsgolre.js +0 -150
  115. package/dist/session-CrU8f8DI.js +0 -743
  116. package/dist/slide-pull-client-B9KA8bU6.js +0 -6253
  117. package/dist/source-key-DIJG8BA0.js +0 -42
  118. package/dist/three-d-YYghQndN.js +0 -1346
  119. package/dist/transfer-p6iCC2R7.js +0 -6
  120. package/dist/units-EJdC96r6.js +0 -4
  121. package/dist/worksheet-pull-client-eIcQ-xlD.js +0 -458
  122. package/dist/xlsx-CRcSzZNq.js +0 -8482
  123. /package/dist/{chunk-DmhlhrBa.js → chunk-Dy4uBu1J.js} +0 -0
  124. /package/dist/{mathjax-DoyWZbSp.js → mathjax-BhwN6ilc.js} +0 -0
  125. /package/dist/{read-only-comment-decoration-Dz7eTQ4d.js → read-only-comment-decoration-PidH0wnP.js} +0 -0
  126. /package/dist/{read-only-comment-margin-DkgzASAl.js → read-only-comment-margin-B52rDVKo.js} +0 -0
  127. /package/dist/{renderer-module-contract-D91rkYHH.js → renderer-module-contract-CWM7jv6d.js} +0 -0
  128. /package/dist/{visible-index-BgiHEc1z.js → visible-index-FeVA0mGE.js} +0 -0
@@ -1,2995 +0,0 @@
1
- import { t as e } from "./chunk-DmhlhrBa.js";
2
- import { $ as t, $t as n, L as r, R as i, U as a, _t as o, ft as s, ln as c, lt as l, r as u, un as d, z as f } from "./hyperlink-ArrU3ArU.js";
3
- import { C as p, D as m, M as h, N as g, O as _, S as v, T as y, _ as b, a as x, b as ee, c as S, d as te, f as ne, g as re, h as ie, i as C, l as w, m as ae, n as oe, o as se, p as ce, r as le, s as ue, t as de, u as fe, v as pe, w as me, x as he, y as ge } from "./canvas-viewer-mechanics-Cpk0YFvM.js";
4
- import { c as _e, d as ve, f as ye, i as be, l as xe, n as Se, o as T, r as Ce, s as we, t as Te, u as Ee } from "./dom-interaction-boundary-CBUQJsIM.js";
5
- import { A as De, C as E, D as Oe, E as ke, M as Ae, O as D, S as je, T as Me, _ as Ne, a as Pe, b as Fe, c as Ie, d as Le, f as Re, g as ze, h as Be, j as Ve, k as He, l as Ue, m as We, n as Ge, o as Ke, p as qe, s as Je, t as O, v as Ye, w as Xe, x as Ze, y as Qe } from "./document-pull-client-yKxI8aDH.js";
6
- import { n as $e } from "./cjk-fallback-bLI3z70h.js";
7
- import { l as et, s as tt } from "./pixel-budget-Dgjw269h.js";
8
- import { a as k } from "./units-EJdC96r6.js";
9
- import { i as nt, s as rt } from "./raster-target-ojDdQizC.js";
10
- import { n as it } from "./renderer-module-contract-D91rkYHH.js";
11
- import { n as at, t as A } from "./highlight-rect-C5hkRqUr.js";
12
- import { t as ot } from "./bounded-raw-part-cache-Cg1BsSZQ.js";
13
- import { o as j } from "./source-key-DIJG8BA0.js";
14
- import { i as st, n as M, r as ct, t as lt } from "./comments-Diid5ujN.js";
15
- //#region packages/core/src/fonts/open-type-metrics.ts
16
- var N = (e) => (e.charCodeAt(0) << 24 >>> 0 | e.charCodeAt(1) << 16 | e.charCodeAt(2) << 8 | e.charCodeAt(3)) >>> 0, ut = N("ttcf"), dt = N("OTTO"), ft = N("true"), pt = N("typ1"), mt = N("head"), ht = N("hhea"), gt = N("OS/2"), _t = N("cmap"), P = [
17
- [4352, 4607],
18
- [11904, 12287],
19
- [12352, 12543],
20
- [12544, 12591],
21
- [12592, 12687],
22
- [12704, 12735],
23
- [12784, 12799],
24
- [13312, 19903],
25
- [19968, 40959],
26
- [40960, 42191],
27
- [43360, 43391],
28
- [44032, 55203],
29
- [63744, 64255],
30
- [131072, 205743]
31
- ];
32
- function F(e, t, n) {
33
- return Number.isSafeInteger(t) && Number.isSafeInteger(n) && t >= 0 && n >= 0 && t <= e - n;
34
- }
35
- function vt(e, t, n) {
36
- if (n < 16) return !1;
37
- let r = e.getUint16(t + 2);
38
- if (r < 16 || r > n) return !1;
39
- let i = e.getUint16(t + 6);
40
- if (i === 0 || i % 2 != 0) return !1;
41
- let a = i / 2, o = t + 14, s = o + a * 2 + 2, c = s + a * 2, l = c + a * 2;
42
- if (l + a * 2 > t + r) return !1;
43
- let u = -1;
44
- for (let t = 0; t < a; t++) {
45
- let n = e.getUint16(s + t * 2), r = e.getUint16(o + t * 2);
46
- if (n > r || n <= u) return !1;
47
- u = r;
48
- }
49
- for (let n = 0; n < a; n++) {
50
- let i = e.getUint16(s + n * 2), a = e.getUint16(o + n * 2), u = e.getInt16(c + n * 2), d = l + n * 2, f = e.getUint16(d);
51
- for (let [n, o] of P) {
52
- let s = Math.max(i, n), c = Math.min(a, o);
53
- if (!(s > c)) {
54
- if (f === 0) {
55
- if (s < c || s + u & 65535) return !0;
56
- continue;
57
- }
58
- for (let n = s; n <= c; n++) {
59
- let a = d + f + (n - i) * 2;
60
- if (a + 2 > t + r) break;
61
- let o = e.getUint16(a);
62
- if (o !== 0 && o + u & 65535) return !0;
63
- }
64
- }
65
- }
66
- }
67
- return !1;
68
- }
69
- function yt(e, t, n, r) {
70
- if (n < 16) return !1;
71
- let i = e.getUint32(t + 4), a = e.getUint32(t + 12);
72
- if (i < 16 || i > n || a > (i - 16) / 12) return !1;
73
- let o = -1;
74
- for (let n = 0; n < a; n++) {
75
- let i = t + 16 + n * 12, a = e.getUint32(i), s = e.getUint32(i + 4), c = e.getUint32(i + 8);
76
- if (a > s || s > 1114111 || a <= o) return !1;
77
- if (o = s, a > P[P.length - 1][1]) break;
78
- for (let [e, t] of P) {
79
- let n = Math.max(a, e), i = Math.min(s, t);
80
- if (!(n > i)) {
81
- if (r) {
82
- if (c !== 0) return !0;
83
- } else if (n < i || c + (n - a) !== 0) return !0;
84
- }
85
- }
86
- }
87
- return !1;
88
- }
89
- function bt(e, t) {
90
- if (!t || t.length < 4) return !1;
91
- let n = e.getUint16(t.offset + 2);
92
- if (4 + n * 8 > t.length) return !1;
93
- for (let r = 0; r < n; r++) {
94
- let n = t.offset + 4 + r * 8, i = e.getUint16(n), a = e.getUint16(n + 2);
95
- if (i !== 0 && !(i === 3 && (a === 1 || a === 10))) continue;
96
- let o = e.getUint32(n + 4);
97
- if (o > t.length - 2) continue;
98
- let s = t.offset + o, c = t.length - o, l = e.getUint16(s);
99
- if (l === 4 && vt(e, s, c) || l === 12 && yt(e, s, c, !1) || l === 13 && yt(e, s, c, !0)) return !0;
100
- }
101
- return !1;
102
- }
103
- function xt(e, t) {
104
- if (t !== void 0 && (!Number.isSafeInteger(t) || t < 0) || e.byteLength < 12) return null;
105
- let n = new DataView(e.buffer, e.byteOffset, e.byteLength), r = 0;
106
- if (n.getUint32(0) === ut) {
107
- if (t === void 0 || e.byteLength < 12) return null;
108
- let i = n.getUint32(8);
109
- if (t >= i || !F(e.byteLength, 12, i * 4)) return null;
110
- r = n.getUint32(12 + t * 4);
111
- } else if (t !== void 0 && t !== 0) return null;
112
- if (!F(e.byteLength, r, 12)) return null;
113
- let i = n.getUint32(r);
114
- if (i !== 65536 && i !== dt && i !== ft && i !== pt) return null;
115
- let a = n.getUint16(r + 4);
116
- if (!F(e.byteLength, r + 12, a * 16)) return null;
117
- let o = /* @__PURE__ */ new Map();
118
- for (let t = 0; t < a; t++) {
119
- let i = r + 12 + t * 16, a = n.getUint32(i), s = n.getUint32(i + 8), c = n.getUint32(i + 12);
120
- if (o.has(a) || !F(e.byteLength, s, c)) return null;
121
- o.set(a, {
122
- offset: s,
123
- length: c
124
- });
125
- }
126
- let s = o.get(mt), c = o.get(ht);
127
- if (!s || s.length < 20 || !c || c.length < 10) return null;
128
- let l = n.getUint16(s.offset + 18);
129
- if (l < 16 || l > 16384) return null;
130
- let u = o.get(gt), d = u !== void 0 && u.length >= 78;
131
- return Object.freeze({
132
- unitsPerEm: l,
133
- hheaAscent: n.getInt16(c.offset + 4),
134
- hheaDescent: n.getInt16(c.offset + 6),
135
- hheaLineGap: n.getInt16(c.offset + 8),
136
- hasEastAsianCmap: bt(n, o.get(_t)),
137
- ...d ? {
138
- typoAscent: n.getInt16(u.offset + 68),
139
- typoDescent: n.getInt16(u.offset + 70),
140
- typoLineGap: n.getInt16(u.offset + 72),
141
- winAscent: n.getUint16(u.offset + 74),
142
- winDescent: n.getUint16(u.offset + 76),
143
- useTypoMetrics: (n.getUint16(u.offset + 62) & 128) != 0
144
- } : {}
145
- });
146
- }
147
- //#endregion
148
- //#region packages/docx/src/worker.ts?worker&inline
149
- var St = "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();v.__wbg_docxarchive_free(e,0)}acknowledge_document_chunk(e,t,n){let r=v.docxarchive_acknowledge_document_chunk(this.__wbg_ptr,e,t,n);if(r[1])throw p(r[0])}assert_healthy(){let e=v.docxarchive_assert_healthy(this.__wbg_ptr);if(e[1])throw p(e[0])}cancel_document_cursor(){v.docxarchive_cancel_document_cursor(this.__wbg_ptr)}close_document_session(){v.docxarchive_close_document_session(this.__wbg_ptr)}document_chunk_done(){let e=v.docxarchive_document_chunk_done(this.__wbg_ptr);if(e[2])throw p(e[1]);return e[0]!==0}document_cursor_resource_usage(){let e=v.docxarchive_document_cursor_resource_usage(this.__wbg_ptr);if(e[3])throw p(e[2]);var t=i(e[0],e[1]).slice();return v.__wbindgen_free(e[0],e[1]*1,1),t}extract_image(e){let t=f(e,v.__wbindgen_malloc,v.__wbindgen_realloc),n=_,r=v.docxarchive_extract_image(this.__wbg_ptr,t,n);if(r[3])throw p(r[2]);var a=i(r[0],r[1]).slice();return v.__wbindgen_free(r[0],r[1]*1,1),a}constructor(e,t,n,i){let a=d(e,v.__wbindgen_malloc),o=_,s=v.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 p(s[1]);return this.__wbg_ptr=s[0]>>>0,r.register(this,this.__wbg_ptr,this),this}open_document_cursor(e,t){let n=v.docxarchive_open_document_cursor(this.__wbg_ptr,e,t);if(n[1])throw p(n[0])}parse(){let e=v.docxarchive_parse(this.__wbg_ptr);if(e[3])throw p(e[2]);var t=i(e[0],e[1]).slice();return v.__wbindgen_free(e[0],e[1]*1,1),t}pull_document_chunk(e,t,n,r){let a=v.docxarchive_pull_document_chunk(this.__wbg_ptr,e,t,n,r);if(a[3])throw p(a[2]);var o=i(a[0],a[1]).slice();return v.__wbindgen_free(a[0],a[1]*1,1),o}resource_usage(){let e=v.docxarchive_resource_usage(this.__wbg_ptr);if(e[3])throw p(e[2]);var t=i(e[0],e[1]).slice();return v.__wbindgen_free(e[0],e[1]*1,1),t}to_markdown(){let e,t;try{let i=v.docxarchive_to_markdown(this.__wbg_ptr);var n=i[0],r=i[1];if(i[3])throw n=0,r=0,p(i[2]);return e=n,t=r,s(n,r)}finally{v.__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{v.__wbindgen_free(n,r,1)}},__wbg_new_227d7c05414eb861:function(){return Error()},__wbg_stack_3b0d974bbf31e44f:function(e,t){let n=t.stack,r=f(n,v.__wbindgen_malloc,v.__wbindgen_realloc),i=_;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=v.__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=>v.__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!==v.memory.buffer)&&(a=new DataView(v.memory.buffer)),a}function s(e,t){return e>>>=0,ee(e,t)}let c=null;function l(){return(c===null||c.byteLength===0)&&(c=new Uint8Array(v.memory.buffer)),c}function u(e){return e==null}function d(e,t){let n=t(e.length*1,1)>>>0;return l().set(e,n/1),_=e.length,n}function f(e,t,n){if(n===void 0){let n=g.encode(e),r=t(n.length,1)>>>0;return l().subarray(r,r+n.length).set(n),_=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=g.encodeInto(e,t);o+=a.written,i=n(i,r,o,1)>>>0}return _=o,i}function p(e){let t=v.__wbindgen_externrefs.get(e);return v.__externref_table_dealloc(e),t}let m=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0});m.decode();let h=0;function ee(e,t){return h+=t,h>=2146435072&&(m=new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!0}),m.decode(),h=t),m.decode(l().subarray(e,e+t))}const g=new TextEncoder;`encodeInto`in g||(g.encodeInto=function(e,t){let n=g.encode(e);return t.set(n),{read:e.length,written:n.length}});let _=0,v;function te(e,t){return v=e.exports,a=null,c=null,v.__wbindgen_start(),v}async function ne(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 y(e){if(v!==void 0)return v;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 ne(await e,t);return te(r,i)}async function b(e){return v=void 0,a=null,c=null,y(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)}};function re(e){return e===`image-dimension`||e===`image-pixels`||e===`active-decoded-bytes`}function C(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function ie(e){if(!(!e||typeof e!=`object`))try{let t=e,n=t.code,r=t.metric,i=t.limit,a=t.observed;return n!==`ooxml-decoded-image-limit`||!re(r)||!C(i)||!C(a)||a<=i?void 0:{metric:r,limit:i,observed:a}}catch{return}}var w,T,E,D=e((()=>{w=1<<25,T=1<<27,w*4,T*4,E=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 O(e){if(!(typeof e!=`object`||!e))try{let t=e,n=t.code,r=t.message;return n===`ooxml-tiff-decode`&&typeof r==`string`?{message:r}:void 0}catch{return}}var ae=e((()=>{}));function oe(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 se=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`)}},k=class e extends Error{code=`parser-crashed`;constructor(t){super(t),this.name=`WasmTrapError`,Object.setPrototypeOf(this,e.prototype)}};function ce(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 le(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 ue(e,t){return e({module_or_path:t})}var de=class{runtime;wasmInput=null;currentArchive=null;constructor(e,t={}){this.init=e,this.options=t,this.runtime=new se(()=>this.invokeConfigured(this.init),()=>this.invokeConfigured(this.options.reinit??this.init),fe),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 k(`WASM parser was recycled`))}invokeConfigured(e){return this.wasmInput===null?Promise.reject(Error(`WasmParserHost: setWasmInput was never called`)):ue(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,le(e)}};function fe(e){return ce(e)?new k(`WASM parser trapped and was recycled: ${e instanceof Error?e.message:String(e)}`):null}function A(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function pe(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return A(t.requiredBytes)&&A(t.offeredBytes)&&t.requiredBytes>t.offeredBytes}var j=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 M(e){if(e instanceof j)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`||!pe(r)))return new j(r)}function me(e,t,n){let r=M(e);if(!(!r||r.offeredBytes!==t||r.requiredBytes>n))return r}D(),ae();const N=`OOXML_RESOURCE_LIMIT:`;function P(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function F(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return P(t.archiveEntryCount)&&P(t.declaredInflatedBytes)&&(t.largestInflatedEntryBytes===void 0||P(t.largestInflatedEntryBytes))&&P(t.distinctInflatedBytes)&&P(t.operationInflatedBytes)}function I(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw TypeError(`OOXML resource usage checkpoint is not valid JSON`)}if(!F(t))throw TypeError(`OOXML resource usage checkpoint is invalid`);return t}function L(e){return e===`docx`||e===`xlsx`||e===`pptx`}function R(e){return e===`container`||e===`decompression`||e===`parsing`||e===`serialization`||e===`layout`||e===`rendering`||e===`worker`}function z(e,t){return typeof e==`string`&&e.length>0&&e.length<=t&&!/[\\u0000-\\u001f\\u007f]/u.test(e)}function B(e){return z(e,128)&&/^[a-z0-9][a-z0-9-]*$/u.test(e)}function he(e){return!z(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 V=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}]]),ge=new Set([...V.keys()].map(e=>e.slice(0,e.indexOf(`:`)))),_e=new Set([...V.keys()].map(e=>e.slice(e.indexOf(`:`)+1)));function ve(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return!L(t.format)||!z(t.operation,256)||!B(t.resource)||!B(t.metric)||!P(t.limit)||!P(t.observed)||typeof t.configurable!=`boolean`||!F(t.usage)?!1:!(`part`in t)||he(t.part)}function H(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;if(!R(t.stage)||!ve(t.violation))return!1;let n=t.violation,r=V.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:!(ge.has(n.resource)&&_e.has(n.metric))}function ye(e){return{archiveEntryCount:e.archiveEntryCount,declaredInflatedBytes:e.declaredInflatedBytes,...e.largestInflatedEntryBytes===void 0?{}:{largestInflatedEntryBytes:e.largestInflatedEntryBytes},distinctInflatedBytes:e.distinctInflatedBytes,operationInflatedBytes:e.operationInflatedBytes}}function be(e){if(!H(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:ye(t.usage)}};return H(n)?n:void 0}function U(e){let t=e.violation;return`OOXML resource limit exceeded${t.part?` for ${t.part}`:``}: ${t.metric} ${t.observed} > ${t.limit}`}function xe(e){let t=e instanceof Error?e.message:String(e);if(!t.startsWith(N))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`||!H(r.details)))return new S(U(r.details),r.details)}function Se(e){let t=ie(e);if(t){let e=new E(t.metric,t.limit,t.observed);return{message:e.message,errorName:e.name,code:e.code,decodedImage:t}}let n=O(e);if(n)return{message:n.message,errorName:`TiffDecodeError`,code:`ooxml-tiff-decode`};let r=M(e);if(r)return{message:r.message,errorName:r.name,code:r.code,insufficientCredit:{requiredBytes:r.requiredBytes,offeredBytes:r.offeredBytes}};let i=e instanceof x||e instanceof S?e:xe(e);if(i instanceof S){let e=be(i.details);return e?{message:typeof i.message==`string`?i.message:U(e),errorName:`OoxmlResourceLimitError`,code:`ooxml-resource-limit`,resourceLimit:e}:{message:`Invalid OOXML resource-limit error payload`,errorName:`Error`}}if(i instanceof x)return{message:typeof i.message==`string`?i.message:String(i.message),errorName:z(i.name,128)?i.name:`OoxmlError`,...B(i.code)?{code:i.code}:{}};let a=e instanceof Error?e.message:String(e);if(typeof a==`string`&&a.startsWith(N))return{message:`Invalid OOXML resource-limit payload`,errorName:`Error`};let o=e instanceof Error?e:Error(a),s=o;return{message:typeof o.message==`string`?o.message:String(o.message),errorName:z(o.name,128)?o.name:`Error`,...typeof s.code==`string`?{code:s.code}:{}}}function W(e){try{return Se(e)}catch{return{message:`Worker operation failed with an unreadable error`,errorName:`Error`}}}function Ce(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 we(e){return[e.maxArchiveEntryBytes===null?0n:BigInt(e.maxArchiveEntryBytes),e.maxTotalInflatedBytes===null?0n:BigInt(e.maxTotalInflatedBytes),e.maxArchiveEntries===null?0n:BigInt(e.maxArchiveEntries)]}const G=`ooxml-pull-v1`;function K(e,t){if(!Number.isSafeInteger(e)||e<=0)throw RangeError(`${t} must be a positive safe integer`)}function Te(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 q=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,K(this.maxRetainedBytes,`max retained lease bytes`),K(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}},Ee=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){Te(e.sessionId),K(e.operationId,`operation id`),K(e.generation,`generation`),K(e.maxByteCredit,`max byte credit`),e.wireLeaseIdStart!==void 0&&K(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=W(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(K(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:G,...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){K(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(K(e,`byte credit`),e>this.options.maxByteCredit)throw RangeError(`byte credit exceeds host maximum`)}accepted(e,t,n=!1){return{kind:`accepted`,protocol:G,...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:G,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}}};function De(e){try{let t=e(e=>e.document_cursor_resource_usage?.());return t?I(t):void 0}catch(e){if(String(e).includes(`document cursor usage is unavailable`))return;throw e}}const J=67108864;var Y=class{coordinator=new q;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 Ee({...e,maxByteCredit:J,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 me(e,n,J)||e}let i=Ce(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:()=>De(this.executeArchive)}})}dispatch(e,t){return!this.host||!this.identity?(t({protocol:G,kind:`error`,sessionId:e.sessionId,operationId:e.operationId,generation:e.generation,requestId:e.requestId,error:W(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 q}}requireArchive(){let e=this.archive();if(!e)throw Error(`No docx loaded`);return e}};function Oe(e){return!!e&&typeof e==`object`&&e.protocol===`ooxml-pull-v1`}const X=new de(y,{freeArchive:e=>e.free(),reinit:b}),Z=new Y(()=>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(Oe(n)){try{await Z.dispatch(n,$)}catch(e){$({protocol:G,kind:`error`,sessionId:n.sessionId,operationId:n.operationId,generation:n.generation,requestId:n.requestId,error:W(e)})}return}if(n.type===`init`){X.setWasmInput(oe(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]=we(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:I(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,...W(e)})}};", Ct = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", St], { type: "text/javascript;charset=utf-8" });
150
- function wt(e) {
151
- let t;
152
- try {
153
- if (t = Ct && (self.URL || self.webkitURL).createObjectURL(Ct), !t) throw "";
154
- let n = new Worker(t, {
155
- type: "module",
156
- name: e?.name
157
- });
158
- return n.addEventListener("error", () => {
159
- (self.URL || self.webkitURL).revokeObjectURL(t);
160
- }), n;
161
- } catch {
162
- return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(St), {
163
- type: "module",
164
- name: e?.name
165
- });
166
- }
167
- }
168
- //#endregion
169
- //#region packages/docx/src/wasm/docx_parser_bg.wasm?url
170
- var Tt = new URL("docx_parser_bg.wasm", import.meta.url).href;
171
- //#endregion
172
- //#region packages/docx/src/bookmark-nav.ts
173
- function Et(e) {
174
- let t = /* @__PURE__ */ new Map();
175
- for (let n of e.pages) for (let e of n.bookmarkStarts) e.name !== "" && !t.has(e.name) && t.set(e.name, n.pageIndex);
176
- return t;
177
- }
178
- //#endregion
179
- //#region packages/docx/src/embedded-fonts.ts
180
- async function Dt(e, t) {
181
- let n = e.embeddedFonts;
182
- if (!n || n.length === 0) return {
183
- faces: [],
184
- metrics: {}
185
- };
186
- let r = [], i = /* @__PURE__ */ new Set();
187
- for (let e of n) {
188
- let t = Ot(e.style) === "bold" ? 700 : 400, n = kt(e.style), a = `${Ae(e.fontName)}:${t}:${n}`;
189
- i.has(a) || (i.add(a), r.push(e));
190
- }
191
- let a = (await Promise.all(r.map(async (e) => {
192
- try {
193
- let n = await t(e.partPath), r = e.partPath.toLowerCase().endsWith(".odttf"), i = {
194
- family: e.fontName,
195
- bytes: n,
196
- odttf: r,
197
- fontKey: e.fontKey,
198
- weight: Ot(e.style),
199
- style: kt(e.style)
200
- };
201
- if (!Ee(n)) return {
202
- face: i,
203
- metric: null
204
- };
205
- let a = i, o = null;
206
- try {
207
- let t = r ? xe(n, e.fontKey ?? "") : n;
208
- a = {
209
- ...i,
210
- bytes: t,
211
- odttf: !1,
212
- fontKey: ""
213
- };
214
- let s = xt(t), c = s?.hasEastAsianCmap ? Me(s) : 0;
215
- c > 0 && (o = Object.freeze({
216
- family: e.fontName,
217
- requestedFamily: e.fontName,
218
- weight: a.weight === "bold" ? 700 : 400,
219
- style: a.style,
220
- sourceIdentity: `embedded:${e.partPath}`,
221
- synthesized: !1,
222
- eastAsianLineHeightRatio: c
223
- }));
224
- } catch {}
225
- return {
226
- face: a,
227
- metric: o
228
- };
229
- } catch {
230
- return null;
231
- }
232
- }))).filter((e) => e !== null);
233
- if (a.length === 0) return {
234
- faces: [],
235
- metrics: {}
236
- };
237
- let o = await ve(a.map((e) => e.face)), s = new Set(o.map((e) => {
238
- let t = e.family.trim().replace(/^(['"])(.*)\1$/, "$2"), n = e.weight === "bold" ? 700 : Number(e.weight) || 400, r = e.style === "italic" ? "italic" : "normal";
239
- return `${Ae(t)}:${n}:${r}`;
240
- })), c = {};
241
- for (let e of a) {
242
- if (!e.metric) continue;
243
- let t = Ae(e.face.family), n = e.face.weight === "bold" ? 700 : 400, r = e.face.style, i = `${t}:${n}:${r}`;
244
- s.has(i) && (c[n === 400 && r === "normal" ? t : i] = e.metric);
245
- }
246
- return {
247
- faces: o,
248
- metrics: Object.freeze(c)
249
- };
250
- }
251
- function Ot(e) {
252
- return e === "bold" || e === "boldItalic" ? "bold" : "normal";
253
- }
254
- function kt(e) {
255
- return e === "italic" || e === "boldItalic" ? "italic" : "normal";
256
- }
257
- //#endregion
258
- //#region packages/docx/src/element-context.ts
259
- var I = fe, At = 16384;
260
- function jt(e, t) {
261
- let n = Math.min(e.length, t);
262
- if (n > 0 && n < e.length) {
263
- let t = e.charCodeAt(n - 1), r = e.charCodeAt(n);
264
- t >= 55296 && t <= 56319 && r >= 56320 && r <= 57343 && n--;
265
- }
266
- return e.slice(0, n);
267
- }
268
- function Mt(e, t) {
269
- let n = [], r = 0, i = !1;
270
- for (let a of e) {
271
- if (a.length === 0) continue;
272
- if (r > 0) {
273
- if (r >= t) {
274
- i = !0;
275
- break;
276
- }
277
- n.push("\n"), r++;
278
- }
279
- let e = jt(a, Math.max(0, t - r));
280
- if (n.push(e), r += e.length, e.length < a.length) {
281
- i = !0;
282
- break;
283
- }
284
- }
285
- let a = n.join("");
286
- return {
287
- ...a.length === 0 ? {} : { text: a },
288
- truncated: i
289
- };
290
- }
291
- function* L(e) {
292
- if (e.kind === "paragraph") {
293
- for (let t of e.lines) {
294
- let e = t.placements.flatMap((e) => e.kind === "text" ? [e.text] : []).join("");
295
- e && (yield e);
296
- }
297
- return;
298
- }
299
- if (e.kind === "table") {
300
- for (let t of e.rows) for (let e of t.cells) for (let t of e.blocks) yield* L(t.layout);
301
- return;
302
- }
303
- if (e.kind === "note" || e.kind === "textbox") for (let t of e.story.blocks) yield* L(t);
304
- }
305
- function* Nt(e) {
306
- for (let t of e.drawing.commands) (t.kind === "text" || t.kind === "watermark-text") && (yield t.text);
307
- for (let t of e.textBoxes) yield* L(t);
308
- }
309
- function Pt(e) {
310
- let t = e ?? At;
311
- if (!Number.isFinite(t) || t < 0) throw RangeError("maxTextCharacters must be a finite non-negative number.");
312
- return Math.min(I, Math.floor(t));
313
- }
314
- function Ft(e) {
315
- return {
316
- story: e.story,
317
- storyInstance: e.storyInstance,
318
- path: [...e.path]
319
- };
320
- }
321
- function It(e) {
322
- return "drawing" in e ? e.drawing.inkBounds : e.placement.bounds;
323
- }
324
- function Lt(e) {
325
- let t = It(e), n = [
326
- E(e.pointToPage, t),
327
- E(e.pointToPage, {
328
- xPt: t.xPt + t.widthPt,
329
- yPt: t.yPt
330
- }),
331
- E(e.pointToPage, {
332
- xPt: t.xPt,
333
- yPt: t.yPt + t.heightPt
334
- }),
335
- E(e.pointToPage, {
336
- xPt: t.xPt + t.widthPt,
337
- yPt: t.yPt + t.heightPt
338
- })
339
- ], 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));
340
- return {
341
- xPt: r,
342
- yPt: i,
343
- widthPt: a - r,
344
- heightPt: o - i
345
- };
346
- }
347
- function R(e, t) {
348
- return t.xPt >= e.xPt && t.xPt <= e.xPt + e.widthPt && t.yPt >= e.yPt && t.yPt <= e.yPt + e.heightPt;
349
- }
350
- function Rt(e, t) {
351
- let n = !1;
352
- for (let r = 0, i = t.length - 1; r < t.length; i = r++) {
353
- let a = t[r], o = t[i];
354
- 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);
355
- }
356
- return n;
357
- }
358
- function zt(e, t) {
359
- return R(e.inkBounds, t) ? e.clip ? e.clip.kind === "rect" ? R(e.clip.rect, t) : Rt(t, e.clip.points) : !0 : !1;
360
- }
361
- function Bt(e, t, n) {
362
- for (let n of e.clips) {
363
- let e = je(n.pointToPage, t);
364
- if (!e || !R(n.bounds, e)) return !1;
365
- }
366
- return "drawing" in e ? zt(e.drawing, n) : R(e.placement.bounds, n);
367
- }
368
- function z(e, t) {
369
- return e.commands.find((e) => e.kind === "resource" && e.resourceKind === t);
370
- }
371
- function Vt(e) {
372
- return z(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" : z(e, "image") ? "image" : null;
373
- }
374
- function Ht(e, t, n, r, i, a) {
375
- let o = "drawing" in e ? Vt(e.drawing) : e.placement.resourceKind;
376
- if (!o) return null;
377
- let s, c = !1, l, u;
378
- if (o === "chart") {
379
- let t = "drawing" in e ? z(e.drawing, "chart").resourceKey : e.placement.resourceKey, n = i.resolve(t, "chart"), r = te(n.model, a);
380
- s = r.text, c = r.truncated, u = n.model.series.length;
381
- } else if (o === "image") {
382
- let t = "drawing" in e ? z(e.drawing, "image").resourceKey : e.placement.resourceKey, n = i.descriptors.find((e) => e.resourceKey === t && e.kind === "image" && "mimeType" in e);
383
- if (!n) throw Error(`Unknown image paint resource: ${t}`);
384
- l = n.mimeType;
385
- } else {
386
- let t = Mt(Nt(e), a);
387
- s = t.text, c = t.truncated;
388
- }
389
- return {
390
- format: "docx",
391
- kind: "element",
392
- pageIndex: t,
393
- elementIndex: n,
394
- elementType: o,
395
- point: { ...r },
396
- bounds: Lt(e),
397
- source: Ft("drawing" in e ? e.drawing.source : e.source),
398
- ...s === void 0 ? {} : { text: s },
399
- ...l === void 0 ? {} : { mimeType: l },
400
- ...u === void 0 ? {} : { seriesCount: u },
401
- truncated: c,
402
- truncationReasons: c ? ["text"] : [],
403
- textCharacters: s?.length ?? 0,
404
- maxTextCharacters: a
405
- };
406
- }
407
- function Ut(e, t, n, r, i = {}) {
408
- if (!Number.isFinite(n.xPt) || !Number.isFinite(n.yPt)) throw RangeError("DOCX hit-test point must contain finite page coordinates.");
409
- let a = Pt(i.maxTextCharacters), o = Fe(e, t);
410
- for (let e = o.length - 1; e >= 0; e--) {
411
- let i = o[e], s = je(i.pointToPage, n);
412
- if (!s || !Bt(i, n, s)) continue;
413
- let c = Ht(i, t, e, n, r, a);
414
- if (c) return c;
415
- }
416
- return null;
417
- }
418
- function Wt(e, t, n, r) {
419
- return Ut(Xe(e, {
420
- currentDate: r.currentDate,
421
- defaultCurrentDateMs: r.defaultCurrentDateMs,
422
- showTrackedChanges: r.showTrackedChanges
423
- }, t).layout, t, n, De(e), r);
424
- }
425
- function Gt(e, t) {
426
- let n = Pt(t), r = e.text === void 0 ? void 0 : jt(e.text, n), i = e.truncated || e.text !== void 0 && r.length < e.text.length;
427
- return {
428
- ...structuredClone(e),
429
- ...r === void 0 ? {} : { text: r },
430
- truncated: i,
431
- truncationReasons: i ? ["text"] : [],
432
- textCharacters: r?.length ?? 0,
433
- maxTextCharacters: n
434
- };
435
- }
436
- //#endregion
437
- //#region packages/docx/src/revisions.ts
438
- function B(e) {
439
- let t = st(e.id);
440
- return t === void 0 ? void 0 : `${e.kind}\u0000${t}`;
441
- }
442
- function V(e) {
443
- return Object.freeze({
444
- ...e,
445
- path: Object.freeze([...e.path])
446
- });
447
- }
448
- function Kt(e, t) {
449
- 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]);
450
- }
451
- function qt(e, t) {
452
- let n = 0, r = e.length;
453
- for (; n < r;) {
454
- let i = n + Math.floor((r - n) / 2);
455
- e[i] < t ? n = i + 1 : r = i;
456
- }
457
- return n;
458
- }
459
- function Jt(e, t) {
460
- let n = Array(e.length), r;
461
- for (let i = e.length - 1; i >= 0; --i) {
462
- n[i] = r;
463
- let a = e[i], o = t.get(j(a.source))?.[0];
464
- o !== void 0 && (r = Object.freeze({
465
- source: V(a.source),
466
- sourceRunIndex: o
467
- }));
468
- }
469
- let i = Array(e.length), a;
470
- for (let n = 0; n < e.length; n += 1) {
471
- i[n] = a;
472
- let r = e[n], o = t.get(j(r.source))?.at(-1);
473
- o !== void 0 && (a = Object.freeze({
474
- source: V(r.source),
475
- sourceRunIndex: o
476
- }));
477
- }
478
- return {
479
- following: n,
480
- preceding: i
481
- };
482
- }
483
- function Yt(e, t, n, r, i, a) {
484
- let o = r[e], s = i.get(j(o.source)) ?? [], c = s[qt(s, n)], l = s[qt(s, t) - 1], u = c ?? l;
485
- return u === void 0 ? a.following[e] ?? a.preceding[e] : Object.freeze({
486
- source: V(o.source),
487
- sourceRunIndex: u
488
- });
489
- }
490
- function Xt(e, t, n = /* @__PURE__ */ new Map()) {
491
- let r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Set();
492
- e.forEach((e, t) => {
493
- let n = B(e);
494
- n === void 0 || i.has(n) || (r.has(n) ? (r.delete(n), i.add(n)) : r.set(n, t));
495
- });
496
- let a = t.blocks.sources.flatMap((e) => {
497
- if (e.story !== "body") return [];
498
- let n = t.blocks.resolve(e);
499
- return n.type === "paragraph" ? [{
500
- source: e,
501
- runs: n.runs
502
- }] : [];
503
- }), o = new Map([...n].map(([e, t]) => [e, Object.freeze([...t].sort((e, t) => e - t))])), s = Jt(a, o), c = [];
504
- for (let [e, t] of a.entries()) {
505
- let n = 0;
506
- for (; n < t.runs.length;) {
507
- let i = t.runs[n], l = i.revision?.kind ? B({
508
- kind: i.revision.kind,
509
- id: i.revision.id
510
- }) : void 0, u = l === void 0 ? void 0 : r.get(l);
511
- if (u === void 0) {
512
- n += 1;
513
- continue;
514
- }
515
- let d = n;
516
- for (n += 1; n < t.runs.length;) {
517
- let e = t.runs[n].revision;
518
- if (!e?.kind || B({
519
- kind: e.kind,
520
- id: e.id
521
- }) !== l) break;
522
- n += 1;
523
- }
524
- let f = n, p = o.get(j(t.source)) ?? [], m = (p[qt(p, d)] ?? f) < f ? void 0 : Yt(e, d, f, a, o, s);
525
- c.push(Object.freeze({
526
- revisionIndex: u,
527
- source: V(t.source),
528
- startRunIndex: d,
529
- endRunIndex: f,
530
- ...m === void 0 ? {} : { geometryFallback: m }
531
- }));
532
- }
533
- }
534
- return c;
535
- }
536
- function Zt(e, t, n = /* @__PURE__ */ new Map(), r = {}) {
537
- if ((e?.length ?? 0) === 0) return [];
538
- let i = Xt(e ?? [], t, n), a = r.completedSourceKeys;
539
- return a === void 0 ? i : i.filter((e) => {
540
- let t = n.get(j(e.source));
541
- return t !== void 0 && [...t].some((t) => t >= e.startRunIndex && t < e.endRunIndex) || a.has(j(e.source));
542
- });
543
- }
544
- function Qt(e, t) {
545
- let n = t.filter((t) => t.sourceRunIndex !== void 0 && Kt(t.source, e.source) && t.sourceRunIndex >= e.startRunIndex && t.sourceRunIndex < e.endRunIndex);
546
- if (n.length > 0) return n;
547
- let r = e.geometryFallback;
548
- return r === void 0 ? [] : t.filter((e) => e.sourceRunIndex === r.sourceRunIndex && Kt(e.source, r.source));
549
- }
550
- //#endregion
551
- //#region packages/docx/src/layout/progressive.ts
552
- var $t = 12;
553
- async function en(e, t, n, r = {}) {
554
- let { onPreview: i, scheduler: a } = r;
555
- return ze(Ne(e, t, n, i && e.sequence.length > $t ? { onPages: (e, t) => {
556
- i(Object.freeze({
557
- layout: e,
558
- exact: !1,
559
- coveredEntries: t
560
- }));
561
- } } : void 0), a);
562
- }
563
- //#endregion
564
- //#region packages/docx/src/document-layout-events.ts
565
- var H = /* @__PURE__ */ new WeakMap();
566
- function U(e, t) {
567
- let n = Object.freeze({ ...t });
568
- for (let t of [...H.get(e) ?? []]) try {
569
- t.notify(n);
570
- } catch (e) {
571
- try {
572
- t.report(e);
573
- } catch {}
574
- }
575
- }
576
- function tn(e, t, n, r) {
577
- let i = H.get(e);
578
- i || (i = /* @__PURE__ */ new Set(), H.set(e, i));
579
- let a = Object.freeze({
580
- notify: n,
581
- report: r
582
- });
583
- i.add(a);
584
- try {
585
- n(Object.freeze({ ...t() }));
586
- } catch (e) {
587
- try {
588
- r(e);
589
- } catch {}
590
- }
591
- return () => {
592
- i?.delete(a), i?.size === 0 && H.delete(e);
593
- };
594
- }
595
- //#endregion
596
- //#region packages/docx/src/document-layout-view.ts
597
- var W = /* @__PURE__ */ new WeakMap(), nn = /* @__PURE__ */ new WeakMap(), rn = Symbol("docxLayoutViewRequester");
598
- function G(e) {
599
- let t = D(e), n = t.activeLayoutOptions;
600
- return {
601
- showTrackedChanges: n?.showTrackedChanges === !0,
602
- currentDate: n?.currentDateMs ?? t.defaultCurrentDateMs
603
- };
604
- }
605
- async function K(e, t, n) {
606
- let r = D(e), i = ke(t.currentDate, r.defaultCurrentDateMs, t.showTrackedChanges === !0), a = Object.freeze({
607
- showTrackedChanges: i.showTrackedChanges === !0,
608
- currentDate: i.currentDateMs
609
- }), o = {
610
- showTrackedChanges: a.showTrackedChanges,
611
- currentDate: a.currentDate,
612
- [rn]: n
613
- };
614
- await e.setLayoutView(o);
615
- let s = G(e);
616
- return s.currentDate === a.currentDate && s.showTrackedChanges === a.showTrackedChanges;
617
- }
618
- function an(e, t) {
619
- let n = Object.freeze({ ...G(e) }), r = (nn.get(e) ?? 0) + 1;
620
- nn.set(e, r);
621
- let i = Object.freeze({
622
- view: n,
623
- generation: r,
624
- requester: t
625
- });
626
- for (let t of [...W.get(e) ?? []]) try {
627
- t.notify(i);
628
- } catch (e) {
629
- try {
630
- t.report(e);
631
- } catch {}
632
- }
633
- }
634
- function on(e, t, n) {
635
- let r = W.get(e);
636
- r || (r = /* @__PURE__ */ new Set(), W.set(e, r));
637
- let i = Object.freeze({
638
- notify: t,
639
- report: n
640
- });
641
- return r.add(i), () => {
642
- r?.delete(i), r?.size === 0 && W.delete(e);
643
- };
644
- }
645
- //#endregion
646
- //#region packages/docx/src/document.ts
647
- function sn(e, t) {
648
- return e !== null && e.currentDateMs === t.currentDateMs && e.showTrackedChanges === !0 == (t.showTrackedChanges === !0);
649
- }
650
- function cn() {
651
- let e, t;
652
- return {
653
- promise: new Promise((n, r) => {
654
- e = n, t = r;
655
- }),
656
- resolve: e,
657
- reject: t
658
- };
659
- }
660
- var ln = Object.freeze([]), un = Object.freeze([]), dn = Object.freeze({
661
- comments: Object.freeze([]),
662
- revisions: Object.freeze([])
663
- });
664
- function q(e, t) {
665
- return Ve({
666
- comments: e,
667
- revisions: t
668
- }, "DOCX review metadata");
669
- }
670
- var J = class e {
671
- _metrics = null;
672
- _cjkFallback = "jp";
673
- _document = null;
674
- _source = null;
675
- _meta = null;
676
- _review = dn;
677
- _layoutLifecycle = new be();
678
- _layoutObservers = new Ce();
679
- _layoutCompletion = null;
680
- _layoutAbort = null;
681
- _bookmarkPages = null;
682
- _commentAnchorRanges = null;
683
- _revisionAnchorRanges = null;
684
- _reviewProjectionIndex = null;
685
- _parseRequestId = null;
686
- _progressive = null;
687
- _parseWatchdog;
688
- _parseWatchdogMs;
689
- _layoutViewGeneration = 0;
690
- _mode = "main";
691
- _threeD;
692
- _regionMap;
693
- _chartEx;
694
- _tiff;
695
- _worker;
696
- _bridge;
697
- _rawParts = new ot({
698
- maxEntries: 64,
699
- maxBytes: n
700
- });
701
- _embeddedFontFaces = [];
702
- _googleFontFaces = [];
703
- _fetchImage = (e, t) => this.getImage(e, t);
704
- constructor(e, t, n, r) {
705
- this._worker = e, this._mode = t, Oe(this, n), this._bridge = new me(this._worker, {
706
- correlate: (e) => "protocol" in e && e.protocol === "ooxml-pull-v1" ? e.requestId : "id" in e ? e.id : void 0,
707
- onUnsolicited: (e) => this._onWorkerLayoutPush(e),
708
- toError: (e) => {
709
- if (!("protocol" in e || e.type !== "error")) return Object.assign(a(e), {
710
- ...e.reason === void 0 ? {} : { reason: e.reason },
711
- ...e.outgoingColumnIndex === void 0 ? {} : { outgoingColumnIndex: e.outgoingColumnIndex },
712
- ...e.outgoingColumnCount === void 0 ? {} : { outgoingColumnCount: e.outgoingColumnCount },
713
- ...e.incomingColumnCount === void 0 ? {} : { incomingColumnCount: e.incomingColumnCount }
714
- });
715
- }
716
- });
717
- let i = new URL(r ?? Tt, location.href).href;
718
- this._bridge.post({
719
- type: "init",
720
- wasmUrl: i
721
- });
722
- }
723
- static async load(t, n = {}) {
724
- let i = $e(n.cjkFallback), a = f(n), o = Date.now(), s = n.mode ?? "main", c = new r({
725
- enabled: !0,
726
- format: "docx",
727
- mode: s,
728
- policy: a.policy,
729
- onMetrics: a.onResourceMetrics,
730
- emitToConsole: a.debug
731
- });
732
- try {
733
- if (s === "worker" && (typeof Worker > "u" || typeof OffscreenCanvas > "u")) throw Error("mode: 'worker' requires Worker and OffscreenCanvas support");
734
- let r;
735
- if (typeof t == "string") {
736
- let e = await fetch(t);
737
- if (!e.ok) throw Error(`Failed to fetch: ${e.status} ${e.statusText}`);
738
- r = await e.arrayBuffer();
739
- } else r = t;
740
- r = g(await h(r, n.password)), c.setSourceBytes(r.byteLength), c.checkpoint("container ready");
741
- let l = s === "worker" ? (await import("./render-worker-host-IkHrYOci.js")).createRenderWorker() : new wt(), u = s === "worker" ? it(n) : void 0, d = s === "worker" && !!n.progressiveLayout, f;
742
- try {
743
- f = new e(l, s, o, n.wasmUrl), f._metrics = c, f._cjkFallback = i;
744
- let t = D(f), p = ke(n.currentDate, t.defaultCurrentDateMs, n.showTrackedChanges === !0);
745
- t.activeLayoutOptions = p, await f._parse(r, a.policy, s === "worker" ? !!n.useGoogleFonts : !1, n.workerTimeoutMs, (e) => c.observeUsage(e), u, d ? {
746
- onPartial: n.onLayoutPartial,
747
- onComplete: n.onLayoutComplete,
748
- onProgress: n.onLayoutProgress,
749
- layoutOptions: p,
750
- abort: new AbortController(),
751
- firstPublication: cn(),
752
- published: !1,
753
- settled: !1
754
- } : void 0), s === "worker" && f._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.")), n.math && f._mode === "worker" && !u?.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."), n.threeD && f._mode === "worker" && !u?.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."), f._threeD = f._mode === "worker" ? void 0 : n.threeD, n.regionMap && f._mode === "worker" && !u?.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."), f._regionMap = f._mode === "worker" ? void 0 : n.regionMap, n.chartEx && f._mode === "worker" && !u?.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."), f._chartEx = f._mode === "worker" ? void 0 : n.chartEx, n.tiff && f._mode === "worker" && !u?.tiff && console.warn("[ooxml] a custom TIFF codec cannot cross the worker boundary; recognized TIFF images will use an unavailable-image placeholder in mode: 'worker'. Use the codec from @silurus/ooxml/tiff to display them."), f._tiff = f._mode === "worker" ? void 0 : n.tiff, f._mode === "main" && n.useGoogleFonts && f._document && (f._googleFontFaces = await m(Re(f._document, i), Le));
755
- let h;
756
- if (f._mode === "main" && f._document?.embeddedFonts?.length) {
757
- let e = f, t = await Dt(f._document, (t) => e.getFontBytes(t));
758
- f._embeddedFontFaces = t.faces, h = t.metrics;
759
- }
760
- let g;
761
- if (f._mode === "main" && n.math && f._document && Ke(f._document) && (g = await Je(f._document, n.math)), f._mode === "main" && f._document && f._source) {
762
- let e = f, t = D(f);
763
- t.services = Ue(f._source, {
764
- fontMetrics: h,
765
- measureResolvedFontMetrics: !0,
766
- resolvedFontMetricCandidates: qe(f._document, f._source.fontFamilyCharsets),
767
- useGoogleFonts: !!n.useGoogleFonts,
768
- cjkFallback: i,
769
- embeddedFaces: f._embeddedFontFaces,
770
- googleFaces: f._googleFontFaces,
771
- mathResources: g?.records,
772
- mathDrawables: g?.drawables
773
- });
774
- let r = t.services, a = Pe(f._source, r, t.defaultCurrentDateMs), o = f._source.fatalParse === null, s = t.activeLayoutOptions;
775
- if (!s) throw Error("Active layout view was not recorded at load");
776
- let c = { onProgress: n.onLayoutProgress ? (t) => e._layoutObservers.notify("onLayoutProgress", n.onLayoutProgress, { committedUnits: t }) : void 0 };
777
- if (o && n.progressiveLayout) {
778
- let e = a.layoutVariants, t = f, i = new AbortController();
779
- t._layoutAbort = i;
780
- let o = cn(), l = null, u = !0;
781
- t._layoutCompletion = en(f._source.bodyLayoutInput, r, s, {
782
- scheduler: {
783
- ...c,
784
- signal: i.signal
785
- },
786
- onPreview: (r) => {
787
- if (!u) return;
788
- let i = l === null, a = t._replaceMainLayoutPublication(e, s, l, r.layout);
789
- if (a === null) {
790
- u = !1;
791
- return;
792
- }
793
- if (l = a, i) t._layoutLifecycle.begin(), U(t, {
794
- pageCount: r.layout.pages.length,
795
- exact: r.exact,
796
- complete: !1
797
- }), o.resolve();
798
- else {
799
- if (!t._isLayoutViewActive(s)) return;
800
- U(t, {
801
- pageCount: r.layout.pages.length,
802
- exact: r.exact,
803
- complete: !1
804
- }), t._layoutObservers.notify("onLayoutPartial", n.onLayoutPartial, {
805
- availableUnits: r.layout.pages.length,
806
- exact: r.exact
807
- });
808
- }
809
- }
810
- }).then((r) => {
811
- u && t._replaceMainLayoutPublication(e, s, l, r) === null && (u = !1), t._layoutLifecycle.succeed(), U(t, {
812
- pageCount: t.pageCount,
813
- exact: !0,
814
- complete: !0
815
- }), t._layoutObservers.notify("onLayoutComplete", n.onLayoutComplete), o.resolve();
816
- }).catch((e) => {
817
- if (l === null) {
818
- o.reject(e);
819
- return;
820
- }
821
- if (e instanceof Be) {
822
- t._layoutLifecycle.succeed();
823
- return;
824
- }
825
- let r = t._layoutLifecycle.fail(e);
826
- U(t, {
827
- pageCount: t.pageCount,
828
- exact: !1,
829
- complete: !1,
830
- error: r
831
- }), t._layoutObservers.notify("onLayoutComplete", n.onLayoutComplete, r);
832
- }), await o.promise;
833
- } else if (o && (n.sliceLayout || n.onLayoutProgress)) {
834
- let e = await We(f._source.bodyLayoutInput, r, s, c);
835
- a.layoutVariants.prime(s, e);
836
- } else a.layoutVariants.layoutFor(s);
837
- }
838
- return await f._resourceUsage(n.workerTimeoutMs ?? 1e3).then((e) => c.observeUsage(e), () => void 0), c.checkpoint("model and layout ready"), c.succeed({ pages: f.pageCount }), f;
839
- } catch (e) {
840
- let t = f;
841
- throw p(l, t ? () => t.destroy() : void 0), e;
842
- }
843
- } catch (e) {
844
- throw c.fail(e), e;
845
- }
846
- }
847
- async _parse(e, t, n = !1, r, i, a, o) {
848
- if (o) {
849
- await this._parseProgressively(e, t, n, r, i, a, o);
850
- return;
851
- }
852
- let s = await this._bridge.request((r) => this._mode === "worker" ? {
853
- type: "parse",
854
- id: r,
855
- data: e,
856
- resourcePolicy: t,
857
- useGoogleFonts: n,
858
- cjkFallback: this._cjkFallback,
859
- defaultCurrentDateMs: D(this).defaultCurrentDateMs,
860
- ...this._parseViewFields(),
861
- renderers: a
862
- } : {
863
- type: "parse",
864
- id: r,
865
- data: e,
866
- resourcePolicy: t
867
- }, [e], { timeoutMs: r });
868
- if ("protocol" in s) throw Error("DOCX parse open returned a pull-protocol response");
869
- if (this._mode === "worker") if ("usage" in s && s.usage && i?.(s.usage), s.type === "mainThreadVerticalFallback") {
870
- let e = await Ge(this._bridge.transport(O), s, {
871
- timeoutMs: r,
872
- onUsage: i
873
- });
874
- this._source = e.source, this._document = e.document, this._meta = null, this._mode = "main";
875
- } else this._meta = s.meta;
876
- else {
877
- let e = s, t = await Ge(this._bridge.transport(O), e, {
878
- timeoutMs: r,
879
- onUsage: i
880
- });
881
- this._source = t.source, this._document = t.document;
882
- }
883
- this._review = q(this._meta?.comments ?? this._document?.comments ?? [], this._meta?.revisions ?? this._document?.revisions ?? []);
884
- }
885
- _onWorkerLayoutPush(e) {
886
- if (v((e, t) => this._worker.postMessage(e, t), e) || !("forId" in e) || e.forId !== this._parseRequestId) return;
887
- this._rearmParseWatchdog();
888
- let t = this._progressive;
889
- if (t?.settled) return;
890
- if (e.type === "layoutProgress") {
891
- this._layoutObservers.notify("onLayoutProgress", t?.onProgress, { committedUnits: e.committedPages });
892
- return;
893
- }
894
- if (e.type !== "layoutPartial" || !t) return;
895
- let n = !t.published || this._isLayoutViewActive(t.layoutOptions);
896
- if (n && this._applyLayoutPartial(e.partial), t.published) {
897
- if (!n) return;
898
- U(this, {
899
- pageCount: e.partial.pageCount,
900
- exact: e.partial.exact,
901
- complete: !1
902
- }), this._layoutObservers.notify("onLayoutPartial", t.onPartial, {
903
- availableUnits: e.partial.pageCount,
904
- exact: e.partial.exact
905
- });
906
- return;
907
- }
908
- t.published = !0, this._layoutLifecycle.begin(), U(this, {
909
- pageCount: e.partial.pageCount,
910
- exact: e.partial.exact,
911
- complete: !1
912
- }), t.firstPublication.resolve();
913
- }
914
- _applyLayoutPartial(e) {
915
- let t = e.review ?? this._meta;
916
- this._meta = {
917
- pageCount: e.pageCount,
918
- pageSizes: e.pageSizes,
919
- bookmarkPages: e.bookmarkPages,
920
- revisions: t?.revisions ?? [],
921
- comments: t?.comments ?? [],
922
- footnotes: t?.footnotes ?? [],
923
- endnotes: t?.endnotes ?? [],
924
- commentAnchorRanges: e.commentAnchorRanges,
925
- revisionAnchorRanges: e.revisionAnchorRanges
926
- }, e.review && (this._review = q(e.review.comments, e.review.revisions)), this._invalidateLayoutDerivedCaches();
927
- }
928
- _onAuthoritativeMeta(e) {
929
- this._clearParseWatchdog();
930
- let t = this._progressive;
931
- if (!t?.settled) {
932
- if (!t || this._isLayoutViewActive(t.layoutOptions) || !this._meta) this._meta = e;
933
- else {
934
- let t = this._meta;
935
- this._meta = {
936
- ...e,
937
- pageCount: t.pageCount,
938
- pageSizes: t.pageSizes,
939
- bookmarkPages: t.bookmarkPages,
940
- commentAnchorRanges: t.commentAnchorRanges,
941
- revisionAnchorRanges: t.revisionAnchorRanges
942
- };
943
- }
944
- this._invalidateLayoutDerivedCaches(), this._review = q(e.comments, e.revisions), t && (t.settled = !0, this._layoutLifecycle.succeed(), U(this, {
945
- pageCount: this.pageCount,
946
- exact: !0,
947
- complete: !0
948
- }), t.firstPublication.resolve(), this._layoutObservers.notify("onLayoutComplete", t.onComplete));
949
- }
950
- }
951
- _invalidateLayoutDerivedCaches() {
952
- this._bookmarkPages = null, this._commentAnchorRanges = null, this._revisionAnchorRanges = null, this._reviewProjectionIndex = null;
953
- }
954
- _replaceMainLayoutPublication(e, t, n, r) {
955
- let i = e.replaceIfCurrent(t, n, r);
956
- return i !== null && this._isLayoutViewActive(t) && this._invalidateLayoutDerivedCaches(), i;
957
- }
958
- _isLayoutViewActive(e) {
959
- return sn(D(this).activeLayoutOptions, e);
960
- }
961
- _rearmParseWatchdog() {
962
- this._parseWatchdogMs !== void 0 && (clearTimeout(this._parseWatchdog), this._parseWatchdog = setTimeout(() => this._onParseWentSilent(), this._parseWatchdogMs));
963
- }
964
- _clearParseWatchdog() {
965
- clearTimeout(this._parseWatchdog), this._parseWatchdog = void 0, this._parseWatchdogMs = void 0;
966
- }
967
- _onParseWentSilent() {
968
- let e = this._progressive, t = this._parseWatchdogMs;
969
- this._clearParseWatchdog();
970
- let n = /* @__PURE__ */ Error(`worker layout produced no progress for ${t}ms`);
971
- e && this._failWorkerProgressive(e, n), this._bridge.terminate();
972
- }
973
- _failWorkerProgressive(e, t) {
974
- if (e.settled) return;
975
- if (e.settled = !0, this._clearParseWatchdog(), !e.published) {
976
- e.firstPublication.reject(t);
977
- return;
978
- }
979
- let n = this._layoutLifecycle.fail(t);
980
- U(this, {
981
- pageCount: this.pageCount,
982
- exact: !1,
983
- complete: !1,
984
- error: n
985
- }), this._layoutObservers.notify("onLayoutComplete", e.onComplete, n);
986
- }
987
- _parseViewFields() {
988
- let e = D(this), t = e.activeLayoutOptions;
989
- return t ? {
990
- ...t.currentDateMs === e.defaultCurrentDateMs ? {} : { currentDateMs: t.currentDateMs },
991
- ...t.showTrackedChanges === !0 ? { showTrackedChanges: !0 } : {}
992
- } : {};
993
- }
994
- async _parseProgressively(e, t, n, r, i, a, o) {
995
- this._progressive = o, this._layoutAbort = o.abort, this._parseWatchdogMs = r, this._layoutCompletion = this._bridge.request((r) => (this._parseRequestId = r, {
996
- type: "parse",
997
- id: r,
998
- data: e,
999
- resourcePolicy: t,
1000
- useGoogleFonts: n,
1001
- cjkFallback: this._cjkFallback,
1002
- defaultCurrentDateMs: D(this).defaultCurrentDateMs,
1003
- ...this._parseViewFields(),
1004
- renderers: a,
1005
- progressiveLayout: !0
1006
- }), [e], { timeoutMs: !1 }).then(async (e) => {
1007
- if (this._parseRequestId = null, "protocol" in e) throw Error("DOCX parse open returned a pull-protocol response");
1008
- if ("usage" in e && e.usage && i?.(e.usage), e.type === "mainThreadVerticalFallback") {
1009
- this._clearParseWatchdog(), o.settled = !0, this._progressive = null, this._layoutAbort = null;
1010
- let t = await Ge(this._bridge.transport(O), e, {
1011
- timeoutMs: r,
1012
- onUsage: i
1013
- });
1014
- this._source = t.source, this._document = t.document, this._meta = null, this._mode = "main", this._review = q(t.document.comments ?? [], t.document.revisions ?? []), o.firstPublication.resolve();
1015
- return;
1016
- }
1017
- this._onAuthoritativeMeta(e.meta);
1018
- }, (e) => {
1019
- if (this._parseRequestId = null, this._clearParseWatchdog(), !o.settled) {
1020
- if (o.abort.signal.aborted) {
1021
- o.settled = !0, this._layoutLifecycle.succeed(), o.firstPublication.resolve();
1022
- return;
1023
- }
1024
- this._failWorkerProgressive(o, e);
1025
- }
1026
- }), this._rearmParseWatchdog(), await o.firstPublication.promise;
1027
- }
1028
- destroy() {
1029
- this._layoutAbort?.abort(), this._layoutAbort = null, this._clearParseWatchdog(), this._parseRequestId = null, this._progressive = null, this._layoutViewGeneration++, this._bridge.terminate(), this._document = null, this._source = null, this._meta = null, this._review = dn, D(this).services = null, this._bookmarkPages = null, this._commentAnchorRanges = null, this._revisionAnchorRanges = null, this._reviewProjectionIndex = null, this._rawParts.clear(), this._embeddedFontFaces.length > 0 && (ye(this._embeddedFontFaces), this._embeddedFontFaces = []), this._googleFontFaces.length > 0 && (_(this._googleFontFaces), this._googleFontFaces = []), s(this._fetchImage), l(this._fetchImage);
1030
- }
1031
- async getImage(e, t) {
1032
- return this._rawParts.get(e, t, () => this._bridge.request((t) => ({
1033
- type: "extractImage",
1034
- id: t,
1035
- path: e
1036
- })).then((e) => {
1037
- let n = e.bytes;
1038
- return new Blob([n], { type: t });
1039
- }));
1040
- }
1041
- async getFontBytes(e) {
1042
- let t = (await this._bridge.request((t) => ({
1043
- type: "extractImage",
1044
- id: t,
1045
- path: e
1046
- }))).bytes;
1047
- return new Uint8Array(t);
1048
- }
1049
- async _resourceUsage(e) {
1050
- return (await this._bridge.request((e) => ({
1051
- type: "resourceUsage",
1052
- id: e
1053
- }), void 0, { timeoutMs: e })).usage;
1054
- }
1055
- async getResourceMetrics() {
1056
- let e = this._metrics;
1057
- if (!e) throw Error("Document not loaded");
1058
- return i(e, (e) => this._resourceUsage(e));
1059
- }
1060
- async toMarkdown() {
1061
- return (await this._bridge.request((e) => ({
1062
- type: "toMarkdown",
1063
- id: e
1064
- }))).markdown;
1065
- }
1066
- get pageCount() {
1067
- return this._meta ? this._meta.pageCount : this._document ? this._getLayout()?.pages.length ?? 0 : 0;
1068
- }
1069
- get layoutComplete() {
1070
- return this._layoutLifecycle.complete;
1071
- }
1072
- async waitUntilLayoutComplete() {
1073
- this._layoutCompletion && await this._layoutCompletion, this._layoutLifecycle.throwIfFailed();
1074
- }
1075
- get mode() {
1076
- return this._mode;
1077
- }
1078
- get document() {
1079
- 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");
1080
- if (!this._document) throw Error("Document not loaded");
1081
- return this._document;
1082
- }
1083
- get comments() {
1084
- return this._reviewSnapshot().comments;
1085
- }
1086
- get revisions() {
1087
- return this._reviewSnapshot().revisions;
1088
- }
1089
- commentAnchorRanges() {
1090
- if (this._meta) return this._meta.commentAnchorRanges ?? ln;
1091
- if (!this._document || !this._source) return [];
1092
- let e = this._reviewSnapshot().comments;
1093
- if (e.length === 0) return ln;
1094
- let t = D(this), n = t.services;
1095
- if (!n) throw Error("Document layout services are not initialized");
1096
- let r = He(n);
1097
- if (!r) throw Error("Document layout variant store is not initialized");
1098
- let i = t.activeLayoutOptions, a = i ? r.layoutFor(i) : r.defaultLayout;
1099
- this._reviewProjectionIndex ??= Ze(a);
1100
- let o = this._layoutLifecycle?.complete ?? !0 ? void 0 : { completedSourceKeys: this._reviewProjectionIndex.completedSourceKeys };
1101
- return this._commentAnchorRanges ??= lt(e, this._source, this._reviewProjectionIndex.renderedRunIndex, o), this._commentAnchorRanges;
1102
- }
1103
- revisionAnchorRanges() {
1104
- if (this._meta) return this._meta.revisionAnchorRanges ?? un;
1105
- if (!this._document || !this._source) return [];
1106
- let e = this._reviewSnapshot().revisions;
1107
- if (e.length === 0) return un;
1108
- let t = D(this), n = t.services;
1109
- if (!n) throw Error("Document layout services are not initialized");
1110
- let r = He(n);
1111
- if (!r) throw Error("Document layout variant store is not initialized");
1112
- let i = t.activeLayoutOptions, a = i ? r.layoutFor(i) : r.defaultLayout;
1113
- this._reviewProjectionIndex ??= Ze(a);
1114
- let o = this._layoutLifecycle?.complete ?? !0 ? void 0 : { completedSourceKeys: this._reviewProjectionIndex.completedSourceKeys };
1115
- return this._revisionAnchorRanges ??= Zt(e, this._source, this._reviewProjectionIndex.renderedRunIndex, o), this._revisionAnchorRanges;
1116
- }
1117
- _reviewSnapshot() {
1118
- return this._review ||= q(this._meta?.comments ?? this._document?.comments ?? [], this._meta?.revisions ?? this._document?.revisions ?? []), this._review;
1119
- }
1120
- get footnotes() {
1121
- return this._meta?.footnotes ?? this._document?.footnotes ?? [];
1122
- }
1123
- get endnotes() {
1124
- return this._meta?.endnotes ?? this._document?.endnotes ?? [];
1125
- }
1126
- _getLayout() {
1127
- if (!this._document) return null;
1128
- let e = D(this), t = e.services;
1129
- if (!t) throw Error("Document layout services are not initialized");
1130
- let n = He(t);
1131
- if (!n) throw Error("Document layout variant store is not initialized");
1132
- let r = e.activeLayoutOptions;
1133
- return r ? n.layoutFor(r) : n.defaultLayout;
1134
- }
1135
- async setLayoutView(e = {}) {
1136
- let t = e[rn], n = D(this), r = ke(e.currentDate, n.defaultCurrentDateMs, e.showTrackedChanges === !0), i = ++this._layoutViewGeneration, a = n.activeLayoutOptions;
1137
- if (!sn(a, r)) {
1138
- if (this._mode === "worker" && this._meta) {
1139
- let e = await this._bridge.request((e) => ({
1140
- type: "selectLayoutView",
1141
- id: e,
1142
- currentDateMs: r.currentDateMs,
1143
- showTrackedChanges: r.showTrackedChanges === !0
1144
- }));
1145
- if (i !== this._layoutViewGeneration) return;
1146
- let a = e;
1147
- n.activeLayoutOptions = r, this._meta = {
1148
- ...this._meta,
1149
- ...a.meta
1150
- }, this._invalidateLayoutDerivedCaches(), an(this, t);
1151
- return;
1152
- }
1153
- n.activeLayoutOptions = r, this._invalidateLayoutDerivedCaches(), an(this, t);
1154
- }
1155
- }
1156
- _getBookmarkPages() {
1157
- if (this._bookmarkPages) return this._bookmarkPages;
1158
- if (this._meta) return this._bookmarkPages = new Map(this._meta.bookmarkPages), this._bookmarkPages;
1159
- let e = this._getLayout();
1160
- return e ? (this._bookmarkPages = Et(e), this._bookmarkPages) : null;
1161
- }
1162
- getBookmarkPage(e) {
1163
- return this._getBookmarkPages()?.get(e);
1164
- }
1165
- pageSize(e) {
1166
- if (this._meta) {
1167
- let t = this._meta.pageSizes, n = t[Math.max(0, Math.min(e, t.length - 1))];
1168
- return n ? {
1169
- widthPt: n.widthPt,
1170
- heightPt: n.heightPt
1171
- } : {
1172
- widthPt: 0,
1173
- heightPt: 0
1174
- };
1175
- }
1176
- if (!this._document) return {
1177
- widthPt: 0,
1178
- heightPt: 0
1179
- };
1180
- let t = this._getLayout();
1181
- if (!t || t.pages.length === 0) return {
1182
- widthPt: 0,
1183
- heightPt: 0
1184
- };
1185
- let n = Math.max(0, Math.min(e, t.pages.length - 1)), r = t.pages[n].geometry;
1186
- return {
1187
- widthPt: r.widthPt,
1188
- heightPt: r.heightPt
1189
- };
1190
- }
1191
- _withActiveView(e) {
1192
- let t = D(this).activeLayoutOptions;
1193
- if (!t) return e;
1194
- let n = { ...e };
1195
- return e.currentDate === void 0 && (n.currentDate = t.currentDateMs), e.showTrackedChanges === void 0 && t.showTrackedChanges === !0 && (n.showTrackedChanges = !0), n;
1196
- }
1197
- renderPage(e, t, n = {}) {
1198
- if (this._mode === "worker") throw Error("renderPage(canvas) is unavailable in mode: 'worker'; use renderPageToBitmap() and paint it via an ImageBitmapRenderingContext");
1199
- if (!this._source) throw Error("Document not loaded");
1200
- return Ie(this._source, e, t, {
1201
- ...this._withActiveView(n),
1202
- fetchImage: this._fetchImage,
1203
- layoutServices: D(this).services ?? void 0,
1204
- defaultCurrentDateMs: D(this).defaultCurrentDateMs,
1205
- threeD: this._threeD,
1206
- regionMap: this._regionMap,
1207
- chartEx: this._chartEx,
1208
- tiff: this._tiff
1209
- });
1210
- }
1211
- async renderPageToBitmap(e, n = {}) {
1212
- let { onTextRun: r, ...i } = n, a = {
1213
- ...this._withActiveView(i),
1214
- dpr: i.dpr ?? t()
1215
- };
1216
- if (this._mode === "worker") {
1217
- let t = await this._bridge.request((t) => ({
1218
- type: "renderPage",
1219
- id: t,
1220
- pageIndex: e,
1221
- opts: a
1222
- }));
1223
- try {
1224
- if (r) for (let e of t.runs) r(e);
1225
- } catch (e) {
1226
- throw o(t.bitmap), e;
1227
- }
1228
- return t.bitmap;
1229
- }
1230
- let s = new OffscreenCanvas(1, 1);
1231
- return await this.renderPage(s, e, {
1232
- ...a,
1233
- onTextRun: r
1234
- }), s.transferToImageBitmap();
1235
- }
1236
- async collectPageRuns(e, t = {}) {
1237
- let n = { ...this._withActiveView(t) };
1238
- if (this._mode === "worker") return (await this._bridge.request((t) => ({
1239
- type: "collectRuns",
1240
- id: t,
1241
- pageIndex: e,
1242
- opts: n
1243
- }))).runs;
1244
- let r = D(this), i = r.services;
1245
- if (!i) throw Error("Document layout services are not initialized");
1246
- return Qe(i, e, {
1247
- currentDate: n.currentDate,
1248
- defaultCurrentDateMs: r.defaultCurrentDateMs,
1249
- width: n.width,
1250
- showTrackedChanges: n.showTrackedChanges
1251
- });
1252
- }
1253
- async getCommentThreads(e, t = {}) {
1254
- let { includeResolved: n, ...r } = t, i = await this.collectPageRuns(e, r);
1255
- return ct(this.comments, this.commentAnchorRanges(), i, { includeResolved: n });
1256
- }
1257
- async getElementContextAt(e, t, n = {}) {
1258
- let r = this._withActiveView(n);
1259
- if (this._mode === "worker") return (await this._bridge.request((n) => ({
1260
- type: "hitTestElement",
1261
- id: n,
1262
- pageIndex: e,
1263
- point: t,
1264
- opts: r
1265
- }))).context;
1266
- let i = D(this), a = i.services;
1267
- if (!a) throw Error("Document layout services are not initialized");
1268
- return Wt(a, e, t, {
1269
- ...r,
1270
- defaultCurrentDateMs: i.defaultCurrentDateMs
1271
- });
1272
- }
1273
- };
1274
- //#endregion
1275
- //#region packages/docx/src/tate-chu-yoko-overlay.ts
1276
- function fn(e, t) {
1277
- if (!e.eastAsianVert) return 1;
1278
- let n = t(e.text);
1279
- return !(n > 0) || e.w >= n ? 1 : e.w / n;
1280
- }
1281
- //#endregion
1282
- //#region packages/docx/src/text-layer.ts
1283
- function Y(e, t, n) {
1284
- 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);
1285
- }
1286
- function X(e, t, n, r, i, a, o) {
1287
- e.innerHTML = "", Y(e, "ooxmlSelectionSurface", "docx"), Y(e, "pageIndex", o === void 0 ? void 0 : String(o));
1288
- let s = e.ownerDocument ?? document;
1289
- for (let [o, c] of t.entries()) {
1290
- let t = s.createElement("span");
1291
- Y(t, "ooxmlSelectionRun", "docx"), Y(t, "runIndex", String(o)), c.paragraphId !== void 0 && Y(t, "paragraphId", c.paragraphId), c.source !== void 0 && (Y(t, "sourceStory", c.source.story), Y(t, "sourceStoryInstance", c.source.storyInstance), Y(t, "sourcePath", JSON.stringify(c.source.path))), t.textContent = c.text;
1292
- let l = c.transform ?? "";
1293
- if (a && c.eastAsianVert) {
1294
- let e = fn(c, a(c.font));
1295
- e !== 1 && (l = `${l ? `${l} ` : ""}scaleX(${e})`);
1296
- }
1297
- 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`;
1298
- t.style.cssText = `position:absolute;left:${A(c.x, n)};top:${A(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) => {
1299
- e.preventDefault(), i(d);
1300
- })), e.appendChild(t);
1301
- }
1302
- }
1303
- function Z(e, t, n, r, i, a, o = {}) {
1304
- e.innerHTML = "";
1305
- let s = o.match ?? "rgba(255, 214, 0, 0.42)", c = o.active ?? "rgba(255, 140, 0, 0.55)";
1306
- for (let o of n) {
1307
- let n = o.active ? c : s;
1308
- for (let s of o.slices) {
1309
- let o = t[s.runIndex];
1310
- if (!o) continue;
1311
- let c = a(o.font), l = at(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, _ = fn(o, c), v = h * _, y = g * _;
1312
- if (y <= 0) continue;
1313
- let b = document.createElement("div"), x = o.transform ? `transform:${o.transform};transform-origin:top left;` : "";
1314
- b.style.cssText = `position:absolute;left:${A(o.x + v, r)};top:${A(o.y, i)};width:${A(y, r)};height:${A(o.h, i)};` + x + `background:${n};pointer-events:none;`, e.appendChild(b);
1315
- }
1316
- }
1317
- }
1318
- //#endregion
1319
- //#region packages/docx/src/find.ts
1320
- var pn = class {
1321
- _pageRuns = /* @__PURE__ */ new Map();
1322
- _matches = [];
1323
- _active = -1;
1324
- _generation = 0;
1325
- _runsRevision = 0;
1326
- constructor(e, t) {
1327
- this._pageCount = e, this._collectPageRuns = t;
1328
- }
1329
- invalidate() {
1330
- this._generation++, this._runsRevision++, this._pageRuns.clear(), this._matches = [], this._active = -1;
1331
- }
1332
- pageRuns(e) {
1333
- return this._pageRuns.get(e);
1334
- }
1335
- setPageRuns(e, t) {
1336
- this._runsRevision++, this._pageRuns.set(e, t);
1337
- }
1338
- _matchAt(e) {
1339
- return this._matches[e];
1340
- }
1341
- pageHighlights(e) {
1342
- let t = [];
1343
- for (let n = 0; n < this._matches.length; n++) {
1344
- let r = this._matches[n];
1345
- r.page === e && t.push({
1346
- slices: r.slices,
1347
- active: n === this._active
1348
- });
1349
- }
1350
- return t;
1351
- }
1352
- activePage() {
1353
- let e = this._matchAt(this._active);
1354
- return e ? e.page : null;
1355
- }
1356
- matches() {
1357
- return this._matches.map((e, t) => ({
1358
- matchIndex: t,
1359
- text: e.text,
1360
- location: { page: e.page }
1361
- }));
1362
- }
1363
- async find(e, t = {}) {
1364
- let n = ++this._generation;
1365
- if (e.length === 0) return this._runsRevision++, this._pageRuns.clear(), this._matches = [], this._active = -1, [];
1366
- let r = this._runsRevision, i = new Map(this._pageRuns), a = this._pageCount();
1367
- for (let e = 0; e < a; e++) {
1368
- let t = i.get(e);
1369
- if (!t) {
1370
- try {
1371
- t = await this._collectPageRuns(e);
1372
- } catch (e) {
1373
- if (n !== this._generation) return [];
1374
- throw e;
1375
- }
1376
- if (n !== this._generation) return [];
1377
- i.set(e, t);
1378
- }
1379
- }
1380
- if (n !== this._generation) return [];
1381
- let o = r === this._runsRevision ? i : new Map([...i, ...this._pageRuns]), s = [];
1382
- for (let n = 0; n < a; n++) {
1383
- let r = o.get(n) ?? [], i = ae(r);
1384
- for (let a of ie(i, e, t)) {
1385
- let e = a.slices.map((e) => r[e.runIndex].text.slice(e.start, e.end)).join("");
1386
- s.push({
1387
- page: n,
1388
- text: e,
1389
- slices: a.slices
1390
- });
1391
- }
1392
- }
1393
- return this._runsRevision++, this._pageRuns = o, this._matches = s, this._active = -1, this.matches();
1394
- }
1395
- next() {
1396
- return this._active = ne(this._active, this._matches.length), this._activePublic();
1397
- }
1398
- prev() {
1399
- return this._active = ce(this._active, this._matches.length), this._activePublic();
1400
- }
1401
- _activePublic() {
1402
- let e = this._matchAt(this._active);
1403
- return e ? {
1404
- matchIndex: this._active,
1405
- text: e.text,
1406
- location: { page: e.page }
1407
- } : null;
1408
- }
1409
- };
1410
- //#endregion
1411
- //#region packages/docx/src/selection-context.ts
1412
- function mn(e, t, n, r, i = {}) {
1413
- let a = e.find((e) => e.id === n && e.parentId === void 0);
1414
- if (!a) return null;
1415
- let o = new Map(e.map((e) => [e.id, e])), s = e.filter((e) => {
1416
- if (e.parentId === void 0) return !1;
1417
- let t = e, n = /* @__PURE__ */ new Set();
1418
- for (; t.parentId !== void 0 && !n.has(t.id);) {
1419
- n.add(t.id);
1420
- let e = o.get(t.parentId);
1421
- if (!e) return !1;
1422
- if (e.id === a.id) return !0;
1423
- t = e;
1424
- }
1425
- return !1;
1426
- }), c = Se({
1427
- id: a.id,
1428
- author: a.author,
1429
- date: a.date,
1430
- text: a.paragraphs?.join("\n") ?? a.text,
1431
- status: a.resolved ? "resolved" : "active"
1432
- }, s.map((e) => ({
1433
- id: e.id,
1434
- author: e.author,
1435
- date: e.date,
1436
- text: e.paragraphs?.join("\n") ?? e.text,
1437
- status: e.resolved ? "resolved" : "active"
1438
- })), i.maxTextCharacters), l = t.find((e) => e.commentId === n)?.source;
1439
- return Object.freeze({
1440
- format: "docx",
1441
- kind: "comment",
1442
- pageIndex: r,
1443
- commentId: n,
1444
- ...l ? { source: Object.freeze({
1445
- ...l,
1446
- path: Object.freeze([...l.path])
1447
- }) } : {},
1448
- thread: c.thread,
1449
- truncated: c.truncated,
1450
- truncationReasons: c.truncated ? ["text"] : [],
1451
- textCharacters: c.textCharacters,
1452
- maxTextCharacters: c.maxTextCharacters
1453
- });
1454
- }
1455
- function hn(e) {
1456
- if (e === void 0 || !/^\d+$/.test(e)) return null;
1457
- let t = Number(e);
1458
- return Number.isSafeInteger(t) ? t : null;
1459
- }
1460
- function gn(e) {
1461
- for (let t = e; t; t = t.parentElement) {
1462
- let e = hn(t.dataset.pageIndex);
1463
- if (e !== null) return e;
1464
- }
1465
- return null;
1466
- }
1467
- var _n = new Set([
1468
- "body",
1469
- "header",
1470
- "footer",
1471
- "footnote",
1472
- "endnote",
1473
- "textbox"
1474
- ]);
1475
- function vn(e) {
1476
- let t = e.dataset.sourceStory, n = e.dataset.sourceStoryInstance, r = e.dataset.sourcePath;
1477
- if (!t || !_n.has(t) || !n || !r) return null;
1478
- try {
1479
- let e = JSON.parse(r);
1480
- return !Array.isArray(e) || e.length === 0 || e.length > 32 || !e.every((e) => Number.isSafeInteger(e) && e >= 0) ? null : {
1481
- story: t,
1482
- storyInstance: n,
1483
- path: [...e]
1484
- };
1485
- } catch {
1486
- return null;
1487
- }
1488
- }
1489
- function Q(e, t, n = {}) {
1490
- let r = ue(e, t, (e) => {
1491
- let t = gn(e), n = hn(e.dataset.runIndex);
1492
- return t === null || n === null ? null : {
1493
- pageIndex: t,
1494
- runIndex: n,
1495
- ...e.dataset.paragraphId === void 0 ? {} : { paragraphId: e.dataset.paragraphId },
1496
- ...vn(e) === null ? {} : { source: vn(e) }
1497
- };
1498
- }, {
1499
- maxChars: n.maxTextCharacters,
1500
- maxLocators: n.maxRunLocators
1501
- });
1502
- if (!r) return null;
1503
- let i = [...r.locators].sort((e, t) => e.pageIndex - t.pageIndex || e.runIndex - t.runIndex);
1504
- return {
1505
- format: "docx",
1506
- kind: "text",
1507
- text: r.text,
1508
- pageIndexes: [...new Set(i.map((e) => e.pageIndex))],
1509
- paragraphIds: [...new Set(i.flatMap((e) => e.paragraphId ? [e.paragraphId] : []))],
1510
- runs: i,
1511
- truncated: r.truncated,
1512
- truncationReasons: r.truncationReasons,
1513
- textCharacters: r.textCharacters,
1514
- maxTextCharacters: r.maxTextCharacters,
1515
- maxRunLocators: r.maxLocators
1516
- };
1517
- }
1518
- //#endregion
1519
- //#region packages/docx/src/focused-view-runtime.ts
1520
- function $(e, t, n, r, i) {
1521
- return r === "worker" ? e.renderPageToBitmap(n, i) : e.renderPage(t, n, i);
1522
- }
1523
- //#endregion
1524
- //#region packages/docx/src/viewer.ts
1525
- var yn = Symbol("DocxViewer.borrowedDocument"), bn = class e {
1526
- _documentOwner;
1527
- get _doc() {
1528
- return this._documentOwner.current;
1529
- }
1530
- _borrowed;
1531
- _hostWindow;
1532
- _currentPage = 0;
1533
- _scale = null;
1534
- _canvas;
1535
- _wrapper;
1536
- _canvasMount;
1537
- _textLayer = null;
1538
- _highlightLayer = null;
1539
- _elementLayer = null;
1540
- _find;
1541
- _findRequestGeneration = 0;
1542
- _measureCtx = null;
1543
- _opts;
1544
- _mode;
1545
- _renderDispatcher;
1546
- _errorRouter;
1547
- _destroyed = !1;
1548
- _selectionChangeListener = null;
1549
- _selectionContextKey = "null";
1550
- _elementContext = null;
1551
- _elementHitGeneration = 0;
1552
- _layoutViewGeneration = 0;
1553
- _layoutViewPublicationGeneration = 0;
1554
- _navigationGeneration = 0;
1555
- _layoutUnsubscribe = null;
1556
- _internalHyperlinkGeneration = 0;
1557
- _layoutWaiters = /* @__PURE__ */ new Set();
1558
- _layoutFailed = !1;
1559
- _loadingLayer;
1560
- _elementClickListener = null;
1561
- _contextMenuListener = null;
1562
- static fromDocument(t, n, r = {}) {
1563
- let i = G(n);
1564
- return new e(t, {
1565
- ...r,
1566
- currentDate: i.currentDate,
1567
- showTrackedChanges: i.showTrackedChanges,
1568
- [yn]: n
1569
- });
1570
- }
1571
- constructor(e, t = {}) {
1572
- this._canvas = e, this._opts = t;
1573
- let n = t[yn];
1574
- this._borrowed = n !== void 0, this._mode = w("DocxViewer", t.mode, n), this._documentOwner = new x("DocxViewer", n ?? null, !1);
1575
- let r = e.ownerDocument?.defaultView ?? (typeof window < "u" ? window : null);
1576
- if (!r) throw Error("DocxViewer requires a canvas with an active Window");
1577
- this._hostWindow = r, this._canvasMount = new de(e, {
1578
- wrapperCssText: "position:relative;display:inline-block;vertical-align:top;",
1579
- forceDisplayBlock: !0
1580
- }), this._wrapper = this._canvasMount.wrapper, this._renderDispatcher = new C(e, this._mode === "worker"), this._errorRouter = new le("DocxViewer", t.onError);
1581
- let i = new oe(this._wrapper, t.enableTextSelection === !0, t.enableElementSelection === !0);
1582
- this._textLayer = i.textLayer, this._highlightLayer = i.highlightLayer, this._elementLayer = i.elementLayer, this._loadingLayer = this._wrapper.ownerDocument.createElement("div"), this._loadingLayer.style.cssText = [
1583
- "position:absolute",
1584
- "inset:0",
1585
- "display:none",
1586
- "align-items:center",
1587
- "justify-content:center",
1588
- "background:rgba(255,255,255,0.72)",
1589
- "pointer-events:none",
1590
- "z-index:4"
1591
- ].join(";"), this._loadingLayer.setAttribute("role", "status"), this._loadingLayer.setAttribute("aria-live", "polite"), this._loadingLayer.setAttribute("aria-label", "Loading page");
1592
- let a = this._wrapper.ownerDocument.createElement("progress");
1593
- a.setAttribute("aria-hidden", "true"), this._loadingLayer.appendChild(a), this._wrapper.insertBefore(this._loadingLayer, this._elementLayer), this._textLayer && (t.onSelectionContextChange || t.enableElementSelection) && (this._selectionChangeListener = () => this._emitSelectionContextChange(), this._wrapper.ownerDocument.addEventListener("selectionchange", this._selectionChangeListener)), t.enableElementSelection && (this._elementClickListener = (e) => {
1594
- this._onElementClick(e).catch((e) => this._reportRenderError(e));
1595
- }, this._wrapper.addEventListener("click", this._elementClickListener)), t.onContextMenu && (this._contextMenuListener = (e) => this._onContextMenu(e), this._wrapper.addEventListener("contextmenu", this._contextMenuListener)), this._find = new pn(() => this.pageCount, (e) => this._collectPageRuns(e)), n && this._bindLayoutDocument(n);
1596
- }
1597
- async load(e) {
1598
- if (this._destroyed) throw Error("DocxViewer is destroyed");
1599
- if (this._borrowed) throw Error("DocxViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.");
1600
- let t = !1;
1601
- try {
1602
- let n = await this._documentOwner.replace(() => J.load(e, {
1603
- password: this._opts.password,
1604
- useGoogleFonts: this._opts.useGoogleFonts,
1605
- cjkFallback: this._opts.cjkFallback,
1606
- maxZipEntryBytes: this._opts.maxZipEntryBytes,
1607
- resourceLimits: this._opts.resourceLimits,
1608
- debug: this._opts.debug,
1609
- onResourceMetrics: this._opts.onResourceMetrics,
1610
- workerTimeoutMs: this._opts.workerTimeoutMs,
1611
- wasmUrl: this._opts.wasmUrl,
1612
- math: this._opts.math,
1613
- threeD: this._opts.threeD,
1614
- regionMap: this._opts.regionMap,
1615
- chartEx: this._opts.chartEx,
1616
- tiff: this._opts.tiff,
1617
- mode: this._mode,
1618
- ...this._opts.progressiveLayout ? { progressiveLayout: !0 } : {},
1619
- ...this._opts.sliceLayout ? { sliceLayout: !0 } : {},
1620
- onLayoutProgress: this._opts.onLayoutProgress,
1621
- onLayoutPartial: this._opts.onLayoutPartial,
1622
- onLayoutComplete: this._opts.onLayoutComplete,
1623
- ...this._opts.showTrackedChanges === !0 ? { showTrackedChanges: !0 } : {},
1624
- ...this._opts.currentDate === void 0 ? {} : { currentDate: this._opts.currentDate }
1625
- }), () => {
1626
- this._invalidateElementContext(!1), t = !0, this._renderDispatcher.begin(), this._findRequestGeneration++, this._find.invalidate(), this._unbindLayoutDocument();
1627
- });
1628
- if (!n) return;
1629
- if (this._destroyed) throw Error("DocxViewer is destroyed");
1630
- this._currentPage = 0, this._bindLayoutDocument(n), this._find.invalidate(), await this._render();
1631
- } catch (e) {
1632
- throw this._destroyed ? Error("DocxViewer is destroyed") : e instanceof Error ? e : Error(String(e));
1633
- }
1634
- t && !this._destroyed && this._emitSelectionContextChange();
1635
- }
1636
- get pageCount() {
1637
- return this._doc?.pageCount ?? 0;
1638
- }
1639
- get currentPage() {
1640
- return this._currentPage;
1641
- }
1642
- get layoutComplete() {
1643
- return this._doc?.layoutComplete ?? !0;
1644
- }
1645
- async waitUntilLayoutComplete() {
1646
- await this._errorRouter.ownBackgroundLifecycle(async () => {
1647
- await this._doc?.waitUntilLayoutComplete?.();
1648
- });
1649
- }
1650
- get canvasElement() {
1651
- return this._canvas;
1652
- }
1653
- async goToPage(e) {
1654
- let t = this._doc;
1655
- if (!t) return;
1656
- let n = this._cancelPendingNavigation(), r = Math.max(0, Number.isNaN(e) ? 0 : Math.trunc(e));
1657
- if (r >= this.pageCount && !this.layoutComplete) {
1658
- this._setLoading(!0);
1659
- try {
1660
- await this._waitForPage(t, r, n);
1661
- } finally {
1662
- n === this._navigationGeneration && this._setLoading(!1);
1663
- }
1664
- }
1665
- if (this._destroyed || n !== this._navigationGeneration || t !== this._doc) return;
1666
- let i = Math.max(0, Math.min(r, this.pageCount - 1)), a = i !== this._currentPage;
1667
- a && this._invalidateElementContext(!1), this._currentPage = i, await this._render(), a && !this._destroyed && this._emitSelectionContextChange();
1668
- }
1669
- async nextPage() {
1670
- await this.goToPage(this._currentPage + 1);
1671
- }
1672
- async prevPage() {
1673
- await this.goToPage(this._currentPage - 1);
1674
- }
1675
- _naturalWidthPx() {
1676
- return !this._doc || this._doc.pageCount === 0 ? 0 : this._doc.pageSize(this._currentPage).widthPt * k;
1677
- }
1678
- _renderWidth() {
1679
- if (this._scale === null) return this._opts.width;
1680
- let e = this._naturalWidthPx();
1681
- return e <= 0 ? this._opts.width : Math.round(e * this._scale);
1682
- }
1683
- getScale() {
1684
- if (this._scale !== null) return this._scale;
1685
- let e = this._naturalWidthPx();
1686
- return e <= 0 ? 1 : this._opts.width && this._opts.width > 0 ? this._opts.width / e : 1;
1687
- }
1688
- _zoomMin() {
1689
- return this._opts.zoomMin ?? .1;
1690
- }
1691
- _zoomMax() {
1692
- return this._opts.zoomMax ?? 4;
1693
- }
1694
- async setScale(e) {
1695
- let t = re(e, this._zoomMin(), this._zoomMax()), n = t !== this.getScale();
1696
- this._scale = t, await this._render(), n && this._opts.onScaleChange?.(t);
1697
- }
1698
- async zoomIn() {
1699
- await this.setScale(pe(this.getScale()));
1700
- }
1701
- async zoomOut() {
1702
- await this.setScale(ge(this.getScale()));
1703
- }
1704
- async fitWidth() {
1705
- await this._fit("width");
1706
- }
1707
- async fitPage() {
1708
- await this._fit("page");
1709
- }
1710
- async _fit(e) {
1711
- if (!this._doc || this._doc.pageCount === 0) return;
1712
- let t = this._doc.pageSize(this._currentPage), n = this._fitContainer();
1713
- if (!n) return;
1714
- let r = b({
1715
- contentWidth: t.widthPt * k,
1716
- contentHeight: t.heightPt * k,
1717
- containerWidth: n.clientWidth,
1718
- containerHeight: n.clientHeight
1719
- }, e);
1720
- r <= 0 || await this.setScale(r);
1721
- }
1722
- _fitContainer() {
1723
- return this._opts.container ?? this._wrapper.parentElement ?? null;
1724
- }
1725
- async findText(e, t = {}) {
1726
- let n = this._doc;
1727
- if (!n) return [];
1728
- let r = ++this._findRequestGeneration;
1729
- if (e.length > 0 && !n.layoutComplete && (await this._errorRouter.ownBackgroundLifecycle(() => n.waitUntilLayoutComplete()), this._destroyed || this._doc !== n || r !== this._findRequestGeneration)) return [];
1730
- let i = await this._errorRouter.ownAwaitable(() => this._find.find(e, t));
1731
- return this._redrawHighlights(), i;
1732
- }
1733
- async findNext() {
1734
- return this._activateMatch(this._find.next());
1735
- }
1736
- async findPrev() {
1737
- return this._activateMatch(this._find.prev());
1738
- }
1739
- clearFind() {
1740
- this._findRequestGeneration++, this._find.invalidate(), this._redrawHighlights();
1741
- }
1742
- async _activateMatch(e) {
1743
- return e ? (e.location.page === this._currentPage ? this._redrawHighlights() : await this.goToPage(e.location.page), e) : (this._redrawHighlights(), null);
1744
- }
1745
- _redrawHighlights() {
1746
- let e = this._find.pageRuns(this._currentPage) ?? [];
1747
- this._buildHighlightLayer(e);
1748
- }
1749
- async getResourceMetrics() {
1750
- if (!this._doc) throw Error("Document not loaded");
1751
- return await this._doc.getResourceMetrics();
1752
- }
1753
- getSelectionContext(e = {}) {
1754
- if (this._destroyed) throw Error("DocxViewer is destroyed");
1755
- return (this._textLayer ? Q(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null, e) : null) ?? (this._elementContext ? Gt(this._elementContext, e.maxTextCharacters) : null);
1756
- }
1757
- _emitSelectionContextChange() {
1758
- let e = this.getSelectionContext();
1759
- e?.kind === "text" && (this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutline());
1760
- let t = JSON.stringify(e);
1761
- t !== this._selectionContextKey && (this._selectionContextKey = t, this._opts.onSelectionContextChange?.(e ? structuredClone(e) : null));
1762
- }
1763
- _setElementContext(e) {
1764
- this._elementContext = e ? structuredClone(e) : null, this._redrawElementOutline(), this._emitSelectionContextChange();
1765
- }
1766
- _invalidateElementContext(e = !0) {
1767
- this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutline(), e && this._emitSelectionContextChange();
1768
- }
1769
- _redrawElementOutline() {
1770
- let e = this._elementContext, t = this._doc;
1771
- if (!e || !t || e.pageIndex !== this._currentPage) {
1772
- S(this._elementLayer, null);
1773
- return;
1774
- }
1775
- let n = t.pageSize(e.pageIndex);
1776
- S(this._elementLayer, {
1777
- x: e.bounds.xPt / n.widthPt,
1778
- y: e.bounds.yPt / n.heightPt,
1779
- width: e.bounds.widthPt / n.widthPt,
1780
- height: e.bounds.heightPt / n.heightPt
1781
- });
1782
- }
1783
- async _onElementClick(e) {
1784
- this._destroyed || e.defaultPrevented || e.button !== 0 || await this._resolveContextAt(e);
1785
- }
1786
- _onContextMenu(e) {
1787
- let t;
1788
- this._opts.onContextMenu?.({
1789
- originalEvent: e,
1790
- getContext: () => t ??= this._resolveContextAt(e)
1791
- });
1792
- }
1793
- async _resolveContextAt(e) {
1794
- let t = this._doc;
1795
- if (this._destroyed || !t) return null;
1796
- if (this._textLayer && Q(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null)) return this._emitSelectionContextChange(), this._destroyed ? null : this.getSelectionContext();
1797
- if (!this._opts.enableElementSelection) return this.getSelectionContext();
1798
- let n = this._canvas.getBoundingClientRect();
1799
- if (n.width <= 0 || n.height <= 0) return this._invalidateElementContext(), null;
1800
- let r = e.clientX - n.left, i = e.clientY - n.top;
1801
- if (r < 0 || i < 0 || r > n.width || i > n.height) return this._invalidateElementContext(), null;
1802
- let a = ++this._elementHitGeneration, o = this._currentPage, s = t.pageSize(o), c;
1803
- try {
1804
- c = await t.getElementContextAt(o, {
1805
- xPt: r / n.width * s.widthPt,
1806
- yPt: i / n.height * s.heightPt
1807
- }, {
1808
- currentDate: this._opts.currentDate,
1809
- showTrackedChanges: this._opts.showTrackedChanges,
1810
- maxTextCharacters: I
1811
- });
1812
- } catch (e) {
1813
- if (this._destroyed || a !== this._elementHitGeneration || o !== this._currentPage || t !== this._doc) return null;
1814
- throw e;
1815
- }
1816
- return this._destroyed || a !== this._elementHitGeneration || o !== this._currentPage || t !== this._doc ? null : (this._setElementContext(c), this._destroyed ? null : this.getSelectionContext());
1817
- }
1818
- destroy() {
1819
- this._destroyed || (this._destroyed = !0, this._findRequestGeneration++, this._layoutViewGeneration++, this._unbindLayoutDocument(), this._errorRouter.close(), this._renderDispatcher.destroy(), Ye(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());
1820
- }
1821
- async _render() {
1822
- let e = this._renderDispatcher.begin();
1823
- try {
1824
- await this._renderPage(e);
1825
- } catch (t) {
1826
- if (!this._renderDispatcher.isCurrent(e)) return;
1827
- throw t;
1828
- }
1829
- }
1830
- _reportRenderError(e) {
1831
- this._errorRouter.report(e);
1832
- }
1833
- async _renderPage(e) {
1834
- if (!this._doc) return;
1835
- let t = this._mode === "worker", n = this._renderWidth(), r = this._doc.pageSize(this._currentPage), i = n ?? r.widthPt * 1.3333333333333333, a = r.widthPt > 0 ? i * r.heightPt / r.widthPt : 0, o = [], s = (e) => o.push(e), c = this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1), l = {
1836
- width: n,
1837
- dpr: this._opts.dpr,
1838
- imageResources: this._opts.imageResources,
1839
- defaultTextColor: this._opts.defaultTextColor,
1840
- currentDate: this._opts.currentDate,
1841
- showTrackedChanges: this._opts.showTrackedChanges,
1842
- onTextRun: s
1843
- };
1844
- if (t) {
1845
- let t = await $(this._doc, this._canvas, this._currentPage, "worker", l);
1846
- if (!this._renderDispatcher.commitBitmap(e, t, {
1847
- cssWidth: i > 0 ? i : Math.round(t.width / c),
1848
- cssHeight: a > 0 ? a : Math.round(t.height / c)
1849
- })) return;
1850
- } else if (await $(this._doc, this._canvas, this._currentPage, "main", l), !this._renderDispatcher.isCurrent(e)) return;
1851
- this._textLayer && this._buildTextLayer(this._textLayer, o), this._find.setPageRuns(this._currentPage, o), this._buildHighlightLayer(o), this._opts.onPageChange?.(this._currentPage, this.pageCount, this.layoutComplete);
1852
- }
1853
- _bindLayoutDocument(e) {
1854
- this._unbindLayoutDocument(), this._layoutFailed = !1, this._layoutViewPublicationGeneration = 0;
1855
- let t = on(e, (t) => this._onLayoutViewPublication(e, t), (e) => this._reportRenderError(e)), n = !0, r = tn(e, () => ({
1856
- pageCount: e.pageCount,
1857
- exact: e.layoutComplete,
1858
- complete: e.layoutComplete
1859
- }), (t) => {
1860
- if (n) {
1861
- n = !1;
1862
- return;
1863
- }
1864
- this._onLayoutPublication(e, t);
1865
- }, (e) => this._reportRenderError(e));
1866
- this._layoutUnsubscribe = () => {
1867
- r(), t();
1868
- };
1869
- }
1870
- _unbindLayoutDocument() {
1871
- this._layoutUnsubscribe?.(), this._layoutUnsubscribe = null, this._layoutFailed = !1, this._cancelPendingNavigation();
1872
- }
1873
- _onLayoutPublication(e, t) {
1874
- if (!(this._destroyed || e !== this._doc)) {
1875
- if (this._wakeLayoutWaiters(), t.error !== void 0) {
1876
- this._layoutFailed = !0, this._errorRouter.reportBackground(t.error, this._opts.onLayoutComplete !== void 0);
1877
- return;
1878
- }
1879
- this._find.invalidate(), this._currentPage = Math.max(0, Math.min(this._currentPage, t.pageCount - 1)), this._render().catch((e) => this._reportRenderError(e));
1880
- }
1881
- }
1882
- _onLayoutViewPublication(e, t) {
1883
- this._destroyed || e !== this._doc || t.generation <= this._layoutViewPublicationGeneration || (this._layoutViewPublicationGeneration = t.generation, t.requester !== this && (this._layoutViewGeneration++, this._opts = {
1884
- ...this._opts,
1885
- currentDate: t.view.currentDate,
1886
- showTrackedChanges: t.view.showTrackedChanges
1887
- }, this._find.invalidate(), this._currentPage = Math.max(0, Math.min(this._currentPage, e.pageCount - 1)), this._render().catch((e) => this._reportRenderError(e))));
1888
- }
1889
- async _waitForPage(e, t, n) {
1890
- await this._errorRouter.ownBackgroundLifecycle(async () => {
1891
- for (; !this._destroyed && n === this._navigationGeneration && e === this._doc && t >= e.pageCount && !e.layoutComplete && !this._layoutFailed;) await new Promise((e) => {
1892
- this._layoutWaiters.add(e);
1893
- });
1894
- e === this._doc && (e.layoutComplete || this._layoutFailed) && await e.waitUntilLayoutComplete();
1895
- });
1896
- }
1897
- _wakeLayoutWaiters() {
1898
- for (let e of this._layoutWaiters) e();
1899
- this._layoutWaiters.clear();
1900
- }
1901
- _cancelPendingNavigation() {
1902
- let e = ++this._navigationGeneration;
1903
- return this._wakeLayoutWaiters(), this._setLoading(!1), e;
1904
- }
1905
- _setLoading(e) {
1906
- this._loadingLayer.style.display = e ? "flex" : "none";
1907
- }
1908
- async setShowTrackedChanges(e) {
1909
- let t = ++this._layoutViewGeneration, n = this._doc;
1910
- if (this._opts.showTrackedChanges === !0 === e) {
1911
- n && await K(n, {
1912
- showTrackedChanges: e,
1913
- currentDate: this._opts.currentDate
1914
- }, this);
1915
- return;
1916
- }
1917
- let r = {
1918
- ...this._opts,
1919
- showTrackedChanges: e
1920
- };
1921
- (!n || await K(n, {
1922
- showTrackedChanges: e,
1923
- currentDate: r.currentDate
1924
- }, this)) && (this._destroyed || t !== this._layoutViewGeneration || n !== this._doc || (this._opts = r, this._find.invalidate(), this._currentPage = Math.max(0, Math.min(this._currentPage, this.pageCount - 1)), await this._render()));
1925
- }
1926
- _buildHighlightLayer(e) {
1927
- let t = this._highlightLayer;
1928
- if (!t) return;
1929
- let { width: n, height: r } = this._canvasCssPx();
1930
- Z(t, e, this._find.pageHighlights(this._currentPage), n, r, (e) => this._measureForFont(e), this._opts.findHighlightColors);
1931
- }
1932
- _canvasCssPx() {
1933
- return {
1934
- width: parseFloat(this._canvas.style.width) || this._canvas.width,
1935
- height: parseFloat(this._canvas.style.height) || this._canvas.height
1936
- };
1937
- }
1938
- _measureForFont(e) {
1939
- this._measureCtx ||= document.createElement("canvas").getContext("2d");
1940
- let t = this._measureCtx;
1941
- return t ? (t.font = e, (e) => t.measureText(e).width) : (e) => e.length;
1942
- }
1943
- async _collectPageRuns(e) {
1944
- return this._doc ? this._doc.collectPageRuns(e, {
1945
- width: this._renderWidth(),
1946
- currentDate: this._opts.currentDate,
1947
- showTrackedChanges: this._opts.showTrackedChanges
1948
- }) : [];
1949
- }
1950
- _buildTextLayer(e, t) {
1951
- let { width: n, height: r } = this._canvasCssPx();
1952
- X(e, t, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), this._currentPage);
1953
- }
1954
- _hyperlinkHandler() {
1955
- return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
1956
- if (e.kind === "external") {
1957
- u(e.url, void 0, this._hostWindow);
1958
- return;
1959
- }
1960
- let t = this._doc;
1961
- if (!t) return;
1962
- let n = ++this._internalHyperlinkGeneration;
1963
- this._navigateInternalHyperlink(t, e.ref, n).catch((e) => this._reportRenderError(e));
1964
- });
1965
- }
1966
- async _navigateInternalHyperlink(e, t, n) {
1967
- if (e.layoutComplete || await e.waitUntilLayoutComplete(), this._destroyed || this._doc !== e || n !== this._internalHyperlinkGeneration) return;
1968
- let r = e.getBookmarkPage(t);
1969
- r !== void 0 && await this.goToPage(r);
1970
- }
1971
- }, xn = 150, Sn = "0 1px 3px rgba(0,0,0,0.2)", Cn = 12, wn = 13, Tn = Symbol("DocxScrollViewer.borrowedDocument"), En;
1972
- function Dn() {
1973
- return En ??= import("./comment-ui-runtime-DcJOYlw-.js");
1974
- }
1975
- var On = class e {
1976
- _documentOwner;
1977
- get _doc() {
1978
- return this._documentOwner.current;
1979
- }
1980
- _borrowed;
1981
- _opts;
1982
- _errorRouter;
1983
- _container;
1984
- _wrapper;
1985
- _scrollHost;
1986
- _spacer;
1987
- _mode;
1988
- _scale = 1;
1989
- _scaleEstablished = !1;
1990
- _pendingScale = null;
1991
- _slots = /* @__PURE__ */ new Map();
1992
- _free = [];
1993
- _heights = [];
1994
- _scrollGeometry = {
1995
- offsets: [],
1996
- totalHeight: 0
1997
- };
1998
- _lastRange = null;
1999
- _lastTopIndex = -1;
2000
- _lastReportedTotal = -1;
2001
- _lastReportedLayoutComplete = null;
2002
- _layoutUnsubscribe = null;
2003
- _presentedPageCount = 0;
2004
- _scrollListener = null;
2005
- _selectionChangeListener = null;
2006
- _selectionContextKey = "null";
2007
- _elementClickListener = null;
2008
- _contextMenuListener = null;
2009
- _commentOutsidePointerListener = null;
2010
- _elementContext = null;
2011
- _activeCommentId = null;
2012
- _activeCommentPage = null;
2013
- _commentUi = null;
2014
- _commentPageById = /* @__PURE__ */ new Map();
2015
- _commentRunsByPage = /* @__PURE__ */ new Map();
2016
- _commentIndexedPages = /* @__PURE__ */ new Set();
2017
- _commentScanFrontier = 0;
2018
- _commentNavigationGeneration = 0;
2019
- _internalHyperlinkGeneration = 0;
2020
- _commentAnchorRangesForMargin = null;
2021
- _commentAnchorIds = /* @__PURE__ */ new Set();
2022
- _reviewOriginPx = 0;
2023
- _commentGeometryScheduled = !1;
2024
- _commentGeometryFrame = null;
2025
- _pendingCommentGeometry = /* @__PURE__ */ new Map();
2026
- _elementHitGeneration = 0;
2027
- _destroyed = !1;
2028
- _measureCtx;
2029
- _bitmapInFlight = /* @__PURE__ */ new Set();
2030
- _renderEpoch = 0;
2031
- _settleTimer = null;
2032
- _wheelListener = null;
2033
- _pendingZoomAnchor = null;
2034
- _resizeObserver = null;
2035
- _prevBase = 0;
2036
- _lastFitWidth = 0;
2037
- _pageShadow;
2038
- _find = new pn(() => this.pageCount, (e) => this._collectPageRuns(e));
2039
- _findActive = !1;
2040
- _findRequestGeneration = 0;
2041
- _showTrackedChanges;
2042
- _currentDate;
2043
- _layoutViewGeneration = 0;
2044
- _layoutViewPublicationGeneration = 0;
2045
- static fromDocument(t, n, r = {}) {
2046
- let i = G(n);
2047
- return new e(t, {
2048
- ...r,
2049
- currentDate: i.currentDate,
2050
- showTrackedChanges: i.showTrackedChanges,
2051
- [Tn]: n
2052
- });
2053
- }
2054
- constructor(e, t = {}) {
2055
- 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.");
2056
- this._container = e, this._opts = t, this._errorRouter = new le("DocxScrollViewer", t.onError), this._showTrackedChanges = t.showTrackedChanges === !0, this._currentDate = t.currentDate, this._pageShadow = t.pageShadow ?? Sn;
2057
- let n = t[Tn];
2058
- this._borrowed = n !== void 0, n ? (this._documentOwner = new x("DocxScrollViewer", n, !1), this._mode = w("DocxScrollViewer", t.mode, n)) : (this._documentOwner = new x("DocxScrollViewer"), this._mode = w("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() && Dn().then((e) => {
2059
- if (!this._destroyed) {
2060
- this._commentUi = e;
2061
- for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
2062
- }
2063
- }).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) => {
2064
- this._onElementClick(e).catch((e) => this._reportRenderError(e));
2065
- }, 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) => {
2066
- if (!Te(e, this._wrapper, "ooxmlCommentId") && this._activeCommentId !== null) {
2067
- this._activeCommentId = null, this._activeCommentPage = null;
2068
- for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
2069
- this._emitSelectionContextChange();
2070
- }
2071
- }, this._wrapper.ownerDocument.addEventListener("pointerdown", this._commentOutsidePointerListener)), this._opts.enableZoom !== !1 && (this._wheelListener = (e) => {
2072
- if (!(e.ctrlKey || e.metaKey) || (e.preventDefault(), e.deltaY === 0)) return;
2073
- let t = this._scrollHost.getBoundingClientRect(), n = e.clientX - t.left, r = e.clientY - t.top;
2074
- this._pendingZoomAnchor = Number.isFinite(n) && Number.isFinite(r) ? {
2075
- x: n,
2076
- y: r
2077
- } : null, this.setScale(he(this._scale, e.deltaY, e.deltaMode));
2078
- }, 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._bindLayoutDocument(n), this.relayout());
2079
- }
2080
- async load(e) {
2081
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2082
- if (this._borrowed) throw Error("DocxScrollViewer.load() is unsupported on a Viewer created by fromDocument(); the borrowed document is already loaded.");
2083
- let t = !1;
2084
- try {
2085
- let n = await this._documentOwner.replace(() => J.load(e, {
2086
- password: this._opts.password,
2087
- useGoogleFonts: this._opts.useGoogleFonts,
2088
- cjkFallback: this._opts.cjkFallback,
2089
- maxZipEntryBytes: this._opts.maxZipEntryBytes,
2090
- resourceLimits: this._opts.resourceLimits,
2091
- debug: this._opts.debug,
2092
- onResourceMetrics: this._opts.onResourceMetrics,
2093
- workerTimeoutMs: this._opts.workerTimeoutMs,
2094
- wasmUrl: this._opts.wasmUrl,
2095
- math: this._opts.math,
2096
- threeD: this._opts.threeD,
2097
- regionMap: this._opts.regionMap,
2098
- chartEx: this._opts.chartEx,
2099
- tiff: this._opts.tiff,
2100
- mode: this._mode,
2101
- ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2102
- ...this._currentDate === void 0 ? {} : { currentDate: this._currentDate },
2103
- ...this._opts.progressiveLayout ? { progressiveLayout: !0 } : {},
2104
- ...this._opts.sliceLayout ? { sliceLayout: !0 } : {},
2105
- onLayoutProgress: this._opts.onLayoutProgress,
2106
- onLayoutPartial: this._opts.onLayoutPartial,
2107
- onLayoutComplete: this._opts.onLayoutComplete
2108
- }), (e) => {
2109
- if (this._invalidateElementContext(!1), t = !0, this._findRequestGeneration++, this._find.invalidate(), this._findActive = !1, this._activeCommentId = null, this._activeCommentPage = null, this._resetCommentNavigation(), this._unbindLayoutDocument(), e) {
2110
- for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
2111
- this._lastTopIndex = -1, this._lastReportedTotal = -1, this._lastReportedLayoutComplete = null;
2112
- }
2113
- });
2114
- if (!n) return;
2115
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2116
- this._bindLayoutDocument(n), this._find.invalidate(), this._findActive = !1, this._activeCommentId = null, this._activeCommentPage = null, this._resetCommentNavigation();
2117
- let r = [];
2118
- this._relayout(r), await Promise.all(r);
2119
- } catch (e) {
2120
- throw this._destroyed ? Error("DocxScrollViewer is destroyed") : e instanceof Error ? e : Error(String(e));
2121
- }
2122
- t && !this._destroyed && this._emitSelectionContextChange();
2123
- }
2124
- get pageCount() {
2125
- return this._doc?.pageCount ?? 0;
2126
- }
2127
- get layoutComplete() {
2128
- return this._doc?.layoutComplete ?? !0;
2129
- }
2130
- async waitUntilLayoutComplete() {
2131
- await this._errorRouter.ownBackgroundLifecycle(async () => {
2132
- await this._doc?.waitUntilLayoutComplete?.();
2133
- });
2134
- }
2135
- _bindLayoutDocument(e) {
2136
- this._unbindLayoutDocument(), this._layoutViewPublicationGeneration = 0, this._presentedPageCount = e.pageCount;
2137
- let t = on(e, (t) => this._onLayoutViewPublication(e, t), (e) => this._reportRenderError(e)), n = !0, r = tn(e, () => ({
2138
- pageCount: e.pageCount,
2139
- exact: e.layoutComplete,
2140
- complete: e.layoutComplete
2141
- }), (t) => {
2142
- if (n) {
2143
- n = !1;
2144
- return;
2145
- }
2146
- this._onLayoutPublication(e, t);
2147
- }, (e) => this._reportRenderError(e));
2148
- this._layoutUnsubscribe = () => {
2149
- r(), t();
2150
- };
2151
- }
2152
- _unbindLayoutDocument() {
2153
- this._layoutUnsubscribe?.(), this._layoutUnsubscribe = null, this._presentedPageCount = 0;
2154
- }
2155
- _onLayoutPublication(e, t) {
2156
- if (!(this._destroyed || e !== this._doc)) {
2157
- if (t.error !== void 0) {
2158
- this._errorRouter.reportBackground(t.error, this._opts.onLayoutComplete !== void 0);
2159
- return;
2160
- }
2161
- this._find.invalidate(), this._refreshCommentSurface(), this._applyLayoutPublication(t);
2162
- }
2163
- }
2164
- _onLayoutViewPublication(e, t) {
2165
- this._destroyed || e !== this._doc || t.generation <= this._layoutViewPublicationGeneration || (this._layoutViewPublicationGeneration = t.generation, t.requester !== this && (this._layoutViewGeneration++, this._showTrackedChanges = t.view.showTrackedChanges, this._currentDate = t.view.currentDate, this._find.invalidate(), this._applyLayoutPublication({
2166
- pageCount: e.pageCount,
2167
- exact: !0,
2168
- complete: e.layoutComplete
2169
- })));
2170
- }
2171
- _refreshCommentSurface() {
2172
- if (!(!this._commentsEnabled() || this._slots.size === 0)) {
2173
- this._syncSpacerWidth();
2174
- for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
2175
- }
2176
- }
2177
- _applyLayoutPublication(e) {
2178
- let t = [...this._slots];
2179
- this._presentedPageCount = e.pageCount, this._renderEpoch++, this.relayout();
2180
- for (let [e, n] of t) e >= this._presentedPageCount || this._slots.get(e) !== n || this._refreshSlotAtomically(e, n);
2181
- }
2182
- _pageWidthPx(e) {
2183
- return this._doc.pageSize(e).widthPt * k * this._scale;
2184
- }
2185
- _pageHeightPx(e) {
2186
- return this._doc.pageSize(e).heightPt * k * this._scale;
2187
- }
2188
- _fitWidthPx() {
2189
- if (this._opts.width && this._opts.width > 0) return this._opts.width;
2190
- let e = this._scrollHost.clientWidth || this._container.clientWidth;
2191
- if (e <= 0) return 0;
2192
- let { left: t, right: n } = this._padH(), r = e - t - n;
2193
- return r <= 0 ? 0 : r;
2194
- }
2195
- _hasCommentMargin() {
2196
- return this._hasDisplayableComments() && this._commentsOptions()?.cards !== !1;
2197
- }
2198
- _hasDisplayableComments() {
2199
- if (!this._commentsEnabled()) return !1;
2200
- let e = this._doc;
2201
- if (!e) return !1;
2202
- let t = e.commentAnchorRanges();
2203
- if (this._commentAnchorRangesForMargin !== t && (this._commentAnchorRangesForMargin = t, this._commentAnchorIds = new Set(t.map((e) => e.commentId))), this._commentAnchorIds.size === 0) return !1;
2204
- let n = this._commentsOptions()?.includeResolved === !0;
2205
- return e.comments.some((e) => this._commentAnchorIds.has(e.id) && e.parentId === void 0 && (n || e.resolved !== !0));
2206
- }
2207
- _commentMarginExtent() {
2208
- return this._hasCommentMargin() ? (Cn + 280) * this._commentZoom() : 0;
2209
- }
2210
- _commentZoom() {
2211
- return this._scaleEstablished ? this._scale : 1;
2212
- }
2213
- _commentsEnabled() {
2214
- return this._opts.comments === !0 || typeof this._opts.comments == "object";
2215
- }
2216
- _commentsOptions() {
2217
- return typeof this._opts.comments == "object" ? this._opts.comments : void 0;
2218
- }
2219
- _commentSide() {
2220
- let e = this._commentsOptions()?.side;
2221
- return e === "left" || e === "right" ? e : (this._container.ownerDocument.defaultView?.getComputedStyle?.(this._container).direction || this._container.dir || this._container.style.direction) === "rtl" ? "left" : "right";
2222
- }
2223
- _syncCommentMarginGeometry(e) {
2224
- if (!e) return;
2225
- e.style.display = this._hasCommentMargin() ? "" : "none";
2226
- let t = this._commentZoom(), n = `calc(100% + ${Cn * t}px)`;
2227
- e.style.left = this._commentSide() === "right" ? n : "", e.style.right = this._commentSide() === "left" ? n : "", e.style.width = `${280 * t}px`, e.style.fontSize = `${wn}px`, e.dataset.ooxmlCommentZoom = String(t);
2228
- }
2229
- _widestPageWidthPt() {
2230
- if (!this._doc) return 0;
2231
- let e = 0, t = this._presentedPageCount || this._doc.pageCount;
2232
- for (let n = 0; n < t; n++) {
2233
- let t = this._doc.pageSize(n).widthPt;
2234
- t > e && (e = t);
2235
- }
2236
- return e;
2237
- }
2238
- _baseScale() {
2239
- if (!this._doc || this._doc.pageCount === 0) return 0;
2240
- let e = this._fitWidthPx();
2241
- if (e <= 0) return 0;
2242
- let t = this._widestPageWidthPt();
2243
- return t <= 0 ? 0 : e / (t * k);
2244
- }
2245
- relayout() {
2246
- this._relayout();
2247
- }
2248
- _relayout(e) {
2249
- if (this._doc) {
2250
- if (this._doc.layoutComplete !== !1 && (this._presentedPageCount = this._doc.pageCount), this._scaleEstablished) {
2251
- let e = this._baseScale();
2252
- if (e > 0 && e !== this._prevBase) {
2253
- let t = this._prevBase > 0 ? this._scale / this._prevBase : 1;
2254
- this._prevBase = e, this.setScale(e * t);
2255
- }
2256
- } else {
2257
- let e = this._baseScale();
2258
- if (e > 0) {
2259
- if (this._scale = e, this._prevBase = e, this._lastFitWidth = this._fitWidthPx(), this._scaleEstablished = !0, this._pendingScale !== null) {
2260
- let e = this._pendingScale;
2261
- this._pendingScale = null, e !== this._scale && (this._scale = e, this._opts.onScaleChange?.(e));
2262
- }
2263
- } else return;
2264
- }
2265
- this._recomputeHeights(), this._syncSpacer(), this._mountVisible(e);
2266
- for (let [e, t] of this._slots) t.renderedPage === e && t.renderedScale >= 0 && this._redrawSlotComments(e, t);
2267
- }
2268
- }
2269
- _recomputeHeights() {
2270
- let e = Math.min(this._presentedPageCount, this._doc.pageCount), t = Array(e);
2271
- for (let n = 0; n < e; n++) t[n] = this._pageHeightPx(n);
2272
- this._heights = t, this._scrollGeometry = we(t, this._gap(), this._pad());
2273
- }
2274
- _gap() {
2275
- return this._opts.gap ?? 16;
2276
- }
2277
- _overscan() {
2278
- return this._opts.overscan ?? 1;
2279
- }
2280
- _pad() {
2281
- let e = this._gap();
2282
- return {
2283
- leading: this._opts.paddingTop ?? e,
2284
- trailing: this._opts.paddingBottom ?? e
2285
- };
2286
- }
2287
- _padH() {
2288
- let e = this._gap();
2289
- return {
2290
- left: this._opts.paddingLeft ?? e,
2291
- right: this._opts.paddingRight ?? e
2292
- };
2293
- }
2294
- _pageIndexAtOffset(e, t) {
2295
- let { offsets: n } = e, r = 0, i = n.length - 1, a = 0;
2296
- for (; r <= i;) {
2297
- let e = r + i >> 1;
2298
- n[e] <= t ? (a = e, r = e + 1) : i = e - 1;
2299
- }
2300
- return a;
2301
- }
2302
- _range() {
2303
- return T(this._scrollGeometry, this._scrollHost.scrollTop, this._scrollHost.clientHeight, this._overscan());
2304
- }
2305
- _syncSpacer() {
2306
- let e = this._range();
2307
- this._lastRange = e, this._spacer.style.height = `${e.totalHeight}px`, this._syncSpacerWidth();
2308
- }
2309
- _syncSpacerWidth() {
2310
- let { left: e, right: t } = this._padH(), n = 0;
2311
- for (let e = 0; e < this._heights.length; e++) {
2312
- let t = this._pageWidthPx(e);
2313
- t > n && (n = t);
2314
- }
2315
- let r = this._commentMarginExtent(), i = this._commentSide() === "left" ? r : 0, a = i - this._reviewOriginPx, o = Math.max(0, this._scrollHost.scrollLeft + a);
2316
- this._spacer.style.width = `${n + r + e + t}px`, a !== 0 && (this._reviewOriginPx = i, this._scrollHost.style["--ooxml-review-origin-x"] = `${i}px`, this._scrollHost.scrollLeft = o);
2317
- }
2318
- _onScroll() {
2319
- !this._doc || !this._scaleEstablished || this._mountVisible(void 0, !1);
2320
- }
2321
- _mountVisible(e, t = !0) {
2322
- if (!this._doc || this._doc.pageCount === 0) return;
2323
- let n = this._range();
2324
- this._lastRange = n;
2325
- for (let [e, t] of [...this._slots]) (e < n.start || e > n.end) && this._recycleSlot(e, t);
2326
- for (let r = n.start; r <= n.end; r++) if (!this._slots.has(r)) {
2327
- let t = this._acquireSlot();
2328
- this._positionSlot(t, r, n), this._slots.set(r, t);
2329
- let i = this._renderSlot(r, t, e === void 0);
2330
- e && i && e.push(i);
2331
- } else if (t) {
2332
- let t = this._slots.get(r);
2333
- this._positionSlot(t, r, n);
2334
- let i = this._renderSlot(r, t, e === void 0);
2335
- e && i && e.push(i);
2336
- }
2337
- this._emitVisiblePageChange(n);
2338
- }
2339
- _emitVisiblePageChange(e) {
2340
- if (!this._doc) return;
2341
- let t = this._doc.pageCount, n = this.layoutComplete;
2342
- e.topIndex === this._lastTopIndex && t === this._lastReportedTotal && n === this._lastReportedLayoutComplete || (this._lastTopIndex = e.topIndex, this._lastReportedTotal = t, this._lastReportedLayoutComplete = n, this._opts.onVisiblePageChange?.(e.topIndex, t, n));
2343
- }
2344
- _applyPageShadow(e) {
2345
- this._pageShadow !== !1 && (e.style.boxShadow = this._pageShadow);
2346
- }
2347
- _acquireSlot() {
2348
- let e = this._free.pop();
2349
- if (e) return this._scrollHost.appendChild(e.wrapper), e;
2350
- let t = document.createElement("div");
2351
- t.style.cssText = "position:absolute;";
2352
- let n = document.createElement("canvas");
2353
- n.style.cssText = "display:block;background:#fff;", this._applyPageShadow(n), t.appendChild(n);
2354
- let r = null;
2355
- 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));
2356
- let i = document.createElement("div");
2357
- i.style.cssText = "position:absolute;top:0;left:0;width:100%;height:100%;overflow:hidden;pointer-events:none;", t.appendChild(i);
2358
- let a = null, o = null, s = null;
2359
- this._commentsEnabled() && (a = document.createElement("div"), a.style.cssText = "position:absolute;inset:0;overflow:hidden;pointer-events:none;", t.appendChild(a), this._commentsOptions()?.cards !== !1 && (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)));
2360
- let c = se(t, this._opts.enableElementSelection === !0);
2361
- return this._scrollHost.appendChild(t), {
2362
- wrapper: t,
2363
- canvas: n,
2364
- textLayer: r,
2365
- highlightLayer: i,
2366
- elementLayer: c,
2367
- commentTintLayer: a,
2368
- commentMargin: o,
2369
- commentDecorationLayer: s,
2370
- commentRuns: Object.freeze([]),
2371
- commentGeometry: null,
2372
- renderedPage: -1,
2373
- renderedScale: -1,
2374
- dispatcher: new C(n, this._mode === "worker")
2375
- };
2376
- }
2377
- _recycleSlot(e, t) {
2378
- this._slots.delete(e), t.dispatcher.destroy(), this._destroyed || (t.dispatcher = new C(t.canvas, this._mode === "worker")), t.textLayer && (t.textLayer.innerHTML = "", this._clearTextLayerPreview(t.textLayer)), 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, S(t.elementLayer, null), t.renderedPage = -1, t.renderedScale = -1, t.wrapper.remove(), this._free.push(t);
2379
- }
2380
- _positionSlot(e, t, n) {
2381
- e.wrapper.style.top = `${n.offsets[t]}px`;
2382
- let r = this._pageWidthPx(t), i = this._pageHeightPx(t);
2383
- if (e.wrapper.style.width = `${r}px`, e.wrapper.style.height = `${i}px`, this._syncCommentMarginGeometry(e.commentMargin), e.commentDecorationLayer) {
2384
- let t = this._commentMarginExtent();
2385
- e.commentDecorationLayer.style.left = this._commentSide() === "left" ? `${-t}px` : "0px", e.commentDecorationLayer.style.width = `${r + t}px`, e.commentDecorationLayer.style.height = `${i}px`;
2386
- }
2387
- this._redrawElementOutlineForSlot(t, e);
2388
- let { left: a } = this._padH(), o = Math.max(a, (this._scrollHost.clientWidth - r) / 2);
2389
- e.wrapper.style.left = this._commentSide() === "left" && this._commentsEnabled() ? `calc(${o}px + var(--ooxml-review-origin-x, 0px))` : `${o}px`;
2390
- }
2391
- _dpr() {
2392
- return this._opts.dpr ?? (typeof window < "u" && window.devicePixelRatio || 1);
2393
- }
2394
- _renderSlot(e, t, n = !0) {
2395
- if (!this._doc || t.renderedPage === e) return null;
2396
- t.renderedPage = e;
2397
- let r = this._dpr(), i = this._pageWidthPx(e), a = this._renderEpoch, o = this._scale, s = t.dispatcher, c = s.begin();
2398
- if (this._mode === "worker") return this._renderSlotBitmap(e, t, i, r, o, s, c, n);
2399
- let l = [], u = !!this._opts.enableTextSelection && !!t.textLayer, d = u || this._findActive || !!t.commentTintLayer, f = d ? (e) => l.push(e) : void 0, p;
2400
- try {
2401
- p = $(this._doc, t.canvas, e, "main", {
2402
- width: i,
2403
- dpr: r,
2404
- imageResources: this._opts.imageResources,
2405
- defaultTextColor: this._opts.defaultTextColor,
2406
- currentDate: this._currentDate,
2407
- ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2408
- onTextRun: f
2409
- });
2410
- } catch (e) {
2411
- return n ? (this._reportRenderError(e), Promise.resolve()) : Promise.reject(e);
2412
- }
2413
- return p.then(() => {
2414
- if (!(!s.isCurrent(c) || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e)) {
2415
- if (t.renderedScale = o, u && t.textLayer) {
2416
- let { width: n, height: r } = this._canvasCssPx(t.canvas);
2417
- X(t.textLayer, l, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
2418
- }
2419
- d && this._refreshFindRuns(e, l), this._commitCommentRuns(e, t, l), this._redrawSlotHighlights(e, t);
2420
- }
2421
- }).catch((r) => {
2422
- if (s.isCurrent(c) && a === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e) if (n) this._reportRenderError(r);
2423
- else throw r;
2424
- });
2425
- }
2426
- _hyperlinkHandler() {
2427
- return this._opts.enableHyperlinks === !1 ? void 0 : this._opts.onHyperlinkClick || ((e) => {
2428
- if (e.kind === "external") {
2429
- u(e.url);
2430
- return;
2431
- }
2432
- let t = this._doc;
2433
- if (!t) return;
2434
- let n = ++this._internalHyperlinkGeneration;
2435
- this._navigateInternalHyperlink(t, e.ref, n).catch((e) => this._reportRenderError(e));
2436
- });
2437
- }
2438
- async _navigateInternalHyperlink(e, t, n) {
2439
- if (e.layoutComplete || await e.waitUntilLayoutComplete(), this._destroyed || this._doc !== e || n !== this._internalHyperlinkGeneration) return;
2440
- let r = e.getBookmarkPage(t);
2441
- r !== void 0 && this.scrollToPage(r);
2442
- }
2443
- _measureForFont(e) {
2444
- this._measureCtx === void 0 && (this._measureCtx = document.createElement("canvas").getContext("2d"));
2445
- let t = this._measureCtx;
2446
- return !t || typeof t.measureText != "function" ? (e) => e.length : (t.font = e, (e) => t.measureText(e).width);
2447
- }
2448
- _canvasCssPx(e) {
2449
- return {
2450
- width: parseFloat(e.style.width) || e.width,
2451
- height: parseFloat(e.style.height) || e.height
2452
- };
2453
- }
2454
- _reportRenderError(e) {
2455
- this._errorRouter.report(e);
2456
- }
2457
- async _renderSlotBitmap(e, t, n, r, i, a = t.dispatcher, o = a.begin(), s = !0) {
2458
- if (this._bitmapInFlight.has(e) || this._slots.get(e) !== t) return;
2459
- let c = this._renderEpoch, l = this._pageHeightPx(e);
2460
- this._bitmapInFlight.add(e);
2461
- let u = !1, d = !!this._opts.enableTextSelection && !!t.textLayer, f = d || this._findActive || !!t.commentTintLayer, p = [];
2462
- try {
2463
- let s = await $(this._doc, t.canvas, e, "worker", {
2464
- width: n,
2465
- dpr: r,
2466
- imageResources: this._opts.imageResources,
2467
- defaultTextColor: this._opts.defaultTextColor,
2468
- currentDate: this._currentDate,
2469
- ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2470
- onTextRun: f ? (e) => p.push(e) : void 0
2471
- });
2472
- if (!a.isCurrent(o) || c !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) {
2473
- s.close();
2474
- return;
2475
- }
2476
- if (!a.commitBitmap(o, s, {
2477
- cssWidth: n,
2478
- cssHeight: l
2479
- })) return;
2480
- if (t.renderedScale = i, t.textLayer && (this._clearTextLayerPreview(t.textLayer), d)) {
2481
- let { width: n, height: r } = this._canvasCssPx(t.canvas);
2482
- X(t.textLayer, p, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
2483
- }
2484
- f && this._refreshFindRuns(e, p), this._commitCommentRuns(e, t, p), this._redrawSlotHighlights(e, t), u = !0;
2485
- } catch (n) {
2486
- if (a.isCurrent(o) && c === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e) if (s) this._reportRenderError(n);
2487
- else throw n;
2488
- } finally {
2489
- this._bitmapInFlight.delete(e);
2490
- let n = this._slots.get(e);
2491
- if (!u && n && (n !== t || c !== this._renderEpoch || !a.isCurrent(o)) && !this._bitmapInFlight.has(e) && !this._destroyed) {
2492
- let t = n.dispatcher;
2493
- await this._renderSlotBitmap(e, n, this._pageWidthPx(e), this._dpr(), this._scale, t, t.begin(), s);
2494
- }
2495
- }
2496
- }
2497
- setScale(e) {
2498
- let t = this._effectiveZoomMin(), n = this._opts.zoomMax ?? 4, r = Math.min(n, Math.max(t, e)), i = this._pendingZoomAnchor;
2499
- if (this._pendingZoomAnchor = null, !this._doc || this._doc.pageCount === 0 || !this._scaleEstablished) {
2500
- this._pendingScale = r;
2501
- return;
2502
- }
2503
- if (r === this._scale) return;
2504
- 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;
2505
- f = Math.min(1, Math.max(0, f));
2506
- let p = this._padH().left, m = this._scrollHost.scrollLeft || 0;
2507
- this._renderEpoch++, this._scale = r, this._recomputeHeights();
2508
- let h = T(this._scrollGeometry, 0, this._scrollHost.clientHeight, this._overscan());
2509
- this._spacer.style.height = `${h.totalHeight}px`, this._syncSpacerWidth();
2510
- 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;
2511
- if (this._scrollHost.scrollTop = Math.min(g, Math.max(0, v)), i) {
2512
- let e = Math.max(0, (this._spacer.offsetWidth || 0) - this._scrollHost.clientWidth);
2513
- this._scrollHost.scrollLeft = ee(m, i.x - p, a, r, { maxScroll: e });
2514
- }
2515
- this._previewVisible(), this._scheduleSettle(), this._opts.onScaleChange?.(r);
2516
- }
2517
- getScale() {
2518
- return this._scaleEstablished ? this._scale : this._pendingScale ?? 1;
2519
- }
2520
- zoomIn() {
2521
- this.setScale(pe(this.getScale()));
2522
- }
2523
- zoomOut() {
2524
- this.setScale(ge(this.getScale(), this._effectiveZoomMin()));
2525
- }
2526
- _effectiveZoomMin() {
2527
- let e = this._opts.zoomMin ?? .1;
2528
- return this._scaleEstablished && this._prevBase > 0 ? Math.min(e, this._prevBase) : e;
2529
- }
2530
- fitWidth() {
2531
- this._fit("width");
2532
- }
2533
- fitPage() {
2534
- this._fit("page");
2535
- }
2536
- _fit(e) {
2537
- if (!this._doc || this._doc.pageCount === 0) return;
2538
- let t = this._doc.pageSize(0), n = b({
2539
- contentWidth: (e === "width" ? this._widestPageWidthPt() : t.widthPt) * k,
2540
- contentHeight: t.heightPt * k,
2541
- containerWidth: this._fitWidthPx(),
2542
- containerHeight: this._scrollHost.clientHeight
2543
- }, e);
2544
- n <= 0 || this.setScale(n);
2545
- }
2546
- _previewVisible() {
2547
- if (!this._doc || this._doc.pageCount === 0) return;
2548
- let e = this._range();
2549
- this._lastRange = e;
2550
- for (let [t, n] of [...this._slots]) (t < e.start || t > e.end) && this._recycleSlot(t, n);
2551
- for (let t = e.start; t <= e.end; t++) {
2552
- let n = this._slots.get(t);
2553
- if (n) this._previewSlot(n, t, e);
2554
- else {
2555
- let n = this._acquireSlot();
2556
- this._positionSlot(n, t, e), this._slots.set(t, n), this._renderSlot(t, n);
2557
- }
2558
- }
2559
- this._emitVisiblePageChange(e);
2560
- }
2561
- _previewSlot(e, t, n) {
2562
- 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) {
2563
- let n = this._scale / e.renderedScale;
2564
- e.textLayer && (e.textLayer.style.transformOrigin = "0 0", e.textLayer.style.width = `${this._pageWidthPx(t) / n}px`, e.textLayer.style.height = `${this._pageHeightPx(t) / n}px`, e.textLayer.style.transform = `scale(${n})`), e.commentMargin && this._commentUi?.previewReadOnlyCommentMargin(e.commentMargin, n);
2565
- for (let t of e.commentTintLayer?.children ?? []) t.dataset.ooxmlCommentMarker !== void 0 && (t.style.transform = `translate(-50%,-50%) scale(${n})`);
2566
- e.commentTintLayer && (e.commentTintLayer.style.visibility = ""), e.commentMargin && (e.commentMargin.style.visibility = ""), e.commentDecorationLayer && (e.commentDecorationLayer.style.visibility = "");
2567
- return;
2568
- }
2569
- e.commentTintLayer && (e.commentTintLayer.style.visibility = "hidden"), e.commentMargin && (e.commentMargin.style.visibility = "hidden"), e.commentDecorationLayer && (e.commentDecorationLayer.style.visibility = "hidden");
2570
- }
2571
- _clearTextLayerPreview(e) {
2572
- e.style.transform = "", e.style.transformOrigin = "", e.style.width = "100%", e.style.height = "100%";
2573
- }
2574
- _scheduleSettle() {
2575
- this._settleTimer !== null && clearTimeout(this._settleTimer), this._settleTimer = setTimeout(() => {
2576
- this._settleTimer = null, this._settleRender();
2577
- }, xn);
2578
- }
2579
- _settleRender() {
2580
- if (!(this._destroyed || !this._doc || this._doc.pageCount === 0)) for (let [e, t] of [...this._slots]) t.renderedScale !== this._scale && this._refreshSlotAtomically(e, t);
2581
- }
2582
- _refreshSlotAtomically(e, t) {
2583
- if (!this._doc) return;
2584
- let n = this._dpr(), r = this._pageWidthPx(e), i = this._scale, a = this._renderEpoch;
2585
- if (this._mode === "worker") {
2586
- this._renderSlotBitmap(e, t, r, n, i);
2587
- return;
2588
- }
2589
- let o = document.createElement("canvas");
2590
- o.style.cssText = "display:block;background:#fff;", this._applyPageShadow(o);
2591
- let s = new C(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;
2592
- $(this._doc, o, e, "main", {
2593
- width: r,
2594
- dpr: n,
2595
- imageResources: this._opts.imageResources,
2596
- defaultTextColor: this._opts.defaultTextColor,
2597
- currentDate: this._currentDate,
2598
- ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2599
- onTextRun: f
2600
- }).then(() => {
2601
- if (!s.isCurrent(c) || a !== this._renderEpoch || this._slots.get(e) !== t || t.renderedPage !== e) {
2602
- s.destroy();
2603
- return;
2604
- }
2605
- let n = t.canvas;
2606
- if (t.dispatcher.destroy(), t.wrapper.insertBefore(o, n), n.remove(), t.canvas = o, t.dispatcher = s, t.renderedScale = i, t.textLayer && (this._clearTextLayerPreview(t.textLayer), u)) {
2607
- let { width: n, height: r } = this._canvasCssPx(o);
2608
- X(t.textLayer, l, n, r, this._hyperlinkHandler(), (e) => this._measureForFont(e), e);
2609
- }
2610
- d && this._refreshFindRuns(e, l), this._commitCommentRuns(e, t, l), this._redrawSlotHighlights(e, t);
2611
- }).catch((n) => {
2612
- s.isCurrent(c) && a === this._renderEpoch && this._slots.get(e) === t && t.renderedPage === e && this._reportRenderError(n), s.destroy();
2613
- });
2614
- }
2615
- async setShowTrackedChanges(e) {
2616
- let t = ++this._layoutViewGeneration, n = this._doc;
2617
- if (this._showTrackedChanges === e) {
2618
- n && await K(n, {
2619
- showTrackedChanges: e,
2620
- currentDate: this._currentDate
2621
- }, this);
2622
- return;
2623
- }
2624
- (!n || await K(n, {
2625
- showTrackedChanges: e,
2626
- currentDate: this._currentDate
2627
- }, this)) && (this._destroyed || t !== this._layoutViewGeneration || n !== this._doc || (this._showTrackedChanges = e, this._find.invalidate(), this._applyLayoutPublication({
2628
- pageCount: n?.pageCount ?? 0,
2629
- exact: !0,
2630
- complete: n?.layoutComplete !== !1
2631
- })));
2632
- }
2633
- scrollToPage(e, t) {
2634
- if (!this._doc || this._doc.pageCount === 0 || !this._scaleEstablished) return;
2635
- let n = Math.max(0, Math.min(e, this._doc.pageCount - 1)), r = T(this._scrollGeometry, 0, this._scrollHost.clientHeight, this._overscan()), i = _e(r.offsets[n] ?? 0, Math.max(0, r.totalHeight - this._scrollHost.clientHeight)), a = this._scrollHost;
2636
- typeof a.scrollTo == "function" ? a.scrollTo({
2637
- top: i,
2638
- behavior: t?.behavior ?? "auto"
2639
- }) : this._scrollHost.scrollTop = i, this._mountVisible();
2640
- }
2641
- _scrollToPageTarget(e, t, n) {
2642
- let r = T(this._scrollGeometry, 0, this._scrollHost.clientHeight, this._overscan()), i = this._pageWidthPx(e), { left: a } = this._padH(), o = Math.max(a, (this._scrollHost.clientWidth - i) / 2) + this._reviewOriginPx, s = Math.max(0, r.totalHeight - this._scrollHost.clientHeight), c = this._spacer.offsetWidth || Number.parseFloat(this._spacer.style.width) || 0, l = Math.max(0, c - this._scrollHost.clientWidth), u = Math.min(s, Math.max(0, (r.offsets[e] ?? 0) + t.y + t.h / 2 - this._scrollHost.clientHeight / 2)), d = Math.min(l, Math.max(0, o + t.x + t.w / 2 - this._scrollHost.clientWidth / 2)), f = this._scrollHost;
2643
- typeof f.scrollTo == "function" ? f.scrollTo({
2644
- top: u,
2645
- left: d,
2646
- behavior: n?.behavior ?? "auto"
2647
- }) : (this._scrollHost.scrollTop = u, this._scrollHost.scrollLeft = d), this._mountVisible();
2648
- }
2649
- _resetCommentNavigation() {
2650
- this._commentNavigationGeneration++, this._commentPageById.clear(), this._commentRunsByPage.clear(), this._commentIndexedPages.clear(), this._commentScanFrontier = 0;
2651
- }
2652
- _advanceCommentScanFrontier() {
2653
- for (; this._commentIndexedPages.has(this._commentScanFrontier);) this._commentScanFrontier++;
2654
- }
2655
- _indexCommentPages(e, t, n) {
2656
- if (!this._commentIndexedPages.has(e)) {
2657
- for (let r of n) this._commentPageById.has(r.commentId) || M(r, t).length > 0 && this._commentPageById.set(r.commentId, e);
2658
- this._commentIndexedPages.add(e), this._advanceCommentScanFrontier();
2659
- }
2660
- }
2661
- async _commentRunsForPage(e, t) {
2662
- for (; !this._destroyed && this._doc === t;) {
2663
- let n = this._scale, r = this._commentRunsByPage.get(e);
2664
- (!r || r.scale !== n) && (r = {
2665
- scale: n,
2666
- runs: t.collectPageRuns(e, {
2667
- width: this._pageWidthPx(e),
2668
- currentDate: this._currentDate,
2669
- ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {}
2670
- })
2671
- }, this._commentRunsByPage.set(e, r));
2672
- try {
2673
- let e = await r.runs;
2674
- if (this._destroyed || this._doc !== t) return null;
2675
- if (this._scale !== n) continue;
2676
- return e;
2677
- } catch (t) {
2678
- throw this._commentRunsByPage.get(e) === r && this._commentRunsByPage.delete(e), t;
2679
- }
2680
- }
2681
- return null;
2682
- }
2683
- async goToComment(e, t) {
2684
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2685
- let n = this._doc;
2686
- if (!n || !n.comments.some((t) => t.id === e && t.parentId === void 0)) return !1;
2687
- let r = ++this._commentNavigationGeneration, i = !n.layoutComplete, a = n.commentAnchorRanges().filter((t) => t.commentId === e), o = t?.pageIndex;
2688
- if (o !== void 0 && (!Number.isInteger(o) || o < 0)) return !1;
2689
- let s = o ?? this._commentPageById.get(e), c, l = async () => {
2690
- let t = n.commentAnchorRanges();
2691
- for (; s === void 0 && this._commentScanFrontier < n.pageCount;) {
2692
- let i = this._commentScanFrontier, a = await this._commentRunsForPage(i, n);
2693
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2694
- if (this._doc !== n || r !== this._commentNavigationGeneration || !a) return;
2695
- this._indexCommentPages(i, a, t), s = this._commentPageById.get(e);
2696
- }
2697
- return s;
2698
- };
2699
- if (o === void 0 && s === void 0 && a.length > 0 && await l(), i && (o !== void 0 && o >= n.pageCount || o === void 0 && s === void 0)) {
2700
- if (await this._errorRouter.ownBackgroundLifecycle(() => n.waitUntilLayoutComplete()), this._destroyed) throw Error("DocxScrollViewer is destroyed");
2701
- if (this._doc !== n || r !== this._commentNavigationGeneration) return !1;
2702
- a = n.commentAnchorRanges().filter((t) => t.commentId === e), this._commentPageById.clear(), this._commentRunsByPage.clear(), this._commentIndexedPages.clear(), this._commentScanFrontier = 0, s = o, o === void 0 && a.length > 0 && await l();
2703
- }
2704
- if (a.length === 0 || o !== void 0 && o >= n.pageCount || s === void 0) return !1;
2705
- let u = await this._commentRunsForPage(s, n);
2706
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2707
- if (this._doc !== n || r !== this._commentNavigationGeneration || !u || (c = a.flatMap((e) => M(e, u))[0], !c)) return !1;
2708
- this._activeCommentId = e, this._activeCommentPage = s, this._elementContext = null, this._scrollToPageTarget(s, c, t);
2709
- for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
2710
- return this._emitSelectionContextChange(), !0;
2711
- }
2712
- async findText(e, t = {}) {
2713
- if (!this._doc) return [];
2714
- let n = ++this._findRequestGeneration;
2715
- if (this._doc.layoutComplete === !1) {
2716
- let e = this._doc;
2717
- if (await this._errorRouter.ownBackgroundLifecycle(() => e.waitUntilLayoutComplete()), this._destroyed || this._doc !== e || n !== this._findRequestGeneration) return [];
2718
- }
2719
- this._findActive = e.length > 0;
2720
- let r = await this._errorRouter.ownAwaitable(() => this._find.find(e, t));
2721
- return this._redrawHighlights(), r;
2722
- }
2723
- async findNext() {
2724
- return this._activateMatch(this._find.next());
2725
- }
2726
- async findPrev() {
2727
- return this._activateMatch(this._find.prev());
2728
- }
2729
- clearFind() {
2730
- this._findRequestGeneration++, this._findActive = !1, this._find.invalidate(), this._redrawHighlights();
2731
- }
2732
- async _activateMatch(e) {
2733
- return e && this.scrollToPage(e.location.page), this._redrawHighlights(), e;
2734
- }
2735
- async _collectPageRuns(e) {
2736
- return this._doc ? this._doc.collectPageRuns(e, {
2737
- width: this._pageWidthPx(e),
2738
- currentDate: this._currentDate,
2739
- ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {}
2740
- }) : [];
2741
- }
2742
- _redrawHighlights() {
2743
- for (let [e, t] of this._slots) this._redrawSlotHighlights(e, t);
2744
- }
2745
- _refreshFindRuns(e, t) {
2746
- this._findActive && this._find.setPageRuns(e, t);
2747
- }
2748
- _commitCommentRuns(e, t, n) {
2749
- t.commentTintLayer && (t.commentRuns = Object.freeze([...n]), this._commentRunsByPage.set(e, {
2750
- scale: this._scale,
2751
- runs: Promise.resolve(t.commentRuns)
2752
- }), 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 = ""));
2753
- }
2754
- _redrawSlotComments(e, t) {
2755
- if (!this._doc || !t.commentTintLayer) return;
2756
- this._syncCommentMarginGeometry(t.commentMargin);
2757
- let n = this._commentUi;
2758
- if (!n) {
2759
- t.commentTintLayer.replaceChildren(), t.commentMargin?.replaceChildren(), t.commentDecorationLayer?.replaceChildren(), t.commentGeometry = null;
2760
- return;
2761
- }
2762
- t.commentGeometry = n.buildDocxCommentMargin(t.commentTintLayer, t.commentMargin, t.commentRuns, {
2763
- comments: this._doc.comments,
2764
- anchors: this._doc.commentAnchorRanges()
2765
- }, this._pageWidthPx(e), this._pageHeightPx(e), this._activeCommentId, (t, n) => {
2766
- let r = n ? t : this._activeCommentId === t ? null : this._activeCommentId;
2767
- if (r !== this._activeCommentId) {
2768
- this._activeCommentId = r, this._activeCommentPage = r ? e : null, this._elementContext = null;
2769
- for (let [e, t] of this._slots) this._redrawSlotComments(e, t);
2770
- this._emitSelectionContextChange();
2771
- }
2772
- }, 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);
2773
- }
2774
- _redrawSlotCommentConnectors(e, t) {
2775
- let n = t.commentDecorationLayer, r = t.commentMargin, i = t.commentGeometry, a = this._commentsOptions()?.connectors;
2776
- if (!n || !r || !i || !a) return;
2777
- let o = this._pageWidthPx(e), s = this._pageHeightPx(e), c = this._commentSide(), l = this._commentMarginExtent(), u = this._commentUi;
2778
- u && u.buildReadOnlyCommentDecoration(n, Object.freeze({
2779
- surfaceBounds: Object.freeze({
2780
- x: c === "left" ? -l : 0,
2781
- y: 0,
2782
- width: o + l,
2783
- height: s
2784
- }),
2785
- contentBounds: Object.freeze({
2786
- x: 0,
2787
- y: 0,
2788
- width: o,
2789
- height: s
2790
- }),
2791
- side: c,
2792
- threads: u.projectReadOnlyCommentMarginScroll(i, r.scrollTop)
2793
- }), {
2794
- route: a.route ?? "bezier",
2795
- stroke: a.stroke ?? "solid",
2796
- color: a.color,
2797
- activeColor: a.activeColor
2798
- });
2799
- }
2800
- _scheduleCommentGeometry(e, t, n = !1) {
2801
- let r = this._pendingCommentGeometry.get(e);
2802
- if (this._pendingCommentGeometry.set(e, {
2803
- slot: t,
2804
- connectorsOnly: r?.slot === t ? r.connectorsOnly && n : n
2805
- }), this._commentGeometryScheduled) return;
2806
- this._commentGeometryScheduled = !0;
2807
- let i = () => {
2808
- this._commentGeometryScheduled = !1, this._commentGeometryFrame = null;
2809
- let e = [...this._pendingCommentGeometry];
2810
- if (this._pendingCommentGeometry.clear(), !this._destroyed) for (let [t, n] of e) {
2811
- let { slot: e, connectorsOnly: r } = n;
2812
- this._slots.get(t) === e && e.renderedScale === this._scale && (r ? this._redrawSlotCommentConnectors(t, e) : this._redrawSlotComments(t, e));
2813
- }
2814
- }, a = this._wrapper.ownerDocument.defaultView;
2815
- a?.requestAnimationFrame ? this._commentGeometryFrame = a.requestAnimationFrame(i) : queueMicrotask(i);
2816
- }
2817
- _redrawSlotHighlights(e, t) {
2818
- if (!this._findActive) {
2819
- t.highlightLayer.innerHTML = "";
2820
- return;
2821
- }
2822
- let n = this._find.pageRuns(e);
2823
- if (!n) {
2824
- t.highlightLayer.innerHTML = "";
2825
- return;
2826
- }
2827
- Z(t.highlightLayer, n, this._find.pageHighlights(e), this._pageWidthPx(e), this._pageHeightPx(e), (e) => this._measureForFont(e), this._opts.findHighlightColors);
2828
- }
2829
- _onResize() {
2830
- if (!this._doc || this._doc.pageCount === 0) return;
2831
- if (!this._scaleEstablished) {
2832
- this.relayout();
2833
- return;
2834
- }
2835
- if (this._opts.refitOnResize === !1) {
2836
- this._lastFitWidth = this._fitWidthPx(), this._mountVisible();
2837
- return;
2838
- }
2839
- let e = this._baseScale();
2840
- if (e <= 0) return;
2841
- let t = this._fitWidthPx();
2842
- if (t === this._lastFitWidth) {
2843
- this._mountVisible();
2844
- return;
2845
- }
2846
- this._lastFitWidth = t;
2847
- let n = this._prevBase > 0 ? this._scale / this._prevBase : 1;
2848
- this._prevBase = e, this.setScale(e * n), this._mountVisible();
2849
- }
2850
- get topVisiblePage() {
2851
- return this._lastRange?.topIndex ?? 0;
2852
- }
2853
- mountedPageIndicesForTest() {
2854
- return [...this._slots.keys()];
2855
- }
2856
- scaleForTest() {
2857
- return this._scale;
2858
- }
2859
- baseScaleForTest() {
2860
- return this._baseScale();
2861
- }
2862
- renderEpochForTest() {
2863
- return this._renderEpoch;
2864
- }
2865
- resizeForTest() {
2866
- this._onResize();
2867
- }
2868
- contentAtViewportYForTest(e) {
2869
- let t = this._range(), n = this._scrollHost.scrollTop + e, r = this._pageIndexAtOffset(t, n), i = this._heights[r] || 0;
2870
- return {
2871
- page: r,
2872
- frac: i > 0 ? Math.min(1, Math.max(0, (n - t.offsets[r]) / i)) : 0
2873
- };
2874
- }
2875
- viewportYOfForTest(e, t) {
2876
- return (this._range().offsets[e] ?? 0) + t * (this._heights[e] || 0) - this._scrollHost.scrollTop;
2877
- }
2878
- async getResourceMetrics() {
2879
- if (!this._doc) throw Error("Document not loaded");
2880
- return await this._doc.getResourceMetrics();
2881
- }
2882
- getSelectionContext(e = {}) {
2883
- if (this._destroyed) throw Error("DocxScrollViewer is destroyed");
2884
- return (this._doc && this._activeCommentId !== null && this._activeCommentPage !== null ? mn(this._doc.comments, this._doc.commentAnchorRanges(), this._activeCommentId, this._activeCommentPage, e) : null) || ((this._opts.enableTextSelection ? Q(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null, e) : null) ?? (this._elementContext ? Gt(this._elementContext, e.maxTextCharacters) : null));
2885
- }
2886
- _emitSelectionContextChange() {
2887
- let e = this.getSelectionContext();
2888
- e?.kind === "text" && (this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutlines());
2889
- let t = JSON.stringify(e);
2890
- t !== this._selectionContextKey && (this._selectionContextKey = t, this._opts.onSelectionContextChange?.(e ? structuredClone(e) : null));
2891
- }
2892
- _setElementContext(e) {
2893
- this._elementContext = e ? structuredClone(e) : null, this._redrawElementOutlines(), this._emitSelectionContextChange();
2894
- }
2895
- _invalidateElementContext(e = !0) {
2896
- this._elementHitGeneration++, this._elementContext = null, this._redrawElementOutlines(), e && this._emitSelectionContextChange();
2897
- }
2898
- _redrawElementOutlines() {
2899
- for (let [e, t] of this._slots) this._redrawElementOutlineForSlot(e, t);
2900
- }
2901
- _redrawElementOutlineForSlot(e, t) {
2902
- let n = this._elementContext, r = this._doc;
2903
- if (!n || !r || n.pageIndex !== e) {
2904
- S(t.elementLayer, null);
2905
- return;
2906
- }
2907
- let i = r.pageSize(e);
2908
- S(t.elementLayer, {
2909
- x: n.bounds.xPt / i.widthPt,
2910
- y: n.bounds.yPt / i.heightPt,
2911
- width: n.bounds.widthPt / i.widthPt,
2912
- height: n.bounds.heightPt / i.heightPt
2913
- });
2914
- }
2915
- async _onElementClick(e) {
2916
- this._destroyed || e.defaultPrevented || e.button !== 0 || await this._resolveContextAt(e);
2917
- }
2918
- _onContextMenu(e) {
2919
- let t;
2920
- this._opts.onContextMenu?.({
2921
- originalEvent: e,
2922
- getContext: () => t ??= this._resolveContextAt(e)
2923
- });
2924
- }
2925
- async _resolveContextAt(e) {
2926
- let t = this._doc;
2927
- if (this._destroyed || !t) return null;
2928
- if (this._opts.enableTextSelection && Q(this._wrapper, this._wrapper.ownerDocument?.getSelection?.() ?? null)) return this._emitSelectionContextChange(), this._destroyed ? null : this.getSelectionContext();
2929
- if (!this._opts.enableElementSelection) return this.getSelectionContext();
2930
- let n = e.target, r = [...this._slots].find(([, e]) => n !== null && e.wrapper.contains(n));
2931
- if (!r) return this._invalidateElementContext(), null;
2932
- let [i, a] = r, o = a.canvas.getBoundingClientRect();
2933
- if (o.width <= 0 || o.height <= 0) return this._invalidateElementContext(), null;
2934
- let s = e.clientX - o.left, c = e.clientY - o.top;
2935
- if (s < 0 || c < 0 || s > o.width || c > o.height) return this._invalidateElementContext(), null;
2936
- let l = ++this._elementHitGeneration, u = t.pageSize(i), d;
2937
- try {
2938
- d = await t.getElementContextAt(i, {
2939
- xPt: s / o.width * u.widthPt,
2940
- yPt: c / o.height * u.heightPt
2941
- }, {
2942
- currentDate: this._currentDate,
2943
- ...this._showTrackedChanges ? { showTrackedChanges: !0 } : {},
2944
- maxTextCharacters: I
2945
- });
2946
- } catch (e) {
2947
- if (this._destroyed || l !== this._elementHitGeneration || t !== this._doc) return null;
2948
- throw e;
2949
- }
2950
- return this._destroyed || l !== this._elementHitGeneration || t !== this._doc ? null : (this._setElementContext(d), this._destroyed ? null : this.getSelectionContext());
2951
- }
2952
- destroy() {
2953
- if (!this._destroyed) {
2954
- this._destroyed = !0, this._findRequestGeneration++, this._errorRouter.close(), this._unbindLayoutDocument(), this._layoutViewGeneration++, 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);
2955
- for (let [e, t] of [...this._slots]) this._recycleSlot(e, t);
2956
- this._free.length = 0, this._documentOwner.close(), this._wrapper.remove();
2957
- }
2958
- }
2959
- };
2960
- //#endregion
2961
- //#region packages/docx/src/types.ts
2962
- function kn(e) {
2963
- let t = [];
2964
- for (let n of e.content) {
2965
- if (n.type !== "paragraph") continue;
2966
- let e = "";
2967
- for (let t of n.runs) t.type === "text" && !t.noteRef && (e += t.text);
2968
- e = e.trim(), e && t.push(e);
2969
- }
2970
- return t.join(" ");
2971
- }
2972
- //#endregion
2973
- //#region src/docx.ts
2974
- var An = /* @__PURE__ */ e({
2975
- DocxDocument: () => J,
2976
- DocxScrollViewer: () => On,
2977
- DocxViewer: () => bn,
2978
- OoxmlDecodedImageLimitError: () => tt,
2979
- OoxmlError: () => c,
2980
- OoxmlResourceLimitError: () => d,
2981
- TiffDecodeError: () => nt,
2982
- autoResize: () => y,
2983
- buildDocxHighlightLayer: () => Z,
2984
- buildDocxTextLayer: () => X,
2985
- isOoxmlDecodedImageLimitError: () => et,
2986
- isTiffDecodeError: () => rt,
2987
- noteText: () => kn,
2988
- openExternalHyperlink: () => u,
2989
- readDocxTextSelectionContext: () => Q,
2990
- resolveCommentAnchorRuns: () => M,
2991
- resolveDocxCommentThreads: () => ct,
2992
- resolveRevisionAnchorRuns: () => Qt
2993
- });
2994
- //#endregion
2995
- export { Q as a, J as c, bn as i, Qt as l, kn as n, Z as o, On as r, X as s, An as t };