calmlens 0.20.0 → 0.21.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 (108) hide show
  1. package/README.md +13 -9
  2. package/bin/calmlens.js +1329 -664
  3. package/cjs/{BrowserUpload-CjSHjx3C.js → BrowserUpload-CeSwiMo5.js} +1 -1
  4. package/cjs/{BrowserUpload-C07aL9Vq.d.ts → BrowserUpload-D-NnAN7g.d.ts} +2 -2
  5. package/cjs/{CalmLensAppClient-NaCxOVlM.js → CalmLensAppClient-0UVCuNqW.js} +30 -10
  6. package/cjs/{CalmLensAppClient-DDLojj0P.d.ts → CalmLensAppClient-gG16T2py.d.ts} +13 -3
  7. package/cjs/{CalmLensOptionKeys-p2QK687A.js → CalmLensOptionKeys-CYY6elxg.js} +183 -347
  8. package/cjs/{CalmLensServerClient-C-jsjn8m.d.ts → CalmLensServerClient-BHx3x_nZ.d.ts} +106 -48
  9. package/cjs/{CalmLensServerClient-BDzTthxE.js → CalmLensServerClient-nfu6_YEW.js} +288 -88
  10. package/cjs/{CalmLensTypes-COJbOuiv.d.ts → CalmLensTypes-CUB0YYVz.d.ts} +26601 -27354
  11. package/cjs/{Classification-D3SkprrQ-CMnQKW13.d.ts → Classification-Q5zGpR8l-CEWjnE39.d.ts} +731 -607
  12. package/cjs/Core-C82YmjjX.d.ts +823 -0
  13. package/cjs/Core-Dc3cteU7.js +998 -0
  14. package/cjs/FileIcons-4qSX7DW2.d.ts +67 -0
  15. package/cjs/{ModerationContextLimits-2nIv7Zh3.js → ModerationContextLimits-BxOmeSqq.js} +669 -269
  16. package/cjs/{ReactUpload-BdTRCTGA.js → ReactUpload-BK2O3dnK.js} +1 -1
  17. package/cjs/{ReactUpload-CRJNPB5T.d.ts → ReactUpload-DiiXfKvj.d.ts} +1 -1
  18. package/cjs/{TestTriggers-DbhsNPdg-DjvVuc2h.js → TestTriggers-BTyXtX0Q-ATuFDhLX.js} +342 -34
  19. package/{esm/TestTriggers-D-fwfhEP-hlaP1oW2.d.ts → cjs/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts} +146 -8
  20. package/cjs/{UploadController-MLVs97Zt.js → UploadController-DLyiLDTB.js} +34 -14
  21. package/cjs/{WebhookPayload-DkukERKE.d.ts → WebhookPayload-BLT2y_Jy.d.ts} +93 -86
  22. package/cjs/app.d.ts +6 -7
  23. package/cjs/app.js +4 -3
  24. package/cjs/elements.d.ts +123 -22
  25. package/cjs/elements.js +553 -156
  26. package/cjs/file-icons.d.ts +2 -67
  27. package/cjs/index-CKRgjV16.d.ts +16 -0
  28. package/cjs/index.d.ts +5 -6
  29. package/cjs/index.js +3 -2
  30. package/cjs/react-native.d.ts +52 -11
  31. package/cjs/react-native.js +231 -99
  32. package/cjs/react.d.ts +42 -9
  33. package/cjs/react.js +381 -118
  34. package/cjs/server.d.ts +48 -7
  35. package/cjs/server.js +7 -3
  36. package/cjs/test-inputs.d.ts +2 -2
  37. package/cjs/test-inputs.js +13 -9
  38. package/cjs/testing.d.ts +24 -14
  39. package/cjs/testing.js +1413 -402
  40. package/cjs/ui-CTBUxnVp.d.ts +139 -0
  41. package/cjs/ui-CZ8exACq.js +1359 -0
  42. package/cjs/ui.d.ts +3 -2
  43. package/cjs/ui.js +45 -22
  44. package/cjs/vue.d.ts +802 -199
  45. package/cjs/vue.js +359 -127
  46. package/esm/{BrowserUpload-C07aL9Vq.d.ts → BrowserUpload-D-NnAN7g.d.ts} +2 -2
  47. package/esm/{BrowserUpload-CAVkRotw.js → BrowserUpload-i9OhCzMJ.js} +1 -1
  48. package/esm/{CalmLensAppClient-PQ9VBvlW.js → CalmLensAppClient-CK4_Py0c.js} +30 -10
  49. package/esm/{CalmLensAppClient-DDLojj0P.d.ts → CalmLensAppClient-gG16T2py.d.ts} +13 -3
  50. package/esm/{CalmLensOptionKeys-Do2mPP6w.js → CalmLensOptionKeys-BGZlIsT2.js} +182 -340
  51. package/esm/{CalmLensServerClient-C-jsjn8m.d.ts → CalmLensServerClient-BHx3x_nZ.d.ts} +106 -48
  52. package/esm/{CalmLensServerClient-C_H5aAsV.js → CalmLensServerClient-dAQUcDWb.js} +265 -89
  53. package/esm/{CalmLensTypes-COJbOuiv.d.ts → CalmLensTypes-CUB0YYVz.d.ts} +26601 -27354
  54. package/esm/{Classification-D3SkprrQ-CMnQKW13.d.ts → Classification-Q5zGpR8l-CEWjnE39.d.ts} +731 -607
  55. package/esm/Core-BxeIud_S.js +843 -0
  56. package/esm/Core-C82YmjjX.d.ts +823 -0
  57. package/esm/FileIcons-4qSX7DW2.d.ts +67 -0
  58. package/esm/{ModerationContextLimits-Chw-AzgL.js → ModerationContextLimits-B6_RalCQ.js} +624 -254
  59. package/esm/{ReactUpload-CRJNPB5T.d.ts → ReactUpload-DiiXfKvj.d.ts} +1 -1
  60. package/esm/{ReactUpload-CMmL0R5Q.js → ReactUpload-DxwVqfX1.js} +1 -1
  61. package/esm/{TestTriggers-DbhsNPdg-CUdrv8Nm.js → TestTriggers-BTyXtX0Q-GRB9jQwo.js} +319 -35
  62. package/{cjs/TestTriggers-D-fwfhEP-hlaP1oW2.d.ts → esm/TestTriggers-D0pYHbkr-D5T0VdSn.d.ts} +146 -8
  63. package/esm/{UploadController-BJZghJpg.js → UploadController-D9Z-h00Q.js} +34 -14
  64. package/esm/{WebhookPayload-DkukERKE.d.ts → WebhookPayload-BLT2y_Jy.d.ts} +93 -86
  65. package/esm/app.d.ts +6 -7
  66. package/esm/app.js +3 -3
  67. package/esm/elements.d.ts +123 -22
  68. package/esm/elements.js +497 -128
  69. package/esm/file-icons.d.ts +2 -67
  70. package/esm/index-CKRgjV16.d.ts +16 -0
  71. package/esm/index.d.ts +5 -6
  72. package/esm/index.js +1 -1
  73. package/esm/react-native.d.ts +52 -11
  74. package/esm/react-native.js +205 -75
  75. package/esm/react.d.ts +42 -9
  76. package/esm/react.js +327 -91
  77. package/esm/server.d.ts +48 -7
  78. package/esm/server.js +3 -3
  79. package/esm/styles.css +142 -22
  80. package/esm/svelte/AssetViewer.svelte +25 -0
  81. package/esm/svelte/CalmLensAsset.svelte +318 -0
  82. package/esm/svelte/CalmLensDocumentViewer.svelte +7 -0
  83. package/esm/svelte/CalmLensImageViewer.svelte +7 -0
  84. package/esm/svelte/CalmLensSpreadsheetViewer.svelte +7 -0
  85. package/esm/svelte/CalmLensTextViewer.svelte +7 -0
  86. package/esm/svelte/CalmLensWebsiteViewer.svelte +7 -0
  87. package/esm/svelte/index.d.ts +29 -6
  88. package/esm/svelte/index.js +7 -2
  89. package/esm/test-inputs.d.ts +2 -2
  90. package/esm/test-inputs.js +1 -1
  91. package/esm/testing.d.ts +24 -14
  92. package/esm/testing.js +1409 -398
  93. package/esm/ui-CTBUxnVp.d.ts +139 -0
  94. package/esm/ui-Cr7s6JHm.js +1258 -0
  95. package/esm/ui.d.ts +3 -2
  96. package/esm/ui.js +4 -3
  97. package/esm/vue.d.ts +802 -199
  98. package/esm/vue.js +308 -103
  99. package/package.json +3 -1
  100. package/cjs/ModerationContext-9lGm-Mna-CcmbRnOy.d.ts +0 -67
  101. package/cjs/index-DxbJ_Xaa.d.ts +0 -253
  102. package/cjs/ui-BSqPGKrZ.d.ts +0 -539
  103. package/cjs/ui-CX1z2pD9.js +0 -586
  104. package/esm/ModerationContext-9lGm-Mna-CcmbRnOy.d.ts +0 -67
  105. package/esm/index-DxbJ_Xaa.d.ts +0 -253
  106. package/esm/svelte/CalmLensMedia.svelte +0 -134
  107. package/esm/ui-BSqPGKrZ.d.ts +0 -539
  108. package/esm/ui-CXH7xJpb.js +0 -461
@@ -0,0 +1,1359 @@
1
+ const require_ModerationContextLimits = require("./ModerationContextLimits-BxOmeSqq.js");
2
+ const require_UploadController = require("./UploadController-DLyiLDTB.js");
3
+ require("./Core-Dc3cteU7.js");
4
+ // src/ui/viewers/PdfLoader.ts
5
+ let loading;
6
+ /**
7
+ * Loads pdf.js, the first time a document viewer needs it: never at import, so pages without
8
+ * documents never download it. With `workerSrc`, pdf.js reads documents in a worker loaded from
9
+ * your app; otherwise its worker module is imported too and reads them on the main thread.
10
+ */
11
+ const loadPdfJs = (options = {}) => {
12
+ loading ??= (async () => {
13
+ const pdfjs = await import("pdfjs-dist");
14
+ if (options.workerSrc) pdfjs.GlobalWorkerOptions.workerSrc = options.workerSrc;
15
+ else {
16
+ const worker = await import("pdfjs-dist/build/pdf.worker.min.mjs");
17
+ globalThis.pdfjsWorker = worker;
18
+ }
19
+ return pdfjs;
20
+ })().catch((error) => {
21
+ loading = void 0;
22
+ throw error;
23
+ });
24
+ return loading;
25
+ };
26
+ /** Opens a document from its URL with pdf.js. */
27
+ const openPdfDocument = async (url, options = {}) => {
28
+ const pdfjs = await loadPdfJs(options);
29
+ return await pdfjs.getDocument({
30
+ url,
31
+ standardFontDataUrl: options.standardFontDataUrl,
32
+ cMapUrl: options.cMapUrl,
33
+ cMapPacked: options.cMapUrl ? true : void 0,
34
+ wasmUrl: options.wasmUrl,
35
+ verbosity: pdfjs.VerbosityLevel.ERRORS
36
+ }).promise;
37
+ };
38
+ // src/ui/viewers/ViewerMessages.ts
39
+ const DEFAULT_VIEWER_MESSAGES = {
40
+ loading: "Loading…",
41
+ imageFailed: "This image can't be shown.",
42
+ openWebsite: "Open {host}",
43
+ websiteLabel: "Website screenshot",
44
+ textLabel: "Text",
45
+ textFailed: "This text can't be shown.",
46
+ documentLabel: "Document",
47
+ documentControls: "Document controls",
48
+ documentFailed: "This document can't be shown here.",
49
+ openDocument: "Open PDF",
50
+ previousPage: "Previous page",
51
+ nextPage: "Next page",
52
+ pageNumber: "Page",
53
+ pageCount: "of {count}",
54
+ pageStatus: "Page {page} of {count}",
55
+ zoomIn: "Zoom in",
56
+ zoomOut: "Zoom out",
57
+ fitWidth: "Fit to width",
58
+ zoomLevel: "{percent}%",
59
+ spreadsheetLabel: "Spreadsheet",
60
+ spreadsheetFailed: "This spreadsheet can't be shown.",
61
+ sheets: "Sheets",
62
+ hiddenSheet: "{name} (hidden)",
63
+ hidden: "Hidden",
64
+ emptySheet: "This sheet is empty.",
65
+ previousRows: "Previous rows",
66
+ nextRows: "Next rows",
67
+ rowRange: "Rows {from}–{to} of {count}",
68
+ sheetNotes: "Comments and charts"
69
+ };
70
+ /** The default messages with your replacements. */
71
+ const resolveViewerMessages = (overrides) => ({
72
+ ...DEFAULT_VIEWER_MESSAGES,
73
+ ...overrides
74
+ });
75
+ /** Fills a message's `{name}` placeholders. */
76
+ const formatViewerMessage = (message, values) => message.replace(/\{(\w+)\}/g, (match, name) => Object.hasOwn(values, name) ? String(values[name]) : match);
77
+ // src/ui/viewers/ViewerUrls.ts
78
+ /** The CDN's error code in a refused response, if it sent one. */
79
+ const responseCode = async (response) => {
80
+ try {
81
+ const body = await response.clone().json();
82
+ return typeof body.code === "string" ? body.code : void 0;
83
+ } catch {
84
+ return;
85
+ }
86
+ };
87
+ /**
88
+ * The CDN URLs a viewer loads: resource paths beneath the asset URL (`src`), public or signed,
89
+ * with the viewer claims that say something. When a URL stops working (`refresh`), as an expired
90
+ * signed one does, it asks `onExpired` once for a fresh asset URL, and again only after that one
91
+ * has worked (`loaded`), so a URL that keeps failing ends in the viewer's fallback. Without
92
+ * `onExpired` nothing is refreshed.
93
+ */
94
+ var ViewerUrls = class {
95
+ #options;
96
+ #src;
97
+ #given;
98
+ #refreshing = false;
99
+ constructor(options) {
100
+ this.#options = options;
101
+ this.#src = options.src;
102
+ this.#given = options.src;
103
+ }
104
+ /** Uses the latest options: a new `src` replaces any refreshed one; callbacks may change freely. */
105
+ set options(options) {
106
+ this.#options = options;
107
+ if (options.src !== this.#given) {
108
+ this.#given = options.src;
109
+ this.#src = options.src;
110
+ }
111
+ }
112
+ /** The asset URL in use: `src`, or the fresh one `onExpired` returned. */
113
+ get src() {
114
+ return this.#src;
115
+ }
116
+ /** A resource's URL beneath the asset URL. The placeholder is never age-gated, so it needs no age claim. */
117
+ url(resource, transform) {
118
+ const { viewerClaims } = this.#options;
119
+ return require_ModerationContextLimits.appendAssetLocation(this.#src, {
120
+ resource,
121
+ transform,
122
+ viewerClaims: resource === "placeholder" && viewerClaims ? { region: viewerClaims.region } : viewerClaims
123
+ });
124
+ }
125
+ /** The URL to load the resource from. */
126
+ get(resource) {
127
+ return Promise.resolve(this.url(resource));
128
+ }
129
+ /**
130
+ * A fresh URL after the last one failed to load, or `undefined` when there is no `onExpired` or
131
+ * the fresh URL already asked for failed too.
132
+ */
133
+ refresh(resource) {
134
+ const { onExpired } = this.#options;
135
+ if (!onExpired || this.#refreshing) return void 0;
136
+ this.#refreshing = true;
137
+ return Promise.resolve().then(() => onExpired()).then((src) => {
138
+ if (typeof src !== "string" || !src) throw new Error("onExpired returned no asset URL");
139
+ this.#src = src;
140
+ return this.url(resource);
141
+ });
142
+ }
143
+ /** Records that the resource's URL worked, so a later failure may refresh it again. */
144
+ loaded(_resource) {
145
+ this.#refreshing = false;
146
+ }
147
+ /** Tells the viewer's owner that the CDN refused the asset to this viewer. */
148
+ unavailable() {
149
+ this.#options.onUnavailable?.();
150
+ }
151
+ };
152
+ /**
153
+ * Fetches a resource as text, asking for a fresh asset URL once when the response fails, as an
154
+ * expired signed one does. A refusal with `asset/not-available` ends at once: the asset can't be
155
+ * shown to this viewer.
156
+ */
157
+ const fetchViewerText = async (urls, resource, signal) => {
158
+ let url = await urls.get(resource);
159
+ for (;;) {
160
+ let response;
161
+ try {
162
+ response = await fetch(url, { signal });
163
+ } catch (error) {
164
+ if (signal.aborted) throw error;
165
+ }
166
+ if (response?.ok) {
167
+ urls.loaded(resource);
168
+ return await response.text();
169
+ }
170
+ if (response && await responseCode(response) === "asset/not-available") {
171
+ urls.unavailable();
172
+ throw new Error(`The ${resource} resource is not available`);
173
+ }
174
+ const fresh = urls.refresh(resource);
175
+ if (!fresh) throw new Error(`Could not load the ${resource} resource`);
176
+ url = await fresh;
177
+ }
178
+ };
179
+ // src/ui/viewers/ViewerBase.ts
180
+ /** Creates an element with attributes (`false` and `undefined` leave one out) and children. */
181
+ const el = (tag, attributes = {}, children = []) => {
182
+ const node = document.createElement(tag);
183
+ for (const [name, value] of Object.entries(attributes)) {
184
+ if (value === void 0 || value === false) continue;
185
+ node.setAttribute(name, value === true ? "" : String(value));
186
+ }
187
+ for (const child of children) if (child) node.append(child);
188
+ return node;
189
+ };
190
+ let ids = 0;
191
+ /** A document-unique ID for ARIA references. */
192
+ const viewerId = (name) => `calmlens-${name}-${++ids}`;
193
+ /**
194
+ * What every viewer shares: the element's class and state, its URLs, its messages, and a load
195
+ * that runs again (cancelling the last) only when the options change what is shown. Functions in
196
+ * the options, such as `onExpired`, may change on every render without loading again.
197
+ */
198
+ var ViewerBase = class {
199
+ #key;
200
+ #abort;
201
+ /** Call `update` with the first options once constructed. */
202
+ constructor(root, kind) {
203
+ this.root = root;
204
+ root.classList.add("calmlens-viewer");
205
+ root.dataset.kind = kind;
206
+ this.frame = el("div", { class: "calmlens-viewer__frame" });
207
+ root.replaceChildren(this.frame);
208
+ }
209
+ update(options) {
210
+ this.options = options;
211
+ if (this.urls) this.urls.options = options;
212
+ const { asset, viewerClaims, label, messages } = options;
213
+ const key = JSON.stringify([
214
+ asset.projectId,
215
+ asset.id,
216
+ viewerClaims,
217
+ label,
218
+ messages,
219
+ this.describe(options)
220
+ ]);
221
+ if (key === this.#key) return;
222
+ this.#key = key;
223
+ this.#abort?.abort();
224
+ const abort = new AbortController();
225
+ this.#abort = abort;
226
+ this.messages = resolveViewerMessages(messages);
227
+ this.urls = new ViewerUrls(options);
228
+ this.state = "loading";
229
+ (async () => {
230
+ try {
231
+ await this.load(abort.signal);
232
+ } catch {
233
+ if (!abort.signal.aborted) this.fail();
234
+ }
235
+ })();
236
+ }
237
+ destroy() {
238
+ this.#abort?.abort();
239
+ this.#abort = void 0;
240
+ this.#key = void 0;
241
+ this.root.replaceChildren();
242
+ this.frame.replaceChildren();
243
+ }
244
+ set state(state) {
245
+ this.root.dataset.state = state;
246
+ this.root.setAttribute("aria-busy", String(state === "loading"));
247
+ }
248
+ /** A notice in place of the content, announced to screen readers. */
249
+ notice(message, ...children) {
250
+ return el("div", {
251
+ class: "calmlens-viewer__notice",
252
+ role: "status"
253
+ }, [el("p", {}, [message]), ...children]);
254
+ }
255
+ /** The loading notice, shown until the content arrives. */
256
+ loadingNotice() {
257
+ return el("div", {
258
+ class: "calmlens-viewer__notice",
259
+ role: "status"
260
+ }, [el("p", {}, [this.messages.loading])]);
261
+ }
262
+ };
263
+ // src/ui/viewers/DocumentViewer.ts
264
+ const MIN_ZOOM = .25;
265
+ const MAX_ZOOM = 5;
266
+ const ZOOM_STEP = 1.25;
267
+ /**
268
+ * Shows a PDF (a PDF asset, or a document or presentation CalmLens rendered as one) a page at a
269
+ * time with pdf.js, which loads only when a document is shown: page buttons and a page number
270
+ * field, zoom and fit to width, a link that opens the PDF itself, and keys for each. Each page's
271
+ * text is in the page for screen readers. A document pdf.js can't open falls back to the link.
272
+ */
273
+ var DocumentViewer = class extends ViewerBase {
274
+ #document;
275
+ #url;
276
+ #page = 1;
277
+ /** A fixed zoom, or `undefined` to fit the page to the viewer's width. */
278
+ #zoom;
279
+ #scale = 1;
280
+ #renderTask;
281
+ #renders = 0;
282
+ #recovering = false;
283
+ #resize;
284
+ #controls;
285
+ constructor(root) {
286
+ super(root, "document");
287
+ }
288
+ describe({ asset, pdf, initialPage }) {
289
+ return [
290
+ asset.content?.rendered?.kind,
291
+ pdf,
292
+ initialPage
293
+ ];
294
+ }
295
+ /** Opens the document, asking once for a fresh asset URL when it fails, as an expired one does. */
296
+ async #open(signal) {
297
+ let url = this.#url ?? await this.urls.get("rendered");
298
+ for (;;) try {
299
+ const document = await openPdfDocument(url, this.options.pdf);
300
+ this.urls.loaded("rendered");
301
+ return document;
302
+ } catch (error) {
303
+ if (signal.aborted) throw error;
304
+ const fresh = this.urls.refresh("rendered");
305
+ if (!fresh) throw error;
306
+ url = await fresh;
307
+ this.#url = url;
308
+ }
309
+ }
310
+ async load(signal) {
311
+ this.#close();
312
+ this.#url = void 0;
313
+ this.frame.replaceChildren(this.loadingNotice());
314
+ this.#url = await this.urls.get("rendered");
315
+ await loadPdfJs(this.options.pdf);
316
+ const document = await this.#open(signal);
317
+ if (signal.aborted) {
318
+ document.loadingTask.destroy();
319
+ return;
320
+ }
321
+ signal.addEventListener("abort", () => this.#close(document));
322
+ this.#document = document;
323
+ this.#page = Math.min(Math.max(1, Math.trunc(this.options.initialPage ?? 1) || 1), document.numPages);
324
+ this.#zoom = void 0;
325
+ this.#build();
326
+ await this.#render(signal);
327
+ }
328
+ #build() {
329
+ const { messages } = this;
330
+ const button = (label, symbol, attributes = {}) => el("button", {
331
+ type: "button",
332
+ class: "calmlens-button",
333
+ "aria-label": label,
334
+ title: label,
335
+ ...attributes
336
+ }, [el("span", { "aria-hidden": "true" }, [symbol])]);
337
+ const pagesId = viewerId("document");
338
+ const pageField = viewerId("page");
339
+ const previous = button(messages.previousPage, "‹");
340
+ const next = button(messages.nextPage, "›");
341
+ const page = el("input", {
342
+ id: pageField,
343
+ type: "number",
344
+ inputmode: "numeric",
345
+ min: 1,
346
+ class: "calmlens-viewer__page-field"
347
+ });
348
+ const count = el("span");
349
+ const zoomOut = button(messages.zoomOut, "−");
350
+ const zoomIn = button(messages.zoomIn, "+");
351
+ const zoomLevel = el("span", { class: "calmlens-viewer__zoom" });
352
+ const fit = button(messages.fitWidth, "↔", { "aria-pressed": "true" });
353
+ const open = el("a", {
354
+ class: "calmlens-button calmlens-viewer__link",
355
+ href: this.#url,
356
+ target: "_blank",
357
+ rel: "noopener noreferrer"
358
+ }, [messages.openDocument]);
359
+ const canvas = el("canvas", { "aria-hidden": "true" });
360
+ const text = el("div", { class: "calmlens-viewer__sr" });
361
+ const sheet = el("div", {
362
+ class: "calmlens-viewer__page",
363
+ role: "group"
364
+ }, [canvas, text]);
365
+ const pages = el("div", {
366
+ id: pagesId,
367
+ class: "calmlens-viewer__pages",
368
+ role: "region",
369
+ "aria-label": this.options.label || messages.documentLabel,
370
+ tabindex: 0
371
+ }, [sheet]);
372
+ const status = el("p", {
373
+ class: "calmlens-viewer__sr",
374
+ role: "status"
375
+ });
376
+ const toolbar = el("div", {
377
+ class: "calmlens-viewer__bar",
378
+ role: "toolbar",
379
+ "aria-label": messages.documentControls,
380
+ "aria-controls": pagesId
381
+ }, [
382
+ previous,
383
+ el("label", {
384
+ for: pageField,
385
+ class: "calmlens-viewer__page-label"
386
+ }, [messages.pageNumber]),
387
+ page,
388
+ count,
389
+ el("span", { class: "calmlens-viewer__spacer" }),
390
+ zoomOut,
391
+ zoomLevel,
392
+ zoomIn,
393
+ fit,
394
+ open
395
+ ]);
396
+ previous.addEventListener("click", () => this.#go(this.#page - 1));
397
+ next.addEventListener("click", () => this.#go(this.#page + 1));
398
+ toolbar.insertBefore(next, count.nextSibling);
399
+ page.addEventListener("change", () => this.#go(Number(page.value)));
400
+ page.addEventListener("keydown", (event) => {
401
+ if (event.key === "Enter") this.#go(Number(page.value));
402
+ });
403
+ zoomOut.addEventListener("click", () => this.#setZoom(this.#scale / ZOOM_STEP));
404
+ zoomIn.addEventListener("click", () => this.#setZoom(this.#scale * ZOOM_STEP));
405
+ fit.addEventListener("click", () => this.#setZoom(void 0));
406
+ pages.addEventListener("keydown", (event) => this.#onKey(event));
407
+ this.#controls = {
408
+ previous,
409
+ next,
410
+ page,
411
+ count,
412
+ zoomOut,
413
+ zoomIn,
414
+ zoomLevel,
415
+ fit,
416
+ open,
417
+ pages,
418
+ sheet,
419
+ canvas,
420
+ text,
421
+ status
422
+ };
423
+ this.frame.replaceChildren(toolbar, pages, status);
424
+ if (typeof ResizeObserver !== "undefined") {
425
+ let width = 0;
426
+ this.#resize = new ResizeObserver(([entry]) => {
427
+ const next = Math.round(entry?.contentRect.width ?? 0);
428
+ if (next === width) return;
429
+ width = next;
430
+ if (this.#zoom === void 0) this.#render();
431
+ });
432
+ this.#resize.observe(pages);
433
+ }
434
+ }
435
+ #onKey(event) {
436
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
437
+ const action = {
438
+ PageDown: () => this.#go(this.#page + 1),
439
+ ArrowRight: () => this.#go(this.#page + 1),
440
+ PageUp: () => this.#go(this.#page - 1),
441
+ ArrowLeft: () => this.#go(this.#page - 1),
442
+ Home: () => this.#go(1),
443
+ End: () => this.#go(this.#document?.numPages ?? 1),
444
+ "+": () => this.#setZoom(this.#scale * ZOOM_STEP),
445
+ "=": () => this.#setZoom(this.#scale * ZOOM_STEP),
446
+ "-": () => this.#setZoom(this.#scale / ZOOM_STEP),
447
+ "0": () => this.#setZoom(void 0)
448
+ }[event.key];
449
+ if (!action) return;
450
+ event.preventDefault();
451
+ action();
452
+ }
453
+ #go(page) {
454
+ const count = this.#document?.numPages ?? 1;
455
+ const target = Number.isFinite(page) ? Math.min(Math.max(1, Math.round(page)), count) : this.#page;
456
+ if (target === this.#page) {
457
+ if (this.#controls) this.#controls.page.value = String(this.#page);
458
+ return;
459
+ }
460
+ this.#page = target;
461
+ this.#render();
462
+ }
463
+ #setZoom(zoom) {
464
+ this.#zoom = zoom === void 0 ? void 0 : Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, zoom));
465
+ this.#render();
466
+ }
467
+ /** Draws the current page and puts its text, number and zoom in the controls. */
468
+ async #render(signal) {
469
+ const document = this.#document;
470
+ const controls = this.#controls;
471
+ if (!document || !controls) return;
472
+ const render = ++this.#renders;
473
+ this.#renderTask?.cancel();
474
+ const pageNumber = this.#page;
475
+ const { messages } = this;
476
+ const pageLabel = formatViewerMessage(messages.pageStatus, {
477
+ page: pageNumber,
478
+ count: document.numPages
479
+ });
480
+ controls.page.value = String(pageNumber);
481
+ controls.page.max = String(document.numPages);
482
+ controls.count.textContent = formatViewerMessage(messages.pageCount, { count: document.numPages });
483
+ controls.previous.disabled = pageNumber <= 1;
484
+ controls.next.disabled = pageNumber >= document.numPages;
485
+ controls.fit.setAttribute("aria-pressed", String(this.#zoom === void 0));
486
+ controls.sheet.setAttribute("aria-label", pageLabel);
487
+ try {
488
+ const page = await document.getPage(pageNumber);
489
+ if (render !== this.#renders) return;
490
+ const natural = page.getViewport({ scale: 1 });
491
+ const available = controls.pages.clientWidth - 32;
492
+ const scale = this.#zoom ?? (available > 0 ? available / natural.width : 1);
493
+ this.#scale = scale;
494
+ controls.zoomLevel.textContent = formatViewerMessage(messages.zoomLevel, { percent: Math.round(scale * 100) });
495
+ controls.zoomOut.disabled = scale <= MIN_ZOOM;
496
+ controls.zoomIn.disabled = scale >= MAX_ZOOM;
497
+ const viewport = page.getViewport({ scale });
498
+ const ratio = typeof devicePixelRatio === "number" && devicePixelRatio || 1;
499
+ const { canvas } = controls;
500
+ canvas.width = Math.floor(viewport.width * ratio);
501
+ canvas.height = Math.floor(viewport.height * ratio);
502
+ canvas.style.width = `${Math.floor(viewport.width)}px`;
503
+ canvas.style.height = `${Math.floor(viewport.height)}px`;
504
+ const task = page.render({
505
+ canvas,
506
+ viewport,
507
+ transform: ratio === 1 ? void 0 : [
508
+ ratio,
509
+ 0,
510
+ 0,
511
+ ratio,
512
+ 0,
513
+ 0
514
+ ]
515
+ });
516
+ this.#renderTask = task;
517
+ task.promise.catch(() => {});
518
+ const content = await page.getTextContent();
519
+ if (render !== this.#renders) return;
520
+ controls.text.textContent = content.items.map((item) => "str" in item ? `${item.str}${item.hasEOL ? "\n" : ""}` : "").join("");
521
+ await task.promise;
522
+ if (render !== this.#renders) return;
523
+ this.#recovering = false;
524
+ controls.status.textContent = pageLabel;
525
+ this.state = "loaded";
526
+ } catch (error) {
527
+ if (render !== this.#renders || signal?.aborted) return;
528
+ if (error?.name === "RenderingCancelledException") return;
529
+ const fresh = this.#recovering ? void 0 : this.urls.refresh("rendered");
530
+ if (!fresh) return this.fail();
531
+ this.#recovering = true;
532
+ try {
533
+ const url = await fresh;
534
+ const reopened = await openPdfDocument(url, this.options.pdf);
535
+ this.urls.loaded("rendered");
536
+ this.#url = url;
537
+ controls.open.href = url;
538
+ this.#document?.loadingTask.destroy();
539
+ this.#document = reopened;
540
+ await this.#render(signal);
541
+ } catch {
542
+ this.fail();
543
+ }
544
+ }
545
+ }
546
+ #close(document = this.#document) {
547
+ this.#renderTask?.cancel();
548
+ this.#renderTask = void 0;
549
+ this.#resize?.disconnect();
550
+ this.#resize = void 0;
551
+ this.#controls = void 0;
552
+ if (document) document.loadingTask.destroy();
553
+ if (document === this.#document) this.#document = void 0;
554
+ }
555
+ fail() {
556
+ this.#close();
557
+ this.state = "error";
558
+ const link = this.#url && el("a", {
559
+ class: "calmlens-button calmlens-viewer__link",
560
+ href: this.#url,
561
+ target: "_blank",
562
+ rel: "noopener noreferrer"
563
+ }, [this.messages.openDocument]);
564
+ this.frame.replaceChildren(this.notice(this.messages.documentFailed, link));
565
+ }
566
+ destroy() {
567
+ this.#close();
568
+ super.destroy();
569
+ }
570
+ };
571
+ /** Shows a PDF, or a document rendered as one, in `root`. */
572
+ const createDocumentViewer = (root, options) => {
573
+ const viewer = new DocumentViewer(root);
574
+ viewer.update(options);
575
+ return viewer;
576
+ };
577
+ // src/ui/viewers/ImageViewers.ts
578
+ /** Widths offered for a public image, so the browser fetches the smallest that fills the frame. */
579
+ const IMAGE_WIDTHS = [
580
+ 320,
581
+ 640,
582
+ 960,
583
+ 1280,
584
+ 1920,
585
+ 2560
586
+ ];
587
+ /** The blurred placeholder shown while the image loads: the stored ThumbHash, or the CDN's. */
588
+ const placeholderFor = (asset, urls) => {
589
+ const hash = asset.content?.preview?.thumbhash;
590
+ if (hash) try {
591
+ return require_UploadController.placeholderHashToDataURL(hash);
592
+ } catch {}
593
+ return asset.content?.rendered || asset.content?.preview ? urls.url("placeholder") : void 0;
594
+ };
595
+ /**
596
+ * Loads the rendered image into `image` at responsive widths, asking once for a fresh asset URL
597
+ * when it fails to load (as an expired signed one does).
598
+ */
599
+ const loadRenderedImage = async (urls, image, { sizes, width }, signal, done) => {
600
+ const widths = IMAGE_WIDTHS.filter((candidate) => !width || candidate < width);
601
+ const setSources = (src) => {
602
+ if (widths.length) {
603
+ image.srcset = [...widths, ...width ? [width] : []].map((candidate) => `${urls.url("rendered", { width: candidate })} ${candidate}w`).join(", ");
604
+ image.sizes = sizes;
605
+ }
606
+ image.src = src;
607
+ };
608
+ image.addEventListener("load", () => {
609
+ urls.loaded("rendered");
610
+ done("loaded");
611
+ });
612
+ image.addEventListener("error", () => {
613
+ const fresh = urls.refresh("rendered");
614
+ if (!fresh) return done("error");
615
+ fresh.then((url) => {
616
+ if (!signal.aborted) setSources(url);
617
+ }, () => done("error"));
618
+ });
619
+ const url = await urls.get("rendered");
620
+ if (!signal.aborted) setSources(url);
621
+ };
622
+ /**
623
+ * Shows an image asset's rendered file, fitted inside the element (the whole frame, for an embed
624
+ * page), over its blurred placeholder until it loads.
625
+ */
626
+ var ImageViewer = class extends ViewerBase {
627
+ constructor(root) {
628
+ super(root, "image");
629
+ }
630
+ describe({ asset, sizes }) {
631
+ return [
632
+ asset.content?.rendered,
633
+ asset.content?.preview?.thumbhash,
634
+ sizes
635
+ ];
636
+ }
637
+ async load(signal) {
638
+ const { asset, label = "", sizes = "100vw" } = this.options;
639
+ const rendered = asset.content?.rendered;
640
+ if (rendered?.width && rendered.height) this.root.style.setProperty("--calmlens-viewer-ratio", `${rendered.width} / ${rendered.height}`);
641
+ const placeholderUrl = placeholderFor(asset, this.urls);
642
+ const placeholder = placeholderUrl && el("img", {
643
+ class: "calmlens-viewer__placeholder",
644
+ src: placeholderUrl,
645
+ alt: "",
646
+ "aria-hidden": "true"
647
+ });
648
+ const image = el("img", {
649
+ class: "calmlens-viewer__image",
650
+ alt: label,
651
+ width: rendered?.width ?? void 0,
652
+ height: rendered?.height ?? void 0,
653
+ decoding: "async"
654
+ });
655
+ this.frame.replaceChildren(...[placeholder, image].filter((node) => !!node));
656
+ await loadRenderedImage(this.urls, image, {
657
+ sizes,
658
+ width: rendered?.width
659
+ }, signal, (outcome) => {
660
+ if (signal.aborted) return;
661
+ if (outcome === "error") return this.fail();
662
+ this.state = "loaded";
663
+ if (placeholder) placeholder.remove();
664
+ });
665
+ }
666
+ fail() {
667
+ this.state = "error";
668
+ this.frame.replaceChildren(this.notice(this.messages.imageFailed));
669
+ }
670
+ };
671
+ /** The page's address, if it is a web address the viewer may link to. */
672
+ const websiteUrl = (asset) => {
673
+ if (!asset.externalUrl) return void 0;
674
+ try {
675
+ const url = new URL(asset.externalUrl);
676
+ return url.protocol === "https:" || url.protocol === "http:" ? url : void 0;
677
+ } catch {
678
+ return;
679
+ }
680
+ };
681
+ /**
682
+ * Shows a website asset: a link to the original page, then its screenshot at the element's width,
683
+ * scrolling down the page.
684
+ */
685
+ var WebsiteViewer = class extends ViewerBase {
686
+ constructor(root) {
687
+ super(root, "website");
688
+ }
689
+ describe({ asset }) {
690
+ return [
691
+ asset.content?.rendered,
692
+ asset.content?.preview?.thumbhash,
693
+ asset.externalUrl
694
+ ];
695
+ }
696
+ #link() {
697
+ const url = websiteUrl(this.options.asset);
698
+ return url ? el("div", { class: "calmlens-viewer__bar" }, [el("a", {
699
+ class: "calmlens-button calmlens-viewer__link",
700
+ href: url.href,
701
+ target: "_blank",
702
+ rel: "noopener noreferrer nofollow"
703
+ }, [formatViewerMessage(this.messages.openWebsite, { host: url.host })])]) : void 0;
704
+ }
705
+ async load(signal) {
706
+ const { asset, label } = this.options;
707
+ const rendered = asset.content?.rendered;
708
+ if (!rendered) return this.fail();
709
+ const name = label || this.messages.websiteLabel;
710
+ const placeholderUrl = placeholderFor(asset, this.urls);
711
+ const placeholder = placeholderUrl && el("img", {
712
+ class: "calmlens-viewer__placeholder",
713
+ src: placeholderUrl,
714
+ alt: "",
715
+ "aria-hidden": "true"
716
+ });
717
+ const image = el("img", {
718
+ class: "calmlens-viewer__image",
719
+ alt: name,
720
+ width: rendered.width ?? void 0,
721
+ height: rendered.height ?? void 0,
722
+ decoding: "async"
723
+ });
724
+ const page = el("div", {
725
+ class: "calmlens-viewer__scroll",
726
+ role: "region",
727
+ "aria-label": name,
728
+ tabindex: 0
729
+ }, [placeholder, image]);
730
+ this.frame.replaceChildren(...[this.#link(), page].filter((node) => !!node));
731
+ await loadRenderedImage(this.urls, image, {
732
+ sizes: "100vw",
733
+ width: rendered.width
734
+ }, signal, (outcome) => {
735
+ if (signal.aborted) return;
736
+ if (outcome === "error") return this.fail();
737
+ this.state = "loaded";
738
+ if (placeholder) placeholder.remove();
739
+ });
740
+ }
741
+ fail() {
742
+ this.state = "error";
743
+ this.frame.replaceChildren(...[this.#link(), this.notice(this.messages.imageFailed)].filter((node) => !!node));
744
+ }
745
+ };
746
+ /** Shows an image asset's rendered file in `root`. */
747
+ const createImageViewer = (root, options) => {
748
+ const viewer = new ImageViewer(root);
749
+ viewer.update(options);
750
+ return viewer;
751
+ };
752
+ /** Shows a website asset's screenshot and a link to the page in `root`. */
753
+ const createWebsiteViewer = (root, options) => {
754
+ const viewer = new WebsiteViewer(root);
755
+ viewer.update(options);
756
+ return viewer;
757
+ };
758
+ // src/ui/viewers/Spreadsheet.ts
759
+ const SHEET_LINE = /^# Sheet "((?:[^"\\]|\\.)*)"( \(hidden\))?$/;
760
+ const ROW_LINE = /^Row (\d+)( \(hidden\))?: (.*)$/;
761
+ const CELL = /^([A-Z]{1,3})( \(hidden\))?=/;
762
+ const CELL_SEPARATOR = / \| (?=[A-Z]{1,3}(?: \(hidden\))?=)/;
763
+ /** A column's index from its letters: `A` is 0, `Z` 25 and `AA` 26. */
764
+ const spreadsheetColumnIndex = (name) => [...name].reduce((index, letter) => index * 26 + letter.charCodeAt(0) - 64, 0) - 1;
765
+ const unquote = (name) => name.replace(/\\(.)/g, "$1");
766
+ /**
767
+ * Reads a spreadsheet's sheets from the text CalmLens extracts from it: a `# Sheet "name"` line
768
+ * per sheet (marked `(hidden)` when it is), then a `Row 3: A=… | B=…` line per row that has cells,
769
+ * then its comments and chart titles. A cell value that itself contains ` | B=` reads as two
770
+ * cells. Text before the first sheet heading, as in a file that isn't a spreadsheet's text, reads
771
+ * as one unnamed sheet's notes.
772
+ */
773
+ const parseSpreadsheetText = (text) => {
774
+ const sheets = [];
775
+ let sheet;
776
+ const current = () => {
777
+ if (!sheet) {
778
+ sheet = {
779
+ name: "",
780
+ hidden: false,
781
+ rows: [],
782
+ columns: [],
783
+ notes: []
784
+ };
785
+ sheets.push(sheet);
786
+ }
787
+ return sheet;
788
+ };
789
+ for (const line of text.split(/\r?\n/)) {
790
+ if (!line.trim()) continue;
791
+ const heading = SHEET_LINE.exec(line);
792
+ if (heading) {
793
+ sheet = {
794
+ name: unquote(heading[1]),
795
+ hidden: Boolean(heading[2]),
796
+ rows: [],
797
+ columns: [],
798
+ notes: []
799
+ };
800
+ sheets.push(sheet);
801
+ continue;
802
+ }
803
+ const row = ROW_LINE.exec(line);
804
+ const cells = row?.[3]?.split(CELL_SEPARATOR).map((part) => {
805
+ const cell = CELL.exec(part);
806
+ if (!cell) return void 0;
807
+ const columnName = cell[1];
808
+ return {
809
+ column: spreadsheetColumnIndex(columnName),
810
+ columnName,
811
+ hidden: Boolean(cell[2]),
812
+ text: part.slice(cell[0].length)
813
+ };
814
+ });
815
+ if (row && cells?.every((cell) => cell !== void 0)) current().rows.push({
816
+ number: Number(row[1]),
817
+ hidden: Boolean(row[2]),
818
+ cells
819
+ });
820
+ else current().notes.push(line);
821
+ }
822
+ for (const { rows, columns } of sheets) {
823
+ const seen = /* @__PURE__ */ new Map();
824
+ for (const { cells } of rows) for (const { column, columnName, hidden } of cells) if (!seen.has(column)) seen.set(column, {
825
+ column,
826
+ columnName,
827
+ hidden
828
+ });
829
+ columns.push(...[...seen.values()].sort((a, b) => a.column - b.column));
830
+ }
831
+ return sheets;
832
+ };
833
+ /** The rows of one page of a sheet, with their one-based positions among the sheet's rows. */
834
+ const getSpreadsheetPage = (sheet, page, pageSize) => {
835
+ const pages = Math.max(1, Math.ceil(sheet.rows.length / pageSize));
836
+ const index = Math.min(Math.max(0, page), pages - 1);
837
+ const rows = sheet.rows.slice(index * pageSize, (index + 1) * pageSize);
838
+ return {
839
+ rows,
840
+ from: rows.length ? index * pageSize + 1 : 0,
841
+ to: index * pageSize + rows.length,
842
+ pages
843
+ };
844
+ };
845
+ // src/ui/viewers/TextViewers.ts
846
+ /**
847
+ * The text to show: `text`, then `getText`, then the inline `content.extractedText`, then a text
848
+ * asset's `original` file.
849
+ */
850
+ const readText = async ({ asset, text, getText }, urls, signal) => {
851
+ if (text !== void 0) return text;
852
+ if (getText) return await getText();
853
+ const extracted = asset.content?.extractedText;
854
+ if (extracted?.type === "string") return extracted.content;
855
+ if (asset.type === "plaintext-document") return await fetchViewerText(urls, "original", signal);
856
+ throw new Error("The asset has no text to show");
857
+ };
858
+ const describeText = ({ asset, text }) => [
859
+ asset.type,
860
+ asset.content?.extractedText,
861
+ text
862
+ ];
863
+ /**
864
+ * Shows text, such as a text asset's: always as text, never as markup, wrapped to the element's
865
+ * width in a focusable region that scrolls.
866
+ */
867
+ var TextViewer = class extends ViewerBase {
868
+ constructor(root) {
869
+ super(root, "text");
870
+ }
871
+ describe(options) {
872
+ return describeText(options);
873
+ }
874
+ async load(signal) {
875
+ this.frame.replaceChildren(this.loadingNotice());
876
+ const text = await readText(this.options, this.urls, signal);
877
+ if (signal.aborted) return;
878
+ const content = el("pre", {
879
+ class: "calmlens-viewer__text",
880
+ dir: "auto"
881
+ });
882
+ content.textContent = text;
883
+ this.frame.replaceChildren(el("div", {
884
+ class: "calmlens-viewer__scroll",
885
+ role: "region",
886
+ "aria-label": this.options.label || this.messages.textLabel,
887
+ tabindex: 0
888
+ }, [content]));
889
+ this.state = "loaded";
890
+ }
891
+ fail() {
892
+ this.state = "error";
893
+ this.frame.replaceChildren(this.notice(this.messages.textFailed));
894
+ }
895
+ };
896
+ /**
897
+ * Shows a spreadsheet's sheets, read from the text CalmLens extracts: a tab per sheet and a table
898
+ * of its cells, a page of rows at a time. Cell text is always shown as text.
899
+ */
900
+ var SpreadsheetViewer = class extends ViewerBase {
901
+ #sheets = [];
902
+ #selected = 0;
903
+ /** The page each sheet shows, by sheet index. */
904
+ #pages = [];
905
+ #panel;
906
+ #tabs = [];
907
+ constructor(root) {
908
+ super(root, "spreadsheet");
909
+ }
910
+ describe(options) {
911
+ return [...describeText(options), options.pageSize];
912
+ }
913
+ get #pageSize() {
914
+ const size = this.options.pageSize;
915
+ return size && Number.isSafeInteger(size) && size > 0 ? size : 100;
916
+ }
917
+ async load(signal) {
918
+ this.frame.replaceChildren(this.loadingNotice());
919
+ const text = await readText(this.options, this.urls, signal);
920
+ if (signal.aborted) return;
921
+ this.#sheets = parseSpreadsheetText(text);
922
+ this.#selected = 0;
923
+ this.#pages = this.#sheets.map(() => 0);
924
+ if (!this.#sheets.length) this.#sheets = [{
925
+ name: "",
926
+ hidden: false,
927
+ rows: [],
928
+ columns: [],
929
+ notes: []
930
+ }];
931
+ const tablist = el("div", {
932
+ class: "calmlens-viewer__tabs",
933
+ role: "tablist",
934
+ "aria-label": this.messages.sheets
935
+ });
936
+ const panelId = viewerId("sheet");
937
+ this.#tabs = this.#sheets.map((sheet, index) => {
938
+ const tab = el("button", {
939
+ type: "button",
940
+ role: "tab",
941
+ id: viewerId("sheet-tab"),
942
+ "aria-controls": panelId,
943
+ class: "calmlens-viewer__tab",
944
+ "data-hidden": sheet.hidden
945
+ }, [sheet.hidden ? formatViewerMessage(this.messages.hiddenSheet, { name: sheet.name }) : sheet.name || String(index + 1)]);
946
+ tab.addEventListener("click", () => this.#select(index));
947
+ tab.addEventListener("keydown", (event) => this.#onTabKey(event, index));
948
+ return tab;
949
+ });
950
+ tablist.append(...this.#tabs);
951
+ this.#panel = el("div", {
952
+ class: "calmlens-viewer__panel",
953
+ role: "tabpanel",
954
+ id: panelId,
955
+ tabindex: 0
956
+ });
957
+ const label = this.options.label || this.messages.spreadsheetLabel;
958
+ this.frame.replaceChildren(el("div", {
959
+ class: "calmlens-viewer__sheets",
960
+ role: "group",
961
+ "aria-label": label
962
+ }, [this.#sheets.length > 1 && tablist, this.#panel]));
963
+ this.#select(0);
964
+ this.state = "loaded";
965
+ }
966
+ #onTabKey(event, index) {
967
+ const last = this.#tabs.length - 1;
968
+ const target = event.key === "ArrowRight" ? index === last ? 0 : index + 1 : event.key === "ArrowLeft" ? index === 0 ? last : index - 1 : event.key === "Home" ? 0 : event.key === "End" ? last : void 0;
969
+ if (target === void 0) return;
970
+ event.preventDefault();
971
+ this.#select(target);
972
+ this.#tabs[target]?.focus();
973
+ }
974
+ #select(index) {
975
+ this.#selected = index;
976
+ this.#tabs.forEach((tab, tabIndex) => {
977
+ tab.setAttribute("aria-selected", String(tabIndex === index));
978
+ tab.tabIndex = tabIndex === index ? 0 : -1;
979
+ });
980
+ const tab = this.#tabs[index];
981
+ if (tab) this.#panel?.setAttribute("aria-labelledby", tab.id);
982
+ else this.#panel?.setAttribute("aria-label", this.#sheets[index]?.name || this.messages.spreadsheetLabel);
983
+ this.#renderSheet();
984
+ }
985
+ #renderSheet() {
986
+ const panel = this.#panel;
987
+ const sheet = this.#sheets[this.#selected];
988
+ if (!panel || !sheet) return;
989
+ const { messages } = this;
990
+ const page = getSpreadsheetPage(sheet, this.#pages[this.#selected] ?? 0, this.#pageSize);
991
+ const children = [];
992
+ if (sheet.rows.length) {
993
+ const header = el("tr", {}, [el("td", { class: "calmlens-viewer__corner" }), ...sheet.columns.map(({ columnName, hidden }) => el("th", {
994
+ scope: "col",
995
+ "data-hidden": hidden
996
+ }, [columnName, hidden && el("span", { class: "calmlens-viewer__tag" }, [messages.hidden])]))]);
997
+ const body = page.rows.map((row) => {
998
+ const cells = new Map(row.cells.map((cell) => [cell.column, cell.text]));
999
+ return el("tr", { "data-hidden": row.hidden }, [el("th", {
1000
+ scope: "row",
1001
+ "data-hidden": row.hidden
1002
+ }, [String(row.number), row.hidden && el("span", { class: "calmlens-viewer__tag" }, [messages.hidden])]), ...sheet.columns.map(({ column }) => {
1003
+ const cell = el("td");
1004
+ cell.textContent = cells.get(column) ?? "";
1005
+ return cell;
1006
+ })]);
1007
+ });
1008
+ children.push(el("div", { class: "calmlens-viewer__table" }, [el("table", {}, [el("thead", {}, [header]), el("tbody", {}, body)])]));
1009
+ } else children.push(el("p", { class: "calmlens-viewer__empty" }, [messages.emptySheet]));
1010
+ if (page.pages > 1) {
1011
+ const pageIndex = Math.min(this.#pages[this.#selected] ?? 0, page.pages - 1);
1012
+ const go = (offset) => {
1013
+ this.#pages[this.#selected] = pageIndex + offset;
1014
+ this.#renderSheet();
1015
+ panel.querySelector(`[data-pager="${offset < 0 ? "previous" : "next"}"]`)?.focus();
1016
+ };
1017
+ const previous = el("button", {
1018
+ type: "button",
1019
+ class: "calmlens-button",
1020
+ "data-pager": "previous",
1021
+ disabled: pageIndex === 0
1022
+ }, [messages.previousRows]);
1023
+ const next = el("button", {
1024
+ type: "button",
1025
+ class: "calmlens-button",
1026
+ "data-pager": "next",
1027
+ disabled: pageIndex === page.pages - 1
1028
+ }, [messages.nextRows]);
1029
+ previous.addEventListener("click", () => go(-1));
1030
+ next.addEventListener("click", () => go(1));
1031
+ children.push(el("div", { class: "calmlens-viewer__pager" }, [
1032
+ previous,
1033
+ el("p", { role: "status" }, [formatViewerMessage(messages.rowRange, {
1034
+ from: page.from,
1035
+ to: page.to,
1036
+ count: sheet.rows.length
1037
+ })]),
1038
+ next
1039
+ ]));
1040
+ }
1041
+ if (sheet.notes.length) {
1042
+ const notes = el("ul");
1043
+ for (const note of sheet.notes) {
1044
+ const item = el("li");
1045
+ item.textContent = note;
1046
+ notes.append(item);
1047
+ }
1048
+ children.push(el("section", {
1049
+ class: "calmlens-viewer__notes",
1050
+ "aria-label": messages.sheetNotes
1051
+ }, [notes]));
1052
+ }
1053
+ panel.replaceChildren(...children.filter((node) => node !== void 0));
1054
+ }
1055
+ fail() {
1056
+ this.state = "error";
1057
+ this.frame.replaceChildren(this.notice(this.messages.spreadsheetFailed));
1058
+ }
1059
+ };
1060
+ /** Shows text in `root`. */
1061
+ const createTextViewer = (root, options) => {
1062
+ const viewer = new TextViewer(root);
1063
+ viewer.update(options);
1064
+ return viewer;
1065
+ };
1066
+ /** Shows a spreadsheet's sheets in `root`. */
1067
+ const createSpreadsheetViewer = (root, options) => {
1068
+ const viewer = new SpreadsheetViewer(root);
1069
+ viewer.update(options);
1070
+ return viewer;
1071
+ };
1072
+ // src/ui/viewers/index.ts
1073
+ /** Mounts each viewer, by kind, for the bindings. */
1074
+ const ASSET_VIEWERS = {
1075
+ image: createImageViewer,
1076
+ website: createWebsiteViewer,
1077
+ text: createTextViewer,
1078
+ document: createDocumentViewer,
1079
+ spreadsheet: createSpreadsheetViewer
1080
+ };
1081
+ // src/ui/AssetViewerMount.ts
1082
+ const isMountedViewerKind = (kind) => kind === "document" || kind === "text" || kind === "spreadsheet";
1083
+ /**
1084
+ * The viewer options for `CalmLensAsset`'s options: the asset URL in use, the info, and the
1085
+ * session's refresh and unavailable notice, so the viewer follows the same asset URL.
1086
+ */
1087
+ const getMountedViewerOptions = (options, session) => {
1088
+ const { src, info } = session.state;
1089
+ return {
1090
+ src,
1091
+ asset: info,
1092
+ viewerClaims: options.viewerClaims,
1093
+ label: options.alt,
1094
+ onExpired: options.onExpired ? () => session.refresh() : void 0,
1095
+ onUnavailable: () => session.unavailable(),
1096
+ pdf: options.document?.pdf,
1097
+ initialPage: options.document?.initialPage,
1098
+ pageSize: options.spreadsheet?.pageSize,
1099
+ getText: options.spreadsheet?.getText
1100
+ };
1101
+ };
1102
+ /**
1103
+ * Keeps the viewer for a document, text or spreadsheet view mounted in `root`, replacing it when
1104
+ * the kind changes and destroying it when there is none. `onState` reports each state the viewer
1105
+ * reaches (`loading`, `loaded`, `error`).
1106
+ */
1107
+ var AssetViewerMount = class {
1108
+ #root;
1109
+ #kind;
1110
+ #viewer;
1111
+ #observer;
1112
+ #onState;
1113
+ update(root, kind, options, onState) {
1114
+ this.#onState = onState;
1115
+ if (!root || !kind) {
1116
+ this.destroy();
1117
+ return;
1118
+ }
1119
+ if (root !== this.#root || kind !== this.#kind) {
1120
+ this.destroy();
1121
+ this.#root = root;
1122
+ this.#kind = kind;
1123
+ if (typeof MutationObserver !== "undefined") {
1124
+ this.#observer = new MutationObserver(() => {
1125
+ const state = root.dataset.state;
1126
+ if (state) this.#onState?.(state);
1127
+ });
1128
+ this.#observer.observe(root, {
1129
+ attributes: true,
1130
+ attributeFilter: ["data-state"]
1131
+ });
1132
+ }
1133
+ this.#viewer = ASSET_VIEWERS[kind](root, options);
1134
+ return;
1135
+ }
1136
+ this.#viewer?.update(options);
1137
+ }
1138
+ destroy() {
1139
+ this.#observer?.disconnect();
1140
+ this.#observer = void 0;
1141
+ this.#viewer?.destroy();
1142
+ this.#viewer = void 0;
1143
+ this.#root = void 0;
1144
+ this.#kind = void 0;
1145
+ }
1146
+ };
1147
+ // src/ui/MediaStream.ts
1148
+ /** The MIME type of an HLS playlist, which Safari and iOS play natively. */
1149
+ const HLS_MIME_TYPE = "application/vnd.apple.mpegurl";
1150
+ /** Whether the browser has Media Source Extensions, which hls.js plays a stream through. */
1151
+ const hasMediaSource = () => typeof window !== "undefined" && ("MediaSource" in window || "ManagedMediaSource" in window);
1152
+ /**
1153
+ * Loads hls.js's light build, which plays HLS without subtitles or DRM, only when a stream is to
1154
+ * play through Media Source Extensions.
1155
+ */
1156
+ const loadHls = async () => (await import("hls.js/light")).default;
1157
+ /** The stream URL each element last fell back from, so it keeps playing the file afterwards. */
1158
+ const failedStreams = /* @__PURE__ */ new WeakMap();
1159
+ /** A video or audio element's source, from its view, when it has a stream to play. */
1160
+ const streamSource = (view) => (view.kind === "video" || view.kind === "audio") && view.stream ? {
1161
+ src: view.src,
1162
+ stream: view.stream
1163
+ } : void 0;
1164
+ const play = (media, { src, stream }, onExpired) => {
1165
+ let hls;
1166
+ let stopped = false;
1167
+ const playback = {
1168
+ streaming: true,
1169
+ fallBack: () => {
1170
+ playback.streaming = false;
1171
+ failedStreams.set(media, stream);
1172
+ hls?.destroy();
1173
+ hls = void 0;
1174
+ if (!stopped) media.src = src;
1175
+ },
1176
+ stop: () => {
1177
+ stopped = true;
1178
+ hls?.destroy();
1179
+ hls = void 0;
1180
+ }
1181
+ };
1182
+ if (failedStreams.get(media) === stream) {
1183
+ playback.streaming = false;
1184
+ media.src = src;
1185
+ } else if (media.canPlayType(HLS_MIME_TYPE)) media.src = stream;
1186
+ else if (hasMediaSource()) loadHls().then((HlsPlayer) => {
1187
+ if (stopped || !playback.streaming) return;
1188
+ if (!HlsPlayer.isSupported()) return playback.fallBack();
1189
+ const player = new HlsPlayer();
1190
+ hls = player;
1191
+ let refreshing = false;
1192
+ player.on(HlsPlayer.Events.ERROR, (_event, data) => {
1193
+ if (refreshing || hls !== player) return;
1194
+ if (data.response?.code === 403 && onExpired()) {
1195
+ refreshing = true;
1196
+ player.stopLoad();
1197
+ } else if (data.fatal) playback.fallBack();
1198
+ });
1199
+ player.loadSource(stream);
1200
+ player.attachMedia(media);
1201
+ }, playback.fallBack);
1202
+ else {
1203
+ playback.streaming = false;
1204
+ media.src = src;
1205
+ }
1206
+ return playback;
1207
+ };
1208
+ /**
1209
+ * Plays the adaptive stream of `CalmLensAsset`'s video or audio, when its view has one: as the
1210
+ * element's own source where the browser plays HLS (Safari and iOS), through hls.js where it has
1211
+ * Media Source Extensions (hls.js loads only then), and otherwise, or once the stream fails, from
1212
+ * the rendered file. Without a stream the component sets the file as the element's `src` itself.
1213
+ * `onExpired` runs when the stream's URL is refused, as an expired signed one is; it returns
1214
+ * `true` when a fresh asset URL is on its way, which replaces the stream once it renders.
1215
+ */
1216
+ var MediaStreamPlayer = class {
1217
+ #media;
1218
+ #key;
1219
+ #playback;
1220
+ #onExpired;
1221
+ constructor(onExpired) {
1222
+ this.#onExpired = onExpired;
1223
+ }
1224
+ /**
1225
+ * Call after every render with the video or audio element shown (or none) and the view: it
1226
+ * starts, replaces or stops the stream when either changed.
1227
+ */
1228
+ update(media, view) {
1229
+ const source = media ? streamSource(view) : void 0;
1230
+ const key = source && `${source.src}\n${source.stream}`;
1231
+ if (media === this.#media && key === this.#key) return;
1232
+ const previous = this.#media;
1233
+ const stopped = this.#playback !== void 0;
1234
+ this.stop();
1235
+ this.#media = media ?? void 0;
1236
+ this.#key = key;
1237
+ if (media && source) this.#playback = play(media, source, () => this.#onExpired(media));
1238
+ else if (media && stopped && media === previous && "src" in view && view.src) media.src = view.src;
1239
+ }
1240
+ /**
1241
+ * For a video or audio element's `error`: `true` when it switched from the stream to the
1242
+ * rendered file. `false` means the file itself failed, for the component's session to handle.
1243
+ */
1244
+ recover(media) {
1245
+ const playback = media === this.#media ? this.#playback : void 0;
1246
+ if (!playback?.streaming) return false;
1247
+ playback.fallBack();
1248
+ return true;
1249
+ }
1250
+ /** Stops the stream, when the component unmounts. */
1251
+ stop() {
1252
+ this.#playback?.stop();
1253
+ this.#playback = void 0;
1254
+ this.#media = void 0;
1255
+ this.#key = void 0;
1256
+ }
1257
+ };
1258
+ Object.defineProperty(exports, "ASSET_VIEWERS", {
1259
+ enumerable: true,
1260
+ get: function() {
1261
+ return ASSET_VIEWERS;
1262
+ }
1263
+ });
1264
+ Object.defineProperty(exports, "AssetViewerMount", {
1265
+ enumerable: true,
1266
+ get: function() {
1267
+ return AssetViewerMount;
1268
+ }
1269
+ });
1270
+ Object.defineProperty(exports, "DEFAULT_VIEWER_MESSAGES", {
1271
+ enumerable: true,
1272
+ get: function() {
1273
+ return DEFAULT_VIEWER_MESSAGES;
1274
+ }
1275
+ });
1276
+ Object.defineProperty(exports, "MediaStreamPlayer", {
1277
+ enumerable: true,
1278
+ get: function() {
1279
+ return MediaStreamPlayer;
1280
+ }
1281
+ });
1282
+ Object.defineProperty(exports, "createDocumentViewer", {
1283
+ enumerable: true,
1284
+ get: function() {
1285
+ return createDocumentViewer;
1286
+ }
1287
+ });
1288
+ Object.defineProperty(exports, "createImageViewer", {
1289
+ enumerable: true,
1290
+ get: function() {
1291
+ return createImageViewer;
1292
+ }
1293
+ });
1294
+ Object.defineProperty(exports, "createSpreadsheetViewer", {
1295
+ enumerable: true,
1296
+ get: function() {
1297
+ return createSpreadsheetViewer;
1298
+ }
1299
+ });
1300
+ Object.defineProperty(exports, "createTextViewer", {
1301
+ enumerable: true,
1302
+ get: function() {
1303
+ return createTextViewer;
1304
+ }
1305
+ });
1306
+ Object.defineProperty(exports, "createWebsiteViewer", {
1307
+ enumerable: true,
1308
+ get: function() {
1309
+ return createWebsiteViewer;
1310
+ }
1311
+ });
1312
+ Object.defineProperty(exports, "formatViewerMessage", {
1313
+ enumerable: true,
1314
+ get: function() {
1315
+ return formatViewerMessage;
1316
+ }
1317
+ });
1318
+ Object.defineProperty(exports, "getMountedViewerOptions", {
1319
+ enumerable: true,
1320
+ get: function() {
1321
+ return getMountedViewerOptions;
1322
+ }
1323
+ });
1324
+ Object.defineProperty(exports, "getSpreadsheetPage", {
1325
+ enumerable: true,
1326
+ get: function() {
1327
+ return getSpreadsheetPage;
1328
+ }
1329
+ });
1330
+ Object.defineProperty(exports, "isMountedViewerKind", {
1331
+ enumerable: true,
1332
+ get: function() {
1333
+ return isMountedViewerKind;
1334
+ }
1335
+ });
1336
+ Object.defineProperty(exports, "loadPdfJs", {
1337
+ enumerable: true,
1338
+ get: function() {
1339
+ return loadPdfJs;
1340
+ }
1341
+ });
1342
+ Object.defineProperty(exports, "parseSpreadsheetText", {
1343
+ enumerable: true,
1344
+ get: function() {
1345
+ return parseSpreadsheetText;
1346
+ }
1347
+ });
1348
+ Object.defineProperty(exports, "resolveViewerMessages", {
1349
+ enumerable: true,
1350
+ get: function() {
1351
+ return resolveViewerMessages;
1352
+ }
1353
+ });
1354
+ Object.defineProperty(exports, "spreadsheetColumnIndex", {
1355
+ enumerable: true,
1356
+ get: function() {
1357
+ return spreadsheetColumnIndex;
1358
+ }
1359
+ });