@eternalheart/vue-file-preview 1.6.8 → 1.6.10

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 (45) hide show
  1. package/README.md +896 -896
  2. package/README.zh-CN.md +896 -896
  3. package/lib/chunks/index-B6pWnG9T.mjs +155 -0
  4. package/lib/chunks/index-BFGzHt2W.mjs +383 -0
  5. package/lib/chunks/index-BmOdi03q.mjs +104 -0
  6. package/lib/chunks/{index-D6tN6EZR.mjs → index-C-dh-RAc.mjs} +1 -1
  7. package/lib/chunks/{index-DbQYYr9C.mjs → index-CDPBjkt1.mjs} +32 -31
  8. package/lib/chunks/{index-DL3r7NGE.mjs → index-COB3-Z9z.mjs} +2800 -2797
  9. package/lib/chunks/{index-CodGY6nz.mjs → index-CcOy8dzx.mjs} +174 -171
  10. package/lib/chunks/{index-Hj5oboUU.mjs → index-CyaXSkiB.mjs} +1661 -1620
  11. package/lib/chunks/{index-CRTvjRyt.mjs → index-D4tZu2Iu.mjs} +519 -516
  12. package/lib/chunks/{index-bgq5MUC6.mjs → index-DPjcZwes.mjs} +105 -102
  13. package/lib/chunks/index-DVl5veaL.mjs +52 -0
  14. package/lib/chunks/{index-C3isZ_ue.mjs → index-DeHwj_uO.mjs} +71 -68
  15. package/lib/chunks/index-Dxi2kH8a.mjs +118 -0
  16. package/lib/chunks/{index-D18co0be.mjs → index-Rzntf5Ve.mjs} +110 -97
  17. package/lib/chunks/index-XauBLKhq.mjs +295 -0
  18. package/lib/chunks/index-ZhDIQCCX.mjs +356 -0
  19. package/lib/chunks/{index-CG01fzip.mjs → index-d5Fma0eH.mjs} +38 -38
  20. package/lib/chunks/index-ijSZ9bx4.mjs +133 -0
  21. package/lib/chunks/index-ka1HxWR8.mjs +90 -0
  22. package/lib/chunks/index-nOiM5Slr.mjs +51 -0
  23. package/lib/chunks/index-qn0a-KU_.mjs +113 -0
  24. package/lib/chunks/index-uRooADVC.mjs +108 -0
  25. package/lib/chunks/{useShikiHighlight-xcK26Bn3.mjs → useShikiHighlight-D2ozB5dP.mjs} +5 -5
  26. package/lib/composables/useThemeMode.d.ts +3 -0
  27. package/lib/index.cjs +65 -61
  28. package/lib/index.css +1 -1
  29. package/lib/index.mjs +8 -8
  30. package/lib/renderers/Cad/index.vue.d.ts +1 -0
  31. package/lib/renderers/Video/index.vue.d.ts +1 -0
  32. package/lib/renderers/base.types.d.ts +1 -2
  33. package/package.json +115 -115
  34. package/lib/chunks/index-B1OYfn_2.mjs +0 -378
  35. package/lib/chunks/index-BJpiAJuf.mjs +0 -87
  36. package/lib/chunks/index-BgtFv2mf.mjs +0 -116
  37. package/lib/chunks/index-CJYCIk06.mjs +0 -49
  38. package/lib/chunks/index-CVN9K0qA.mjs +0 -105
  39. package/lib/chunks/index-D4O2OC-3.mjs +0 -270
  40. package/lib/chunks/index-D5JP7cnv.mjs +0 -110
  41. package/lib/chunks/index-DJAZU94G.mjs +0 -104
  42. package/lib/chunks/index-DYI-zHxA.mjs +0 -152
  43. package/lib/chunks/index-TlmEk0Wz.mjs +0 -48
  44. package/lib/chunks/index-XEPcqTt4.mjs +0 -115
  45. package/lib/chunks/index-Z3_lfqRQ.mjs +0 -348
package/README.md CHANGED
@@ -1,896 +1,896 @@
1
- # Vue File Preview [![npm version](https://img.shields.io/npm/v/@eternalheart/vue-file-preview.svg)](https://www.npmjs.com/package/@eternalheart/vue-file-preview)[![license](https://img.shields.io/npm/l/@eternalheart/vue-file-preview.svg)](https://github.com/wh131462/file-preview/blob/master/LICENSE)[![downloads](https://img.shields.io/npm/dm/@eternalheart/vue-file-preview.svg)](https://www.npmjs.com/package/@eternalheart/vue-file-preview)
2
-
3
- English | [简体中文](./README.zh-CN.md)
4
-
5
- A modern, feature-rich file preview component for Vue 3 with support for images, videos, audio, PDFs, Office documents (Word, Excel, PowerPoint), Markdown, and code files.
6
-
7
- ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/2728.svg" width="20" height="20" alt="✨" /> Features
8
-
9
- - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f3a8.svg" width="16" height="16" alt="🎨" style="vertical-align: middle;" /> **Modern UI** - Clean and modern interface with smooth animations
10
- - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4c1.svg" width="16" height="16" alt="📁" style="vertical-align: middle;" /> **Multi-format Support** - Supports 20+ file formats
11
- - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1fa9f.svg" width="16" height="16" alt="🪟" style="vertical-align: middle;" /> **Two Display Modes** - Full-screen modal **or** inline embedded preview
12
- - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f5bc.svg" width="16" height="16" alt="🖼️" style="vertical-align: middle;" /> **Powerful Image Viewer** - Zoom, rotate, drag, mouse wheel zoom
13
- - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f3ac.svg" width="16" height="16" alt="🎬" style="vertical-align: middle;" /> **Custom Video Player** - Built on Video.js, supports multiple video formats
14
- - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f3b5.svg" width="16" height="16" alt="🎵" style="vertical-align: middle;" /> **Custom Audio Player** - Beautiful audio control interface
15
- - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4c4.svg" width="16" height="16" alt="📄" style="vertical-align: middle;" /> **PDF Viewer** - Pagination support
16
- - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4ca.svg" width="16" height="16" alt="📊" style="vertical-align: middle;" /> **Office Documents Support** - Word, Excel, PowerPoint file preview
17
- - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4dd.svg" width="16" height="16" alt="📝" style="vertical-align: middle;" /> **Markdown Rendering** - GitHub Flavored Markdown support
18
- - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4bb.svg" width="16" height="16" alt="💻" style="vertical-align: middle;" /> **Code Highlighting** - Supports 40+ programming languages
19
- - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4f1.svg" width="16" height="16" alt="📱" style="vertical-align: middle;" /> **Responsive Design** - Adapts to all screen sizes
20
- - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/2328.svg" width="16" height="16" alt="⌨️" style="vertical-align: middle;" /> **Keyboard Navigation** - Arrow, Home, End, and ESC key support
21
-
22
- ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4e6.svg" width="20" height="20" alt="📦" /> Installation
23
-
24
- ```bash
25
- # Using npm
26
- npm install @eternalheart/vue-file-preview
27
-
28
- # Using yarn
29
- yarn add @eternalheart/vue-file-preview
30
-
31
- # Using pnpm
32
- pnpm add @eternalheart/vue-file-preview
33
- ```
34
-
35
- **Important:** You also need to import the CSS file:
36
-
37
- ```ts
38
- import '@eternalheart/vue-file-preview/style.css';
39
- ```
40
-
41
- > **Note:** The `pdfjs-dist` dependency will be automatically installed for PDF preview support. No additional installation is required.
42
-
43
- ### PDF.js Configuration (Optional)
44
-
45
- If you need to preview PDF files, it's recommended to configure PDF.js to use local static files for better performance and stability:
46
-
47
- #### Method 1: Use CDN (Default)
48
-
49
- By default, the component automatically uses unpkg CDN to load PDF.js, no additional configuration needed.
50
-
51
- #### Method 2: Use Local Static Files (Recommended for Production)
52
-
53
- 1. Copy PDF.js files to your public directory:
54
-
55
- ```bash
56
- cp -r node_modules/pdfjs-dist/legacy/build/pdf.worker.min.mjs public/pdfjs/
57
- cp -r node_modules/pdfjs-dist/cmaps public/pdfjs/
58
- cp -r node_modules/pdfjs-dist/standard_fonts public/pdfjs/
59
- cp -r node_modules/pdfjs-dist/wasm public/pdfjs/
60
- ```
61
-
62
- 2. Configure PDF.js in your app entry:
63
-
64
- ```ts
65
- import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf.mjs';
66
- import { configurePdfWorker } from '@eternalheart/vue-file-preview';
67
-
68
- configurePdfWorker(pdfjsLib, {
69
- workerSrc: '/pdfjs/pdf.worker.min.mjs',
70
- cMapUrl: '/pdfjs/cmaps/',
71
- cMapPacked: true,
72
- standardFontDataUrl: '/pdfjs/standard_fonts/',
73
- wasmUrl: '/pdfjs/wasm/',
74
- });
75
- ```
76
-
77
- Call this during client application initialization, before the first PDF render. The worker must use the legacy build matching the installed `pdfjs-dist` version.
78
-
79
- #### Auto-copy with Vite (Recommended)
80
-
81
- Configure auto-copy in `vite.config.ts`:
82
-
83
- ```ts
84
- import { defineConfig } from 'vite';
85
- import { viteStaticCopy } from 'vite-plugin-static-copy';
86
-
87
- export default defineConfig({
88
- plugins: [
89
- viteStaticCopy({
90
- targets: [
91
- {
92
- src: 'node_modules/pdfjs-dist/legacy/build/pdf.worker.min.mjs',
93
- dest: 'pdfjs'
94
- },
95
- {
96
- src: 'node_modules/pdfjs-dist/cmaps',
97
- dest: 'pdfjs'
98
- },
99
- {
100
- src: 'node_modules/pdfjs-dist/standard_fonts',
101
- dest: 'pdfjs'
102
- },
103
- {
104
- src: 'node_modules/pdfjs-dist/wasm',
105
- dest: 'pdfjs'
106
- }
107
- ]
108
- })
109
- ]
110
- });
111
- ```
112
-
113
- ### Vite Bundler Note (AVIF Decoder)
114
-
115
- If your project bundler is Vite and you happen to have `@jsquash/avif` installed (transitively or directly), the production build may fail with:
116
-
117
- ```
118
- [commonjs--resolver] Invalid value "iife" for option "worker.format"
119
- - UMD and IIFE output formats are not supported for code-splitting builds.
120
- file: .../@jsquash/avif/codec/enc/avif_enc_mt.js
121
- ```
122
-
123
- This happens because `@jsquash/avif` ships a multi-threaded worker that uses code-splitting, while Vite's default `worker.format` is `'iife'`, which does not support split chunks.
124
-
125
- **Fix** — add this to your `vite.config.ts`:
126
-
127
- ```ts
128
- export default defineConfig({
129
- // ... your existing config
130
- worker: {
131
- format: 'es',
132
- },
133
- });
134
- ```
135
-
136
- `'es'` produces module workers (`type: 'module'`), supported by all modern browsers and compatible with code-splitting.
137
-
138
- > Note: `@jsquash/avif` is only used as a fallback when the browser does not natively support AVIF (Chrome 85+, Firefox 93+, Safari 16+ all support it natively). If your target browsers cover the native list, you can also remove `@jsquash/avif` from your dependencies entirely.
139
-
140
- ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f680.svg" width="20" height="20" alt="🚀" /> Quick Start
141
-
142
- ### Basic Usage
143
-
144
- ```vue
145
- <script setup lang="ts">
146
- import { ref } from 'vue';
147
- import { FilePreviewModal } from '@eternalheart/vue-file-preview';
148
- import '@eternalheart/vue-file-preview/style.css';
149
-
150
- const files = ref<File[]>([]);
151
- const currentIndex = ref(0);
152
- const isOpen = ref(false);
153
-
154
- const handleFileSelect = (e: Event) => {
155
- const file = (e.target as HTMLInputElement).files?.[0];
156
- if (file) {
157
- files.value = [file];
158
- currentIndex.value = 0;
159
- isOpen.value = true;
160
- }
161
- };
162
- </script>
163
-
164
- <template>
165
- <input type="file" @change="handleFileSelect" />
166
-
167
- <FilePreviewModal
168
- :files="files"
169
- :current-index="currentIndex"
170
- :is-open="isOpen"
171
- @close="isOpen = false"
172
- @navigate="currentIndex = $event"
173
- />
174
- </template>
175
- ```
176
-
177
- ### Multiple Input Types
178
-
179
- The component supports three types of file inputs:
180
-
181
- ```vue
182
- <script setup lang="ts">
183
- import { ref } from 'vue';
184
- import { FilePreviewModal, type PreviewFileInput } from '@eternalheart/vue-file-preview';
185
- import '@eternalheart/vue-file-preview/style.css';
186
-
187
- // Assume file1 comes from a File API source: <input type="file">,
188
- // drag & drop, clipboard paste, or fetch().then(r => r.blob())
189
- const file1 = new File(['content'], 'example.txt', { type: 'text/plain' });
190
-
191
- const files: PreviewFileInput[] = [
192
- // 1. Native File object (auto revoked when unmounted)
193
- file1,
194
-
195
- // 2. HTTP URL string (loaded on demand)
196
- 'https://example.com/image.jpg',
197
-
198
- // 3. File object with metadata (recommended for remote resources)
199
- {
200
- name: 'document.pdf',
201
- type: 'application/pdf',
202
- url: '/path/to/document.pdf',
203
- size: 1024,
204
- },
205
- ];
206
-
207
- // Memory note: If you generate URLs via URL.createObjectURL(),
208
- // call URL.revokeObjectURL() when files are removed to avoid memory leaks.
209
-
210
- const isOpen = ref(true);
211
- </script>
212
-
213
- <template>
214
- <FilePreviewModal
215
- :files="files"
216
- :current-index="0"
217
- :is-open="isOpen"
218
- @close="isOpen = false"
219
- />
220
- </template>
221
- ```
222
-
223
- ### Embedded Mode (`FilePreviewEmbed`)
224
-
225
- Besides the full-screen modal, the library also ships an **embedded** variant that renders the preview inline inside any container. Useful for detail panels, side-by-side layouts, dashboards, etc.
226
-
227
- ```vue
228
- <script setup lang="ts">
229
- import { ref } from 'vue';
230
- import { FilePreviewEmbed } from '@eternalheart/vue-file-preview';
231
- import '@eternalheart/vue-file-preview/style.css';
232
-
233
- const index = ref(0);
234
-
235
- const files = [
236
- 'https://example.com/image.jpg',
237
- { name: 'document.pdf', type: 'application/pdf', url: '/doc.pdf' },
238
- ];
239
- </script>
240
-
241
- <template>
242
- <div style="width: 100%; height: 520px">
243
- <FilePreviewEmbed
244
- :files="files"
245
- :current-index="index"
246
- @navigate="index = $event"
247
- />
248
- </div>
249
- </template>
250
- ```
251
-
252
- Differences from `FilePreviewModal`:
253
-
254
- - No teleport, no full-screen overlay, no `isOpen` / `@close`
255
- - Does **not** show the close button in the toolbar
256
- - Keyboard navigation (←/→/Home/End) is scoped to the embed container (focus-based)
257
- - Size defaults to `width: 100%; height: 100%`; override via `width` / `height` props
258
-
259
- ```vue
260
- <!-- Explicit size -->
261
- <FilePreviewEmbed :files="files" :width="800" :height="500" />
262
- ```
263
-
264
- ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4d6.svg" width="20" height="20" alt="📖" /> Supported File Formats
265
-
266
- ### Images
267
- - **Formats**: JPG, PNG, GIF, WebP, SVG, BMP, ICO, HEIC/HEIF, AVIF, TIFF, RAW, PSD, JPEG 2000
268
- - **Features**: Zoom (0.01x - 10x), rotate, drag, mouse wheel zoom, double-click reset, multi-page TIFF
269
- - **Decoding**: HEIC/RAW/PSD use a Worker-first path with a main-thread fallback; other advanced formats are loaded on demand
270
-
271
- ### Videos
272
- - **Formats**: MP4, WebM, OGG, MOV, AVI, MKV, M4V, 3GP, FLV
273
- - **Features**: Custom player, progress control, volume adjustment, fullscreen
274
-
275
- ### Audio
276
- - **Formats**: MP3, WAV, OGG, M4A, AAC, FLAC
277
- - **Features**: Custom player, progress bar, volume control, skip forward/backward
278
-
279
- ### Documents
280
- - **PDF**: Pagination, zoom
281
- - **Word**: DOCX and legacy DOC (97–2003) support
282
- - **Excel**: XLSX and legacy XLS (97–2003) support
283
- - **PowerPoint**: PPTX and legacy PPT (97–2003) slide preview
284
-
285
- ### Fonts
286
- - **Formats**: TTF, OTF, WOFF, WOFF2
287
- - **Features**: Font metadata (family, designer, version), character set preview, custom text input, multi-size display
288
-
289
- ### CAD / 3D Models
290
- - **Formats**: DXF, STL, OBJ, GLTF, GLB
291
- - **Features**: Interactive 3D viewer with orbit/zoom/pan controls, wireframe/solid toggle, grid & axes display, auto-centering
292
-
293
- ### Code & Text
294
- - **Markdown**: GitHub Flavored Markdown, code highlighting
295
- - **Code Files**: Vue, Svelte, Astro, JS/TS, Dart, GraphQL, Protobuf, Prisma, Terraform, PowerShell, Scala, and 40+ languages
296
- - **Config/Logs**: YAML, TOML, INI, ENV, PROPERTIES, BAT, CMD, TEX, MAP, LOG, DIFF, PATCH, etc.
297
-
298
- ### Structured Data
299
- - **JSON**: Auto formatting + syntax highlighting
300
- - **CSV/TSV**: Zero-dependency parser, table view with headers and row/column stats
301
- - **XML**: `DOMParser` validation + pretty print + syntax highlighting
302
-
303
- ### Subtitles & Lyrics
304
- - **SRT / WebVTT**: Zero-dependency parser, structured cue list (index, time range, text)
305
- - **LRC / Enhanced LRC**: Lyric files with `[mm:ss.xx]` line stamps (and inline `<mm:ss.xx>` per-word stamps for ELRC), with `[ti:][ar:][al:]` metadata header
306
- - **ASS / SSA**: Advanced SubStation Alpha — extracts Dialogue events, strips `\N` `\h` and `{...}` override codes, surfaces Style names
307
- - **TTML / DFXP**: W3C / Apple Music XML captions, supports `begin` / `end` / `dur` and `<br/>`
308
-
309
- ### Archives
310
- - **ZIP**: Tree view + inline preview for text/code/image entries, download fallback for other types
311
-
312
- ### Outlook Email
313
- - **MSG**: Headers, body rendering, attachment list
314
-
315
- ### E-books
316
- - **EPUB**: Chapter navigation, pagination
317
-
318
- ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/26a0.svg" width="20" height="20" alt="⚠️" /> Limitations &amp; Performance
319
-
320
- ### Support Levels
321
-
322
- **✅ Full Support (Production Ready)**
323
- - Images (JPG, PNG, GIF, WebP, SVG, BMP, ICO)
324
- - Videos (MP4, WebM, OGG)
325
- - Audio (MP3, WAV, OGG)
326
- - PDF
327
- - Markdown
328
- - Code files (40+ languages via Shiki, lazy-loaded)
329
- - JSON, CSV, XML
330
-
331
- **⚠️ Partial Support (Preview Only)**
332
- - **Office (DOCX, XLSX, PPTX)**: Basic layout and text rendering. Complex formatting (charts, macros, embedded objects) may not render accurately.
333
- - **ZIP**: Directory tree browsing + inline preview for text/code/images. Large archives (&gt;100MB) may cause performance issues.
334
- - **Fonts (TTF, OTF, WOFF)**: Metadata + character preview. Full font feature testing not supported.
335
-
336
- **🧪 Experimental**
337
- - **MSG (Outlook Email)**: Headers and plain text body. Complex HTML body may not render correctly.
338
- - **EPUB**: Basic chapter navigation. CSS styling may differ from native readers. DRM-protected files not supported.
339
- - **Subtitle formats (SRT, ASS, TTML, LRC)**: Text display only. No video sync or advanced styling.
340
-
341
- ### Performance Boundaries
342
-
343
- | File Size | Status | Notes |
344
- |-----------|--------|-------|
345
- | &lt; 50MB | ✅ Recommended | Smooth preview experience |
346
- | 50-100MB | ⚠️ May lag | UI may become unresponsive during load |
347
- | &gt; 100MB | ❌ Not recommended | Browser memory limits may be exceeded |
348
-
349
- **Special Cases:**
350
- - **ZIP archives**: Performance depends on file count, not just size
351
- - **Office documents**: Complex files (&gt;200 pages, heavy images) may timeout
352
- - **Code highlighting**: Files &gt;5MB may take 3-5s to highlight
353
-
354
- ### Browser Compatibility
355
-
356
- **Minimum Requirements:**
357
- - Chrome 90+ / Edge 90+
358
- - Firefox 88+
359
- - Safari 14+
360
-
361
- **Known Limitations:**
362
- - **Safari iOS**: Video autoplay requires user interaction
363
- - **Firefox**: AVIF support requires Firefox 93+ (fallback decoder included)
364
- - **Office formats**: Rendering quality varies across browsers
365
- - **EPUB**: Some CSS features unsupported in older browsers
366
-
367
- ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f3ae.svg" width="20" height="20" alt="🎮" /> API Reference
368
-
369
- ### FilePreviewModal Props
370
-
371
- | Prop | Type | Required | Description |
372
- |------|------|----------|-------------|
373
- | `files` | `PreviewFileInput[]` | ✅ | Array of files (supports File objects, file objects, or URL strings) |
374
- | `currentIndex` | `number` | ✅ | Current file index |
375
- | `isOpen` | `boolean` | ✅ | Whether the modal is open |
376
- | `customRenderers` | `CustomRenderer[]` | ❌ | Custom renderers for specific file types |
377
- | `locale` | `Locale` | ❌ | UI language (`'zh-CN'` default, `'en-US'` built-in) |
378
- | `messages` | `Partial<Record<Locale, Partial<Messages>>>` | ❌ | Custom translation overrides |
379
- | `headless` | `boolean` | ❌ | Headless mode — hides toolbar and navigation arrows |
380
- | `theme` | `Theme` | ❌ | Theme mode: `'auto' \| 'dark' \| 'light'` (default `'dark'`) |
381
- | `showDownload` | `boolean` | ❌ | Whether to show the download button (default `true`) |
382
- | `showClose` | `boolean` | ❌ | Whether to show the close button (default `true` for modal) |
383
- | `showNavigation` | `boolean` | ❌ | Whether to show file navigation arrows (default `true`) |
384
- | `loopNavigation` | `boolean` | ❌ | Whether file navigation wraps around (default `false`) |
385
-
386
- ### FilePreviewModal Events
387
-
388
- | Event | Payload | Description |
389
- |-------|---------|-------------|
390
- | `close` | - | Emitted when the modal should close |
391
- | `navigate` | `number` | Emitted when navigating to a different file index |
392
-
393
- ### FilePreviewEmbed Props
394
-
395
- | Prop | Type | Required | Default | Description |
396
- |------|------|----------|---------|-------------|
397
- | `files` | `PreviewFileInput[]` | ✅ | - | Array of files |
398
- | `currentIndex` | `number` | ❌ | `0` | Current file index |
399
- | `customRenderers` | `CustomRenderer[]` | ❌ | - | Custom renderers |
400
- | `width` | `number \| string` | ❌ | `'100%'` | Container width |
401
- | `height` | `number \| string` | ❌ | `'100%'` | Container height |
402
- | `locale` | `Locale` | ❌ | `'zh-CN'` | UI language (`'zh-CN'` or `'en-US'`) |
403
- | `messages` | `Partial<Record<Locale, Partial<Messages>>>` | ❌ | - | Custom translation overrides |
404
- | `headless` | `boolean` | ❌ | `false` | Headless mode — hides toolbar and navigation arrows |
405
- | `theme` | `Theme` | ❌ | `'dark'` | Theme mode: `'auto' \| 'dark' \| 'light'` |
406
- | `showDownload` | `boolean` | ❌ | `true` | Whether to show the download button |
407
- | `showClose` | `boolean` | ❌ | `false` | Whether to show the close button (default `false` for embed) |
408
- | `showNavigation` | `boolean` | ❌ | `true` | Whether to show file navigation arrows |
409
- | `loopNavigation` | `boolean` | ❌ | `false` | Whether file navigation wraps around |
410
-
411
- ### FilePreviewEmbed Events
412
-
413
- | Event | Payload | Description |
414
- |-------|---------|-------------|
415
- | `navigate` | `number` | Emitted when navigating to a different file index |
416
-
417
- ### FilePreviewContent (advanced)
418
-
419
- Both `FilePreviewModal` and `FilePreviewEmbed` are thin wrappers around the exported lower-level `FilePreviewContent` component. Use it directly when building a fully custom wrapper:
420
-
421
- ```vue
422
- <FilePreviewContent
423
- mode="embed"
424
- :files="files"
425
- :current-index="index"
426
- @navigate="index = $event"
427
- />
428
- ```
429
-
430
- ### File Type Definitions
431
-
432
- ```typescript
433
- // Supports three types of file input
434
- type PreviewFileInput = File | PreviewFileLink | string;
435
-
436
- // 1. Native File object (Browser File API)
437
- const file: File = ...;
438
-
439
- // 2. File object
440
- interface PreviewFileLink {
441
- id?: string; // Optional unique identifier
442
- name: string; // File name
443
- type: string; // MIME type
444
- url: string; // File URL (supports blob URLs and HTTP URLs)
445
- size?: number; // File size in bytes
446
- }
447
-
448
- // 3. HTTP URL string
449
- const url: string = 'https://example.com/file.pdf';
450
- ```
451
-
452
- ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f9e9.svg" width="20" height="20" alt="🧩" /> Custom Renderers
453
-
454
- The library supports custom renderers for handling file types not built-in. Custom renderers can optionally provide toolbar configurations and integrate with the library's architecture.
455
-
456
- ### Event-Driven Toolbar Updates
457
-
458
- Custom renderers can implement real-time toolbar updates using Vue 3's reactivity system:
459
-
460
- **Benefits:**
461
- - **Real-time updates**: Toolbar reflects state changes immediately via Vue reactivity
462
- - **Better performance**: No polling overhead, leverages Vue's efficient change detection
463
- - **Type-safe**: Full TypeScript support with proper interfaces
464
-
465
- **Implementation:**
466
-
467
- ```vue
468
- <script setup lang="ts">
469
- import { ref, computed, watch } from 'vue';
470
- import { ChevronLeft, ChevronRight } from 'lucide-vue-next';
471
- import type { ToolbarGroup } from '@eternalheart/vue-file-preview';
472
-
473
- interface Props {
474
- url: string;
475
- }
476
-
477
- const props = defineProps<Props>();
478
- const emit = defineEmits<{
479
- pageChange: [current: number, total: number];
480
- }>();
481
-
482
- const currentPage = ref(1);
483
- const totalPages = ref(10);
484
-
485
- // Emit page changes
486
- watch([currentPage, totalPages], () => {
487
- emit('pageChange', currentPage.value, totalPages.value);
488
- });
489
-
490
- const getToolbarGroups = (): ToolbarGroup[] => [
491
- {
492
- items: [
493
- {
494
- type: 'button',
495
- icon: ChevronLeft,
496
- tooltip: 'Previous Page',
497
- action: () => currentPage.value = Math.max(1, currentPage.value - 1),
498
- disabled: currentPage.value <= 1
499
- },
500
- {
501
- type: 'text',
502
- content: `${currentPage.value} / ${totalPages.value}`,
503
- minWidth: '4rem'
504
- },
505
- {
506
- type: 'button',
507
- icon: ChevronRight,
508
- tooltip: 'Next Page',
509
- action: () => currentPage.value = Math.min(totalPages.value, currentPage.value + 1),
510
- disabled: currentPage.value >= totalPages.value
511
- }
512
- ]
513
- }
514
- ];
515
-
516
- // Expose for parent component
517
- defineExpose({
518
- getToolbarGroups
519
- });
520
- </script>
521
-
522
- <template>
523
- <div>Your custom renderer UI</div>
524
- </template>
525
- ```
526
-
527
- **Main component usage:**
528
-
529
- ```vue
530
- <script setup>
531
- import { CustomRenderer } from './CustomRenderer.vue';
532
-
533
- const files = [
534
- { name: 'custom.xyz', type: 'application/custom', url: '/path/to/file' }
535
- ];
536
- </script>
537
-
538
- <template>
539
- <FilePreviewModal
540
- :files="files"
541
- :custom-renderers="[
542
- {
543
- test: (file) => file.type === 'application/custom',
544
- render: () => CustomRenderer
545
- }
546
- ]"
547
- />
548
- </template>
549
- ```
550
-
551
- The main component automatically tracks reactive changes in `getToolbarGroups()` via Vue's reactivity system. No manual subscription needed.
552
-
553
- ### Renderer Lazy Loading
554
-
555
- All built-in renderers use code-splitting via `defineAsyncComponent` to minimize the main bundle size and improve initial load performance.
556
-
557
- **Architecture:**
558
-
559
- - **Registration**: Renderers register in `src/renderers/lazy.ts` using `defineAsyncComponent` wrappers
560
- - **Loading**: Each renderer is a separate chunk, loaded on-demand when needed
561
- - **Fallback**: `RendererLoading` component handles the loading state
562
-
563
- Each renderer is emitted as a separate async chunk and loaded only when needed.
564
-
565
- **Implementation Example:**
566
-
567
- ```ts
568
- // src/renderers/lazy.ts
569
- import { defineAsyncComponent } from 'vue';
570
-
571
- const wrap = (loader: () => Promise<any>) =>
572
- defineAsyncComponent({
573
- loader,
574
- loadingComponent: RendererLoading,
575
- delay: 0
576
- });
577
-
578
- export const CustomRenderer = wrap(() => import('./Custom/index.vue'));
579
- ```
580
-
581
- ```vue
582
- <!-- src/FilePreviewContent.vue -->
583
- <script setup>
584
- import { CustomRenderer } from './renderers/lazy'; // ✅ Lazy import
585
- // NOT: import CustomRenderer from './renderers/Custom/index.vue'; // ❌ Direct import breaks code-splitting
586
- </script>
587
-
588
- <template>
589
- <CustomRenderer
590
- v-if="fileType === 'custom'"
591
- ref="rendererRef"
592
- :url="currentFile.url"
593
- />
594
- </template>
595
- ```
596
-
597
- **For Custom Renderers:**
598
-
599
- If you want your custom renderer to benefit from code-splitting, use the same pattern:
600
-
601
- ```vue
602
- <script setup>
603
- import { defineAsyncComponent } from 'vue';
604
-
605
- const MyCustomRenderer = defineAsyncComponent(() => import('./MyCustomRenderer.vue'));
606
-
607
- const files = [...];
608
- </script>
609
-
610
- <template>
611
- <FilePreviewModal
612
- :files="files"
613
- :custom-renderers="[
614
- {
615
- test: (file) => file.type === 'application/custom',
616
- render: () => MyCustomRenderer
617
- }
618
- ]"
619
- />
620
- </template>
621
- ```
622
-
623
- ### i18n Integration
624
-
625
- Custom renderers can access the library's i18n system via the `useTranslator()` composable for consistent multilingual support.
626
-
627
- **Architecture:**
628
-
629
- - **Dictionary Source**: `file-preview-core/src/i18n/messages/` (zh-CN.ts, en-US.ts)
630
- - **No Hardcoding**: All user-visible text must use translation keys
631
- - **Automatic Locale Switching**: Follows the `locale` prop passed to `FilePreviewModal`
632
-
633
- **Usage in Custom Renderers:**
634
-
635
- ```vue
636
- <script setup lang="ts">
637
- import { ref } from 'vue';
638
- import { useTranslator } from '@eternalheart/vue-file-preview';
639
-
640
- interface Props {
641
- url: string;
642
- }
643
-
644
- const props = defineProps<Props>();
645
- const { t } = useTranslator();
646
- const error = ref<string | null>(null);
647
- </script>
648
-
649
- <template>
650
- <div v-if="error" class="vfp-text-fg-primary">
651
- {{ t('custom.load_failed') }}: {{ error }}
652
- </div>
653
- <div v-else>
654
- <button>{{ t('common.download') }}</button>
655
- <span>{{ t('custom.loading') }}</span>
656
- </div>
657
- </template>
658
- ```
659
-
660
- **Note on Usage:**
661
-
662
- - In `<template>`: Use `t('key')` directly (automatically unwrapped)
663
- - In `<script>`: Use `t.value('key')` for imperative calls
664
-
665
- **Adding Custom Translation Keys:**
666
-
667
- For custom renderers, extend translations via the `messages` prop (do NOT modify source files in `node_modules`):
668
-
669
- ```vue
670
- <template>
671
- <FilePreviewModal
672
- :files="files"
673
- locale="en-US"
674
- :messages="{
675
- 'en-US': {
676
- 'custom.load_failed': 'Failed to load custom file',
677
- 'custom.file_size': 'File size: {size} KB'
678
- },
679
- 'zh-CN': {
680
- 'custom.load_failed': '自定义文件加载失败',
681
- 'custom.file_size': '文件大小: {size} KB'
682
- }
683
- }"
684
- :custom-renderers="[...]"
685
- />
686
- </template>
687
- ```
688
-
689
- **Guidelines:**
690
- - Use `<scope>.<snake_name>` format (e.g., `custom.load_failed`, `custom.parse_error`)
691
- - Provide translations for all enabled locales (`zh-CN` and `en-US`)
692
- - Common keys already available: `common.loading`, `common.download`, `common.close`, `toolbar.*`
693
-
694
- **Parameterized Translations:**
695
-
696
- ```vue
697
- <template>
698
- <!-- Dictionary: 'custom.file_size': 'File size: {size} KB' -->
699
- <span>{{ t('custom.file_size', { size: 1024 }) }}</span>
700
- <!-- → "File size: 1024 KB" -->
701
- </template>
702
- ```
703
-
704
- **Toolbar Integration:**
705
-
706
- Toolbar items should also use translated strings:
707
-
708
- ```ts
709
- const getToolbarGroups = (): ToolbarGroup[] => [
710
- {
711
- items: [
712
- {
713
- type: 'button',
714
- icon: Download,
715
- tooltip: t.value('common.download'), // ✅ Translated (use .value in script)
716
- action: handleDownload
717
- }
718
- ]
719
- }
720
- ];
721
- ```
722
-
723
- ### Theme Adaptation
724
-
725
- Custom renderers must use semantic color tokens to support the library's `'auto' | 'dark' | 'light'` theme system.
726
-
727
- **Semantic Token System:**
728
-
729
- All colors are defined as CSS variables (`--fp-*`) and exposed via Tailwind classes with the `vfp-` prefix:
730
-
731
- | Usage | Class | Description |
732
- |-------|-------|-------------|
733
- | **Text (fg)** | | |
734
- | Primary text | `vfp-text-fg-primary` | Highest contrast |
735
- | Body text | `vfp-text-fg-secondary` | Default text |
736
- | Secondary text | `vfp-text-fg-tertiary` | Captions, counters |
737
- | Muted text | `vfp-text-fg-muted` | Placeholders |
738
- | Disabled text | `vfp-text-fg-disabled` | Disabled buttons |
739
- | **Background (surface)** | | |
740
- | Surface 1 | `vfp-bg-surface-1` | Cards, weakest |
741
- | Surface 2 | `vfp-bg-surface-2` | Hover states |
742
- | Surface 3 | `vfp-bg-surface-3` | Emphasis |
743
- | Toolbar | `vfp-bg-surface-toolbar` | Top toolbar |
744
- | **Borders** | | |
745
- | Weak border | `vfp-border-line-weak` | Subtle lines |
746
- | Standard border | `vfp-border-line` | Default borders |
747
- | Strong border | `vfp-border-line-strong` | Emphasis |
748
- | **Code** | | |
749
- | Code background | `vfp-bg-code-bg` | Dark: #1e1e1e / Light: #f6f8fa |
750
- | Code text | `vfp-text-code-fg` | Follows theme |
751
- | **Accent** | | |
752
- | Accent background | `vfp-bg-accent` | Primary buttons |
753
- | Accent hover | `vfp-bg-accent-hover` | Hover state |
754
-
755
- **✅ Correct Usage:**
756
-
757
- ```vue
758
- <template>
759
- <div class="vfp-bg-surface-1 vfp-border vfp-border-line-weak vfp-rounded">
760
- <h2 class="vfp-text-fg-primary vfp-text-lg">Title</h2>
761
- <p class="vfp-text-fg-secondary">Body text</p>
762
- <button class="vfp-bg-surface-2 hover:vfp-bg-surface-3 vfp-text-fg-primary">
763
- Click me
764
- </button>
765
- <pre class="vfp-bg-code-bg vfp-text-code-fg">{{ code }}</pre>
766
- </div>
767
- </template>
768
- ```
769
-
770
- **For `<style scoped>` blocks**, use CSS variables:
771
-
772
- ```vue
773
- <style scoped>
774
- .my-block {
775
- color: var(--fp-fg-primary);
776
- background: var(--fp-surface-2);
777
- border: 1px solid var(--fp-line);
778
- }
779
-
780
- .my-code {
781
- background: var(--fp-code-bg);
782
- color: var(--fp-code-fg);
783
- }
784
- </style>
785
- ```
786
-
787
- **❌ Incorrect Usage (DO NOT USE):**
788
-
789
- ```vue
790
- <!-- ❌ Literal color classes — breaks theme switching -->
791
- <div class="vfp-text-white/90 vfp-bg-white/10 vfp-border-white/15">
792
- <div class="vfp-text-gray-700 vfp-bg-gray-100">
793
-
794
- <!-- ❌ Inline literal colors -->
795
- <div :style="{ color: '#ffffff', background: '#1f2937' }">
796
-
797
- <!-- ❌ Hardcoded dark-only colors in scoped style -->
798
- <style scoped>
799
- .foo { color: rgba(255, 255, 255, 0.75); } /* Use var(--fp-fg-secondary) */
800
- .foo { background: #1e1e1e; } /* Use var(--fp-code-bg) */
801
- </style>
802
- ```
803
-
804
- **Theme-Aware Third-Party Libraries:**
805
-
806
- For libraries with theme props (e.g., `shiki`), use `useResolvedTheme()`:
807
-
808
- ```vue
809
- <script setup lang="ts">
810
- import { ref, watch } from 'vue';
811
- import { codeToHtml } from 'shiki';
812
- import { useResolvedTheme } from '@eternalheart/vue-file-preview';
813
-
814
- const props = defineProps<{ code: string; lang: string }>();
815
- const resolvedTheme = useResolvedTheme(); // Ref<'dark' | 'light'>
816
- const highlighted = ref('');
817
-
818
- const highlightCode = async () => {
819
- highlighted.value = await codeToHtml(props.code, {
820
- lang: props.lang,
821
- theme: resolvedTheme.value === 'light' ? 'github-light' : 'dark-plus'
822
- });
823
- };
824
-
825
- // Re-highlight when theme changes
826
- watch(resolvedTheme, highlightCode, { immediate: true });
827
- </script>
828
-
829
- <template>
830
- <div v-html="highlighted"></div>
831
- </template>
832
- ```
833
-
834
- **Testing:**
835
-
836
- Always test your custom renderer in both Light and Dark themes:
837
-
838
- ```vue
839
- <FilePreviewModal
840
- :files="files"
841
- theme="light" // Switch between 'light', 'dark', 'auto'
842
- :custom-renderers="[...]"
843
- />
844
- ```
845
-
846
- Verify:
847
- - Text is readable in both themes (no white-on-white or black-on-black)
848
- - Borders and dividers are visible
849
- - Hover states have sufficient contrast
850
- - Code blocks follow theme (not always dark)
851
-
852
- ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/2328.svg" width="20" height="20" alt="⌨️" /> Keyboard Shortcuts
853
-
854
- - `ESC` - Close preview
855
- - `←` - Previous file
856
- - `→` - Next file
857
- - `Home` - First file
858
- - `End` - Last file
859
- - `Mouse Wheel` - Zoom image (image preview only)
860
-
861
- ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4da.svg" width="20" height="20" alt="📚" /> Documentation
862
-
863
- - [Full Documentation](https://wh131462.github.io/file-preview/docs/)
864
- - [Vue Demo](https://wh131462.github.io/file-preview/vue/)
865
- - [React Demo](https://wh131462.github.io/file-preview/)
866
-
867
- ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f6e0.svg" width="20" height="20" alt="🛠️" /> Development
868
-
869
- ```bash
870
- # Clone repository
871
- git clone https://github.com/wh131462/file-preview.git
872
-
873
- # Install dependencies
874
- pnpm install
875
-
876
- # Start dev server (Vue demo app)
877
- pnpm dev:vue-example
878
-
879
- # Build library
880
- pnpm build:vue
881
- ```
882
-
883
- ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4c4.svg" width="20" height="20" alt="📄" /> License
884
-
885
- [MIT](./LICENSE) © [EternalHeart](https://github.com/wh131462)
886
-
887
- ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f91d.svg" width="20" height="20" alt="🤝" /> Contributing
888
-
889
- Issues and Pull Requests are welcome!
890
-
891
- ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f517.svg" width="20" height="20" alt="🔗" /> Links
892
-
893
- - [GitHub](https://github.com/wh131462/file-preview)
894
- - [npm](https://www.npmjs.com/package/@eternalheart/vue-file-preview)
895
- - [Vue Demo](https://wh131462.github.io/file-preview/vue/)
896
- - [Issue Tracker](https://github.com/wh131462/file-preview/issues)
1
+ # Vue File Preview [![npm version](https://img.shields.io/npm/v/@eternalheart/vue-file-preview.svg)](https://www.npmjs.com/package/@eternalheart/vue-file-preview)[![license](https://img.shields.io/npm/l/@eternalheart/vue-file-preview.svg)](https://github.com/wh131462/file-preview/blob/master/LICENSE)[![downloads](https://img.shields.io/npm/dm/@eternalheart/vue-file-preview.svg)](https://www.npmjs.com/package/@eternalheart/vue-file-preview)
2
+
3
+ English | [简体中文](./README.zh-CN.md)
4
+
5
+ A modern, feature-rich file preview component for Vue 3 with support for images, videos, audio, PDFs, Office documents (Word, Excel, PowerPoint), Markdown, and code files.
6
+
7
+ ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/2728.svg" width="20" height="20" alt="✨" /> Features
8
+
9
+ - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f3a8.svg" width="16" height="16" alt="🎨" style="vertical-align: middle;" /> **Modern UI** - Clean and modern interface with smooth animations
10
+ - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4c1.svg" width="16" height="16" alt="📁" style="vertical-align: middle;" /> **Multi-format Support** - Supports 20+ file formats
11
+ - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1fa9f.svg" width="16" height="16" alt="🪟" style="vertical-align: middle;" /> **Two Display Modes** - Full-screen modal **or** inline embedded preview
12
+ - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f5bc.svg" width="16" height="16" alt="🖼️" style="vertical-align: middle;" /> **Powerful Image Viewer** - Zoom, rotate, drag, mouse wheel zoom
13
+ - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f3ac.svg" width="16" height="16" alt="🎬" style="vertical-align: middle;" /> **Custom Video Player** - Built on Video.js, supports multiple video formats
14
+ - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f3b5.svg" width="16" height="16" alt="🎵" style="vertical-align: middle;" /> **Custom Audio Player** - Beautiful audio control interface
15
+ - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4c4.svg" width="16" height="16" alt="📄" style="vertical-align: middle;" /> **PDF Viewer** - Pagination support
16
+ - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4ca.svg" width="16" height="16" alt="📊" style="vertical-align: middle;" /> **Office Documents Support** - Word, Excel, PowerPoint file preview
17
+ - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4dd.svg" width="16" height="16" alt="📝" style="vertical-align: middle;" /> **Markdown Rendering** - GitHub Flavored Markdown support
18
+ - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4bb.svg" width="16" height="16" alt="💻" style="vertical-align: middle;" /> **Code Highlighting** - Supports 40+ programming languages
19
+ - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4f1.svg" width="16" height="16" alt="📱" style="vertical-align: middle;" /> **Responsive Design** - Adapts to all screen sizes
20
+ - <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/2328.svg" width="16" height="16" alt="⌨️" style="vertical-align: middle;" /> **Keyboard Navigation** - Arrow, Home, End, and ESC key support
21
+
22
+ ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4e6.svg" width="20" height="20" alt="📦" /> Installation
23
+
24
+ ```bash
25
+ # Using npm
26
+ npm install @eternalheart/vue-file-preview
27
+
28
+ # Using yarn
29
+ yarn add @eternalheart/vue-file-preview
30
+
31
+ # Using pnpm
32
+ pnpm add @eternalheart/vue-file-preview
33
+ ```
34
+
35
+ **Important:** You also need to import the CSS file:
36
+
37
+ ```ts
38
+ import '@eternalheart/vue-file-preview/style.css';
39
+ ```
40
+
41
+ > **Note:** The `pdfjs-dist` dependency will be automatically installed for PDF preview support. No additional installation is required.
42
+
43
+ ### PDF.js Configuration (Optional)
44
+
45
+ If you need to preview PDF files, it's recommended to configure PDF.js to use local static files for better performance and stability:
46
+
47
+ #### Method 1: Use CDN (Default)
48
+
49
+ By default, the component automatically uses unpkg CDN to load PDF.js, no additional configuration needed.
50
+
51
+ #### Method 2: Use Local Static Files (Recommended for Production)
52
+
53
+ 1. Copy PDF.js files to your public directory:
54
+
55
+ ```bash
56
+ cp -r node_modules/pdfjs-dist/legacy/build/pdf.worker.min.mjs public/pdfjs/
57
+ cp -r node_modules/pdfjs-dist/cmaps public/pdfjs/
58
+ cp -r node_modules/pdfjs-dist/standard_fonts public/pdfjs/
59
+ cp -r node_modules/pdfjs-dist/wasm public/pdfjs/
60
+ ```
61
+
62
+ 2. Configure PDF.js in your app entry:
63
+
64
+ ```ts
65
+ import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf.mjs';
66
+ import { configurePdfWorker } from '@eternalheart/vue-file-preview';
67
+
68
+ configurePdfWorker(pdfjsLib, {
69
+ workerSrc: '/pdfjs/pdf.worker.min.mjs',
70
+ cMapUrl: '/pdfjs/cmaps/',
71
+ cMapPacked: true,
72
+ standardFontDataUrl: '/pdfjs/standard_fonts/',
73
+ wasmUrl: '/pdfjs/wasm/',
74
+ });
75
+ ```
76
+
77
+ Call this during client application initialization, before the first PDF render. The worker must use the legacy build matching the installed `pdfjs-dist` version.
78
+
79
+ #### Auto-copy with Vite (Recommended)
80
+
81
+ Configure auto-copy in `vite.config.ts`:
82
+
83
+ ```ts
84
+ import { defineConfig } from 'vite';
85
+ import { viteStaticCopy } from 'vite-plugin-static-copy';
86
+
87
+ export default defineConfig({
88
+ plugins: [
89
+ viteStaticCopy({
90
+ targets: [
91
+ {
92
+ src: 'node_modules/pdfjs-dist/legacy/build/pdf.worker.min.mjs',
93
+ dest: 'pdfjs'
94
+ },
95
+ {
96
+ src: 'node_modules/pdfjs-dist/cmaps',
97
+ dest: 'pdfjs'
98
+ },
99
+ {
100
+ src: 'node_modules/pdfjs-dist/standard_fonts',
101
+ dest: 'pdfjs'
102
+ },
103
+ {
104
+ src: 'node_modules/pdfjs-dist/wasm',
105
+ dest: 'pdfjs'
106
+ }
107
+ ]
108
+ })
109
+ ]
110
+ });
111
+ ```
112
+
113
+ ### Vite Bundler Note (AVIF Decoder)
114
+
115
+ If your project bundler is Vite and you happen to have `@jsquash/avif` installed (transitively or directly), the production build may fail with:
116
+
117
+ ```
118
+ [commonjs--resolver] Invalid value "iife" for option "worker.format"
119
+ - UMD and IIFE output formats are not supported for code-splitting builds.
120
+ file: .../@jsquash/avif/codec/enc/avif_enc_mt.js
121
+ ```
122
+
123
+ This happens because `@jsquash/avif` ships a multi-threaded worker that uses code-splitting, while Vite's default `worker.format` is `'iife'`, which does not support split chunks.
124
+
125
+ **Fix** — add this to your `vite.config.ts`:
126
+
127
+ ```ts
128
+ export default defineConfig({
129
+ // ... your existing config
130
+ worker: {
131
+ format: 'es',
132
+ },
133
+ });
134
+ ```
135
+
136
+ `'es'` produces module workers (`type: 'module'`), supported by all modern browsers and compatible with code-splitting.
137
+
138
+ > Note: `@jsquash/avif` is only used as a fallback when the browser does not natively support AVIF (Chrome 85+, Firefox 93+, Safari 16+ all support it natively). If your target browsers cover the native list, you can also remove `@jsquash/avif` from your dependencies entirely.
139
+
140
+ ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f680.svg" width="20" height="20" alt="🚀" /> Quick Start
141
+
142
+ ### Basic Usage
143
+
144
+ ```vue
145
+ <script setup lang="ts">
146
+ import { ref } from 'vue';
147
+ import { FilePreviewModal } from '@eternalheart/vue-file-preview';
148
+ import '@eternalheart/vue-file-preview/style.css';
149
+
150
+ const files = ref<File[]>([]);
151
+ const currentIndex = ref(0);
152
+ const isOpen = ref(false);
153
+
154
+ const handleFileSelect = (e: Event) => {
155
+ const file = (e.target as HTMLInputElement).files?.[0];
156
+ if (file) {
157
+ files.value = [file];
158
+ currentIndex.value = 0;
159
+ isOpen.value = true;
160
+ }
161
+ };
162
+ </script>
163
+
164
+ <template>
165
+ <input type="file" @change="handleFileSelect" />
166
+
167
+ <FilePreviewModal
168
+ :files="files"
169
+ :current-index="currentIndex"
170
+ :is-open="isOpen"
171
+ @close="isOpen = false"
172
+ @navigate="currentIndex = $event"
173
+ />
174
+ </template>
175
+ ```
176
+
177
+ ### Multiple Input Types
178
+
179
+ The component supports three types of file inputs:
180
+
181
+ ```vue
182
+ <script setup lang="ts">
183
+ import { ref } from 'vue';
184
+ import { FilePreviewModal, type PreviewFileInput } from '@eternalheart/vue-file-preview';
185
+ import '@eternalheart/vue-file-preview/style.css';
186
+
187
+ // Assume file1 comes from a File API source: <input type="file">,
188
+ // drag & drop, clipboard paste, or fetch().then(r => r.blob())
189
+ const file1 = new File(['content'], 'example.txt', { type: 'text/plain' });
190
+
191
+ const files: PreviewFileInput[] = [
192
+ // 1. Native File object (auto revoked when unmounted)
193
+ file1,
194
+
195
+ // 2. HTTP URL string (loaded on demand)
196
+ 'https://example.com/image.jpg',
197
+
198
+ // 3. File object with metadata (recommended for remote resources)
199
+ {
200
+ name: 'document.pdf',
201
+ type: 'application/pdf',
202
+ url: '/path/to/document.pdf',
203
+ size: 1024,
204
+ },
205
+ ];
206
+
207
+ // Memory note: If you generate URLs via URL.createObjectURL(),
208
+ // call URL.revokeObjectURL() when files are removed to avoid memory leaks.
209
+
210
+ const isOpen = ref(true);
211
+ </script>
212
+
213
+ <template>
214
+ <FilePreviewModal
215
+ :files="files"
216
+ :current-index="0"
217
+ :is-open="isOpen"
218
+ @close="isOpen = false"
219
+ />
220
+ </template>
221
+ ```
222
+
223
+ ### Embedded Mode (`FilePreviewEmbed`)
224
+
225
+ Besides the full-screen modal, the library also ships an **embedded** variant that renders the preview inline inside any container. Useful for detail panels, side-by-side layouts, dashboards, etc.
226
+
227
+ ```vue
228
+ <script setup lang="ts">
229
+ import { ref } from 'vue';
230
+ import { FilePreviewEmbed } from '@eternalheart/vue-file-preview';
231
+ import '@eternalheart/vue-file-preview/style.css';
232
+
233
+ const index = ref(0);
234
+
235
+ const files = [
236
+ 'https://example.com/image.jpg',
237
+ { name: 'document.pdf', type: 'application/pdf', url: '/doc.pdf' },
238
+ ];
239
+ </script>
240
+
241
+ <template>
242
+ <div style="width: 100%; height: 520px">
243
+ <FilePreviewEmbed
244
+ :files="files"
245
+ :current-index="index"
246
+ @navigate="index = $event"
247
+ />
248
+ </div>
249
+ </template>
250
+ ```
251
+
252
+ Differences from `FilePreviewModal`:
253
+
254
+ - No teleport, no full-screen overlay, no `isOpen` / `@close`
255
+ - Does **not** show the close button in the toolbar
256
+ - Keyboard navigation (←/→/Home/End) is scoped to the embed container (focus-based)
257
+ - Size defaults to `width: 100%; height: 100%`; override via `width` / `height` props
258
+
259
+ ```vue
260
+ <!-- Explicit size -->
261
+ <FilePreviewEmbed :files="files" :width="800" :height="500" />
262
+ ```
263
+
264
+ ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4d6.svg" width="20" height="20" alt="📖" /> Supported File Formats
265
+
266
+ ### Images
267
+ - **Formats**: JPG, PNG, GIF, WebP, SVG, BMP, ICO, HEIC/HEIF, AVIF, TIFF, RAW, PSD, JPEG 2000
268
+ - **Features**: Zoom (0.01x - 10x), rotate, drag, mouse wheel zoom, double-click reset, multi-page TIFF
269
+ - **Decoding**: HEIC/RAW/PSD use a Worker-first path with a main-thread fallback; other advanced formats are loaded on demand
270
+
271
+ ### Videos
272
+ - **Formats**: MP4, WebM, OGG, MOV, AVI, MKV, M4V, 3GP, FLV
273
+ - **Features**: Custom player, progress control, volume adjustment, fullscreen
274
+
275
+ ### Audio
276
+ - **Formats**: MP3, WAV, OGG, M4A, AAC, FLAC
277
+ - **Features**: Custom player, progress bar, volume control, skip forward/backward
278
+
279
+ ### Documents
280
+ - **PDF**: Pagination, zoom
281
+ - **Word**: DOCX and legacy DOC (97–2003) support
282
+ - **Excel**: XLSX and legacy XLS (97–2003) support
283
+ - **PowerPoint**: PPTX and legacy PPT (97–2003) slide preview
284
+
285
+ ### Fonts
286
+ - **Formats**: TTF, OTF, WOFF, WOFF2
287
+ - **Features**: Font metadata (family, designer, version), character set preview, custom text input, multi-size display
288
+
289
+ ### CAD / 3D Models
290
+ - **Formats**: DXF, STL, OBJ, GLTF, GLB
291
+ - **Features**: Interactive 3D viewer with orbit/zoom/pan controls, wireframe/solid toggle, grid & axes display, auto-centering
292
+
293
+ ### Code & Text
294
+ - **Markdown**: GitHub Flavored Markdown, code highlighting
295
+ - **Code Files**: Vue, Svelte, Astro, JS/TS, Dart, GraphQL, Protobuf, Prisma, Terraform, PowerShell, Scala, and 40+ languages
296
+ - **Config/Logs**: YAML, TOML, INI, ENV, PROPERTIES, BAT, CMD, TEX, MAP, LOG, DIFF, PATCH, etc.
297
+
298
+ ### Structured Data
299
+ - **JSON**: Auto formatting + syntax highlighting
300
+ - **CSV/TSV**: Zero-dependency parser, table view with headers and row/column stats
301
+ - **XML**: `DOMParser` validation + pretty print + syntax highlighting
302
+
303
+ ### Subtitles & Lyrics
304
+ - **SRT / WebVTT**: Zero-dependency parser, structured cue list (index, time range, text)
305
+ - **LRC / Enhanced LRC**: Lyric files with `[mm:ss.xx]` line stamps (and inline `<mm:ss.xx>` per-word stamps for ELRC), with `[ti:][ar:][al:]` metadata header
306
+ - **ASS / SSA**: Advanced SubStation Alpha — extracts Dialogue events, strips `\N` `\h` and `{...}` override codes, surfaces Style names
307
+ - **TTML / DFXP**: W3C / Apple Music XML captions, supports `begin` / `end` / `dur` and `<br/>`
308
+
309
+ ### Archives
310
+ - **ZIP**: Tree view + inline preview for text/code/image entries, download fallback for other types
311
+
312
+ ### Outlook Email
313
+ - **MSG**: Headers, body rendering, attachment list
314
+
315
+ ### E-books
316
+ - **EPUB**: Chapter navigation, pagination
317
+
318
+ ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/26a0.svg" width="20" height="20" alt="⚠️" /> Limitations &amp; Performance
319
+
320
+ ### Support Levels
321
+
322
+ **✅ Full Support (Production Ready)**
323
+ - Images (JPG, PNG, GIF, WebP, SVG, BMP, ICO)
324
+ - Videos (MP4, WebM, OGG)
325
+ - Audio (MP3, WAV, OGG)
326
+ - PDF
327
+ - Markdown
328
+ - Code files (40+ languages via Shiki, lazy-loaded)
329
+ - JSON, CSV, XML
330
+
331
+ **⚠️ Partial Support (Preview Only)**
332
+ - **Office (DOCX, XLSX, PPTX)**: Basic layout and text rendering. Complex formatting (charts, macros, embedded objects) may not render accurately.
333
+ - **ZIP**: Directory tree browsing + inline preview for text/code/images. Large archives (&gt;100MB) may cause performance issues.
334
+ - **Fonts (TTF, OTF, WOFF)**: Metadata + character preview. Full font feature testing not supported.
335
+
336
+ **🧪 Experimental**
337
+ - **MSG (Outlook Email)**: Headers and plain text body. Complex HTML body may not render correctly.
338
+ - **EPUB**: Basic chapter navigation. CSS styling may differ from native readers. DRM-protected files not supported.
339
+ - **Subtitle formats (SRT, ASS, TTML, LRC)**: Text display only. No video sync or advanced styling.
340
+
341
+ ### Performance Boundaries
342
+
343
+ | File Size | Status | Notes |
344
+ |-----------|--------|-------|
345
+ | &lt; 50MB | ✅ Recommended | Smooth preview experience |
346
+ | 50-100MB | ⚠️ May lag | UI may become unresponsive during load |
347
+ | &gt; 100MB | ❌ Not recommended | Browser memory limits may be exceeded |
348
+
349
+ **Special Cases:**
350
+ - **ZIP archives**: Performance depends on file count, not just size
351
+ - **Office documents**: Complex files (&gt;200 pages, heavy images) may timeout
352
+ - **Code highlighting**: Files &gt;5MB may take 3-5s to highlight
353
+
354
+ ### Browser Compatibility
355
+
356
+ **Minimum Requirements:**
357
+ - Chrome 90+ / Edge 90+
358
+ - Firefox 88+
359
+ - Safari 14+
360
+
361
+ **Known Limitations:**
362
+ - **Safari iOS**: Video autoplay requires user interaction
363
+ - **Firefox**: AVIF support requires Firefox 93+ (fallback decoder included)
364
+ - **Office formats**: Rendering quality varies across browsers
365
+ - **EPUB**: Some CSS features unsupported in older browsers
366
+
367
+ ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f3ae.svg" width="20" height="20" alt="🎮" /> API Reference
368
+
369
+ ### FilePreviewModal Props
370
+
371
+ | Prop | Type | Required | Description |
372
+ |------|------|----------|-------------|
373
+ | `files` | `PreviewFileInput[]` | ✅ | Array of files (supports File objects, file objects, or URL strings) |
374
+ | `currentIndex` | `number` | ✅ | Current file index |
375
+ | `isOpen` | `boolean` | ✅ | Whether the modal is open |
376
+ | `customRenderers` | `CustomRenderer[]` | ❌ | Custom renderers for specific file types |
377
+ | `locale` | `Locale` | ❌ | UI language (`'zh-CN'` default, `'en-US'` built-in) |
378
+ | `messages` | `Partial<Record<Locale, Partial<Messages>>>` | ❌ | Custom translation overrides |
379
+ | `headless` | `boolean` | ❌ | Headless mode — hides toolbar and navigation arrows |
380
+ | `theme` | `Theme` | ❌ | Theme mode: `'auto' \| 'dark' \| 'light'` (default `'dark'`) |
381
+ | `showDownload` | `boolean` | ❌ | Whether to show the download button (default `true`) |
382
+ | `showClose` | `boolean` | ❌ | Whether to show the close button (default `true` for modal) |
383
+ | `showNavigation` | `boolean` | ❌ | Whether to show file navigation arrows (default `true`) |
384
+ | `loopNavigation` | `boolean` | ❌ | Whether file navigation wraps around (default `false`) |
385
+
386
+ ### FilePreviewModal Events
387
+
388
+ | Event | Payload | Description |
389
+ |-------|---------|-------------|
390
+ | `close` | - | Emitted when the modal should close |
391
+ | `navigate` | `number` | Emitted when navigating to a different file index |
392
+
393
+ ### FilePreviewEmbed Props
394
+
395
+ | Prop | Type | Required | Default | Description |
396
+ |------|------|----------|---------|-------------|
397
+ | `files` | `PreviewFileInput[]` | ✅ | - | Array of files |
398
+ | `currentIndex` | `number` | ❌ | `0` | Current file index |
399
+ | `customRenderers` | `CustomRenderer[]` | ❌ | - | Custom renderers |
400
+ | `width` | `number \| string` | ❌ | `'100%'` | Container width |
401
+ | `height` | `number \| string` | ❌ | `'100%'` | Container height |
402
+ | `locale` | `Locale` | ❌ | `'zh-CN'` | UI language (`'zh-CN'` or `'en-US'`) |
403
+ | `messages` | `Partial<Record<Locale, Partial<Messages>>>` | ❌ | - | Custom translation overrides |
404
+ | `headless` | `boolean` | ❌ | `false` | Headless mode — hides toolbar and navigation arrows |
405
+ | `theme` | `Theme` | ❌ | `'dark'` | Theme mode: `'auto' \| 'dark' \| 'light'` |
406
+ | `showDownload` | `boolean` | ❌ | `true` | Whether to show the download button |
407
+ | `showClose` | `boolean` | ❌ | `false` | Whether to show the close button (default `false` for embed) |
408
+ | `showNavigation` | `boolean` | ❌ | `true` | Whether to show file navigation arrows |
409
+ | `loopNavigation` | `boolean` | ❌ | `false` | Whether file navigation wraps around |
410
+
411
+ ### FilePreviewEmbed Events
412
+
413
+ | Event | Payload | Description |
414
+ |-------|---------|-------------|
415
+ | `navigate` | `number` | Emitted when navigating to a different file index |
416
+
417
+ ### FilePreviewContent (advanced)
418
+
419
+ Both `FilePreviewModal` and `FilePreviewEmbed` are thin wrappers around the exported lower-level `FilePreviewContent` component. Use it directly when building a fully custom wrapper:
420
+
421
+ ```vue
422
+ <FilePreviewContent
423
+ mode="embed"
424
+ :files="files"
425
+ :current-index="index"
426
+ @navigate="index = $event"
427
+ />
428
+ ```
429
+
430
+ ### File Type Definitions
431
+
432
+ ```typescript
433
+ // Supports three types of file input
434
+ type PreviewFileInput = File | PreviewFileLink | string;
435
+
436
+ // 1. Native File object (Browser File API)
437
+ const file: File = ...;
438
+
439
+ // 2. File object
440
+ interface PreviewFileLink {
441
+ id?: string; // Optional unique identifier
442
+ name: string; // File name
443
+ type: string; // MIME type
444
+ url: string; // File URL (supports blob URLs and HTTP URLs)
445
+ size?: number; // File size in bytes
446
+ }
447
+
448
+ // 3. HTTP URL string
449
+ const url: string = 'https://example.com/file.pdf';
450
+ ```
451
+
452
+ ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f9e9.svg" width="20" height="20" alt="🧩" /> Custom Renderers
453
+
454
+ The library supports custom renderers for handling file types not built-in. Custom renderers can optionally provide toolbar configurations and integrate with the library's architecture.
455
+
456
+ ### Event-Driven Toolbar Updates
457
+
458
+ Custom renderers can implement real-time toolbar updates using Vue 3's reactivity system:
459
+
460
+ **Benefits:**
461
+ - **Real-time updates**: Toolbar reflects state changes immediately via Vue reactivity
462
+ - **Better performance**: No polling overhead, leverages Vue's efficient change detection
463
+ - **Type-safe**: Full TypeScript support with proper interfaces
464
+
465
+ **Implementation:**
466
+
467
+ ```vue
468
+ <script setup lang="ts">
469
+ import { ref, computed, watch } from 'vue';
470
+ import { ChevronLeft, ChevronRight } from 'lucide-vue-next';
471
+ import type { ToolbarGroup } from '@eternalheart/vue-file-preview';
472
+
473
+ interface Props {
474
+ url: string;
475
+ }
476
+
477
+ const props = defineProps<Props>();
478
+ const emit = defineEmits<{
479
+ pageChange: [current: number, total: number];
480
+ }>();
481
+
482
+ const currentPage = ref(1);
483
+ const totalPages = ref(10);
484
+
485
+ // Emit page changes
486
+ watch([currentPage, totalPages], () => {
487
+ emit('pageChange', currentPage.value, totalPages.value);
488
+ });
489
+
490
+ const getToolbarGroups = (): ToolbarGroup[] => [
491
+ {
492
+ items: [
493
+ {
494
+ type: 'button',
495
+ icon: ChevronLeft,
496
+ tooltip: 'Previous Page',
497
+ action: () => currentPage.value = Math.max(1, currentPage.value - 1),
498
+ disabled: currentPage.value <= 1
499
+ },
500
+ {
501
+ type: 'text',
502
+ content: `${currentPage.value} / ${totalPages.value}`,
503
+ minWidth: '4rem'
504
+ },
505
+ {
506
+ type: 'button',
507
+ icon: ChevronRight,
508
+ tooltip: 'Next Page',
509
+ action: () => currentPage.value = Math.min(totalPages.value, currentPage.value + 1),
510
+ disabled: currentPage.value >= totalPages.value
511
+ }
512
+ ]
513
+ }
514
+ ];
515
+
516
+ // Expose for parent component
517
+ defineExpose({
518
+ getToolbarGroups
519
+ });
520
+ </script>
521
+
522
+ <template>
523
+ <div>Your custom renderer UI</div>
524
+ </template>
525
+ ```
526
+
527
+ **Main component usage:**
528
+
529
+ ```vue
530
+ <script setup>
531
+ import { CustomRenderer } from './CustomRenderer.vue';
532
+
533
+ const files = [
534
+ { name: 'custom.xyz', type: 'application/custom', url: '/path/to/file' }
535
+ ];
536
+ </script>
537
+
538
+ <template>
539
+ <FilePreviewModal
540
+ :files="files"
541
+ :custom-renderers="[
542
+ {
543
+ test: (file) => file.type === 'application/custom',
544
+ render: () => CustomRenderer
545
+ }
546
+ ]"
547
+ />
548
+ </template>
549
+ ```
550
+
551
+ The main component automatically tracks reactive changes in `getToolbarGroups()` via Vue's reactivity system. No manual subscription needed.
552
+
553
+ ### Renderer Lazy Loading
554
+
555
+ All built-in renderers use code-splitting via `defineAsyncComponent` to minimize the main bundle size and improve initial load performance.
556
+
557
+ **Architecture:**
558
+
559
+ - **Registration**: Renderers register in `src/renderers/lazy.ts` using `defineAsyncComponent` wrappers
560
+ - **Loading**: Each renderer is a separate chunk, loaded on-demand when needed
561
+ - **Fallback**: `RendererLoading` component handles the loading state
562
+
563
+ Each renderer is emitted as a separate async chunk and loaded only when needed.
564
+
565
+ **Implementation Example:**
566
+
567
+ ```ts
568
+ // src/renderers/lazy.ts
569
+ import { defineAsyncComponent } from 'vue';
570
+
571
+ const wrap = (loader: () => Promise<any>) =>
572
+ defineAsyncComponent({
573
+ loader,
574
+ loadingComponent: RendererLoading,
575
+ delay: 0
576
+ });
577
+
578
+ export const CustomRenderer = wrap(() => import('./Custom/index.vue'));
579
+ ```
580
+
581
+ ```vue
582
+ <!-- src/FilePreviewContent.vue -->
583
+ <script setup>
584
+ import { CustomRenderer } from './renderers/lazy'; // ✅ Lazy import
585
+ // NOT: import CustomRenderer from './renderers/Custom/index.vue'; // ❌ Direct import breaks code-splitting
586
+ </script>
587
+
588
+ <template>
589
+ <CustomRenderer
590
+ v-if="fileType === 'custom'"
591
+ ref="rendererRef"
592
+ :url="currentFile.url"
593
+ />
594
+ </template>
595
+ ```
596
+
597
+ **For Custom Renderers:**
598
+
599
+ If you want your custom renderer to benefit from code-splitting, use the same pattern:
600
+
601
+ ```vue
602
+ <script setup>
603
+ import { defineAsyncComponent } from 'vue';
604
+
605
+ const MyCustomRenderer = defineAsyncComponent(() => import('./MyCustomRenderer.vue'));
606
+
607
+ const files = [...];
608
+ </script>
609
+
610
+ <template>
611
+ <FilePreviewModal
612
+ :files="files"
613
+ :custom-renderers="[
614
+ {
615
+ test: (file) => file.type === 'application/custom',
616
+ render: () => MyCustomRenderer
617
+ }
618
+ ]"
619
+ />
620
+ </template>
621
+ ```
622
+
623
+ ### i18n Integration
624
+
625
+ Custom renderers can access the library's i18n system via the `useTranslator()` composable for consistent multilingual support.
626
+
627
+ **Architecture:**
628
+
629
+ - **Dictionary Source**: `file-preview-core/src/i18n/messages/` (zh-CN.ts, en-US.ts)
630
+ - **No Hardcoding**: All user-visible text must use translation keys
631
+ - **Automatic Locale Switching**: Follows the `locale` prop passed to `FilePreviewModal`
632
+
633
+ **Usage in Custom Renderers:**
634
+
635
+ ```vue
636
+ <script setup lang="ts">
637
+ import { ref } from 'vue';
638
+ import { useTranslator } from '@eternalheart/vue-file-preview';
639
+
640
+ interface Props {
641
+ url: string;
642
+ }
643
+
644
+ const props = defineProps<Props>();
645
+ const { t } = useTranslator();
646
+ const error = ref<string | null>(null);
647
+ </script>
648
+
649
+ <template>
650
+ <div v-if="error" class="vfp-text-fg-primary">
651
+ {{ t('custom.load_failed') }}: {{ error }}
652
+ </div>
653
+ <div v-else>
654
+ <button>{{ t('common.download') }}</button>
655
+ <span>{{ t('custom.loading') }}</span>
656
+ </div>
657
+ </template>
658
+ ```
659
+
660
+ **Note on Usage:**
661
+
662
+ - In `<template>`: Use `t('key')` directly (automatically unwrapped)
663
+ - In `<script>`: Use `t.value('key')` for imperative calls
664
+
665
+ **Adding Custom Translation Keys:**
666
+
667
+ For custom renderers, extend translations via the `messages` prop (do NOT modify source files in `node_modules`):
668
+
669
+ ```vue
670
+ <template>
671
+ <FilePreviewModal
672
+ :files="files"
673
+ locale="en-US"
674
+ :messages="{
675
+ 'en-US': {
676
+ 'custom.load_failed': 'Failed to load custom file',
677
+ 'custom.file_size': 'File size: {size} KB'
678
+ },
679
+ 'zh-CN': {
680
+ 'custom.load_failed': '自定义文件加载失败',
681
+ 'custom.file_size': '文件大小: {size} KB'
682
+ }
683
+ }"
684
+ :custom-renderers="[...]"
685
+ />
686
+ </template>
687
+ ```
688
+
689
+ **Guidelines:**
690
+ - Use `<scope>.<snake_name>` format (e.g., `custom.load_failed`, `custom.parse_error`)
691
+ - Provide translations for all enabled locales (`zh-CN` and `en-US`)
692
+ - Common keys already available: `common.loading`, `common.download`, `common.close`, `toolbar.*`
693
+
694
+ **Parameterized Translations:**
695
+
696
+ ```vue
697
+ <template>
698
+ <!-- Dictionary: 'custom.file_size': 'File size: {size} KB' -->
699
+ <span>{{ t('custom.file_size', { size: 1024 }) }}</span>
700
+ <!-- → "File size: 1024 KB" -->
701
+ </template>
702
+ ```
703
+
704
+ **Toolbar Integration:**
705
+
706
+ Toolbar items should also use translated strings:
707
+
708
+ ```ts
709
+ const getToolbarGroups = (): ToolbarGroup[] => [
710
+ {
711
+ items: [
712
+ {
713
+ type: 'button',
714
+ icon: Download,
715
+ tooltip: t.value('common.download'), // ✅ Translated (use .value in script)
716
+ action: handleDownload
717
+ }
718
+ ]
719
+ }
720
+ ];
721
+ ```
722
+
723
+ ### Theme Adaptation
724
+
725
+ Custom renderers must use semantic color tokens to support the library's `'auto' | 'dark' | 'light'` theme system.
726
+
727
+ **Semantic Token System:**
728
+
729
+ All colors are defined as CSS variables (`--fp-*`) and exposed via Tailwind classes with the `vfp-` prefix:
730
+
731
+ | Usage | Class | Description |
732
+ |-------|-------|-------------|
733
+ | **Text (fg)** | | |
734
+ | Primary text | `vfp-text-fg-primary` | Highest contrast |
735
+ | Body text | `vfp-text-fg-secondary` | Default text |
736
+ | Secondary text | `vfp-text-fg-tertiary` | Captions, counters |
737
+ | Muted text | `vfp-text-fg-muted` | Placeholders |
738
+ | Disabled text | `vfp-text-fg-disabled` | Disabled buttons |
739
+ | **Background (surface)** | | |
740
+ | Surface 1 | `vfp-bg-surface-1` | Cards, weakest |
741
+ | Surface 2 | `vfp-bg-surface-2` | Hover states |
742
+ | Surface 3 | `vfp-bg-surface-3` | Emphasis |
743
+ | Toolbar | `vfp-bg-surface-toolbar` | Top toolbar |
744
+ | **Borders** | | |
745
+ | Weak border | `vfp-border-line-weak` | Subtle lines |
746
+ | Standard border | `vfp-border-line` | Default borders |
747
+ | Strong border | `vfp-border-line-strong` | Emphasis |
748
+ | **Code** | | |
749
+ | Code background | `vfp-bg-code-bg` | Dark: #1e1e1e / Light: #f6f8fa |
750
+ | Code text | `vfp-text-code-fg` | Follows theme |
751
+ | **Accent** | | |
752
+ | Accent background | `vfp-bg-accent` | Primary buttons |
753
+ | Accent hover | `vfp-bg-accent-hover` | Hover state |
754
+
755
+ **✅ Correct Usage:**
756
+
757
+ ```vue
758
+ <template>
759
+ <div class="vfp-bg-surface-1 vfp-border vfp-border-line-weak vfp-rounded">
760
+ <h2 class="vfp-text-fg-primary vfp-text-lg">Title</h2>
761
+ <p class="vfp-text-fg-secondary">Body text</p>
762
+ <button class="vfp-bg-surface-2 hover:vfp-bg-surface-3 vfp-text-fg-primary">
763
+ Click me
764
+ </button>
765
+ <pre class="vfp-bg-code-bg vfp-text-code-fg">{{ code }}</pre>
766
+ </div>
767
+ </template>
768
+ ```
769
+
770
+ **For `<style scoped>` blocks**, use CSS variables:
771
+
772
+ ```vue
773
+ <style scoped>
774
+ .my-block {
775
+ color: var(--fp-fg-primary);
776
+ background: var(--fp-surface-2);
777
+ border: 1px solid var(--fp-line);
778
+ }
779
+
780
+ .my-code {
781
+ background: var(--fp-code-bg);
782
+ color: var(--fp-code-fg);
783
+ }
784
+ </style>
785
+ ```
786
+
787
+ **❌ Incorrect Usage (DO NOT USE):**
788
+
789
+ ```vue
790
+ <!-- ❌ Literal color classes — breaks theme switching -->
791
+ <div class="vfp-text-white/90 vfp-bg-white/10 vfp-border-white/15">
792
+ <div class="vfp-text-gray-700 vfp-bg-gray-100">
793
+
794
+ <!-- ❌ Inline literal colors -->
795
+ <div :style="{ color: '#ffffff', background: '#1f2937' }">
796
+
797
+ <!-- ❌ Hardcoded dark-only colors in scoped style -->
798
+ <style scoped>
799
+ .foo { color: rgba(255, 255, 255, 0.75); } /* Use var(--fp-fg-secondary) */
800
+ .foo { background: #1e1e1e; } /* Use var(--fp-code-bg) */
801
+ </style>
802
+ ```
803
+
804
+ **Theme-Aware Third-Party Libraries:**
805
+
806
+ For libraries with theme props (e.g., `shiki`), use `useResolvedTheme()`:
807
+
808
+ ```vue
809
+ <script setup lang="ts">
810
+ import { ref, watch } from 'vue';
811
+ import { codeToHtml } from 'shiki';
812
+ import { useResolvedTheme } from '@eternalheart/vue-file-preview';
813
+
814
+ const props = defineProps<{ code: string; lang: string }>();
815
+ const resolvedTheme = useResolvedTheme(); // Ref<'dark' | 'light'>
816
+ const highlighted = ref('');
817
+
818
+ const highlightCode = async () => {
819
+ highlighted.value = await codeToHtml(props.code, {
820
+ lang: props.lang,
821
+ theme: resolvedTheme.value === 'light' ? 'github-light' : 'dark-plus'
822
+ });
823
+ };
824
+
825
+ // Re-highlight when theme changes
826
+ watch(resolvedTheme, highlightCode, { immediate: true });
827
+ </script>
828
+
829
+ <template>
830
+ <div v-html="highlighted"></div>
831
+ </template>
832
+ ```
833
+
834
+ **Testing:**
835
+
836
+ Always test your custom renderer in both Light and Dark themes:
837
+
838
+ ```vue
839
+ <FilePreviewModal
840
+ :files="files"
841
+ theme="light" // Switch between 'light', 'dark', 'auto'
842
+ :custom-renderers="[...]"
843
+ />
844
+ ```
845
+
846
+ Verify:
847
+ - Text is readable in both themes (no white-on-white or black-on-black)
848
+ - Borders and dividers are visible
849
+ - Hover states have sufficient contrast
850
+ - Code blocks follow theme (not always dark)
851
+
852
+ ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/2328.svg" width="20" height="20" alt="⌨️" /> Keyboard Shortcuts
853
+
854
+ - `ESC` - Close preview
855
+ - `←` - Previous file
856
+ - `→` - Next file
857
+ - `Home` - First file
858
+ - `End` - Last file
859
+ - `Mouse Wheel` - Zoom image (image preview only)
860
+
861
+ ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4da.svg" width="20" height="20" alt="📚" /> Documentation
862
+
863
+ - [Full Documentation](https://wh131462.github.io/file-preview/docs/)
864
+ - [Vue Demo](https://wh131462.github.io/file-preview/vue/)
865
+ - [React Demo](https://wh131462.github.io/file-preview/)
866
+
867
+ ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f6e0.svg" width="20" height="20" alt="🛠️" /> Development
868
+
869
+ ```bash
870
+ # Clone repository
871
+ git clone https://github.com/wh131462/file-preview.git
872
+
873
+ # Install dependencies
874
+ pnpm install
875
+
876
+ # Start dev server (Vue demo app)
877
+ pnpm dev:vue-example
878
+
879
+ # Build library
880
+ pnpm build:vue
881
+ ```
882
+
883
+ ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f4c4.svg" width="20" height="20" alt="📄" /> License
884
+
885
+ [MIT](./LICENSE) © [EternalHeart](https://github.com/wh131462)
886
+
887
+ ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f91d.svg" width="20" height="20" alt="🤝" /> Contributing
888
+
889
+ Issues and Pull Requests are welcome!
890
+
891
+ ## <img src="https://cdn.jsdelivr.net/gh/twitter/twemoji@latest/assets/svg/1f517.svg" width="20" height="20" alt="🔗" /> Links
892
+
893
+ - [GitHub](https://github.com/wh131462/file-preview)
894
+ - [npm](https://www.npmjs.com/package/@eternalheart/vue-file-preview)
895
+ - [Vue Demo](https://wh131462.github.io/file-preview/vue/)
896
+ - [Issue Tracker](https://github.com/wh131462/file-preview/issues)