@ysgroup/ui 0.1.42 → 0.1.43

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.
@@ -0,0 +1,752 @@
1
+ <!-- YsPdfViewer —— PDF 阅读器(pdf.js 自绘,配色跟主题令牌)。
2
+ 工具条:缩略图侧栏、上一页/下一页/页码跳转、缩小/缩放档位(适合宽度、适合页面、百分比)/放大、旋转、夜间护眼、全屏;
3
+ 连续滚动,只渲染可见页附近的页面(离开视口释放画布),文字层可选中复制;Ctrl+滚轮缩放,+/- 键缩放。
4
+ 亮色:浅灰舞台 + 白纸柔和阴影;暗色:深色舞台 + 白纸略降亮度;夜间护眼:纸张反色成深灰底浅字。
5
+ pdf.js(约 150 KB gzip)和 worker 在第一次打开 PDF 时才加载,不进主包。 -->
6
+ <script setup lang="ts">
7
+ import { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch } from "vue";
8
+ import type { PDFDocumentLoadingTask, PDFDocumentProxy, PDFPageProxy, RenderTask } from "pdfjs-dist";
9
+ import YsViewerIcon from "./YsViewerIcon.vue";
10
+ import YsViewerState from "./YsViewerState.vue";
11
+ import "../preview/viewer.css";
12
+ import {
13
+ PDF_CSS_UNITS,
14
+ PDF_PAGE_GAP,
15
+ PDF_ZOOM_STEPS,
16
+ canvasOutputScale,
17
+ clampPage,
18
+ formatZoom,
19
+ normalizeRotation,
20
+ pageAtOffset,
21
+ pageOffsets,
22
+ parsePageInput,
23
+ resolveScale,
24
+ rotatedSize,
25
+ zoomIn as nextZoomIn,
26
+ zoomOut as nextZoomOut,
27
+ type PdfZoomMode,
28
+ } from "../preview/pdfLayout";
29
+
30
+ type PdfLib = typeof import("../preview/pdfjs");
31
+
32
+ const props = withDefaults(
33
+ defineProps<{
34
+ /** PDF 内容:Blob、ArrayBuffer 或字节。 */
35
+ source: Blob | ArrayBuffer | Uint8Array | null;
36
+ /** 初始缩放:page-width 适合宽度(默认)、page-fit 适合页面,或数字(1 = 100%)。 */
37
+ zoom?: PdfZoomMode;
38
+ /** 初始是否展开缩略图侧栏。 */
39
+ sidebar?: boolean;
40
+ /** 是否显示工具条上的全屏按钮(放在已有全屏按钮的弹窗里时可关掉)。 */
41
+ fullscreenButton?: boolean;
42
+ }>(),
43
+ { zoom: "page-width", sidebar: false, fullscreenButton: true },
44
+ );
45
+
46
+ const emit = defineEmits<{
47
+ loaded: [pages: number];
48
+ error: [message: string];
49
+ }>();
50
+
51
+ const root = ref<HTMLElement | null>(null);
52
+ const scroller = ref<HTMLElement | null>(null);
53
+ const thumbList = ref<HTMLElement | null>(null);
54
+ const status = ref<"loading" | "ready" | "error">("loading");
55
+ const errorText = ref("");
56
+ const numPages = ref(0);
57
+ /** 各页 1 倍、未加用户旋转时的尺寸(pdf 点)。先用第一页尺寸占位,渲染到哪页再更新。 */
58
+ const baseSizes = shallowRef<{ width: number; height: number }[]>([]);
59
+ const zoomMode = ref<PdfZoomMode>(props.zoom);
60
+ const rotation = ref(0);
61
+ const night = ref(false);
62
+ const showSidebar = ref(props.sidebar);
63
+ const current = ref(1);
64
+ const pageInput = ref("1");
65
+ const box = ref({ width: 0, height: 0 });
66
+ const isFullscreen = ref(false);
67
+
68
+ let lib: PdfLib | null = null;
69
+ let doc: PDFDocumentProxy | null = null;
70
+ let task: PDFDocumentLoadingTask | null = null;
71
+ let token = 0;
72
+ const pageEls = new Map<number, HTMLElement>();
73
+ const thumbEls = new Map<number, HTMLElement>();
74
+ type Painted = { key: string; task: RenderTask | null };
75
+ const painted = new Map<number, Painted>();
76
+ const thumbPainted = new Map<number, Painted>();
77
+ let pageObserver: IntersectionObserver | null = null;
78
+ let thumbObserver: IntersectionObserver | null = null;
79
+ let resizeObserver: ResizeObserver | null = null;
80
+ const visiblePages = new Set<number>();
81
+ const visibleThumbs = new Set<number>();
82
+ /** 缩放、旋转前记下当前页和页内位置,之后滚回同一处。 */
83
+ let anchor = { page: 1, fraction: 0 };
84
+
85
+ const scale = computed(() => {
86
+ const size = baseSizes.value[current.value - 1] ?? baseSizes.value[0];
87
+ return size ? resolveScale(zoomMode.value, size, box.value, rotation.value) : 1;
88
+ });
89
+ const renderKey = computed(() => `${scale.value.toFixed(4)}|${rotation.value}`);
90
+ const displaySizes = computed(() =>
91
+ baseSizes.value.map((size) => {
92
+ const r = rotatedSize(size, rotation.value);
93
+ return { width: Math.floor(r.width * scale.value * PDF_CSS_UNITS), height: Math.floor(r.height * scale.value * PDF_CSS_UNITS) };
94
+ }),
95
+ );
96
+ const offsets = computed(() => pageOffsets(displaySizes.value.map((s) => s.height)));
97
+ const zoomLabel = computed(() => formatZoom(scale.value));
98
+ const zoomOptions: { label: string; value: PdfZoomMode }[] = [
99
+ { label: "适合宽度", value: "page-width" },
100
+ { label: "适合页面", value: "page-fit" },
101
+ ...PDF_ZOOM_STEPS.filter((s) => s >= 0.5).map((s) => ({ label: formatZoom(s), value: s })),
102
+ ];
103
+ const THUMB_WIDTH = 112;
104
+
105
+ function thumbHeight(n: number): number {
106
+ const size = baseSizes.value[n - 1] ?? baseSizes.value[0];
107
+ if (!size) return 150;
108
+ const r = rotatedSize(size, rotation.value);
109
+ return Math.round((THUMB_WIDTH * r.height) / r.width);
110
+ }
111
+
112
+ // ---------- 打开文档 ----------
113
+ async function toBytes(source: Blob | ArrayBuffer | Uint8Array): Promise<Uint8Array> {
114
+ if (source instanceof Uint8Array) return source.slice();
115
+ if (source instanceof ArrayBuffer) return new Uint8Array(source.slice(0));
116
+ return new Uint8Array(await source.arrayBuffer());
117
+ }
118
+
119
+ function describe(reason: unknown): string {
120
+ const name = (reason as { name?: string } | null)?.name;
121
+ if (name === "PasswordException") return "PDF 已加密,暂不支持在线查看,请下载后用本地阅读器打开。";
122
+ if (name === "InvalidPDFException") return "文件不是有效的 PDF,或文件已损坏。";
123
+ if (reason instanceof Error && /dynamically imported module|Importing a module script failed|Loading chunk|Failed to fetch/i.test(reason.message)) return "PDF 阅读器加载失败,请检查网络后重试。";
124
+ return "PDF 打开失败,请下载后查看。";
125
+ }
126
+
127
+ async function open() {
128
+ const mine = ++token;
129
+ close();
130
+ status.value = "loading";
131
+ errorText.value = "";
132
+ numPages.value = 0;
133
+ baseSizes.value = [];
134
+ current.value = 1;
135
+ pageInput.value = "1";
136
+ rotation.value = 0;
137
+ zoomMode.value = props.zoom;
138
+ if (!props.source) return;
139
+ try {
140
+ const [loaded, bytes] = await Promise.all([lib ? Promise.resolve(lib) : import("../preview/pdfjs"), toBytes(props.source)]);
141
+ lib = loaded;
142
+ if (mine !== token) return;
143
+ const loading = lib.openPdf(bytes);
144
+ task = loading;
145
+ const pdf = await loading.promise;
146
+ // 期间换了文件时,新的 open() 已经 close() 掉这个任务。
147
+ if (mine !== token) return;
148
+ doc = pdf;
149
+ const first = await pdf.getPage(1);
150
+ if (mine !== token) return;
151
+ const viewport = first.getViewport({ scale: 1 });
152
+ baseSizes.value = Array.from({ length: pdf.numPages }, () => ({ width: viewport.width, height: viewport.height }));
153
+ numPages.value = pdf.numPages;
154
+ status.value = "ready";
155
+ emit("loaded", pdf.numPages);
156
+ await nextTick();
157
+ measure();
158
+ observePages();
159
+ } catch (reason) {
160
+ if (mine !== token) return;
161
+ status.value = "error";
162
+ errorText.value = describe(reason);
163
+ emit("error", errorText.value);
164
+ }
165
+ }
166
+
167
+ function close() {
168
+ for (const entry of painted.values()) entry.task?.cancel();
169
+ for (const entry of thumbPainted.values()) entry.task?.cancel();
170
+ painted.clear();
171
+ thumbPainted.clear();
172
+ visiblePages.clear();
173
+ visibleThumbs.clear();
174
+ pageObserver?.disconnect();
175
+ thumbObserver?.disconnect();
176
+ pageObserver = null;
177
+ thumbObserver = null;
178
+ const old = task;
179
+ task = null;
180
+ doc = null;
181
+ if (old) void old.destroy();
182
+ }
183
+
184
+ // ---------- 渲染 ----------
185
+ /** 页面、缩略图节点只在页数变化或侧栏展开时重建,这时重新收集并交给 IntersectionObserver。 */
186
+ function collect(container: HTMLElement | null, selector: string, map: Map<number, HTMLElement>) {
187
+ map.clear();
188
+ container?.querySelectorAll<HTMLElement>(selector).forEach((el) => map.set(Number(el.dataset.page), el));
189
+ }
190
+
191
+ function observePages() {
192
+ pageObserver?.disconnect();
193
+ if (!scroller.value) return;
194
+ collect(scroller.value, ".ys-pdf__page", pageEls);
195
+ pageObserver = new IntersectionObserver(
196
+ (entries) => {
197
+ for (const entry of entries) {
198
+ const n = Number((entry.target as HTMLElement).dataset.page);
199
+ if (entry.isIntersecting) {
200
+ visiblePages.add(n);
201
+ void paintPage(n);
202
+ } else {
203
+ visiblePages.delete(n);
204
+ release(n, painted, pageEls.get(n));
205
+ }
206
+ }
207
+ },
208
+ { root: scroller.value, rootMargin: "120% 0px" },
209
+ );
210
+ for (const el of pageEls.values()) pageObserver.observe(el);
211
+ if (showSidebar.value) observeThumbs();
212
+ }
213
+
214
+ function observeThumbs() {
215
+ thumbObserver?.disconnect();
216
+ if (!thumbList.value) return;
217
+ collect(thumbList.value, ".ys-pdf__thumb-paper", thumbEls);
218
+ thumbObserver = new IntersectionObserver(
219
+ (entries) => {
220
+ for (const entry of entries) {
221
+ const n = Number((entry.target as HTMLElement).dataset.page);
222
+ if (entry.isIntersecting) {
223
+ visibleThumbs.add(n);
224
+ void paintThumb(n);
225
+ } else {
226
+ visibleThumbs.delete(n);
227
+ release(n, thumbPainted, thumbEls.get(n));
228
+ }
229
+ }
230
+ },
231
+ { root: thumbList.value, rootMargin: "100% 0px" },
232
+ );
233
+ for (const el of thumbEls.values()) thumbObserver.observe(el);
234
+ }
235
+
236
+ function release(n: number, map: Map<number, Painted>, el: HTMLElement | undefined) {
237
+ map.get(n)?.task?.cancel();
238
+ map.delete(n);
239
+ if (!el) return;
240
+ el.querySelector("canvas")?.remove();
241
+ el.querySelector(".textLayer")?.remove();
242
+ el.classList.remove("is-painted");
243
+ }
244
+
245
+ /** 页面实际尺寸和占位不同时更新(同一文档各页大小可以不一样)。 */
246
+ function updateSize(n: number, page: PDFPageProxy) {
247
+ const viewport = page.getViewport({ scale: 1 });
248
+ const size = baseSizes.value[n - 1];
249
+ if (size && Math.abs(size.width - viewport.width) < 0.5 && Math.abs(size.height - viewport.height) < 0.5) return;
250
+ const next = baseSizes.value.slice();
251
+ next[n - 1] = { width: viewport.width, height: viewport.height };
252
+ baseSizes.value = next;
253
+ }
254
+
255
+ function isCancel(reason: unknown): boolean {
256
+ return (reason as { name?: string } | null)?.name === "RenderingCancelledException";
257
+ }
258
+
259
+ async function paintPage(n: number) {
260
+ const pdf = doc;
261
+ const pdfLib = lib;
262
+ if (!pdf || !pdfLib) return;
263
+ const key = renderKey.value;
264
+ const prev = painted.get(n);
265
+ if (prev?.key === key) return;
266
+ prev?.task?.cancel();
267
+ const entry: Painted = { key, task: null };
268
+ painted.set(n, entry);
269
+ try {
270
+ const page = await pdf.getPage(n);
271
+ if (painted.get(n) !== entry) return;
272
+ updateSize(n, page);
273
+ const el = pageEls.get(n);
274
+ if (!el) return;
275
+ const viewport = page.getViewport({
276
+ scale: scale.value * PDF_CSS_UNITS,
277
+ rotation: normalizeRotation(page.rotate + rotation.value),
278
+ });
279
+ entry.key = renderKey.value;
280
+ const out = canvasOutputScale(window.devicePixelRatio || 1, viewport.width, viewport.height);
281
+ const canvas = document.createElement("canvas");
282
+ canvas.className = "ys-pdf__canvas";
283
+ canvas.width = Math.max(1, Math.floor(viewport.width * out));
284
+ canvas.height = Math.max(1, Math.floor(viewport.height * out));
285
+ entry.task = page.render({ canvas, viewport, transform: out !== 1 ? [out, 0, 0, out, 0, 0] : undefined });
286
+ await entry.task.promise;
287
+ if (painted.get(n) !== entry) return;
288
+ // 新画布画好再替换旧的,缩放时不闪白。
289
+ el.querySelector("canvas")?.remove();
290
+ el.prepend(canvas);
291
+ el.classList.add("is-painted");
292
+ el.style.setProperty("--total-scale-factor", String(viewport.scale));
293
+ const layer = document.createElement("div");
294
+ layer.className = "textLayer";
295
+ const text = new pdfLib.pdfjs.TextLayer({ textContentSource: page.streamTextContent({ includeMarkedContent: true }), container: layer, viewport });
296
+ await text.render();
297
+ if (painted.get(n) !== entry) return;
298
+ el.querySelector(".textLayer")?.remove();
299
+ el.append(layer);
300
+ } catch (reason) {
301
+ if (!isCancel(reason) && painted.get(n) === entry) painted.delete(n);
302
+ }
303
+ }
304
+
305
+ async function paintThumb(n: number) {
306
+ const pdf = doc;
307
+ if (!pdf) return;
308
+ const key = String(rotation.value);
309
+ const prev = thumbPainted.get(n);
310
+ if (prev?.key === key) return;
311
+ prev?.task?.cancel();
312
+ const entry: Painted = { key, task: null };
313
+ thumbPainted.set(n, entry);
314
+ try {
315
+ const page = await pdf.getPage(n);
316
+ const el = thumbEls.get(n);
317
+ if (thumbPainted.get(n) !== entry || !el) return;
318
+ const base = page.getViewport({ scale: 1, rotation: normalizeRotation(page.rotate + rotation.value) });
319
+ const viewport = page.getViewport({ scale: THUMB_WIDTH / base.width, rotation: normalizeRotation(page.rotate + rotation.value) });
320
+ const out = Math.min(2, window.devicePixelRatio || 1);
321
+ const canvas = document.createElement("canvas");
322
+ canvas.width = Math.floor(viewport.width * out);
323
+ canvas.height = Math.floor(viewport.height * out);
324
+ entry.task = page.render({ canvas, viewport, transform: out !== 1 ? [out, 0, 0, out, 0, 0] : undefined });
325
+ await entry.task.promise;
326
+ if (thumbPainted.get(n) !== entry) return;
327
+ el.querySelector("canvas")?.remove();
328
+ el.prepend(canvas);
329
+ el.classList.add("is-painted");
330
+ } catch (reason) {
331
+ if (!isCancel(reason) && thumbPainted.get(n) === entry) thumbPainted.delete(n);
332
+ }
333
+ }
334
+
335
+ watch(renderKey, async () => {
336
+ const keep = { ...anchor };
337
+ await nextTick();
338
+ restore(keep);
339
+ for (const n of visiblePages) void paintPage(n);
340
+ });
341
+
342
+ watch(rotation, () => {
343
+ for (const n of visibleThumbs) void paintThumb(n);
344
+ });
345
+
346
+ watch(showSidebar, async (open) => {
347
+ await nextTick();
348
+ measure();
349
+ if (open) observeThumbs();
350
+ else {
351
+ thumbObserver?.disconnect();
352
+ thumbPainted.clear();
353
+ visibleThumbs.clear();
354
+ }
355
+ });
356
+
357
+ // ---------- 滚动、页码 ----------
358
+ function measure() {
359
+ const el = scroller.value;
360
+ if (!el) return;
361
+ box.value = { width: el.clientWidth, height: el.clientHeight };
362
+ }
363
+
364
+ function onScroll() {
365
+ const el = scroller.value;
366
+ if (!el || !numPages.value) return;
367
+ const page = pageAtOffset(offsets.value, el.scrollTop, el.clientHeight);
368
+ const top = offsets.value[page - 1] ?? 0;
369
+ const height = displaySizes.value[page - 1]?.height || 1;
370
+ anchor = { page, fraction: Math.min(1, Math.max(0, (el.scrollTop - top) / height)) };
371
+ if (page !== current.value) {
372
+ current.value = page;
373
+ pageInput.value = String(page);
374
+ scrollThumbIntoView(page);
375
+ }
376
+ }
377
+
378
+ function restore(keep: { page: number; fraction: number }) {
379
+ const el = scroller.value;
380
+ if (!el) return;
381
+ const top = offsets.value[keep.page - 1] ?? 0;
382
+ const height = displaySizes.value[keep.page - 1]?.height ?? 0;
383
+ el.scrollTop = top + keep.fraction * height;
384
+ el.scrollLeft = (el.scrollWidth - el.clientWidth) / 2;
385
+ }
386
+
387
+ function goTo(page: number) {
388
+ const target = clampPage(page, numPages.value);
389
+ const el = scroller.value;
390
+ current.value = target;
391
+ pageInput.value = String(target);
392
+ if (el) el.scrollTop = (offsets.value[target - 1] ?? 0) - PDF_PAGE_GAP / 2;
393
+ scrollThumbIntoView(target);
394
+ }
395
+
396
+ function scrollThumbIntoView(page: number) {
397
+ if (!showSidebar.value) return;
398
+ thumbEls.get(page)?.parentElement?.scrollIntoView({ block: "nearest" });
399
+ }
400
+
401
+ function commitPageInput() {
402
+ const page = parsePageInput(pageInput.value, numPages.value);
403
+ if (page === null) pageInput.value = String(current.value);
404
+ else goTo(page);
405
+ }
406
+
407
+ // ---------- 缩放、旋转、全屏 ----------
408
+ function setZoom(mode: PdfZoomMode) {
409
+ zoomMode.value = mode;
410
+ }
411
+
412
+ function zoomStep(direction: 1 | -1) {
413
+ setZoom(direction > 0 ? nextZoomIn(scale.value) : nextZoomOut(scale.value));
414
+ }
415
+
416
+ function rotate() {
417
+ rotation.value = normalizeRotation(rotation.value + 90);
418
+ }
419
+
420
+ function onWheel(event: WheelEvent) {
421
+ if (!event.ctrlKey && !event.metaKey) return;
422
+ event.preventDefault();
423
+ zoomStep(event.deltaY < 0 ? 1 : -1);
424
+ }
425
+
426
+ function onKeydown(event: KeyboardEvent) {
427
+ const target = event.target as HTMLElement | null;
428
+ if (target?.closest("input, textarea")) return;
429
+ if (event.ctrlKey || event.metaKey || event.altKey) return;
430
+ if (event.key === "+" || event.key === "=") zoomStep(1);
431
+ else if (event.key === "-" || event.key === "_") zoomStep(-1);
432
+ else return;
433
+ event.preventDefault();
434
+ }
435
+
436
+ async function toggleFullscreen() {
437
+ if (document.fullscreenElement) await document.exitFullscreen().catch(() => undefined);
438
+ else await root.value?.requestFullscreen?.().catch(() => undefined);
439
+ }
440
+
441
+ function onFullscreenChange() {
442
+ isFullscreen.value = document.fullscreenElement === root.value;
443
+ }
444
+
445
+ onMounted(() => {
446
+ resizeObserver = new ResizeObserver(() => measure());
447
+ if (scroller.value) resizeObserver.observe(scroller.value);
448
+ document.addEventListener("fullscreenchange", onFullscreenChange);
449
+ });
450
+
451
+ watch(scroller, (el, old) => {
452
+ if (old) resizeObserver?.unobserve(old);
453
+ if (el) {
454
+ resizeObserver?.observe(el);
455
+ measure();
456
+ }
457
+ });
458
+
459
+ watch(() => props.source, () => void open(), { immediate: true });
460
+
461
+ onBeforeUnmount(() => {
462
+ token += 1;
463
+ close();
464
+ resizeObserver?.disconnect();
465
+ document.removeEventListener("fullscreenchange", onFullscreenChange);
466
+ });
467
+
468
+ defineExpose({ goTo, setZoom });
469
+ </script>
470
+
471
+ <template>
472
+ <div ref="root" class="ys-viewer ys-pdf" :class="{ 'is-night': night }" tabindex="-1" @keydown="onKeydown">
473
+ <div v-if="status === 'ready'" class="ys-viewer__bar" role="toolbar" aria-label="PDF 工具条">
474
+ <button type="button" class="ys-viewer__btn ys-viewer__wide-only" :class="{ 'is-active': showSidebar }" :aria-pressed="showSidebar" title="缩略图" aria-label="缩略图" @click="showSidebar = !showSidebar">
475
+ <YsViewerIcon name="sidebar" />
476
+ </button>
477
+ <span class="ys-viewer__sep ys-viewer__wide-only" />
478
+ <button type="button" class="ys-viewer__btn" :disabled="current <= 1" title="上一页" aria-label="上一页" @click="goTo(current - 1)">
479
+ <YsViewerIcon name="chevron-left" />
480
+ </button>
481
+ <span class="ys-viewer__pager">
482
+ <input v-model="pageInput" class="ys-viewer__input" inputmode="numeric" aria-label="页码" @keydown.enter="commitPageInput" @blur="commitPageInput" @focus="($event.target as HTMLInputElement).select()" />
483
+ <span>/ {{ numPages }}</span>
484
+ </span>
485
+ <button type="button" class="ys-viewer__btn" :disabled="current >= numPages" title="下一页" aria-label="下一页" @click="goTo(current + 1)">
486
+ <YsViewerIcon name="chevron-right" />
487
+ </button>
488
+ <span class="ys-viewer__spacer" />
489
+ <button type="button" class="ys-viewer__btn" title="缩小(-)" aria-label="缩小" @click="zoomStep(-1)"><YsViewerIcon name="minus" /></button>
490
+ <el-dropdown trigger="click" placement="bottom" popper-class="ys-viewer-menu" @command="setZoom">
491
+ <button type="button" class="ys-viewer__btn ys-pdf__zoom" aria-label="缩放比例">{{ zoomLabel }}</button>
492
+ <template #dropdown>
493
+ <el-dropdown-menu>
494
+ <el-dropdown-item v-for="item in zoomOptions" :key="String(item.value)" :command="item.value" :class="{ 'is-current': zoomMode === item.value }" :divided="item.value === 0.5">
495
+ {{ item.label }}
496
+ </el-dropdown-item>
497
+ </el-dropdown-menu>
498
+ </template>
499
+ </el-dropdown>
500
+ <button type="button" class="ys-viewer__btn" title="放大(+)" aria-label="放大" @click="zoomStep(1)"><YsViewerIcon name="plus" /></button>
501
+ <button type="button" class="ys-viewer__btn ys-viewer__wide-only" :class="{ 'is-active': zoomMode === 'page-width' }" title="适合宽度" aria-label="适合宽度" @click="setZoom('page-width')">
502
+ <YsViewerIcon name="fit-width" />
503
+ </button>
504
+ <span class="ys-viewer__sep" />
505
+ <button type="button" class="ys-viewer__btn ys-viewer__wide-only" title="顺时针旋转" aria-label="顺时针旋转" @click="rotate"><YsViewerIcon name="rotate" /></button>
506
+ <button type="button" class="ys-viewer__btn" :class="{ 'is-active': night }" :aria-pressed="night" title="夜间护眼" aria-label="夜间护眼" @click="night = !night">
507
+ <YsViewerIcon name="moon" />
508
+ </button>
509
+ <button v-if="fullscreenButton" type="button" class="ys-viewer__btn" :title="isFullscreen ? '退出全屏' : '全屏'" :aria-label="isFullscreen ? '退出全屏' : '全屏'" @click="toggleFullscreen">
510
+ <YsViewerIcon :name="isFullscreen ? 'minimize' : 'maximize'" />
511
+ </button>
512
+ <slot name="toolbar" />
513
+ </div>
514
+
515
+ <YsViewerState v-if="status === 'loading'" title="正在打开 PDF…" />
516
+ <YsViewerState v-else-if="status === 'error'" type="error" title="无法显示此 PDF" :detail="errorText">
517
+ <template v-if="$slots['error-actions']" #actions><slot name="error-actions" /></template>
518
+ </YsViewerState>
519
+
520
+ <div v-show="status === 'ready'" class="ys-pdf__body">
521
+ <aside v-if="showSidebar" ref="thumbList" class="ys-pdf__thumbs" aria-label="缩略图">
522
+ <button v-for="n in numPages" :key="n" type="button" class="ys-pdf__thumb" :class="{ 'is-current': n === current }" :aria-label="`第 ${n} 页`" :aria-current="n === current ? 'page' : undefined" @click="goTo(n)">
523
+ <span class="ys-pdf__thumb-paper" :data-page="n" :style="{ width: `${THUMB_WIDTH}px`, height: `${thumbHeight(n)}px` }" />
524
+ <span class="ys-pdf__thumb-no">{{ n }}</span>
525
+ </button>
526
+ </aside>
527
+ <div ref="scroller" class="ys-pdf__scroller" tabindex="0" aria-label="PDF 页面" @scroll.passive="onScroll" @wheel="onWheel">
528
+ <div class="ys-pdf__pages" :style="{ padding: `${PDF_PAGE_GAP}px`, gap: `${PDF_PAGE_GAP}px` }">
529
+ <div
530
+ v-for="n in numPages"
531
+ :key="n"
532
+ class="ys-pdf__page"
533
+ :data-page="n"
534
+ :style="{ width: `${displaySizes[n - 1]?.width ?? 0}px`, height: `${displaySizes[n - 1]?.height ?? 0}px` }"
535
+ />
536
+ </div>
537
+ </div>
538
+ </div>
539
+ </div>
540
+ </template>
541
+
542
+ <style scoped>
543
+ .ys-pdf__body {
544
+ display: flex;
545
+ flex: 1;
546
+ min-height: 0;
547
+ }
548
+ .ys-pdf__scroller {
549
+ position: relative;
550
+ flex: 1;
551
+ min-width: 0;
552
+ overflow: auto;
553
+ overscroll-behavior: contain;
554
+ }
555
+ .ys-pdf__scroller:focus {
556
+ outline: none;
557
+ }
558
+ .ys-pdf__pages {
559
+ display: flex;
560
+ flex-direction: column;
561
+ align-items: center;
562
+ box-sizing: border-box;
563
+ width: max-content;
564
+ min-width: 100%;
565
+ }
566
+ .ys-pdf__page {
567
+ position: relative;
568
+ flex: none;
569
+ overflow: hidden;
570
+ background: var(--ys-color-paper);
571
+ box-shadow: var(--ys-shadow-paper);
572
+ filter: var(--ys-paper-filter);
573
+ --scale-round-x: 1px;
574
+ --scale-round-y: 1px;
575
+ }
576
+ /* 还没画好的页:纸面上一层很淡的流光,提示正在渲染。 */
577
+ .ys-pdf__page:not(.is-painted)::after {
578
+ position: absolute;
579
+ inset: 0;
580
+ background: linear-gradient(100deg, transparent 30%, color-mix(in srgb, var(--ys-color-text-3) 10%, transparent) 50%, transparent 70%);
581
+ background-size: 200% 100%;
582
+ animation: ys-pdf-shimmer 1.4s ease-in-out infinite;
583
+ content: "";
584
+ }
585
+ @keyframes ys-pdf-shimmer {
586
+ from {
587
+ background-position: 150% 0;
588
+ }
589
+ to {
590
+ background-position: -50% 0;
591
+ }
592
+ }
593
+ .ys-pdf__page :deep(.ys-pdf__canvas) {
594
+ position: absolute;
595
+ inset: 0;
596
+ display: block;
597
+ width: 100%;
598
+ height: 100%;
599
+ }
600
+ .ys-pdf.is-night .ys-pdf__page {
601
+ background: var(--ys-color-paper-night);
602
+ filter: none;
603
+ }
604
+ .ys-pdf.is-night .ys-pdf__page :deep(canvas) {
605
+ filter: var(--ys-paper-filter-night);
606
+ }
607
+ .ys-pdf__zoom {
608
+ min-width: 52px;
609
+ font-weight: 600;
610
+ }
611
+
612
+ /* 缩略图侧栏 */
613
+ .ys-pdf__thumbs {
614
+ display: flex;
615
+ flex: none;
616
+ flex-direction: column;
617
+ align-items: center;
618
+ gap: 4px;
619
+ width: 152px;
620
+ padding: 12px 0;
621
+ overflow-y: auto;
622
+ border-right: 1px solid var(--ys-color-border);
623
+ background: color-mix(in srgb, var(--ys-color-bg-elevated) 70%, var(--ys-color-stage));
624
+ scrollbar-width: thin;
625
+ }
626
+ .ys-pdf__thumb {
627
+ display: flex;
628
+ flex-direction: column;
629
+ align-items: center;
630
+ gap: 4px;
631
+ padding: 6px;
632
+ border: 0;
633
+ border-radius: var(--ys-radius-m);
634
+ background: transparent;
635
+ color: var(--ys-color-text-3);
636
+ font: inherit;
637
+ font-size: 11px;
638
+ font-variant-numeric: tabular-nums;
639
+ cursor: pointer;
640
+ }
641
+ .ys-pdf__thumb:hover {
642
+ background: var(--ys-color-bg-hover);
643
+ }
644
+ .ys-pdf__thumb:focus {
645
+ outline: none;
646
+ }
647
+ .ys-pdf__thumb:focus-visible {
648
+ outline: 2px solid color-mix(in srgb, var(--ys-color-primary) 55%, transparent);
649
+ }
650
+ .ys-pdf__thumb-paper {
651
+ position: relative;
652
+ display: block;
653
+ overflow: hidden;
654
+ border-radius: 2px;
655
+ background: var(--ys-color-paper);
656
+ box-shadow: 0 0 0 1px var(--ys-color-border);
657
+ filter: var(--ys-paper-filter);
658
+ }
659
+ .ys-pdf__thumb-paper :deep(canvas) {
660
+ display: block;
661
+ width: 100%;
662
+ height: 100%;
663
+ }
664
+ .ys-pdf__thumb.is-current {
665
+ color: var(--ys-color-primary);
666
+ font-weight: 600;
667
+ }
668
+ .ys-pdf__thumb.is-current .ys-pdf__thumb-paper {
669
+ box-shadow: 0 0 0 2px var(--ys-color-primary);
670
+ }
671
+ .ys-pdf.is-night .ys-pdf__thumb-paper {
672
+ background: var(--ys-color-paper-night);
673
+ filter: none;
674
+ }
675
+ .ys-pdf.is-night .ys-pdf__thumb-paper :deep(canvas) {
676
+ filter: var(--ys-paper-filter-night);
677
+ }
678
+ </style>
679
+
680
+ <style>
681
+ /* pdf.js 文字层(透明文字叠在画布上,可选中复制)。规则取自 pdfjs-dist 6.5 web/pdf_viewer.css 的 .textLayer 部分,
682
+ 只留阅读需要的;不能 scoped(节点由 pdf.js 生成)。 */
683
+ .ys-pdf .textLayer {
684
+ position: absolute;
685
+ inset: 0;
686
+ z-index: 0;
687
+ overflow: clip;
688
+ line-height: 1;
689
+ text-align: initial;
690
+ letter-spacing: normal;
691
+ word-spacing: normal;
692
+ opacity: 1;
693
+ text-size-adjust: none;
694
+ forced-color-adjust: none;
695
+ transform-origin: 0 0;
696
+ caret-color: CanvasText;
697
+ --min-font-size: 1;
698
+ --text-scale-factor: calc(var(--total-scale-factor) * var(--min-font-size));
699
+ --min-font-size-inv: calc(1 / var(--min-font-size));
700
+ }
701
+ .ys-pdf .textLayer :is(span, br) {
702
+ position: absolute;
703
+ color: transparent;
704
+ white-space: pre;
705
+ cursor: text;
706
+ transform-origin: 0% 0%;
707
+ user-select: text;
708
+ }
709
+ .ys-pdf .textLayer > :not(.markedContent),
710
+ .ys-pdf .textLayer .markedContent span:not(.markedContent) {
711
+ z-index: 1;
712
+ --font-height: 0;
713
+ font-size: calc(var(--text-scale-factor) * var(--font-height));
714
+ --scale-x: 1;
715
+ --rotate: 0deg;
716
+ transform: rotate(var(--rotate)) scaleX(var(--scale-x)) scale(var(--min-font-size-inv));
717
+ }
718
+ .ys-pdf .textLayer .markedContent {
719
+ display: contents;
720
+ }
721
+ .ys-pdf .textLayer span[role="img"] {
722
+ cursor: default;
723
+ user-select: none;
724
+ }
725
+ .ys-pdf .textLayer ::selection {
726
+ background: color-mix(in srgb, var(--ys-color-primary) 30%, transparent);
727
+ color: transparent;
728
+ }
729
+ .ys-pdf .textLayer br::selection {
730
+ background: transparent;
731
+ }
732
+ .ys-pdf .textLayer .endOfContent {
733
+ position: absolute;
734
+ inset: 100% 0 0;
735
+ z-index: 0;
736
+ display: block;
737
+ cursor: default;
738
+ user-select: none;
739
+ }
740
+ .ys-pdf .textLayer.selecting .endOfContent {
741
+ top: 0;
742
+ }
743
+ .ys-pdf .textLayer[data-main-rotation="90"] {
744
+ transform: rotate(90deg) translateY(-100%);
745
+ }
746
+ .ys-pdf .textLayer[data-main-rotation="180"] {
747
+ transform: rotate(180deg) translate(-100%, -100%);
748
+ }
749
+ .ys-pdf .textLayer[data-main-rotation="270"] {
750
+ transform: rotate(270deg) translateX(-100%);
751
+ }
752
+ </style>