0%

通用文件预览组件——Web Components 实现方案

最近在做项目时遇到文件预览的需求,每次都要写一堆重复的预览逻辑。正好 Web Components 技术已经相当成熟,决定封装一个通用的文件预览组件。没想到做出来效果还不错,既能在 Vue 项目中用,也能在 React 项目中用,简直是跨框架的神器!

Web Components 简介

  Web Components 是一套不同的 Web API,允许我们创建可重用的自定义元素,这些元素可以封装其功能并在我们的应用程序中独立使用。Web Components 主要由三个核心技术组成:Custom Elements、Shadow DOM 和 Html Templates。这些技术的结合使得我们可以创建完全封装的、可重用的组件,而不依赖任何特定的框架。

  相比于 React、Vue 等现代框架的组件,Web Components 的最大优势在于它的通用性。一个 Web Component 可以在任何支持 Web Components 的环境中使用,无论是 React 应用、Vue 应用、原生 Javascript 应用还是其他任何现代 Web 环境。这对于构建通用的 UI 组件库、跨框架共享组件等场景特别有用。

Web Components 的核心技术

  1. Custom Elements: 定义自定义 Html 元素
  2. Shadow DOM: 封装组件的样式和标记,避免样式冲突
  3. Html Templates: 定义组件的模板结构
  4. ES Modules: 现代 Javascript 模块系统

通用文件预览组件设计

项目结构规划

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 项目结构
// components/
// file-preview/
// file-preview.JS # 主组件类
// file-preview.Css # 组件样式
// templates.JS # 模板定义
// file-handlers/ # 不同文件类型的处理器
// image-handler.JS
// pdf-handler.JS
// text-handler.JS
// video-handler.JS
// audio-handler.JS
// utils.JS # 工具函数
// index.JS # 组件注册入口

基础组件类实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
// components/file-preview/file-preview.JS
class FilePreview extends HtmlElement {
constructor() {
super();

// 创建 shadow root 以隔离样式和 DOM
this.shadow = this.attachShadow({ mode: 'open' });

// 绑定事件处理器 this.handleClose = this.handleClose.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);

// 初始化状态 this.state = {
isOpen: false,
currentFile: null,
currentIndex: 0,
files: [],
loading: false,
error: null
};
}

static get observedAttributes() {
return ['src', 'files', 'visible'];
}

connectedCallback() {
this.render();
this.setupEventListeners();
}

disconnectedCallback() {
this.cleanupEventListeners();
}

attributeChangedCallback(name, oldValue, newValue) {
if (oldValue !== newValue) {
switch (name) {
case 'src':
this.handleSrcChange(newValue);
break;
case 'files':
this.handleFilesChange(newValue);
break;
case 'visible':
this.toggleVisibility(newValue === 'true');
break;
}
}
}

// 渲染组件 render() {
this.shadow.innerHTML = this.getTemplate();
this.styleSheet = this.createStyleSheet();
this.shadow.adoptedStyleSheets = [this.styleSheet];

// 获取关键 DOM 元素的引用 this.overlay = this.shadow.querySelector('.file-preview-overlay');
this.container = this.shadow.querySelector('.file-preview-container');
this.content = this.shadow.querySelector('.file-preview-content');
this.closeBtn = this.shadow.querySelector('.file-preview-close');
this.prevBtn = this.shadow.querySelector('.file-preview-prev');
this.nextBtn = this.shadow.querySelector('.file-preview-next');
this.info = this.shadow.querySelector('.file-preview-info');
this.loader = this.shadow.querySelector('.file-preview-loader');
}

// 获取模板 Html
getTemplate() {
return `
<style>${this.getCss()}</style>
<div class="file-preview-overlay hidden">
<div class="file-preview-container">
<button class="file-preview-close" aria-label="关闭">×</button>

<div class="file-preview-navigation">
<button class="file-preview-prev" aria-label="上一个">&lt;</button>
<button class="file-preview-next" aria-label="下一个">&gt;</button>
</div>

<div class="file-preview-content">
<div class="file-preview-loader">Loading...</div>
<div class="file-preview-error"></div>
<div class="file-preview-placeholder">预览区域</div>
</div>

<div class="file-preview-info">
<span class="file-name"></span>
<span class="file-size"></span>
<span class="file-index"></span>
</div>
</div>
</div>
`;
}

// 获取 Css 样式 getCss() {
return `
:host {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999;
}

.file-preview-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
visibility: hidden;
transition: opacity 0.3s ease, visibility 0.3s ease;
}

.file-preview-overlay.visible {
opacity: 1;
visibility: visible;
}

.file-preview-container {
position: relative;
width: 90%;
max-width: 1200px;
max-height: 90vh;
background: white;
border-radius: 8px;
overflow: hidden;
}

.file-preview-content {
min-height: 400px;
display: flex;
align-items: center;
justify-content: center;
position: relative;
}

.file-preview-content img,
.file-preview-content video,
.file-preview-content iframe {
max-width: 100%;
max-height: 70vh;
object-fit: contain;
}

.file-preview-close {
position: absolute;
top: 15px;
right: 15px;
background: rgba(0, 0, 0, 0.5);
color: white;
border: none;
width: 40px;
height: 40px;
border-radius: 50%;
font-size: 24px;
cursor: pointer;
z-index: 10;
}

.file-preview-navigation {
position: absolute;
top: 50%;
width: 100%;
display: flex;
justify-content: space-between;
padding: 0 20px;
transform: translateY(-50%);
z-index: 10;
}

.file-preview-navigation button {
background: rgba(0, 0, 0, 0.5);
color: white;
border: none;
width: 50px;
height: 50px;
border-radius: 50%;
font-size: 24px;
cursor: pointer;
}

.file-preview-info {
padding: 10px 20px;
background: #f5f5f5;
display: flex;
justify-content: space-between;
font-size: 14px;
color: #666;
}

.file-preview-loader {
display: none;
font-size: 18px;
color: #666;
}

.file-preview-error {
display: none;
color: #ff4444;
padding: 20px;
text-align: center;
}

.hidden {
display: none;
}

.file-preview-overlay.hidden {
display: none;
}
`;
}

// 创建样式表 createStyleSheet() {
const styleSheet = new CssStyleSheet();
styleSheet.replaceSync(this.getCss());
return styleSheet;
}

// 设置事件监听器 setupEventListeners() {
if (this.closeBtn) {
this.closeBtn.addEventListener('click', this.handleClose);
}

if (this.prevBtn) {
this.prevBtn.addEventListener('click', () => this.showPreviousFile());
}

if (this.nextBtn) {
this.nextBtn.addEventListener('click', () => this.showNextFile());
}

// 键盘事件 document.addEventListener('keydown', this.handleKeyDown);
}

// 清理事件监听器 cleanupEventListeners() {
if (this.closeBtn) {
this.closeBtn.removeEventListener('click', this.handleClose);
}

if (this.prevBtn) {
this.prevBtn.removeEventListener('click', this.showPreviousFile);
}

if (this.nextBtn) {
this.nextBtn.removeEventListener('click', this.showNextFile);
}

document.removeEventListener('keydown', this.handleKeyDown);
}

// 事件处理器 handleClose() {
this.hide();
this.dispatchEvent(new CustomEvent('file-preview-close', {
bubbles: true,
composed: true
}));
}

handleKeyDown(event) {
if (!this.state.isOpen) return;

switch (event.key) {
case 'Escape':
this.handleClose();
break;
case 'ArrowLeft':
this.showPreviousFile();
break;
case 'ArrowRight':
this.showNextFile();
break;
}
}

// 显示组件 show() {
this.state.isOpen = true;
this.overlay.classList.add('visible');
this.overlay.classList.remove('hidden');
document.body.style.overflow = 'hidden';
}

// 隐藏组件 hide() {
this.state.isOpen = false;
this.overlay.classList.remove('visible');
setTimeout(() => {
this.overlay.classList.add('hidden');
}, 300);
document.body.style.overflow = '';
this.clearContent();
}

// 切换可见性 toggleVisibility(visible) {
if (visible) {
this.show();
} else {
this.hide();
}
}

// 文件处理相关方法 handleSrcChange(src) {
if (src) {
this.state.files = [{ src, name: this.getFileName(src), size: 0 }];
this.state.currentIndex = 0;
this.show();
this.renderFile(0);
}
}

handleFilesChange(filesString) {
try {
const files = Json.parse(filesString);
if (Array.isArray(files)) {
this.state.files = files.map(file => ({
src: file.src || file.url,
name: file.name || this.getFileName(file.src || file.url),
size: file.size || 0,
type: file.type || this.getFileType(file.src || file.url)
}));

if (this.state.files.length > 0) {
this.show();
this.renderFile(0);
}
}
} catch (error) {
console.error('解析文件列表失败:', error);
}
}

// 获取文件名 getFileName(url) {
try {
const path = new URL(url).pathname;
return path.split('/').pop() || 'unknown';
} catch {
return 'unknown';
}
}

// 获取文件类型 getFileType(url) {
try {
const ext = url.split('.').pop().toLowerCase();
const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
const videoExts = ['mp4', 'webm', 'ogg', 'mov', 'avi'];
const audioExts = ['mp3', 'wav', 'ogg', 'flac'];
const textExts = ['txt', 'md', 'csv', 'Json', 'Xml'];

if (imageExts.includes(ext)) return 'image';
if (videoExts.includes(ext)) return 'video';
if (audioExts.includes(ext)) return 'audio';
if (textExts.includes(ext)) return 'text';

return ext;
} catch {
return 'unknown';
}
}

// 渲染文件 renderFile(index) {
if (index < 0 || index >= this.state.files.length) return;

this.state.currentIndex = index;
const file = this.state.files[index];
this.state.currentFile = file;

this.showLoader();

// 根据文件类型选择渲染方式 const fileType = this.getFileType(file.src);

switch (fileType) {
case 'image':
this.renderImage(file);
break;
case 'video':
this.renderVideo(file);
break;
case 'audio':
this.renderAudio(file);
break;
case 'pdf':
this.renderPdf(file);
break;
case 'text':
this.renderText(file);
break;
default:
this.renderGeneric(file);
break;
}

this.updateFileInfo();
}

// 各种文件类型的渲染方法 renderImage(file) {
const img = document.createElement('img');
img.src = file.src;
img.alt = file.name;

img.onload = () => {
this.clearContent();
this.content.appendChild(img);
this.hideLoader();
};

img.onerror = () => {
this.showError('无法加载图片');
this.hideLoader();
};
}

renderVideo(file) {
const video = document.createElement('video');
video.controls = true;
video.src = file.src;
video.autoplay = false;
video.loop = false;

video.onloadeddata = () => {
this.clearContent();
this.content.appendChild(video);
this.hideLoader();
};

video.onerror = () => {
this.showError('无法加载视频');
this.hideLoader();
};
}

renderAudio(file) {
const audio = document.createElement('audio');
audio.controls = true;
audio.src = file.src;

audio.onloadeddata = () => {
this.clearContent();
this.content.appendChild(audio);
this.hideLoader();
};

audio.onerror = () => {
this.showError('无法加载音频');
this.hideLoader();
};
}

renderPdf(file) {
// 如果浏览器支持 PDF 直接预览 if (this.supportsPdfEmbed()) {
const iframe = document.createElement('iframe');
iframe.src = file.src;
iframe.width = '100%';
iframe.height = '600px';
iframe.style.border = 'none';

this.clearContent();
this.content.appendChild(iframe);
this.hideLoader();
} else {
// 不支持时提供下载链接 this.renderGeneric(file);
}
}

renderText(file) {
// 为了安全起见,这里不直接加载外部文本文件
// 实际应用中可能需要从服务器获取文本内容 this.showError('文本文件预览功能待实现');
this.hideLoader();
}

renderGeneric(file) {
const div = document.createElement('div');
div.className = 'file-preview-generic';
div.innerHTML = `
<div style="text-align: center; padding: 50px;">
<h3>文件预览</h3>
<p>文件名: ${file.name}</p>
<p>类型: ${this.getFileType(file.src)}</p>
<p>大小: ${this.formatFileSize(file.size)}</p>
<button onclick="window.open('${file.src}', '_blank')"
style="margin-top: 20px; padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">
下载文件
</button>
</div>
`;

this.clearContent();
this.content.appendChild(div);
this.hideLoader();
}

// 工具方法 supportsPdfEmbed() {
const embed = document.createElement('embed');
return embed.type === 'application/pdf';
}

showLoader() {
if (this.loader) {
this.loader.style.display = 'block';
}
}

hideLoader() {
if (this.loader) {
this.loader.style.display = 'none';
}
}

showError(message) {
const errorEl = this.shadow.querySelector('.file-preview-error');
if (errorEl) {
errorEl.textContent = message;
errorEl.style.display = 'block';
}
}

clearContent() {
this.content.innerHTML = '<div class="file-preview-placeholder">预览区域</div>';
const errorEl = this.shadow.querySelector('.file-preview-error');
if (errorEl) {
errorEl.style.display = 'none';
}
}

updateFileInfo() {
const file = this.state.files[this.state.currentIndex];
const nameEl = this.shadow.querySelector('.file-name');
const sizeEl = this.shadow.querySelector('.file-size');
const indexEl = this.shadow.querySelector('.file-index');

if (nameEl) nameEl.textContent = file.name;
if (sizeEl) sizeEl.textContent = this.formatFileSize(file.size);
if (indexEl) indexEl.textContent = `${this.state.currentIndex + 1}/${this.state.files.length}`;

// 显示/隐藏导航按钮 if (this.prevBtn) {
this.prevBtn.style.display = this.state.files.length > 1 ? 'block' : 'none';
}
if (this.nextBtn) {
this.nextBtn.style.display = this.state.files.length > 1 ? 'block' : 'none';
}
}

formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 文件导航方法 showPreviousFile() {
if (this.state.files.length <= 1) return;

const newIndex = this.state.currentIndex > 0
? this.state.currentIndex - 1
: this.state.files.length - 1;

this.renderFile(newIndex);
}

showNextFile() {
if (this.state.files.length <= 1) return;

const newIndex = this.state.currentIndex < this.state.files.length - 1
? this.state.currentIndex + 1
: 0;

this.renderFile(newIndex);
}
}

// 定义自定义元素 customElements.define('file-preview', FilePreview);

文件类型处理器模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// components/file-preview/file-handlers/image-handler.JS
export class ImageHandler {
static async load(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = src;
});
}

static getMetadata(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
resolve({
width: img.naturalWidth,
height: img.naturalHeight,
type: 'image',
size: 0 // 图片大小需要另外获取
});
};
img.onerror = reject;
img.src = src;
});
}

static isSupported() {
return true;
}
}

// components/file-preview/file-handlers/pdf-handler.JS
export class PdfHandler {
static isSupported() {
// 检查是否支持 PDF 预览 return !!document.createElement('embed').type;
}

static async load(src) {
if (this.isSupported()) {
return { src, type: 'pdf' };
} else {
throw new Error('浏览器不支持 PDF 预览');
}
}

// 使用 PDF.JS 进行更高级的 PDF 预览 static async loadWithPdfJs(src) {
// 需要引入 PDF.JS 库
// 这里只是示例 if (typeof pdfjsLib !== 'undefined') {
try {
const loadingTask = pdfjsLib.getDocument(src);
const pdf = await loadingTask.promise;
return pdf;
} catch (error) {
throw new Error('PDF 加载失败: ' + error.message);
}
} else {
throw new Error('未找到 PDF.JS 库');
}
}
}

// components/file-preview/file-handlers/text-handler.JS
export class TextHandler {
static async load(src) {
try {
const response = await fetch(src);
const text = await response.text();
return { content: text, type: 'text' };
} catch (error) {
throw new Error('文本文件加载失败: ' + error.message);
}
}

static isSupported() {
return true;
}
}

// components/file-preview/file-handlers/video-handler.JS
export class VideoHandler {
static isSupported() {
return !!document.createElement('video').canPlayType;
}

static async load(src) {
return new Promise((resolve, reject) => {
const video = document.createElement('video');
video.preload = 'metadata';

video.onloadedmetadata = () => {
resolve({
duration: video.duration,
width: video.videoWidth,
height: video.videoHeight,
type: 'video'
});
};

video.onerror = () => {
reject(new Error('视频文件无法播放'));
};

video.src = src;
});
}
}

组件工具函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// components/file-preview/utils.JS
export class FileUtils {
static getMimeType(fileName) {
const ext = fileName.split('.').pop().toLowerCase();
const mimeTypes = {
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'png': 'image/png',
'gif': 'image/gif',
'bmp': 'image/bmp',
'webp': 'image/webp',
'mp4': 'video/mp4',
'webm': 'video/webm',
'ogg': 'video/ogg',
'mp3': 'audio/mpeg',
'wav': 'audio/wav',
'pdf': 'application/pdf',
'txt': 'text/plain',
'Json': 'application/Json'
};

return mimeTypes[ext] || 'application/octet-stream';
}

static getFileExtension(mimeType) {
const extensions = {
'image/jpeg': 'jpg',
'image/png': 'png',
'image/gif': 'gif',
'video/mp4': 'mp4',
'audio/mpeg': 'mp3',
'application/pdf': 'pdf',
'text/plain': 'txt'
};

return extensions[mimeType] || 'bin';
}

static async getFileSize(url) {
try {
const response = await fetch(url, { method: 'HEAD' });
const size = response.headers.get('Content-Length');
return parseInt(size) || 0;
} catch {
return 0;
}
}

static isImageUrl(url) {
const imageRegex = /\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i;
return imageRegex.test(url);
}

static isVideoUrl(url) {
const videoRegex = /\.(mp4|webm|ogg|mov|avi|wmv|flv|mkv)$/i;
return videoRegex.test(url);
}

static isAudioUrl(url) {
const audioRegex = /\.(mp3|wav|ogg|flac|m4a)$/i;
return audioRegex.test(url);
}

static isPdfUrl(url) {
return /\.pdf$/i.test(url);
}
}

export class DomUtils {
static createElement(tag, attrs = {}, children = []) {
const el = document.createElement(tag);

Object.keys(attrs).forEach(key => {
if (key.startsWith('on')) {
// 事件处理器 el.addEventListener(key.substring(2).toLowerCase(), attrs[key]);
} else if (key === 'className') {
el.className = attrs[key];
} else {
el.setAttribute(key, attrs[key]);
}
});

children.forEach(child => {
if (typeof child === 'string') {
el.appendChild(document.createTextNode(child));
} else {
el.appendChild(child);
}
});

return el;
}

static fadeIn(element, duration = 300) {
return new Promise(resolve => {
element.style.opacity = '0';
element.style.transition = `opacity ${duration}ms ease-in-out`;

setTimeout(() => {
element.style.opacity = '1';
}, 10);

setTimeout(() => {
resolve();
}, duration);
});
}

static fadeOut(element, duration = 300) {
return new Promise(resolve => {
element.style.transition = `opacity ${duration}ms ease-in-out`;
element.style.opacity = '0';

setTimeout(() => {
resolve();
}, duration);
});
}
}

组件入口和注册

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// components/file-preview/index.JS
import { FilePreview } from './file-preview.JS';
import { FileUtils, DomUtils } from './utils.JS';
import { ImageHandler } from './file-handlers/image-handler.JS';
import { PdfHandler } from './file-handlers/pdf-handler.JS';
import { VideoHandler } from './file-handlers/video-handler.JS';
import { TextHandler } from './file-handlers/text-handler.JS';

// 确保 DOM 加载完成后注册组件 if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
registerFilePreviewComponent();
});
} else {
registerFilePreviewComponent();
}

function registerFilePreviewComponent() {
// 检查是否已经注册 if (!customElements.get('file-preview')) {
customElements.define('file-preview', FilePreview);
}
}

// 提供工厂函数创建实例 export function createFilePreview(options = {}) {
const preview = document.createElement('file-preview');

if (options.files) {
preview.setAttribute('files', Json.stringify(options.files));
}

if (options.src) {
preview.setAttribute('src', options.src);
}

if (options.visible !== undefined) {
preview.setAttribute('visible', options.visible.toString());
}

return preview;
}

// 导出工具类 export {
FilePreview,
FileUtils,
DomUtils,
ImageHandler,
PdfHandler,
VideoHandler,
TextHandler
};

// 全局命名空间导出(兼容非 ESM 环境)
window.FilePreviewComponents = {
createFilePreview,
FilePreview,
FileUtils,
DomUtils
};

使用示例

基本 Html 使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE Html>
<Html>
<head>
<title>File Preview Demo</title>
</head>
<body>
<h1>文件预览组件演示</h1>

<!-- 图片预览 -->
<button onclick="showSingleImage()">预览单张图片</button>

<!-- 文件列表预览 -->
<button onclick="showFileList()">预览文件列表</button>

<!-- 文件预览组件 -->
<file-preview id="preview"></file-preview>

<script type="module">
import { createFilePreview } from './components/file-preview/index.JS';

// 预览单张图片 function showSingleImage() {
const preview = document.querySelector('file-preview');
preview.setAttribute('src', 'https://example.com/image.jpg');
preview.setAttribute('visible', 'true');
}

// 预览文件列表 function showFileList() {
const files = [
{ src: 'https://example.com/image1.jpg', name: 'image1.jpg', size: 1024000 },
{ src: 'https://example.com/image2.png', name: 'image2.png', size: 2048000 },
{ src: 'https://example.com/document.pdf', name: 'document.pdf', size: 5120000 }
];

const preview = document.querySelector('file-preview');
preview.setAttribute('files', Json.stringify(files));
preview.setAttribute('visible', 'true');
}

// 监听关闭事件 document.querySelector('file-preview').addEventListener('file-preview-close', () => {
console.log('预览已关闭');
});
</script>
</body>
</Html>

React 中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// React 组件包装器 import React, { useEffect, useRef } from 'React';

const FilePreviewWrapper = ({ files, visible, onClose, src }) => {
const ref = useRef(null);

useEffect(() => {
const previewEl = ref.current;

const handleEvents = () => {
if (onClose) {
const handleClose = () => onClose();
previewEl.addEventListener('file-preview-close', handleClose);

return () => {
previewEl.removeEventListener('file-preview-close', handleClose);
};
}
};

return handleEvents();
}, [onClose]);

useEffect(() => {
if (ref.current) {
if (src) {
ref.current.setAttribute('src', src);
}
if (files) {
ref.current.setAttribute('files', Json.stringify(files));
}
ref.current.setAttribute('visible', visible.toString());
}
}, [src, files, visible]);

return <file-preview ref={ref}></file-preview>;
};

// 使用示例 function MyApp() {
const [isVisible, setIsVisible] = useState(false);
const [currentFile, setCurrentFile] = useState('');

const files = [
{ src: 'image1.jpg', name: 'Image 1', size: 1024000 },
{ src: 'image2.jpg', name: 'Image 2', size: 2048000 }
];

return (
<div>
<button onClick={() => setIsVisible(true)}>打开预览</button>
<FilePreviewWrapper
files={files}
visible={isVisible}
onClose={() => setIsVisible(false)}
/>
</div>
);
}

Vue 中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<template>
<div>
<button @click="openPreview">打开预览</button>
<file-preview
ref="preview"
:files="files"
:visible="isVisible"
@file-preview-close="handleClose"
></file-preview>
</div>
</template>

<script>
export default {
name: 'FilePreviewDemo',
data() {
return {
isVisible: false,
files: [
{ src: 'image1.jpg', name: 'Image 1', size: 1024000 },
{ src: 'image2.jpg', name: 'Image 2', size: 2048000 }
]
};
},
mounted() {
// 确保 Web Component 已注册 if (!customElements.get('file-preview')) {
import('./components/file-preview/index.JS');
}
},
methods: {
openPreview() {
this.isVisible = true;
},
handleClose() {
this.isVisible = false;
}
}
};
</script>

高级功能实现

PDF 预览增强

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// enhanced-pdf-handler.JS
export class EnhancedPdfHandler {
constructor(pdfjsLib) {
this.pdfjsLib = pdfjsLib;
}

async renderPdf(canvasId, src, pageNum = 1) {
const canvas = document.getElementById(canvasId);
const ctx = canvas.getContext('2d');

try {
const loadingTask = this.pdfjsLib.getDocument(src);
const pdf = await loadingTask.promise;

const page = await pdf.getPage(pageNum);
const viewport = page.getViewport({ scale: 1.5 });

canvas.width = viewport.width;
canvas.height = viewport.height;

const renderContext = {
canvasContext: ctx,
viewport: viewport
};

await page.render(renderContext).promise;
return pdf.numPages;
} catch (error) {
console.error('PDF 渲染失败:', error);
throw error;
}
}

async getPdfMetadata(src) {
try {
const loadingTask = this.pdfjsLib.getDocument(src);
const pdf = await loadingTask.promise;

const metadata = await pdf.getMetadata();
const numPages = pdf.numPages;

return {
title: metadata.Title || 'Unknown',
author: metadata.Author || 'Unknown',
pages: numPages,
subject: metadata.Subject || '',

keywords: metadata.Keywords || ''
};
} catch (error) {
console.error('获取 PDF 元数据失败:', error);
return null;
}
}
}

视频预览增强

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// enhanced-video-handler.JS
export class EnhancedVideoHandler {
async createVideoPlayer(container, src, options = {}) {
const video = document.createElement('video');
video.src = src;
video.controls = true;
video.autoplay = options.autoplay || false;
video.loop = options.loop || false;
video.muted = options.muted || false;

// 设置播放速率 if (options.playbackRate) {
video.defaultPlaybackRate = options.playbackRate;
}

// 添加事件监听 if (options.onPlay) video.addEventListener('play', options.onPlay);
if (options.onPause) video.addEventListener('pause', options.onPause);
if (options.onEnded) video.addEventListener('ended', options.onEnded);

// 添加进度条 const progressBar = this.createProgressBar();
const timeDisplay = this.createTimeDisplay();

container.appendChild(video);
container.appendChild(progressBar);
container.appendChild(timeDisplay);

// 更新进度条 video.addEventListener('timeupdate', () => {
const percent = (video.currentTime / video.duration) * 100;
progressBar.style.background = `linear-gradient(to right, #007bff ${percent}%, #ddd ${percent}%)`;
timeDisplay.textContent = `${this.formatTime(video.currentTime)} / ${this.formatTime(video.duration)}`;
});

return video;
}

createProgressBar() {
const bar = document.createElement('div');
bar.style.cssText = `
height: 4px;
background: #ddd;
margin: 10px 0;
border-radius: 2px;
overflow: hidden;
cursor: pointer;
`;

const progress = document.createElement('div');
progress.style.cssText = `
height: 100%;
background: #007bff;
width: 0%;
`;

bar.appendChild(progress);
return bar;
}

createTimeDisplay() {
const display = document.createElement('div');
display.style.cssText = `
text-align: center;
font-size: 12px;
color: #666;
margin-bottom: 10px;
`;
display.textContent = '00:00 / 00:00';
return display;
}

formatTime(seconds) {
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
}

性能优化

虚拟滚动实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// virtual-scroll-handler.JS
export class VirtualScrollHandler {
constructor(container, items, renderItem) {
this.container = container;
this.items = items;
this.renderItem = renderItem;
this.itemHeight = 200; // 假设每个项目高度 this.visibleCount = Math.ceil(container.clientHeight / this.itemHeight) + 2;

this.setupContainer();
this.renderVisibleItems();
this.bindEvents();
}

setupContainer() {
this.container.style.cssText = `
height: ${this.items.length * this.itemHeight}px;
position: relative;
overflow-y: auto;
`;
}

renderVisibleItems() {
const scrollTop = this.container.scrollTop;
const startIndex = Math.floor(scrollTop / this.itemHeight);
const endIndex = Math.min(startIndex + this.visibleCount, this.items.length);

// 清除现有内容 this.container.innerHTML = '';

// 创建可视区域的项目 for (let i = startIndex; i < endIndex; i++) {
const itemDiv = this.renderItem(this.items[i]);
itemDiv.style.position = 'absolute';
itemDiv.style.top = `${i * this.itemHeight}px`;
itemDiv.style.left = '0';
itemDiv.style.width = '100%';
this.container.appendChild(itemDiv);
}
}

bindEvents() {
this.container.addEventListener('scroll', () => {
this.renderVisibleItems();
});
}
}

图片懒加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// lazy-load-handler.JS
export class LazyLoadHandler {
constructor() {
this.observer = new IntersectionObserver(
this.handleIntersection.bind(this),
{
rootMargin: '50px 0px', // 提前50px 开始加载 threshold: 0.01
}
);
}

observe(target) {
this.observer.observe(target);
}

handleIntersection(entries) {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
const src = img.dataset.src;

if (src) {
img.src = src;
img.removeAttribute('data-src');
this.observer.unobserve(img);
}
}
});
}

disconnect() {
this.observer.disconnect();
}
}

最佳实践

1. 组件封装最佳实践

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// components/file-preview/advanced-file-preview.JS
class AdvancedFilePreview extends FilePreview {
constructor() {
super();

// 添加额外功能 this.downloadManager = new DownloadManager();
this.shareManager = new ShareManager();
this.annotationManager = new AnnotationManager();
}

connectedCallback() {
super.connectedCallback();
this.setupAdvancedFeatures();
}

setupAdvancedFeatures() {
// 添加下载按钮 const downloadBtn = document.createElement('button');
downloadBtn.className = 'file-preview-download';
downloadBtn.innerHTML = '↓';
downloadBtn.title = '下载';
downloadBtn.addEventListener('click', () => this.downloadCurrentFile());

this.container.querySelector('.file-preview-container').appendChild(downloadBtn);
}

downloadCurrentFile() {
if (this.state.currentFile) {
this.downloadManager.download(this.state.currentFile.src, this.state.currentFile.name);
}
}

// 添加键盘快捷键 handleKeyDown(event) {
super.handleKeyDown(event);

switch (event.key) {
case 'd': // 下载当前文件 if (event.ctrlKey || event.metaKey) {
event.preventDefault();
this.downloadCurrentFile();
}
break;
case 's': // 分享 if (event.ctrlKey || event.metaKey) {
event.preventDefault();
this.shareCurrentFile();
}
break;
}
}

shareCurrentFile() {
if (this.state.currentFile && navigator.share) {
navigator.share({
title: this.state.currentFile.name,
text: `分享文件: ${this.state.currentFile.name}`,
url: this.state.currentFile.src
}).catch(console.error);
}
}
}

customElements.define('advanced-file-preview', AdvancedFilePreview);

2. 错误处理和安全性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 安全检查 class SecurityChecker {
static isValidUrl(url) {
try {
const parsedUrl = new URL(url);
return parsedUrl.protocol === 'https:' || parsedUrl.protocol === 'http:';
} catch {
return false;
}
}

static isSafeFileType(filename) {
const dangerousExts = ['.exe', '.bat', '.cmd', '.scr', '.vbs', '.JS', '.com'];
const ext = filename.toLowerCase().split('.').pop();
return !dangerousExts.includes('.' + ext);
}

static sanitizeFilename(filename) {
// 移除危险字符 return filename.replace(/[<>:"/\\|?*]/g, '_');
}
}

3. 性能监控

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 性能监控 class PerformanceMonitor {
constructor() {
this.metrics = {
loadTimes: [],
renderTimes: [],
memoryUsage: []
};
}

measureLoadTime(operation) {
const start = performance.now();
return operation().finally(() => {
const end = performance.now();
this.metrics.loadTimes.push(end - start);
});
}

measureRenderTime(renderFunction) {
const start = performance.now();
const result = renderFunction();
const end = performance.now();
this.metrics.renderTimes.push(end - start);
return result;
}

getAverageLoadTime() {
return this.metrics.loadTimes.reduce((a, b) => a + b, 0) / this.metrics.loadTimes.length;
}

getAverageRenderTime() {
return this.metrics.renderTimes.reduce((a, b) => a + b, 0) / this.metrics.renderTimes.length;
}
}

总结

  • Web Components 提供了真正的跨框架组件复用能力
  • Shadow DOM 有效隔离了组件的样式和行为
  • 文件预览组件应支持多种格式和丰富的交互功能
  • 性能优化是大型文件预览的关键考量
  • 安全性在文件处理中尤为重要
  • 虚拟滚动和懒加载可以显著提升大列表性能

用 Web Components 做了这个文件预览组件后,最大的感受就是真的可以一处开发,多处复用。以前为了兼容不同的前端框架,要写好几套组件,现在只需要一套就够了。虽然 Web Components 的学习曲线稍微陡峭一些,但一旦掌握后,开发效率提升明显。

扩展阅读

  • Web Components Official Documentation
  • Custom Elements Everywhere
  • Web Components Best Practices
  • Using Shadow DOM
  • Cross-framework Component Development

参考资料

  • Web Components Specification: https://www.w3.org/TR/components-intro/
  • Custom Elements: https://w3c.github.io/webcomponents/spec/custom/
  • Shadow DOM: https://w3c.github.io/webcomponents/spec/shadow/
  • PDF.JS Library: https://mozilla.github.io/pdf.JS/
bulb