docblocks-react-ui 0.16.0 → 0.18.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.
@@ -1,4 +1,4 @@
1
- import { c as X, d as Minus, f as LoaderCircle, i as isSafeDownloadHref, l as TriangleAlert, m as ChevronLeft, p as ChevronRight, r as clamp, s as cn, t as isEmbeddablePdfUrl, u as Plus } from "../constants-D8PSgkwi.mjs";
1
+ import { C as cn, a as clamp, b as PdfFetchError, d as Plus, f as Minus, h as ChevronLeft, l as X, m as ChevronRight, n as ZOOM_STEP, o as isSafeDownloadHref, p as LoaderCircle, r as isEmbeddablePdfUrl, t as ZOOM_MIN, u as TriangleAlert } from "../constants-DWJbJpt5.mjs";
2
2
  import { t as Maximize } from "../Maximize-BBHnCDWL.mjs";
3
3
  import { useCallback, useEffect, useRef, useState } from "react";
4
4
  import { useTranslation } from "react-i18next";
@@ -112,144 +112,210 @@ if (typeof window !== "undefined") fetch(WORKER_URL, { method: "HEAD" }).catch((
112
112
  console.warn("docblocks: the pdf worker asset is unreachable; the preview will use the native viewer fallback.");
113
113
  });
114
114
  //#endregion
115
- //#region src/pdf/PdfFirstPage.tsx
116
- /** The PDF preview of one file block: fetch the resolved
117
- * blob, render the pages to a canvas via pdfjs-dist. The inline view stands
118
- * the first page over the page row; the controls (the previous/next page
119
- * buttons + the page indicator + the fullscreen toggle) stand a bar under
120
- * the canvas. The fullscreen mode opens a portal overlay over the viewport
121
- * (the page scaled to fill the viewport, the same page navigation, the zoom
122
- * bar — the zoom in/out buttons over the scale + the fit-width / the
123
- * fit-height — a separate
124
- * pill to the left of the page controls, the Escape key / the arrow keys /
125
- * the close button / the outside click exit). The overlay's open locks the
126
- * body's scroll (a wheel over the fixed portal chains to the document's
127
- * scroll container — the page behind must not scroll). The page indicator's
128
- * and the scale's numbers stand a fixed width (the digit count's change
129
- * must not shift the buttons). The preview's chrome stands no text
130
- * selection (`select-none`): the page indicator's and the controls' text
131
- * is not document content, and a selection stood there would flag the
132
- * block / pull the format toolbar over a non-text range. A failure stands
133
- * the error note over the native iframe fallback (the document stays
134
- * viewable). The in-flight fetch is aborted on unmount / url change and
135
- * the render task + document are released, so a torn-down preview leaves
136
- * no network request or pdf.js worker behind. */
137
- /** The fullscreen zoom's bounds + the per-click step: the scale's units
138
- * are the css px per pdf point (the device pixel ratio stands the backing
139
- * store's scale, not this factor). */
140
- const ZOOM_MIN = .25;
141
- const ZOOM_MAX = 4;
142
- const ZOOM_STEP = 1.25;
143
- /** Render one page to a canvas (the natural page size, the backing store
144
- * scaled by the device pixel ratio for a crisp retina display). Returns the
145
- * render task (the caller awaits its promise + cancels it on teardown).
146
- * Does NOT await the promise itself, so the caller can cancel the in-flight
147
- * render before it completes. */
148
- function renderPageToCanvas(pdf, pageNumber, canvas) {
149
- return pdf.getPage(pageNumber).then((page) => {
150
- const ratio = window.devicePixelRatio || 1;
151
- const viewport = page.getViewport({ scale: ratio });
152
- canvas.width = Math.max(1, Math.floor(viewport.width));
153
- canvas.height = Math.max(1, Math.floor(viewport.height));
154
- canvas.style.width = `${Math.max(1, Math.floor(viewport.width / ratio))}px`;
155
- canvas.style.height = `${Math.max(1, Math.floor(viewport.height / ratio))}px`;
156
- return page.render({
157
- canvas,
158
- viewport
159
- });
115
+ //#region src/pdf/PdfPageControls.tsx
116
+ /** The PDF preview's page controls bar: the previous / next page buttons
117
+ * + the page indicator + the trailing action (the fullscreen toggle over
118
+ * the inline view, the close over the portaled overlay). The page number
119
+ * stands a fixed width (the total's digit count): the digit count's change
120
+ * (1 → 2) must not shift the buttons. The bar's border + radius read the
121
+ * --docblocks-* tokens over the editor's root and the standard tokens over
122
+ * the portaled overlay (the overlay renders outside the editor's root,
123
+ * where the --docblocks-* tokens are undefined — an undefined var() would
124
+ * fall back to the border's initial 3px/currentColor + the radius's 0). */
125
+ function PdfPageControls({ currentPage, totalPages, onPrevPage, onNextPage, actionSlot, actionLabel, actionIcon: ActionIcon, onAction, portaled }) {
126
+ const { t } = useTranslation("blocks");
127
+ return /* @__PURE__ */ jsxs("div", {
128
+ "data-slot": "docblocks/image-pdf-controls",
129
+ className: cn(`flex items-center justify-center gap-1 px-2 py-1`, portaled ? `rounded-(--radius) border border-(--border) bg-(--muted) select-none` : `
130
+ rounded-(--docblocks-radius) border-(length:--docblocks-table-border-width)
131
+ border-(--docblocks-table-border-color) bg-(--muted)
132
+ `),
133
+ children: [
134
+ /* @__PURE__ */ jsx("button", {
135
+ type: "button",
136
+ "data-slot": "docblocks/image-pdf-prev",
137
+ onClick: onPrevPage,
138
+ disabled: currentPage <= 1,
139
+ "aria-label": t("code.pdfPrevPage"),
140
+ className: "\n flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n disabled:pointer-events-none disabled:opacity-40\n ",
141
+ children: /* @__PURE__ */ jsx(ChevronLeft, { className: "size-4" })
142
+ }),
143
+ /* @__PURE__ */ jsxs("span", {
144
+ "data-slot": "docblocks/image-pdf-page-indicator",
145
+ className: "px-1 text-xs text-(--muted-foreground) tabular-nums",
146
+ children: [
147
+ /* @__PURE__ */ jsx("span", {
148
+ className: "inline-block text-right",
149
+ style: { minWidth: `${Math.max(1, String(totalPages).length)}ch` },
150
+ children: currentPage
151
+ }),
152
+ " / ",
153
+ totalPages
154
+ ]
155
+ }),
156
+ /* @__PURE__ */ jsx("button", {
157
+ type: "button",
158
+ "data-slot": "docblocks/image-pdf-next",
159
+ onClick: onNextPage,
160
+ disabled: currentPage >= totalPages,
161
+ "aria-label": t("code.pdfNextPage"),
162
+ className: "\n flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n disabled:pointer-events-none disabled:opacity-40\n ",
163
+ children: /* @__PURE__ */ jsx(ChevronRight, { className: "size-4" })
164
+ }),
165
+ /* @__PURE__ */ jsx("button", {
166
+ type: "button",
167
+ "data-slot": actionSlot,
168
+ onClick: onAction,
169
+ "aria-label": actionLabel,
170
+ className: "\n ml-1 flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n ",
171
+ children: /* @__PURE__ */ jsx(ActionIcon, { className: "size-4" })
172
+ })
173
+ ]
160
174
  });
161
175
  }
162
- function PdfFirstPage({ id, blockType, url, name }) {
176
+ //#endregion
177
+ //#region src/pdf/PdfZoomControls.tsx
178
+ /** The PDF fullscreen zoom's bar: the zoom out / in buttons over the
179
+ * scale's indicator + the fit-width / fit-height. It stands a separate
180
+ * pill to the left of the page's controls, the same bar's style over the
181
+ * standard tokens (the overlay is portaled over the document body,
182
+ * outside the editor's root, where the --docblocks-* tokens are
183
+ * undefined). */
184
+ function PdfZoomControls({ scale, onZoomOut, onZoomIn, onFitWidth, onFitHeight }) {
185
+ const { t } = useTranslation("blocks");
186
+ return /* @__PURE__ */ jsxs("div", {
187
+ "data-slot": "docblocks/image-pdf-zoom",
188
+ className: "\n flex items-center justify-center gap-1 rounded-(--radius) border border-(--border) bg-(--muted) px-2 py-1\n select-none\n ",
189
+ children: [
190
+ /* @__PURE__ */ jsx("button", {
191
+ type: "button",
192
+ "data-slot": "docblocks/image-pdf-zoom-out",
193
+ onClick: onZoomOut,
194
+ disabled: scale <= ZOOM_MIN + 1e-9,
195
+ "aria-label": t("code.pdfZoomOut"),
196
+ className: "\n flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n disabled:pointer-events-none disabled:opacity-40\n ",
197
+ children: /* @__PURE__ */ jsx(Minus, { className: "size-4" })
198
+ }),
199
+ /* @__PURE__ */ jsxs("span", {
200
+ "data-slot": "docblocks/image-pdf-zoom-indicator",
201
+ className: "inline-block min-w-[4ch] px-1 text-right text-xs text-(--muted-foreground) tabular-nums",
202
+ children: [Math.round(scale * 100), "%"]
203
+ }),
204
+ /* @__PURE__ */ jsx("button", {
205
+ type: "button",
206
+ "data-slot": "docblocks/image-pdf-zoom-in",
207
+ onClick: onZoomIn,
208
+ disabled: scale >= 4 - 1e-9,
209
+ "aria-label": t("code.pdfZoomIn"),
210
+ className: "\n flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n disabled:pointer-events-none disabled:opacity-40\n ",
211
+ children: /* @__PURE__ */ jsx(Plus, { className: "size-4" })
212
+ }),
213
+ /* @__PURE__ */ jsx("button", {
214
+ type: "button",
215
+ "data-slot": "docblocks/image-pdf-fit-width",
216
+ onClick: onFitWidth,
217
+ "aria-label": t("code.pdfFitWidth"),
218
+ className: "\n flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n ",
219
+ children: /* @__PURE__ */ jsx(StretchHorizontal, { className: "size-4" })
220
+ }),
221
+ /* @__PURE__ */ jsx("button", {
222
+ type: "button",
223
+ "data-slot": "docblocks/image-pdf-fit-height",
224
+ onClick: onFitHeight,
225
+ "aria-label": t("code.pdfFitHeight"),
226
+ className: "\n flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n ",
227
+ children: /* @__PURE__ */ jsx(StretchVertical, { className: "size-4" })
228
+ })
229
+ ]
230
+ });
231
+ }
232
+ //#endregion
233
+ //#region src/pdf/use-pdf-zoom.ts
234
+ function usePdfZoom(pdfDocRef, containerRef, currentPage) {
235
+ const [zoom, setZoom] = useState(null);
236
+ const [scale, setScale] = useState(1);
237
+ return {
238
+ zoom,
239
+ scale,
240
+ setScale,
241
+ zoomBy: useCallback((factor) => {
242
+ const pdf = pdfDocRef.current;
243
+ const container = containerRef.current;
244
+ if (pdf === null || container === null) return;
245
+ const width = container.clientWidth;
246
+ const height = container.clientHeight;
247
+ if (width === 0 || height === 0) return;
248
+ pdf.getPage(currentPage).then((page) => {
249
+ const pageViewport = page.getViewport({ scale: 1 });
250
+ const fit = Math.min(width / pageViewport.width, height / pageViewport.height);
251
+ setZoom(clamp((zoom ?? fit) * factor, ZOOM_MIN, 4));
252
+ });
253
+ }, [
254
+ pdfDocRef,
255
+ containerRef,
256
+ currentPage,
257
+ zoom
258
+ ]),
259
+ fitWidth: useCallback(() => {
260
+ const pdf = pdfDocRef.current;
261
+ const container = containerRef.current;
262
+ if (pdf === null || container === null) return;
263
+ const width = container.clientWidth;
264
+ if (width === 0) return;
265
+ pdf.getPage(currentPage).then((page) => {
266
+ const pageViewport = page.getViewport({ scale: 1 });
267
+ setZoom(clamp(width / pageViewport.width, ZOOM_MIN, 4));
268
+ });
269
+ }, [
270
+ pdfDocRef,
271
+ containerRef,
272
+ currentPage
273
+ ]),
274
+ fitHeight: useCallback(() => {
275
+ const pdf = pdfDocRef.current;
276
+ const container = containerRef.current;
277
+ if (pdf === null || container === null) return;
278
+ const height = container.clientHeight;
279
+ if (height === 0) return;
280
+ pdf.getPage(currentPage).then((page) => {
281
+ const pageViewport = page.getViewport({ scale: 1 });
282
+ setZoom(clamp(height / pageViewport.height, ZOOM_MIN, 4));
283
+ });
284
+ }, [
285
+ pdfDocRef,
286
+ containerRef,
287
+ currentPage
288
+ ])
289
+ };
290
+ }
291
+ //#endregion
292
+ //#region src/pdf/PdfFullscreenOverlay.tsx
293
+ /** The PDF preview's fullscreen overlay: the page scaled to fill the
294
+ * viewport over a portal (the same page navigation, the zoom bar — the
295
+ * zoom in / out buttons over the scale + the fit-width / the fit-height —
296
+ * a separate pill to the left of the page controls, the Escape key / the
297
+ * arrow keys / the close button / the outside click exit). A fresh open
298
+ * stands the contain's fit (the mount's fresh zoom state — the last
299
+ * session's zoom is not carried over). The page stands the explicit zoom
300
+ * when set, otherwise the contain's fit (the page's aspect ratio is
301
+ * preserved — the page fills the container's width or height). A zoomed
302
+ * page that overflows the container scrolls (the `m-auto` over the
303
+ * scroller centers the page when it fits and keeps the overflow scrollable
304
+ * when it does not). The overlay's open locks the body's scroll (a wheel
305
+ * over the fixed portal chains to the document's scroll container — the
306
+ * page behind must not scroll). */
307
+ function PdfFullscreenOverlay({ pdfDocRef, phase, currentPage, totalPages, prevPage, nextPage, onClose }) {
163
308
  const { t } = useTranslation("blocks");
164
309
  const canvasRef = useRef(null);
165
- const fullscreenCanvasRef = useRef(null);
166
- const fullscreenContainerRef = useRef(null);
167
- const loadingTaskRef = useRef(null);
168
- const pdfDocRef = useRef(null);
169
- const [phase, setPhase] = useState("loading");
170
- const [error, setError] = useState(null);
171
- const [currentPage, setCurrentPage] = useState(1);
172
- const [totalPages, setTotalPages] = useState(0);
173
- const [isFullscreen, setIsFullscreen] = useState(false);
174
- const [fullscreenZoom, setFullscreenZoom] = useState(null);
175
- const [fullscreenScale, setFullscreenScale] = useState(1);
176
- useEffect(() => {
177
- const controller = new AbortController();
178
- let cancelled = false;
179
- setPhase("loading");
180
- setError(null);
181
- setCurrentPage(1);
182
- setTotalPages(0);
183
- const run = async () => {
184
- try {
185
- const response = await fetch(url, { signal: controller.signal });
186
- if (cancelled) return;
187
- if (!response.ok) throw new Error(`Failed to fetch the PDF (HTTP ${response.status}).`);
188
- const data = new Uint8Array(await response.arrayBuffer());
189
- if (cancelled) return;
190
- const task = getDocument({
191
- data,
192
- wasmUrl: WASM_URL,
193
- useWorkerFetch: false,
194
- BinaryDataFactory: PdfBinaryDataFactory
195
- });
196
- loadingTaskRef.current = task;
197
- const pdf = await task.promise;
198
- if (cancelled) {
199
- loadingTaskRef.current = null;
200
- task.destroy().catch(() => void 0);
201
- return;
202
- }
203
- pdfDocRef.current = pdf;
204
- setTotalPages(pdf.numPages);
205
- setPhase("ready");
206
- } catch (cause) {
207
- if (cancelled || cause instanceof RenderingCancelledException || cause instanceof DOMException && cause.name === "AbortError") return;
208
- const message = cause instanceof Error ? cause.message : String(cause);
209
- setError(message);
210
- setPhase("error");
211
- }
212
- };
213
- run();
214
- return () => {
215
- cancelled = true;
216
- controller.abort();
217
- pdfDocRef.current = null;
218
- const task = loadingTaskRef.current;
219
- loadingTaskRef.current = null;
220
- if (task !== null) task.destroy().catch(() => void 0);
221
- };
222
- }, [url]);
310
+ const containerRef = useRef(null);
311
+ const { zoom, scale, setScale, zoomBy, fitWidth, fitHeight } = usePdfZoom(pdfDocRef, containerRef, currentPage);
312
+ const zoomOut = () => zoomBy(1 / ZOOM_STEP);
313
+ const zoomIn = () => zoomBy(ZOOM_STEP);
223
314
  useEffect(() => {
224
315
  if (phase !== "ready") return;
225
316
  const pdf = pdfDocRef.current;
226
317
  const canvas = canvasRef.current;
227
- if (pdf === null || canvas === null) return;
228
- let cancelled = false;
229
- let renderTask = null;
230
- const run = async () => {
231
- try {
232
- renderTask = await renderPageToCanvas(pdf, currentPage, canvas);
233
- await renderTask.promise;
234
- } catch (cause) {
235
- if (cancelled || cause instanceof RenderingCancelledException || cause instanceof DOMException && cause.name === "AbortError") return;
236
- }
237
- };
238
- run();
239
- return () => {
240
- cancelled = true;
241
- if (renderTask !== null) renderTask.cancel();
242
- };
243
- }, [
244
- url,
245
- currentPage,
246
- phase
247
- ]);
248
- useEffect(() => {
249
- if (!isFullscreen || phase !== "ready") return;
250
- const pdf = pdfDocRef.current;
251
- const canvas = fullscreenCanvasRef.current;
252
- const container = fullscreenContainerRef.current;
318
+ const container = containerRef.current;
253
319
  if (pdf === null || canvas === null || container === null) return;
254
320
  let cancelled = false;
255
321
  let renderToken = 0;
@@ -264,10 +330,10 @@ function PdfFirstPage({ id, blockType, url, name }) {
264
330
  if (cancelled || token !== renderToken) return;
265
331
  const pageViewport = page.getViewport({ scale: 1 });
266
332
  const fit = Math.min(width / pageViewport.width, height / pageViewport.height);
267
- const scale = fullscreenZoom ?? fit;
268
- setFullscreenScale(scale);
333
+ const effectiveScale = zoom ?? fit;
334
+ setScale(effectiveScale);
269
335
  const ratio = window.devicePixelRatio || 1;
270
- const viewport = page.getViewport({ scale: scale * ratio });
336
+ const viewport = page.getViewport({ scale: effectiveScale * ratio });
271
337
  const storeWidth = Math.max(1, Math.floor(viewport.width));
272
338
  const storeHeight = Math.max(1, Math.floor(viewport.height));
273
339
  if (renderedOnce && canvas.width === storeWidth && canvas.height === storeHeight) return;
@@ -302,62 +368,15 @@ function PdfFirstPage({ id, blockType, url, name }) {
302
368
  if (renderTask !== null) renderTask.cancel();
303
369
  };
304
370
  }, [
305
- isFullscreen,
371
+ pdfDocRef,
306
372
  currentPage,
307
373
  phase,
308
- fullscreenZoom
374
+ zoom
309
375
  ]);
310
- const prevPage = useCallback(() => {
311
- setCurrentPage((page) => Math.max(1, page - 1));
312
- }, []);
313
- const nextPage = useCallback(() => {
314
- setCurrentPage((page) => Math.min(totalPages, page + 1));
315
- }, [totalPages]);
316
- const zoomBy = useCallback((factor) => {
317
- const pdf = pdfDocRef.current;
318
- const container = fullscreenContainerRef.current;
319
- if (pdf === null || container === null) return;
320
- const width = container.clientWidth;
321
- const height = container.clientHeight;
322
- if (width === 0 || height === 0) return;
323
- pdf.getPage(currentPage).then((page) => {
324
- const pageViewport = page.getViewport({ scale: 1 });
325
- const fit = Math.min(width / pageViewport.width, height / pageViewport.height);
326
- setFullscreenZoom(clamp((fullscreenZoom ?? fit) * factor, ZOOM_MIN, ZOOM_MAX));
327
- });
328
- }, [currentPage, fullscreenZoom]);
329
- const fitWidth = useCallback(() => {
330
- const pdf = pdfDocRef.current;
331
- const container = fullscreenContainerRef.current;
332
- if (pdf === null || container === null) return;
333
- const width = container.clientWidth;
334
- if (width === 0) return;
335
- pdf.getPage(currentPage).then((page) => {
336
- const pageViewport = page.getViewport({ scale: 1 });
337
- setFullscreenZoom(clamp(width / pageViewport.width, ZOOM_MIN, ZOOM_MAX));
338
- });
339
- }, [currentPage]);
340
- const fitHeight = useCallback(() => {
341
- const pdf = pdfDocRef.current;
342
- const container = fullscreenContainerRef.current;
343
- if (pdf === null || container === null) return;
344
- const height = container.clientHeight;
345
- if (height === 0) return;
346
- pdf.getPage(currentPage).then((page) => {
347
- const pageViewport = page.getViewport({ scale: 1 });
348
- setFullscreenZoom(clamp(height / pageViewport.height, ZOOM_MIN, ZOOM_MAX));
349
- });
350
- }, [currentPage]);
351
- const openFullscreen = useCallback(() => {
352
- setFullscreenZoom(null);
353
- setFullscreenScale(1);
354
- setIsFullscreen(true);
355
- }, []);
356
376
  useEffect(() => {
357
- if (!isFullscreen) return;
358
377
  const onKeyDown = (event) => {
359
378
  if (event.key === "Escape") {
360
- setIsFullscreen(false);
379
+ onClose();
361
380
  return;
362
381
  }
363
382
  if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
@@ -370,19 +389,215 @@ function PdfFirstPage({ id, blockType, url, name }) {
370
389
  window.addEventListener("keydown", onKeyDown);
371
390
  return () => window.removeEventListener("keydown", onKeyDown);
372
391
  }, [
373
- isFullscreen,
392
+ onClose,
374
393
  prevPage,
375
394
  nextPage
376
395
  ]);
377
396
  useEffect(() => {
378
- if (!isFullscreen) return;
379
397
  const body = document.body;
380
398
  const previous = body.style.overflow;
381
399
  body.style.overflow = "hidden";
382
400
  return () => {
383
401
  body.style.overflow = previous;
384
402
  };
385
- }, [isFullscreen]);
403
+ }, []);
404
+ return createPortal(/* @__PURE__ */ jsxs("div", {
405
+ "data-slot": "docblocks/image-pdf-fullscreen-overlay",
406
+ className: "fixed inset-0 z-50 flex flex-col items-center justify-center gap-3 bg-(--background)",
407
+ role: "dialog",
408
+ "aria-modal": "true",
409
+ "aria-label": t("code.pdfFullscreen"),
410
+ onClick: (event) => {
411
+ const target = event.target;
412
+ if (target === null) return;
413
+ if (target.closest("[data-slot=\"docblocks/image-pdf-fullscreen-canvas\"]") !== null) return;
414
+ if (target.closest("[data-slot=\"docblocks/image-pdf-controls\"]") !== null) return;
415
+ if (target.closest("[data-slot=\"docblocks/image-pdf-zoom\"]") !== null) return;
416
+ onClose();
417
+ },
418
+ children: [
419
+ /* @__PURE__ */ jsx("button", {
420
+ type: "button",
421
+ "data-slot": "docblocks/image-pdf-fullscreen-close",
422
+ onClick: onClose,
423
+ "aria-label": t("code.pdfCloseFullscreen"),
424
+ className: "\n absolute top-4 right-4 flex size-8 items-center justify-center rounded-md text-(--foreground)\n transition-colors\n hover:bg-(--accent)\n ",
425
+ children: /* @__PURE__ */ jsx(X, { className: "size-5" })
426
+ }),
427
+ /* @__PURE__ */ jsx("div", {
428
+ ref: containerRef,
429
+ "data-slot": "docblocks/image-pdf-fullscreen-container",
430
+ className: "flex h-[calc(100vh-6rem)] w-[calc(100vw-4rem)] overflow-auto",
431
+ children: /* @__PURE__ */ jsx("canvas", {
432
+ ref: canvasRef,
433
+ "data-slot": "docblocks/image-pdf-fullscreen-canvas",
434
+ className: "m-auto border border-(--border) bg-(--background) shadow-lg"
435
+ })
436
+ }),
437
+ /* @__PURE__ */ jsxs("div", {
438
+ className: "flex items-center gap-2",
439
+ children: [/* @__PURE__ */ jsx(PdfZoomControls, {
440
+ scale,
441
+ onZoomOut: zoomOut,
442
+ onZoomIn: zoomIn,
443
+ onFitWidth: fitWidth,
444
+ onFitHeight: fitHeight
445
+ }), /* @__PURE__ */ jsx(PdfPageControls, {
446
+ portaled: true,
447
+ currentPage,
448
+ totalPages,
449
+ onPrevPage: prevPage,
450
+ onNextPage: nextPage,
451
+ actionSlot: "docblocks/image-pdf-minimize",
452
+ actionLabel: t("code.pdfCloseFullscreen"),
453
+ actionIcon: Minimize,
454
+ onAction: onClose
455
+ })]
456
+ })
457
+ ]
458
+ }), document.body);
459
+ }
460
+ //#endregion
461
+ //#region src/pdf/use-pdf-document.ts
462
+ /** The PDF document's load lifecycle: the resolved url's fetch + parse
463
+ * (pdfjs-dist), the page navigation's state, and the in-flight cleanup —
464
+ * the fetch is aborted on unmount / url change and the render task +
465
+ * document are released, so a torn-down preview leaves no network request
466
+ * or pdf.js worker behind. */
467
+ function usePdfDocument(url) {
468
+ const loadingTaskRef = useRef(null);
469
+ const pdfDocRef = useRef(null);
470
+ const [phase, setPhase] = useState("loading");
471
+ const [error, setError] = useState(null);
472
+ const [currentPage, setCurrentPage] = useState(1);
473
+ const [totalPages, setTotalPages] = useState(0);
474
+ useEffect(() => {
475
+ const controller = new AbortController();
476
+ let cancelled = false;
477
+ setPhase("loading");
478
+ setError(null);
479
+ setCurrentPage(1);
480
+ setTotalPages(0);
481
+ const run = async () => {
482
+ try {
483
+ const response = await fetch(url, { signal: controller.signal });
484
+ if (cancelled) return;
485
+ if (!response.ok) throw new PdfFetchError(`Failed to fetch the PDF (HTTP ${response.status}).`);
486
+ const data = new Uint8Array(await response.arrayBuffer());
487
+ if (cancelled) return;
488
+ const task = getDocument({
489
+ data,
490
+ wasmUrl: WASM_URL,
491
+ useWorkerFetch: false,
492
+ BinaryDataFactory: PdfBinaryDataFactory
493
+ });
494
+ loadingTaskRef.current = task;
495
+ const pdf = await task.promise;
496
+ if (cancelled) {
497
+ loadingTaskRef.current = null;
498
+ task.destroy().catch(() => void 0);
499
+ return;
500
+ }
501
+ pdfDocRef.current = pdf;
502
+ setTotalPages(pdf.numPages);
503
+ setPhase("ready");
504
+ } catch (cause) {
505
+ if (cancelled || cause instanceof RenderingCancelledException || cause instanceof DOMException && cause.name === "AbortError") return;
506
+ const message = cause instanceof Error ? cause.message : String(cause);
507
+ setError(message);
508
+ setPhase("error");
509
+ }
510
+ };
511
+ run();
512
+ return () => {
513
+ cancelled = true;
514
+ controller.abort();
515
+ pdfDocRef.current = null;
516
+ const task = loadingTaskRef.current;
517
+ loadingTaskRef.current = null;
518
+ if (task !== null) task.destroy().catch(() => void 0);
519
+ };
520
+ }, [url]);
521
+ return {
522
+ phase,
523
+ error,
524
+ currentPage,
525
+ totalPages,
526
+ prevPage: useCallback(() => {
527
+ setCurrentPage((page) => Math.max(1, page - 1));
528
+ }, []),
529
+ nextPage: useCallback(() => {
530
+ setCurrentPage((page) => Math.min(totalPages, page + 1));
531
+ }, [totalPages]),
532
+ pdfDocRef
533
+ };
534
+ }
535
+ //#endregion
536
+ //#region src/pdf/PdfFirstPage.tsx
537
+ /** The PDF preview of one file block: fetch the resolved blob, render the
538
+ * pages to a canvas via pdfjs-dist. The inline view stands the page over
539
+ * the page row + the page controls' bar under the canvas; the fullscreen
540
+ * mode opens the portal overlay (`PdfFullscreenOverlay` — the zoom bar,
541
+ * the page navigation, the Escape / arrow keys / the close / the outside
542
+ * click exit, the body's scroll lock). The page indicator's and the
543
+ * scale's numbers stand a fixed width (the digit count's change must not
544
+ * shift the buttons). The preview's chrome stands no text selection
545
+ * (`select-none`): the page indicator's and the controls' text is not
546
+ * document content, and a selection stood there would flag the block /
547
+ * pull the format toolbar over a non-text range. A failure stands the
548
+ * error note over the native iframe fallback (the document stays viewable).
549
+ */
550
+ /** Render one page to a canvas (the natural page size, the backing store
551
+ * scaled by the device pixel ratio for a crisp retina display). Returns the
552
+ * render task (the caller awaits its promise + cancels it on teardown).
553
+ * Does NOT await the promise itself, so the caller can cancel the in-flight
554
+ * render before it completes. */
555
+ function renderPageToCanvas(pdf, pageNumber, canvas) {
556
+ return pdf.getPage(pageNumber).then((page) => {
557
+ const ratio = window.devicePixelRatio || 1;
558
+ const viewport = page.getViewport({ scale: ratio });
559
+ canvas.width = Math.max(1, Math.floor(viewport.width));
560
+ canvas.height = Math.max(1, Math.floor(viewport.height));
561
+ canvas.style.width = `${Math.max(1, Math.floor(viewport.width / ratio))}px`;
562
+ canvas.style.height = `${Math.max(1, Math.floor(viewport.height / ratio))}px`;
563
+ return page.render({
564
+ canvas,
565
+ viewport
566
+ });
567
+ });
568
+ }
569
+ function PdfFirstPage({ id, blockType, url, name }) {
570
+ const { t } = useTranslation("blocks");
571
+ const canvasRef = useRef(null);
572
+ const { phase, error, currentPage, totalPages, prevPage, nextPage, pdfDocRef } = usePdfDocument(url);
573
+ const [isFullscreen, setIsFullscreen] = useState(false);
574
+ const openFullscreen = useCallback(() => setIsFullscreen(true), []);
575
+ const closeFullscreen = useCallback(() => setIsFullscreen(false), []);
576
+ useEffect(() => {
577
+ if (phase !== "ready") return;
578
+ const pdf = pdfDocRef.current;
579
+ const canvas = canvasRef.current;
580
+ if (pdf === null || canvas === null) return;
581
+ let cancelled = false;
582
+ let renderTask = null;
583
+ const run = async () => {
584
+ try {
585
+ renderTask = await renderPageToCanvas(pdf, currentPage, canvas);
586
+ await renderTask.promise;
587
+ } catch (cause) {
588
+ if (cancelled || cause instanceof RenderingCancelledException || cause instanceof DOMException && cause.name === "AbortError") return;
589
+ }
590
+ };
591
+ run();
592
+ return () => {
593
+ cancelled = true;
594
+ if (renderTask !== null) renderTask.cancel();
595
+ };
596
+ }, [
597
+ url,
598
+ currentPage,
599
+ phase
600
+ ]);
386
601
  if (phase === "error") return /* @__PURE__ */ jsxs("div", {
387
602
  "data-slot": "docblocks/image-pdf-preview",
388
603
  "data-block-id": id,
@@ -415,141 +630,6 @@ function PdfFirstPage({ id, blockType, url, name }) {
415
630
  children: name
416
631
  })]
417
632
  });
418
- const inlineControls = /* @__PURE__ */ jsxs("div", {
419
- "data-slot": "docblocks/image-pdf-controls",
420
- className: "\n flex items-center justify-center gap-1 rounded-(--docblocks-radius)\n border-(length:--docblocks-table-border-width) border-(--docblocks-table-border-color) bg-(--muted) px-2 py-1\n ",
421
- children: [
422
- /* @__PURE__ */ jsx("button", {
423
- type: "button",
424
- "data-slot": "docblocks/image-pdf-prev",
425
- onClick: prevPage,
426
- disabled: currentPage <= 1,
427
- "aria-label": t("code.pdfPrevPage"),
428
- className: "\n flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n disabled:pointer-events-none disabled:opacity-40\n ",
429
- children: /* @__PURE__ */ jsx(ChevronLeft, { className: "size-4" })
430
- }),
431
- /* @__PURE__ */ jsxs("span", {
432
- "data-slot": "docblocks/image-pdf-page-indicator",
433
- className: "px-1 text-xs text-(--muted-foreground) tabular-nums",
434
- children: [
435
- /* @__PURE__ */ jsx("span", {
436
- className: "inline-block text-right",
437
- style: { minWidth: `${Math.max(1, String(totalPages).length)}ch` },
438
- children: currentPage
439
- }),
440
- " / ",
441
- totalPages
442
- ]
443
- }),
444
- /* @__PURE__ */ jsx("button", {
445
- type: "button",
446
- "data-slot": "docblocks/image-pdf-next",
447
- onClick: nextPage,
448
- disabled: currentPage >= totalPages,
449
- "aria-label": t("code.pdfNextPage"),
450
- className: "\n flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n disabled:pointer-events-none disabled:opacity-40\n ",
451
- children: /* @__PURE__ */ jsx(ChevronRight, { className: "size-4" })
452
- }),
453
- /* @__PURE__ */ jsx("button", {
454
- type: "button",
455
- "data-slot": "docblocks/image-pdf-fullscreen",
456
- onClick: openFullscreen,
457
- "aria-label": t("code.pdfFullscreen"),
458
- className: "\n ml-1 flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n ",
459
- children: /* @__PURE__ */ jsx(Maximize, { className: "size-4" })
460
- })
461
- ]
462
- });
463
- const fullscreenControls = /* @__PURE__ */ jsxs("div", {
464
- "data-slot": "docblocks/image-pdf-controls",
465
- className: "\n flex items-center justify-center gap-1 rounded-(--radius) border border-(--border) bg-(--muted) px-2 py-1\n select-none\n ",
466
- children: [
467
- /* @__PURE__ */ jsx("button", {
468
- type: "button",
469
- "data-slot": "docblocks/image-pdf-prev",
470
- onClick: prevPage,
471
- disabled: currentPage <= 1,
472
- "aria-label": t("code.pdfPrevPage"),
473
- className: "\n flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n disabled:pointer-events-none disabled:opacity-40\n ",
474
- children: /* @__PURE__ */ jsx(ChevronLeft, { className: "size-4" })
475
- }),
476
- /* @__PURE__ */ jsxs("span", {
477
- "data-slot": "docblocks/image-pdf-page-indicator",
478
- className: "px-1 text-xs text-(--muted-foreground) tabular-nums",
479
- children: [
480
- /* @__PURE__ */ jsx("span", {
481
- className: "inline-block text-right",
482
- style: { minWidth: `${Math.max(1, String(totalPages).length)}ch` },
483
- children: currentPage
484
- }),
485
- " / ",
486
- totalPages
487
- ]
488
- }),
489
- /* @__PURE__ */ jsx("button", {
490
- type: "button",
491
- "data-slot": "docblocks/image-pdf-next",
492
- onClick: nextPage,
493
- disabled: currentPage >= totalPages,
494
- "aria-label": t("code.pdfNextPage"),
495
- className: "\n flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n disabled:pointer-events-none disabled:opacity-40\n ",
496
- children: /* @__PURE__ */ jsx(ChevronRight, { className: "size-4" })
497
- }),
498
- /* @__PURE__ */ jsx("button", {
499
- type: "button",
500
- "data-slot": "docblocks/image-pdf-minimize",
501
- onClick: () => setIsFullscreen(false),
502
- "aria-label": t("code.pdfCloseFullscreen"),
503
- className: "\n ml-1 flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n ",
504
- children: /* @__PURE__ */ jsx(Minimize, { className: "size-4" })
505
- })
506
- ]
507
- });
508
- const fullscreenZoomControls = /* @__PURE__ */ jsxs("div", {
509
- "data-slot": "docblocks/image-pdf-zoom",
510
- className: "\n flex items-center justify-center gap-1 rounded-(--radius) border border-(--border) bg-(--muted) px-2 py-1\n select-none\n ",
511
- children: [
512
- /* @__PURE__ */ jsx("button", {
513
- type: "button",
514
- "data-slot": "docblocks/image-pdf-zoom-out",
515
- onClick: () => zoomBy(1 / ZOOM_STEP),
516
- disabled: fullscreenScale <= .250000001,
517
- "aria-label": t("code.pdfZoomOut"),
518
- className: "\n flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n disabled:pointer-events-none disabled:opacity-40\n ",
519
- children: /* @__PURE__ */ jsx(Minus, { className: "size-4" })
520
- }),
521
- /* @__PURE__ */ jsxs("span", {
522
- "data-slot": "docblocks/image-pdf-zoom-indicator",
523
- className: "inline-block min-w-[4ch] px-1 text-right text-xs text-(--muted-foreground) tabular-nums",
524
- children: [Math.round(fullscreenScale * 100), "%"]
525
- }),
526
- /* @__PURE__ */ jsx("button", {
527
- type: "button",
528
- "data-slot": "docblocks/image-pdf-zoom-in",
529
- onClick: () => zoomBy(ZOOM_STEP),
530
- disabled: fullscreenScale >= 3.999999999,
531
- "aria-label": t("code.pdfZoomIn"),
532
- className: "\n flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n disabled:pointer-events-none disabled:opacity-40\n ",
533
- children: /* @__PURE__ */ jsx(Plus, { className: "size-4" })
534
- }),
535
- /* @__PURE__ */ jsx("button", {
536
- type: "button",
537
- "data-slot": "docblocks/image-pdf-fit-width",
538
- onClick: fitWidth,
539
- "aria-label": t("code.pdfFitWidth"),
540
- className: "\n flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n ",
541
- children: /* @__PURE__ */ jsx(StretchHorizontal, { className: "size-4" })
542
- }),
543
- /* @__PURE__ */ jsx("button", {
544
- type: "button",
545
- "data-slot": "docblocks/image-pdf-fit-height",
546
- onClick: fitHeight,
547
- "aria-label": t("code.pdfFitHeight"),
548
- className: "\n flex size-6 items-center justify-center rounded-sm text-(--muted-foreground) transition-colors\n hover:bg-(--accent) hover:text-(--accent-foreground)\n ",
549
- children: /* @__PURE__ */ jsx(StretchVertical, { className: "size-4" })
550
- })
551
- ]
552
- });
553
633
  return /* @__PURE__ */ jsxs("div", {
554
634
  "data-slot": "docblocks/image-pdf-preview",
555
635
  "data-block-id": id,
@@ -574,46 +654,25 @@ function PdfFirstPage({ id, blockType, url, name }) {
574
654
  })]
575
655
  })]
576
656
  }),
577
- phase === "ready" && inlineControls,
578
- isFullscreen && createPortal(/* @__PURE__ */ jsxs("div", {
579
- "data-slot": "docblocks/image-pdf-fullscreen-overlay",
580
- className: "fixed inset-0 z-50 flex flex-col items-center justify-center gap-3 bg-(--background)",
581
- role: "dialog",
582
- "aria-modal": "true",
583
- "aria-label": t("code.pdfFullscreen"),
584
- onClick: (event) => {
585
- const target = event.target;
586
- if (target === null) return;
587
- if (target.closest("[data-slot=\"docblocks/image-pdf-fullscreen-canvas\"]") !== null) return;
588
- if (target.closest("[data-slot=\"docblocks/image-pdf-controls\"]") !== null) return;
589
- if (target.closest("[data-slot=\"docblocks/image-pdf-zoom\"]") !== null) return;
590
- setIsFullscreen(false);
591
- },
592
- children: [
593
- /* @__PURE__ */ jsx("button", {
594
- type: "button",
595
- "data-slot": "docblocks/image-pdf-fullscreen-close",
596
- onClick: () => setIsFullscreen(false),
597
- "aria-label": t("code.pdfCloseFullscreen"),
598
- className: "\n absolute top-4 right-4 flex size-8 items-center justify-center rounded-md text-(--foreground)\n transition-colors\n hover:bg-(--accent)\n ",
599
- children: /* @__PURE__ */ jsx(X, { className: "size-5" })
600
- }),
601
- /* @__PURE__ */ jsx("div", {
602
- ref: fullscreenContainerRef,
603
- "data-slot": "docblocks/image-pdf-fullscreen-container",
604
- className: "flex h-[calc(100vh-6rem)] w-[calc(100vw-4rem)] overflow-auto",
605
- children: /* @__PURE__ */ jsx("canvas", {
606
- ref: fullscreenCanvasRef,
607
- "data-slot": "docblocks/image-pdf-fullscreen-canvas",
608
- className: "m-auto border border-(--border) bg-(--background) shadow-lg"
609
- })
610
- }),
611
- /* @__PURE__ */ jsxs("div", {
612
- className: "flex items-center gap-2",
613
- children: [fullscreenZoomControls, fullscreenControls]
614
- })
615
- ]
616
- }), document.body)
657
+ phase === "ready" && /* @__PURE__ */ jsx(PdfPageControls, {
658
+ currentPage,
659
+ totalPages,
660
+ onPrevPage: prevPage,
661
+ onNextPage: nextPage,
662
+ actionSlot: "docblocks/image-pdf-fullscreen",
663
+ actionLabel: t("code.pdfFullscreen"),
664
+ actionIcon: Maximize,
665
+ onAction: openFullscreen
666
+ }),
667
+ isFullscreen && /* @__PURE__ */ jsx(PdfFullscreenOverlay, {
668
+ pdfDocRef,
669
+ phase,
670
+ currentPage,
671
+ totalPages,
672
+ prevPage,
673
+ nextPage,
674
+ onClose: closeFullscreen
675
+ })
617
676
  ]
618
677
  });
619
678
  }