vvvfs 0.2.4 → 0.2.6

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.
package/Media.ts CHANGED
@@ -1,880 +1,880 @@
1
- /**
2
- * @file Media.ts
3
- * @description 定义 <fs-img> / <fs-audio> / <fs-video> 共用的媒体元素基类 FsMedia,
4
- * 以及 <fs-audio> 与 <fs-video>;可直接显示 / 播放存储在 vvvfs 中的媒体文件。
5
- * src 为 http(s) 地址时,会先下载到 /home/.cache/cloud/<hostname>/<pathname> 再展示。
6
- * @author IFTC
7
- * @example
8
- * <fs-img src="/home/user/Pictures/logo.png" alt="Logo" width="120"></fs-img>
9
- * <fs-audio src="/home/user/Music/demo.mp3"></fs-audio>
10
- * <fs-video src="https://example.com/video/demo.mp4" width="320"></fs-video>
11
- */
12
- import type { VVVFS, VVVFSOptions } from "./index";
13
-
14
- /**
15
- * 监听的属性列表
16
- */
17
- const OBSERVED_ATTRIBUTES = [
18
- "src",
19
- "path",
20
- "dbname",
21
- "watch",
22
- "controls",
23
- "autoplay",
24
- "loop",
25
- "muted",
26
- "preload",
27
- "width",
28
- "height",
29
- "alt",
30
- ];
31
-
32
- /**
33
- * 默认数据库名
34
- */
35
- const DEFAULT_DB_NAME = "vvvfs";
36
-
37
- /**
38
- * 云端文件缓存根目录
39
- */
40
- const CLOUD_CACHE_ROOT = "/home/.cache/cloud";
41
-
42
- /**
43
- * 判断是否为云端地址(http / https / 协议相对 URL)
44
- * @param src 路径字符串
45
- */
46
- function isRemoteUrl(src: string): boolean {
47
- return /^(https?:\/\/|\/\/)/i.test(src.trim());
48
- }
49
-
50
- /**
51
- * 计算云端文件在 vvvfs 中的缓存路径
52
- * @description /home/.cache/cloud/<hostname>/<pathname>
53
- * @param src 云端地址
54
- */
55
- function cloudCachePath(src: string): string {
56
- const base =
57
- typeof globalThis.location?.href === "string"
58
- ? globalThis.location.href
59
- : "http://localhost/";
60
- const url = new URL(src, base);
61
- let pathname = url.pathname;
62
- try {
63
- pathname = decodeURIComponent(pathname);
64
- } catch {
65
- // 保留原始路径(百分号编码非法时)
66
- }
67
- // 去掉首尾多余的斜杠,避免拼接出重复分隔符
68
- pathname = pathname.replace(/^\/+|\/+$/g, "");
69
- return `${CLOUD_CACHE_ROOT}/${url.hostname}/${pathname}`;
70
- }
71
-
72
- /**
73
- * 会改变文件内容的操作类型(其余操作不会触发刷新)
74
- */
75
- const WATCH_MUTATIONS = new Set([
76
- "create",
77
- "write",
78
- "append",
79
- "rename",
80
- "delete",
81
- "move",
82
- "copy",
83
- "downloadFile",
84
- ]);
85
-
86
- /**
87
- * 刷新重试间隔(毫秒)
88
- * @description vvvfs 的 watch 在操作提交前触发,立即刷新会读到旧内容,
89
- * 因此延迟一段时间后重试,直到读到的文件发生变化。
90
- */
91
- const WATCH_RETRY_DELAY = 50;
92
-
93
- /**
94
- * 刷新最大重试次数
95
- */
96
- const WATCH_MAX_ATTEMPTS = 10;
97
-
98
- /**
99
- * 各元素共用的 Shadow DOM 基础样式
100
- */
101
- const SHADOW_BASE_STYLE = `
102
- :host {
103
- display: inline-block;
104
- }
105
- [hidden] {
106
- display: none;
107
- }
108
- slot {
109
- display: none;
110
- }
111
- :host([data-state="error"]) slot,
112
- :host([data-state="idle"]) slot {
113
- display: block;
114
- }
115
- `;
116
-
117
- /**
118
- * VVVFS 构造函数类型
119
- */
120
- type VVVFSConstructor = new (name?: string, options?: VVVFSOptions) => VVVFS;
121
-
122
- /**
123
- * 媒体元素类型(图片 / 音频 / 视频)
124
- */
125
- type MediaElement = HTMLImageElement | HTMLMediaElement;
126
-
127
- /**
128
- * 全局作用域(VVVFS 库会向 globalThis 挂载 VVVFS / vvvfs)
129
- */
130
- const globalScope = globalThis as typeof globalThis & {
131
- VVVFS?: VVVFSConstructor;
132
- vvvfs?: VVVFS;
133
- };
134
-
135
- /**
136
- * 已创建的 VVVFS 实例缓存(按数据库名共享,避免重复创建)
137
- */
138
- const instanceCache = new Map<string, VVVFS>();
139
-
140
- /**
141
- * 每个 (数据库名, 路径) 对应的元素集合,用于共享同一个 watch 监听器
142
- */
143
- const watcherSets = new Map<string, Set<FsMedia>>();
144
-
145
- /**
146
- * 生成监听键
147
- * @param dbname 数据库名
148
- * @param path 文件路径
149
- */
150
- function watchKey(dbname: string, path: string): string {
151
- return dbname + "\n" + path;
152
- }
153
-
154
- /**
155
- * 注册共享监听器
156
- * @description VVVFS 未提供取消监听的 API,因此同一个 (数据库名, 路径) 只注册一次,
157
- * 集合清空后监听器闭包仍保留在 VVVFS 内部(每个路径仅一个闭包,开销极小)。
158
- * @param el 目标元素
159
- * @param fs VVVFS 实例
160
- * @param dbname 数据库名
161
- * @param path 文件路径
162
- */
163
- function registerWatcher(el: FsMedia, fs: VVVFS, dbname: string, path: string): void {
164
- const key = watchKey(dbname, path);
165
- let set = watcherSets.get(key);
166
- if (!set) {
167
- set = new Set<FsMedia>();
168
- watcherSets.set(key, set);
169
- fs.watch(path, (type) => {
170
- // 只有修改类操作才需要刷新
171
- if (!WATCH_MUTATIONS.has(type)) return false;
172
- const current = watcherSets.get(key);
173
- if (!current || current.size === 0) return false;
174
- for (const target of current) {
175
- if (target.isConnected) target.scheduleWatchRefresh();
176
- }
177
- // 返回 false,避免取消触发监听的文件操作
178
- return false;
179
- });
180
- }
181
- set.add(el);
182
- }
183
-
184
- /**
185
- * 将元素从共享监听集合中移除
186
- * @param el 目标元素
187
- * @param dbname 数据库名
188
- * @param path 文件路径
189
- */
190
- function unregisterWatcher(el: FsMedia, dbname: string, path: string): void {
191
- const key = watchKey(dbname, path);
192
- const set = watcherSets.get(key);
193
- if (!set) return;
194
- set.delete(el);
195
- if (set.size === 0) watcherSets.delete(key);
196
- }
197
-
198
- /**
199
- * load 事件详情
200
- */
201
- export interface FsMediaLoadDetail {
202
- /** 媒体文件路径 */
203
- path: string;
204
- /** 媒体文件对象 */
205
- file: File | null;
206
- }
207
-
208
- /**
209
- * error 事件详情
210
- */
211
- export interface FsMediaErrorDetail {
212
- /** 媒体文件路径 */
213
- path: string;
214
- /** 错误信息 */
215
- message: string;
216
- }
217
-
218
- /**
219
- * 媒体元素基类
220
- * @description <fs-img> / <fs-audio> / <fs-video> 共用,封装文件读取、云端下载与缓存、
221
- * ObjectURL、watch 自动刷新、Shadow DOM 渲染与 load / error 事件。
222
- */
223
- export abstract class FsMedia extends HTMLElement {
224
- /**
225
- * 监听的属性列表
226
- */
227
- static get observedAttributes(): string[] {
228
- return OBSERVED_ATTRIBUTES;
229
- }
230
-
231
- /**
232
- * 内部媒体标签名(img / audio / video)
233
- */
234
- protected abstract readonly mediaTag: string;
235
- /**
236
- * 暴露给 ::part() 的名称
237
- */
238
- protected abstract readonly partName: string;
239
- /**
240
- * 媒体类型名称(用于错误提示)
241
- */
242
- protected abstract readonly mediaLabel: string;
243
- /**
244
- * 接受的 MIME 前缀(image/ 、audio/ 、video/)
245
- */
246
- protected abstract readonly acceptPrefix: string;
247
- /**
248
- * 媒体加载完成对应的事件名(img 为 load,音视频为 loadeddata)
249
- */
250
- protected abstract readonly loadEventName: string;
251
- /**
252
- * Shadow DOM 附加样式
253
- */
254
- protected abstract readonly shadowCss: string;
255
- /**
256
- * 需要从宿主同步到媒体元素的属性
257
- */
258
- protected abstract readonly mediaAttrs: readonly string[];
259
- /**
260
- * 默认开启的属性(仅在初始化时应用,如 controls)
261
- */
262
- protected readonly defaultAttrs: readonly string[] = [];
263
-
264
- /**
265
- * 是否已完成首次属性同步(之后严格遵循宿主属性)
266
- */
267
- #attrsInitialized = false;
268
-
269
- /**
270
- * Shadow Root
271
- */
272
- #shadow: ShadowRoot | null = null;
273
- /**
274
- * 默认插槽(加载失败 / 无路径时的回退内容)
275
- */
276
- #slot: HTMLSlotElement | null = null;
277
- /**
278
- * 内部媒体元素
279
- */
280
- #media: MediaElement | null = null;
281
- /**
282
- * 当前媒体的 ObjectURL
283
- */
284
- #objectURL: string | null = null;
285
- /**
286
- * 当前使用的 VVVFS 实例
287
- */
288
- #fs: VVVFS | null = null;
289
- /**
290
- * 当前展示的文件对象
291
- */
292
- #currentFile: File | null = null;
293
- /**
294
- * 加载令牌(用于丢弃过期的异步结果)
295
- */
296
- #token = 0;
297
- /**
298
- * 是否正在执行由自身触发的读取(避免 watch 递归)
299
- */
300
- #skipWatch = false;
301
- /**
302
- * watch 刷新重试定时器
303
- */
304
- #watchTimer: number | null = null;
305
- /**
306
- * 当前注册的监听信息
307
- */
308
- #watchDbname: string | null = null;
309
- #watchPath: string | null = null;
310
-
311
- /**
312
- * 媒体路径(src 优先,其次 path)
313
- */
314
- get src(): string {
315
- return this.getAttribute("src") ?? this.getAttribute("path") ?? "";
316
- }
317
- set src(value: string) {
318
- this.setAttribute("src", value);
319
- }
320
-
321
- /**
322
- * 数据库名
323
- */
324
- get dbname(): string {
325
- return this.getAttribute("dbname") || DEFAULT_DB_NAME;
326
- }
327
- set dbname(value: string) {
328
- this.setAttribute("dbname", value);
329
- }
330
-
331
- /**
332
- * 是否监听文件变化
333
- * @description watch="true" 时启用监听,watch="false" 时停止监听;
334
- * 属性存在且值不为 "false" 时均视为启用(兼容 `<fs-img watch>` 的写法)
335
- */
336
- get watch(): boolean {
337
- const value = this.getAttribute("watch");
338
- if (value === null) return false;
339
- return value.toLowerCase() !== "false";
340
- }
341
- set watch(value: boolean) {
342
- this.setAttribute("watch", value ? "true" : "false");
343
- }
344
-
345
- /**
346
- * 当前显示的媒体文件对象(未加载或加载失败时为 null)
347
- */
348
- get data(): Blob | null {
349
- return this.#currentFile;
350
- }
351
-
352
- /**
353
- * 元素挂载时
354
- */
355
- connectedCallback(): void {
356
- this.#ensureShadow();
357
- this.#ensureMedia();
358
- this.#syncAttrs();
359
- this.#syncWatch();
360
- void this.refresh();
361
- }
362
-
363
- /**
364
- * 元素卸载时
365
- */
366
- disconnectedCallback(): void {
367
- // 使所有进行中的异步加载失效
368
- this.#token++;
369
- this.#clearWatchTimer();
370
- this.#unregisterWatch();
371
- this.#revokeObjectURL();
372
- this.#setState("idle");
373
- }
374
-
375
- /**
376
- * 属性变化时
377
- * @param name 属性名
378
- */
379
- attributeChangedCallback(name: string): void {
380
- if (!this.isConnected) return;
381
- if (this.mediaAttrs.includes(name)) {
382
- this.#syncAttrs();
383
- return;
384
- }
385
- if (name === "watch") {
386
- this.#syncWatch();
387
- return;
388
- }
389
- if (name === "dbname") {
390
- this.#fs = null;
391
- }
392
- this.#syncWatch();
393
- void this.refresh();
394
- }
395
-
396
- /**
397
- * 手动刷新:重新读取并显示媒体
398
- * @returns 是否成功显示
399
- */
400
- refresh(): Promise<boolean> {
401
- // 自身读取触发的 watch 不递归刷新
402
- if (this.#skipWatch) return Promise.resolve(false);
403
- return this.#reload();
404
- }
405
-
406
- /**
407
- * 调度一次 watch 触发的刷新(内部使用)
408
- * @description 延迟重试,直到读到的文件内容发生变化,
409
- * 以避开 vvvfs watch 在操作提交前触发导致的旧内容问题。
410
- */
411
- scheduleWatchRefresh(): void {
412
- // 自身下载 / 读取触发的 watch 不递归刷新
413
- if (
414
- this.#skipWatch ||
415
- this.#watchTimer !== null ||
416
- !this.isConnected ||
417
- !this.watch
418
- ) {
419
- return;
420
- }
421
- let attempts = 0;
422
- const tick = async () => {
423
- this.#watchTimer = null;
424
- if (this.#skipWatch || !this.isConnected || !this.watch) return;
425
- const changed = await this.#refreshForWatch();
426
- attempts++;
427
- if (!changed && attempts < WATCH_MAX_ATTEMPTS) {
428
- this.#watchTimer = window.setTimeout(tick, WATCH_RETRY_DELAY);
429
- }
430
- };
431
- this.#watchTimer = window.setTimeout(tick, WATCH_RETRY_DELAY);
432
- }
433
-
434
- /**
435
- * 当前生效的 vvvfs 路径
436
- * @description 云端地址会被解析为本地缓存路径;其余情况与 src 一致
437
- */
438
- #targetPath(): string {
439
- const src = this.src;
440
- return isRemoteUrl(src) ? cloudCachePath(src) : src;
441
- }
442
-
443
- /**
444
- * 执行加载
445
- */
446
- async #reload(): Promise<boolean> {
447
- const token = ++this.#token;
448
- const src = this.src;
449
- this.#setState("loading");
450
-
451
- if (!src) {
452
- this.#revokeObjectURL();
453
- this.#clearMedia();
454
- this.#setState("idle");
455
- return false;
456
- }
457
-
458
- const fs = this.#resolveFS();
459
- if (!fs) return false;
460
- this.#syncWatch(fs);
461
-
462
- const remote = isRemoteUrl(src);
463
- const targetPath = remote ? cloudCachePath(src) : src;
464
-
465
- let file: File | null = null;
466
- let displayed = false;
467
- this.#skipWatch = true;
468
- try {
469
- if (remote) {
470
- // 云端文件:缓存优先展示,再通过 HEAD 校验远端大小,必要时重新下载
471
- const result = await this.#loadRemote(fs, targetPath, token);
472
- file = result.file;
473
- displayed = result.displayed;
474
- } else {
475
- file = await fs.read(src);
476
- }
477
- } catch (error) {
478
- if (token === this.#token && this.isConnected) {
479
- this.#fail(error instanceof Error ? error.message : String(error));
480
- }
481
- return false;
482
- } finally {
483
- this.#skipWatch = false;
484
- }
485
-
486
- if (token !== this.#token || !this.isConnected) return false;
487
-
488
- if (!file) {
489
- this.#fail(`文件不存在: ${targetPath}`);
490
- return false;
491
- }
492
-
493
- return displayed ? true : this.#display(file, remote);
494
- }
495
-
496
- /**
497
- * 加载远端文件
498
- * @description 缓存优先:已有缓存时先展示缓存,再发送 HEAD 校验远端文件大小;
499
- * 大小不一致、缺少 Content-Type 或缓存不可显示时重新下载
500
- * @param fs VVVFS 实例
501
- * @param targetPath 缓存路径
502
- * @param token 加载令牌
503
- * @returns 最终文件,以及是否已经展示过缓存
504
- */
505
- async #loadRemote(
506
- fs: VVVFS,
507
- targetPath: string,
508
- token: number,
509
- ): Promise<{ file: File | null; displayed: boolean }> {
510
- const cached = (await fs.exists(targetPath)) ? await fs.read(targetPath) : null;
511
- if (cached) {
512
- // 缓存优先展示
513
- if (token === this.#token && this.isConnected && this.#display(cached, true)) {
514
- // HEAD 校验远端文件大小与类型
515
- const info = await fs.head(this.src);
516
- if (
517
- info.contentType != null &&
518
- info.contentLength != null &&
519
- info.contentLength === cached.size
520
- ) {
521
- // 缓存有效,无需重新下载
522
- return { file: cached, displayed: true };
523
- }
524
- }
525
- }
526
- if (!(await fs.downloadFile(this.src, targetPath))) {
527
- throw new Error(`下载失败: ${this.src}`);
528
- }
529
- const file = await fs.read(targetPath);
530
- return { file, displayed: false };
531
- }
532
-
533
- /**
534
- * watch 触发的刷新:仅当文件内容变化时才重新展示
535
- * @returns 内容是否发生变化(或无需比较)
536
- */
537
- async #refreshForWatch(): Promise<boolean> {
538
- const targetPath = this.#targetPath();
539
- if (!targetPath) return true;
540
- const fs = this.#fs ?? this.#resolveFS();
541
- if (!fs) return true;
542
-
543
- let file: File | null = null;
544
- this.#skipWatch = true;
545
- try {
546
- file = await fs.read(targetPath);
547
- } catch {
548
- return true;
549
- } finally {
550
- this.#skipWatch = false;
551
- }
552
-
553
- if (!this.isConnected) return true;
554
- if (this.#isSameFile(file, this.#currentFile)) return false;
555
-
556
- if (!file) {
557
- this.#fail(`文件不存在: ${targetPath}`);
558
- return true;
559
- }
560
- // 无论是否为对应类型的媒体,内容已变化,处理完毕即停止重试
561
- this.#display(file, isRemoteUrl(this.src));
562
- return true;
563
- }
564
-
565
- /**
566
- * 判断两个文件对象内容是否一致
567
- * @param a 文件 A
568
- * @param b 文件 B
569
- */
570
- #isSameFile(a: File | null, b: File | null): boolean {
571
- if (!a || !b) return a === b;
572
- return (
573
- a.size === b.size &&
574
- a.type === b.type &&
575
- a.name === b.name &&
576
- a.lastModified === b.lastModified
577
- );
578
- }
579
-
580
- /**
581
- * 解析要使用的 VVVFS 实例
582
- */
583
- #resolveFS(): VVVFS | null {
584
- const dbname = this.dbname;
585
- // 默认数据库名时优先复用全局 vvvfs 实例
586
- if (dbname === DEFAULT_DB_NAME && globalScope.vvvfs) {
587
- this.#fs = globalScope.vvvfs;
588
- return this.#fs;
589
- }
590
- if (!instanceCache.has(dbname)) {
591
- if (!globalScope.VVVFS) {
592
- this.#fail("VVVFS 尚未加载,无法创建文件系统实例");
593
- return null;
594
- }
595
- try {
596
- instanceCache.set(dbname, new globalScope.VVVFS(dbname));
597
- } catch (error) {
598
- this.#fail(
599
- "创建 VVVFS 实例失败: " +
600
- (error instanceof Error ? error.message : String(error)),
601
- );
602
- return null;
603
- }
604
- }
605
- this.#fs = instanceCache.get(dbname)!;
606
- return this.#fs;
607
- }
608
-
609
- /**
610
- * 展示文件
611
- * @param file 媒体文件
612
- * @param allowUnknownType 是否允许未知类型(application/octet-stream,交由浏览器按内容嗅探)
613
- * @returns 是否成功展示
614
- */
615
- #display(file: File, allowUnknownType = false): boolean {
616
- const typeMatched = !file.type || file.type.startsWith(this.acceptPrefix);
617
- // 云端文件的 MIME 由缓存路径扩展名推断,扩展名缺失时为 application/octet-stream
618
- const unknownAllowed =
619
- allowUnknownType && file.type === "application/octet-stream";
620
- if (!typeMatched && !unknownAllowed) {
621
- this.#fail(`文件不是${this.mediaLabel}: ${this.#targetPath()}(${file.type})`);
622
- return false;
623
- }
624
- const media = this.#ensureMedia();
625
- media.removeAttribute("hidden");
626
- this.#currentFile = file;
627
- const url = URL.createObjectURL(file);
628
- this.#revokeObjectURL();
629
- this.#objectURL = url;
630
- media.src = url;
631
- return true;
632
- }
633
-
634
- /**
635
- * 加载失败处理
636
- * @param message 错误信息
637
- */
638
- #fail(message: string): void {
639
- this.#revokeObjectURL();
640
- this.#clearMedia();
641
- this.#setState("error");
642
- this.dispatchEvent(
643
- new CustomEvent<FsMediaErrorDetail>("error", {
644
- detail: { path: this.#targetPath(), message },
645
- }),
646
- );
647
- }
648
-
649
- /**
650
- * 确保 Shadow Root 已创建
651
- */
652
- #ensureShadow(): ShadowRoot {
653
- if (!this.#shadow) {
654
- this.#shadow = this.attachShadow({ mode: "open" });
655
- const style = document.createElement("style");
656
- style.textContent = SHADOW_BASE_STYLE + this.shadowCss;
657
- this.#shadow.appendChild(style);
658
- this.#slot = document.createElement("slot");
659
- this.#shadow.appendChild(this.#slot);
660
- }
661
- return this.#shadow;
662
- }
663
-
664
- /**
665
- * 获取(或创建)内部媒体元素
666
- */
667
- #ensureMedia(): MediaElement {
668
- const shadow = this.#ensureShadow();
669
- if (!this.#media) {
670
- const media = document.createElement(this.mediaTag) as MediaElement;
671
- // 暴露为 part,便于外部通过 ::part() 定制样式
672
- media.setAttribute("part", this.partName);
673
- // 无内容时先隐藏
674
- media.toggleAttribute("hidden", true);
675
- media.addEventListener(this.loadEventName, () => {
676
- if (!this.isConnected) return;
677
- this.#setState("loaded");
678
- this.dispatchEvent(
679
- new CustomEvent<FsMediaLoadDetail>("load", {
680
- detail: { path: this.#targetPath(), file: this.#currentFile },
681
- }),
682
- );
683
- });
684
- media.addEventListener("error", () => {
685
- if (!this.isConnected) return;
686
- this.#revokeObjectURL();
687
- this.#setState("error");
688
- this.dispatchEvent(
689
- new CustomEvent<FsMediaErrorDetail>("error", {
690
- detail: { path: this.#targetPath(), message: "媒体加载失败" },
691
- }),
692
- );
693
- });
694
- this.#media = media;
695
- }
696
- if (this.#media.parentNode === null) {
697
- shadow.insertBefore(this.#media, this.#slot);
698
- }
699
- return this.#media;
700
- }
701
-
702
- /**
703
- * 同步 mediaAttrs / defaultAttrs 到内部媒体元素
704
- */
705
- #syncAttrs(): void {
706
- const media = this.#media;
707
- if (!media) return;
708
- for (const name of this.mediaAttrs) {
709
- const value = this.getAttribute(name);
710
- if (value !== null) media.setAttribute(name, value);
711
- else if (!this.#attrsInitialized && this.defaultAttrs.includes(name)) {
712
- media.setAttribute(name, "");
713
- } else media.removeAttribute(name);
714
- }
715
- this.#attrsInitialized = true;
716
- }
717
-
718
- /**
719
- * 同步 watch 监听(路径 / 数据库名 / watch 属性变化时调用)
720
- * @param fs 已解析的 VVVFS 实例(可选)
721
- */
722
- #syncWatch(fs?: VVVFS | null): void {
723
- const dbname = this.dbname;
724
- const path = this.#targetPath();
725
- const watching = this.watch && path.length > 0;
726
-
727
- // 目标未变化时无需处理
728
- if (
729
- watching &&
730
- this.#watchPath === path &&
731
- this.#watchDbname === dbname
732
- ) {
733
- return;
734
- }
735
-
736
- // 先注销旧监听
737
- if (this.#watchPath !== null && this.#watchDbname !== null) {
738
- unregisterWatcher(this, this.#watchDbname, this.#watchPath);
739
- this.#watchDbname = null;
740
- this.#watchPath = null;
741
- }
742
-
743
- if (watching) {
744
- const target = fs ?? this.#fs;
745
- if (target) {
746
- registerWatcher(this, target, dbname, path);
747
- this.#watchDbname = dbname;
748
- this.#watchPath = path;
749
- }
750
- }
751
- }
752
-
753
- /**
754
- * 注销 watch 监听
755
- */
756
- #unregisterWatch(): void {
757
- if (this.#watchPath !== null && this.#watchDbname !== null) {
758
- unregisterWatcher(this, this.#watchDbname, this.#watchPath);
759
- }
760
- this.#watchDbname = null;
761
- this.#watchPath = null;
762
- }
763
-
764
- /**
765
- * 清除 watch 刷新重试定时器
766
- */
767
- #clearWatchTimer(): void {
768
- if (this.#watchTimer !== null) {
769
- window.clearTimeout(this.#watchTimer);
770
- this.#watchTimer = null;
771
- }
772
- }
773
-
774
- /**
775
- * 清空内部媒体元素的 src
776
- */
777
- #clearMedia(): void {
778
- this.#currentFile = null;
779
- if (this.#media) {
780
- this.#media.removeAttribute("src");
781
- this.#media.toggleAttribute("hidden", true);
782
- }
783
- }
784
-
785
- /**
786
- * 释放 ObjectURL
787
- */
788
- #revokeObjectURL(): void {
789
- if (this.#objectURL) {
790
- URL.revokeObjectURL(this.#objectURL);
791
- this.#objectURL = null;
792
- }
793
- }
794
-
795
- /**
796
- * 设置状态(写入 data-state 属性,便于 CSS 定制)
797
- * @param state 状态
798
- */
799
- #setState(state: "idle" | "loading" | "loaded" | "error"): void {
800
- if (state === "idle") this.removeAttribute("data-state");
801
- else this.setAttribute("data-state", state);
802
- }
803
- }
804
-
805
- /**
806
- * 自定义音频元素 <fs-audio>
807
- * @description 直接读取并播放存储在 vvvfs 中的音频文件
808
- * @attributes
809
- * - src / path:音频在 vvvfs 中的路径(src 优先,其次 path)
810
- * - dbname:数据库名,默认 "vvvfs";未指定且存在全局 vvvfs 实例时直接使用该实例
811
- * - controls:是否显示控制条(默认显示,可用 removeAttribute("controls") 关闭)
812
- * - autoplay / loop / muted / preload:透传到内部 <audio> 元素
813
- * - watch:存在时,文件内容发生变化后自动刷新
814
- * @events
815
- * - load:音频数据加载完成(detail: { path, file })
816
- * - error:音频加载失败(detail: { path, message })
817
- * @example <fs-audio src="/home/user/Music/demo.mp3"></fs-audio>
818
- */
819
- export class FsAudio extends FsMedia {
820
- protected readonly mediaTag = "audio";
821
- protected readonly partName = "audio";
822
- protected readonly mediaLabel = "音频";
823
- protected readonly acceptPrefix = "audio/";
824
- protected readonly loadEventName = "loadeddata";
825
- protected readonly mediaAttrs = ["controls", "autoplay", "loop", "muted", "preload"] as const;
826
- protected readonly defaultAttrs = ["controls"] as const;
827
- protected readonly shadowCss = `
828
- audio {
829
- display: block;
830
- max-width: 100%;
831
- }
832
- `;
833
- }
834
-
835
- /**
836
- * 自定义视频元素 <fs-video>
837
- * @description 直接读取并播放存储在 vvvfs 中的视频文件
838
- * @attributes
839
- * - src / path:视频在 vvvfs 中的路径(src 优先,其次 path)
840
- * - dbname:数据库名,默认 "vvvfs";未指定且存在全局 vvvfs 实例时直接使用该实例
841
- * - controls:是否显示控制条(默认显示,可用 removeAttribute("controls") 关闭)
842
- * - autoplay / loop / muted / preload / width / height:透传到内部 <video> 元素
843
- * - watch:存在时,文件内容发生变化后自动刷新
844
- * @events
845
- * - load:视频数据加载完成(detail: { path, file })
846
- * - error:视频加载失败(detail: { path, message })
847
- * @example <fs-video src="/home/user/Videos/demo.mp4" width="320"></fs-video>
848
- */
849
- export class FsVideo extends FsMedia {
850
- protected readonly mediaTag = "video";
851
- protected readonly partName = "video";
852
- protected readonly mediaLabel = "视频";
853
- protected readonly acceptPrefix = "video/";
854
- protected readonly loadEventName = "loadeddata";
855
- protected readonly mediaAttrs = [
856
- "controls",
857
- "autoplay",
858
- "loop",
859
- "muted",
860
- "preload",
861
- "width",
862
- "height",
863
- ] as const;
864
- protected readonly defaultAttrs = ["controls"] as const;
865
- protected readonly shadowCss = `
866
- video {
867
- display: block;
868
- max-width: 100%;
869
- height: auto;
870
- }
871
- `;
872
- }
873
-
874
- // 注册自定义元素(避免重复注册导致报错)
875
- if (typeof customElements !== "undefined" && !customElements.get("fs-audio")) {
876
- customElements.define("fs-audio", FsAudio);
877
- }
878
- if (typeof customElements !== "undefined" && !customElements.get("fs-video")) {
879
- customElements.define("fs-video", FsVideo);
880
- }
1
+ /**
2
+ * @file Media.ts
3
+ * @description 定义 <fs-img> / <fs-audio> / <fs-video> 共用的媒体元素基类 FsMedia,
4
+ * 以及 <fs-audio> 与 <fs-video>;可直接显示 / 播放存储在 vvvfs 中的媒体文件。
5
+ * src 为 http(s) 地址时,会先下载到 /home/.cache/cloud/<hostname>/<pathname> 再展示。
6
+ * @author IFTC
7
+ * @example
8
+ * <fs-img src="/home/user/Pictures/logo.png" alt="Logo" width="120"></fs-img>
9
+ * <fs-audio src="/home/user/Music/demo.mp3"></fs-audio>
10
+ * <fs-video src="https://example.com/video/demo.mp4" width="320"></fs-video>
11
+ */
12
+ import type { VVVFS, VVVFSOptions } from "./index";
13
+
14
+ /**
15
+ * 监听的属性列表
16
+ */
17
+ const OBSERVED_ATTRIBUTES = [
18
+ "src",
19
+ "path",
20
+ "dbname",
21
+ "watch",
22
+ "controls",
23
+ "autoplay",
24
+ "loop",
25
+ "muted",
26
+ "preload",
27
+ "width",
28
+ "height",
29
+ "alt",
30
+ ];
31
+
32
+ /**
33
+ * 默认数据库名
34
+ */
35
+ const DEFAULT_DB_NAME = "vvvfs";
36
+
37
+ /**
38
+ * 云端文件缓存根目录
39
+ */
40
+ const CLOUD_CACHE_ROOT = "/home/.cache/cloud";
41
+
42
+ /**
43
+ * 判断是否为云端地址(http / https / 协议相对 URL)
44
+ * @param src 路径字符串
45
+ */
46
+ function isRemoteUrl(src: string): boolean {
47
+ return /^(https?:\/\/|\/\/)/i.test(src.trim());
48
+ }
49
+
50
+ /**
51
+ * 计算云端文件在 vvvfs 中的缓存路径
52
+ * @description /home/.cache/cloud/<hostname>/<pathname>
53
+ * @param src 云端地址
54
+ */
55
+ function cloudCachePath(src: string): string {
56
+ const base =
57
+ typeof globalThis.location?.href === "string"
58
+ ? globalThis.location.href
59
+ : "http://localhost/";
60
+ const url = new URL(src, base);
61
+ let pathname = url.pathname;
62
+ try {
63
+ pathname = decodeURIComponent(pathname);
64
+ } catch {
65
+ // 保留原始路径(百分号编码非法时)
66
+ }
67
+ // 去掉首尾多余的斜杠,避免拼接出重复分隔符
68
+ pathname = pathname.replace(/^\/+|\/+$/g, "");
69
+ return `${CLOUD_CACHE_ROOT}/${url.hostname}/${pathname}`;
70
+ }
71
+
72
+ /**
73
+ * 会改变文件内容的操作类型(其余操作不会触发刷新)
74
+ */
75
+ const WATCH_MUTATIONS = new Set([
76
+ "create",
77
+ "write",
78
+ "append",
79
+ "rename",
80
+ "delete",
81
+ "move",
82
+ "copy",
83
+ "downloadFile",
84
+ ]);
85
+
86
+ /**
87
+ * 刷新重试间隔(毫秒)
88
+ * @description vvvfs 的 watch 在操作提交前触发,立即刷新会读到旧内容,
89
+ * 因此延迟一段时间后重试,直到读到的文件发生变化。
90
+ */
91
+ const WATCH_RETRY_DELAY = 50;
92
+
93
+ /**
94
+ * 刷新最大重试次数
95
+ */
96
+ const WATCH_MAX_ATTEMPTS = 10;
97
+
98
+ /**
99
+ * 各元素共用的 Shadow DOM 基础样式
100
+ */
101
+ const SHADOW_BASE_STYLE = `
102
+ :host {
103
+ display: inline-block;
104
+ }
105
+ [hidden] {
106
+ display: none;
107
+ }
108
+ slot {
109
+ display: none;
110
+ }
111
+ :host([data-state="error"]) slot,
112
+ :host([data-state="idle"]) slot {
113
+ display: block;
114
+ }
115
+ `;
116
+
117
+ /**
118
+ * VVVFS 构造函数类型
119
+ */
120
+ type VVVFSConstructor = new (name?: string, options?: VVVFSOptions) => VVVFS;
121
+
122
+ /**
123
+ * 媒体元素类型(图片 / 音频 / 视频)
124
+ */
125
+ type MediaElement = HTMLImageElement | HTMLMediaElement;
126
+
127
+ /**
128
+ * 全局作用域(VVVFS 库会向 globalThis 挂载 VVVFS / vvvfs)
129
+ */
130
+ const globalScope = globalThis as typeof globalThis & {
131
+ VVVFS?: VVVFSConstructor;
132
+ vvvfs?: VVVFS;
133
+ };
134
+
135
+ /**
136
+ * 已创建的 VVVFS 实例缓存(按数据库名共享,避免重复创建)
137
+ */
138
+ const instanceCache = new Map<string, VVVFS>();
139
+
140
+ /**
141
+ * 每个 (数据库名, 路径) 对应的元素集合,用于共享同一个 watch 监听器
142
+ */
143
+ const watcherSets = new Map<string, Set<FsMedia>>();
144
+
145
+ /**
146
+ * 生成监听键
147
+ * @param dbname 数据库名
148
+ * @param path 文件路径
149
+ */
150
+ function watchKey(dbname: string, path: string): string {
151
+ return dbname + "\n" + path;
152
+ }
153
+
154
+ /**
155
+ * 注册共享监听器
156
+ * @description VVVFS 未提供取消监听的 API,因此同一个 (数据库名, 路径) 只注册一次,
157
+ * 集合清空后监听器闭包仍保留在 VVVFS 内部(每个路径仅一个闭包,开销极小)。
158
+ * @param el 目标元素
159
+ * @param fs VVVFS 实例
160
+ * @param dbname 数据库名
161
+ * @param path 文件路径
162
+ */
163
+ function registerWatcher(el: FsMedia, fs: VVVFS, dbname: string, path: string): void {
164
+ const key = watchKey(dbname, path);
165
+ let set = watcherSets.get(key);
166
+ if (!set) {
167
+ set = new Set<FsMedia>();
168
+ watcherSets.set(key, set);
169
+ fs.watch(path, (type) => {
170
+ // 只有修改类操作才需要刷新
171
+ if (!WATCH_MUTATIONS.has(type)) return false;
172
+ const current = watcherSets.get(key);
173
+ if (!current || current.size === 0) return false;
174
+ for (const target of current) {
175
+ if (target.isConnected) target.scheduleWatchRefresh();
176
+ }
177
+ // 返回 false,避免取消触发监听的文件操作
178
+ return false;
179
+ });
180
+ }
181
+ set.add(el);
182
+ }
183
+
184
+ /**
185
+ * 将元素从共享监听集合中移除
186
+ * @param el 目标元素
187
+ * @param dbname 数据库名
188
+ * @param path 文件路径
189
+ */
190
+ function unregisterWatcher(el: FsMedia, dbname: string, path: string): void {
191
+ const key = watchKey(dbname, path);
192
+ const set = watcherSets.get(key);
193
+ if (!set) return;
194
+ set.delete(el);
195
+ if (set.size === 0) watcherSets.delete(key);
196
+ }
197
+
198
+ /**
199
+ * load 事件详情
200
+ */
201
+ export interface FsMediaLoadDetail {
202
+ /** 媒体文件路径 */
203
+ path: string;
204
+ /** 媒体文件对象 */
205
+ file: File | null;
206
+ }
207
+
208
+ /**
209
+ * error 事件详情
210
+ */
211
+ export interface FsMediaErrorDetail {
212
+ /** 媒体文件路径 */
213
+ path: string;
214
+ /** 错误信息 */
215
+ message: string;
216
+ }
217
+
218
+ /**
219
+ * 媒体元素基类
220
+ * @description <fs-img> / <fs-audio> / <fs-video> 共用,封装文件读取、云端下载与缓存、
221
+ * ObjectURL、watch 自动刷新、Shadow DOM 渲染与 load / error 事件。
222
+ */
223
+ export abstract class FsMedia extends HTMLElement {
224
+ /**
225
+ * 监听的属性列表
226
+ */
227
+ static get observedAttributes(): string[] {
228
+ return OBSERVED_ATTRIBUTES;
229
+ }
230
+
231
+ /**
232
+ * 内部媒体标签名(img / audio / video)
233
+ */
234
+ protected abstract readonly mediaTag: string;
235
+ /**
236
+ * 暴露给 ::part() 的名称
237
+ */
238
+ protected abstract readonly partName: string;
239
+ /**
240
+ * 媒体类型名称(用于错误提示)
241
+ */
242
+ protected abstract readonly mediaLabel: string;
243
+ /**
244
+ * 接受的 MIME 前缀(image/ 、audio/ 、video/)
245
+ */
246
+ protected abstract readonly acceptPrefix: string;
247
+ /**
248
+ * 媒体加载完成对应的事件名(img 为 load,音视频为 loadeddata)
249
+ */
250
+ protected abstract readonly loadEventName: string;
251
+ /**
252
+ * Shadow DOM 附加样式
253
+ */
254
+ protected abstract readonly shadowCss: string;
255
+ /**
256
+ * 需要从宿主同步到媒体元素的属性
257
+ */
258
+ protected abstract readonly mediaAttrs: readonly string[];
259
+ /**
260
+ * 默认开启的属性(仅在初始化时应用,如 controls)
261
+ */
262
+ protected readonly defaultAttrs: readonly string[] = [];
263
+
264
+ /**
265
+ * 是否已完成首次属性同步(之后严格遵循宿主属性)
266
+ */
267
+ #attrsInitialized = false;
268
+
269
+ /**
270
+ * Shadow Root
271
+ */
272
+ #shadow: ShadowRoot | null = null;
273
+ /**
274
+ * 默认插槽(加载失败 / 无路径时的回退内容)
275
+ */
276
+ #slot: HTMLSlotElement | null = null;
277
+ /**
278
+ * 内部媒体元素
279
+ */
280
+ #media: MediaElement | null = null;
281
+ /**
282
+ * 当前媒体的 ObjectURL
283
+ */
284
+ #objectURL: string | null = null;
285
+ /**
286
+ * 当前使用的 VVVFS 实例
287
+ */
288
+ #fs: VVVFS | null = null;
289
+ /**
290
+ * 当前展示的文件对象
291
+ */
292
+ #currentFile: File | null = null;
293
+ /**
294
+ * 加载令牌(用于丢弃过期的异步结果)
295
+ */
296
+ #token = 0;
297
+ /**
298
+ * 是否正在执行由自身触发的读取(避免 watch 递归)
299
+ */
300
+ #skipWatch = false;
301
+ /**
302
+ * watch 刷新重试定时器
303
+ */
304
+ #watchTimer: number | null = null;
305
+ /**
306
+ * 当前注册的监听信息
307
+ */
308
+ #watchDbname: string | null = null;
309
+ #watchPath: string | null = null;
310
+
311
+ /**
312
+ * 媒体路径(src 优先,其次 path)
313
+ */
314
+ get src(): string {
315
+ return this.getAttribute("src") ?? this.getAttribute("path") ?? "";
316
+ }
317
+ set src(value: string) {
318
+ this.setAttribute("src", value);
319
+ }
320
+
321
+ /**
322
+ * 数据库名
323
+ */
324
+ get dbname(): string {
325
+ return this.getAttribute("dbname") || DEFAULT_DB_NAME;
326
+ }
327
+ set dbname(value: string) {
328
+ this.setAttribute("dbname", value);
329
+ }
330
+
331
+ /**
332
+ * 是否监听文件变化
333
+ * @description watch="true" 时启用监听,watch="false" 时停止监听;
334
+ * 属性存在且值不为 "false" 时均视为启用(兼容 `<fs-img watch>` 的写法)
335
+ */
336
+ get watch(): boolean {
337
+ const value = this.getAttribute("watch");
338
+ if (value === null) return false;
339
+ return value.toLowerCase() !== "false";
340
+ }
341
+ set watch(value: boolean) {
342
+ this.setAttribute("watch", value ? "true" : "false");
343
+ }
344
+
345
+ /**
346
+ * 当前显示的媒体文件对象(未加载或加载失败时为 null)
347
+ */
348
+ get data(): Blob | null {
349
+ return this.#currentFile;
350
+ }
351
+
352
+ /**
353
+ * 元素挂载时
354
+ */
355
+ connectedCallback(): void {
356
+ this.#ensureShadow();
357
+ this.#ensureMedia();
358
+ this.#syncAttrs();
359
+ this.#syncWatch();
360
+ void this.refresh();
361
+ }
362
+
363
+ /**
364
+ * 元素卸载时
365
+ */
366
+ disconnectedCallback(): void {
367
+ // 使所有进行中的异步加载失效
368
+ this.#token++;
369
+ this.#clearWatchTimer();
370
+ this.#unregisterWatch();
371
+ this.#revokeObjectURL();
372
+ this.#setState("idle");
373
+ }
374
+
375
+ /**
376
+ * 属性变化时
377
+ * @param name 属性名
378
+ */
379
+ attributeChangedCallback(name: string): void {
380
+ if (!this.isConnected) return;
381
+ if (this.mediaAttrs.includes(name)) {
382
+ this.#syncAttrs();
383
+ return;
384
+ }
385
+ if (name === "watch") {
386
+ this.#syncWatch();
387
+ return;
388
+ }
389
+ if (name === "dbname") {
390
+ this.#fs = null;
391
+ }
392
+ this.#syncWatch();
393
+ void this.refresh();
394
+ }
395
+
396
+ /**
397
+ * 手动刷新:重新读取并显示媒体
398
+ * @returns 是否成功显示
399
+ */
400
+ refresh(): Promise<boolean> {
401
+ // 自身读取触发的 watch 不递归刷新
402
+ if (this.#skipWatch) return Promise.resolve(false);
403
+ return this.#reload();
404
+ }
405
+
406
+ /**
407
+ * 调度一次 watch 触发的刷新(内部使用)
408
+ * @description 延迟重试,直到读到的文件内容发生变化,
409
+ * 以避开 vvvfs watch 在操作提交前触发导致的旧内容问题。
410
+ */
411
+ scheduleWatchRefresh(): void {
412
+ // 自身下载 / 读取触发的 watch 不递归刷新
413
+ if (
414
+ this.#skipWatch ||
415
+ this.#watchTimer !== null ||
416
+ !this.isConnected ||
417
+ !this.watch
418
+ ) {
419
+ return;
420
+ }
421
+ let attempts = 0;
422
+ const tick = async () => {
423
+ this.#watchTimer = null;
424
+ if (this.#skipWatch || !this.isConnected || !this.watch) return;
425
+ const changed = await this.#refreshForWatch();
426
+ attempts++;
427
+ if (!changed && attempts < WATCH_MAX_ATTEMPTS) {
428
+ this.#watchTimer = window.setTimeout(tick, WATCH_RETRY_DELAY);
429
+ }
430
+ };
431
+ this.#watchTimer = window.setTimeout(tick, WATCH_RETRY_DELAY);
432
+ }
433
+
434
+ /**
435
+ * 当前生效的 vvvfs 路径
436
+ * @description 云端地址会被解析为本地缓存路径;其余情况与 src 一致
437
+ */
438
+ #targetPath(): string {
439
+ const src = this.src;
440
+ return isRemoteUrl(src) ? cloudCachePath(src) : src;
441
+ }
442
+
443
+ /**
444
+ * 执行加载
445
+ */
446
+ async #reload(): Promise<boolean> {
447
+ const token = ++this.#token;
448
+ const src = this.src;
449
+ this.#setState("loading");
450
+
451
+ if (!src) {
452
+ this.#revokeObjectURL();
453
+ this.#clearMedia();
454
+ this.#setState("idle");
455
+ return false;
456
+ }
457
+
458
+ const fs = this.#resolveFS();
459
+ if (!fs) return false;
460
+ this.#syncWatch(fs);
461
+
462
+ const remote = isRemoteUrl(src);
463
+ const targetPath = remote ? cloudCachePath(src) : src;
464
+
465
+ let file: File | null = null;
466
+ let displayed = false;
467
+ this.#skipWatch = true;
468
+ try {
469
+ if (remote) {
470
+ // 云端文件:缓存优先展示,再通过 HEAD 校验远端大小,必要时重新下载
471
+ const result = await this.#loadRemote(fs, targetPath, token);
472
+ file = result.file;
473
+ displayed = result.displayed;
474
+ } else {
475
+ file = await fs.read(src);
476
+ }
477
+ } catch (error) {
478
+ if (token === this.#token && this.isConnected) {
479
+ this.#fail(error instanceof Error ? error.message : String(error));
480
+ }
481
+ return false;
482
+ } finally {
483
+ this.#skipWatch = false;
484
+ }
485
+
486
+ if (token !== this.#token || !this.isConnected) return false;
487
+
488
+ if (!file) {
489
+ this.#fail(`文件不存在: ${targetPath}`);
490
+ return false;
491
+ }
492
+
493
+ return displayed ? true : this.#display(file, remote);
494
+ }
495
+
496
+ /**
497
+ * 加载远端文件
498
+ * @description 缓存优先:已有缓存时先展示缓存,再发送 HEAD 校验远端文件大小;
499
+ * 大小不一致、缺少 Content-Type 或缓存不可显示时重新下载
500
+ * @param fs VVVFS 实例
501
+ * @param targetPath 缓存路径
502
+ * @param token 加载令牌
503
+ * @returns 最终文件,以及是否已经展示过缓存
504
+ */
505
+ async #loadRemote(
506
+ fs: VVVFS,
507
+ targetPath: string,
508
+ token: number,
509
+ ): Promise<{ file: File | null; displayed: boolean }> {
510
+ const cached = (await fs.exists(targetPath)) ? await fs.read(targetPath) : null;
511
+ if (cached) {
512
+ // 缓存优先展示
513
+ if (token === this.#token && this.isConnected && this.#display(cached, true)) {
514
+ // HEAD 校验远端文件大小与类型
515
+ const info = await fs.head(this.src);
516
+ if (
517
+ info.contentType != null &&
518
+ info.contentLength != null &&
519
+ info.contentLength === cached.size
520
+ ) {
521
+ // 缓存有效,无需重新下载
522
+ return { file: cached, displayed: true };
523
+ }
524
+ }
525
+ }
526
+ if (!(await fs.downloadFile(this.src, targetPath))) {
527
+ throw new Error(`下载失败: ${this.src}`);
528
+ }
529
+ const file = await fs.read(targetPath);
530
+ return { file, displayed: false };
531
+ }
532
+
533
+ /**
534
+ * watch 触发的刷新:仅当文件内容变化时才重新展示
535
+ * @returns 内容是否发生变化(或无需比较)
536
+ */
537
+ async #refreshForWatch(): Promise<boolean> {
538
+ const targetPath = this.#targetPath();
539
+ if (!targetPath) return true;
540
+ const fs = this.#fs ?? this.#resolveFS();
541
+ if (!fs) return true;
542
+
543
+ let file: File | null = null;
544
+ this.#skipWatch = true;
545
+ try {
546
+ file = await fs.read(targetPath);
547
+ } catch {
548
+ return true;
549
+ } finally {
550
+ this.#skipWatch = false;
551
+ }
552
+
553
+ if (!this.isConnected) return true;
554
+ if (this.#isSameFile(file, this.#currentFile)) return false;
555
+
556
+ if (!file) {
557
+ this.#fail(`文件不存在: ${targetPath}`);
558
+ return true;
559
+ }
560
+ // 无论是否为对应类型的媒体,内容已变化,处理完毕即停止重试
561
+ this.#display(file, isRemoteUrl(this.src));
562
+ return true;
563
+ }
564
+
565
+ /**
566
+ * 判断两个文件对象内容是否一致
567
+ * @param a 文件 A
568
+ * @param b 文件 B
569
+ */
570
+ #isSameFile(a: File | null, b: File | null): boolean {
571
+ if (!a || !b) return a === b;
572
+ return (
573
+ a.size === b.size &&
574
+ a.type === b.type &&
575
+ a.name === b.name &&
576
+ a.lastModified === b.lastModified
577
+ );
578
+ }
579
+
580
+ /**
581
+ * 解析要使用的 VVVFS 实例
582
+ */
583
+ #resolveFS(): VVVFS | null {
584
+ const dbname = this.dbname;
585
+ // 默认数据库名时优先复用全局 vvvfs 实例
586
+ if (dbname === DEFAULT_DB_NAME && globalScope.vvvfs) {
587
+ this.#fs = globalScope.vvvfs;
588
+ return this.#fs;
589
+ }
590
+ if (!instanceCache.has(dbname)) {
591
+ if (!globalScope.VVVFS) {
592
+ this.#fail("VVVFS 尚未加载,无法创建文件系统实例");
593
+ return null;
594
+ }
595
+ try {
596
+ instanceCache.set(dbname, new globalScope.VVVFS(dbname));
597
+ } catch (error) {
598
+ this.#fail(
599
+ "创建 VVVFS 实例失败: " +
600
+ (error instanceof Error ? error.message : String(error)),
601
+ );
602
+ return null;
603
+ }
604
+ }
605
+ this.#fs = instanceCache.get(dbname)!;
606
+ return this.#fs;
607
+ }
608
+
609
+ /**
610
+ * 展示文件
611
+ * @param file 媒体文件
612
+ * @param allowUnknownType 是否允许未知类型(application/octet-stream,交由浏览器按内容嗅探)
613
+ * @returns 是否成功展示
614
+ */
615
+ #display(file: File, allowUnknownType = false): boolean {
616
+ const typeMatched = !file.type || file.type.startsWith(this.acceptPrefix);
617
+ // 云端文件的 MIME 由缓存路径扩展名推断,扩展名缺失时为 application/octet-stream
618
+ const unknownAllowed =
619
+ allowUnknownType && file.type === "application/octet-stream";
620
+ if (!typeMatched && !unknownAllowed) {
621
+ this.#fail(`文件不是${this.mediaLabel}: ${this.#targetPath()}(${file.type})`);
622
+ return false;
623
+ }
624
+ const media = this.#ensureMedia();
625
+ media.removeAttribute("hidden");
626
+ this.#currentFile = file;
627
+ const url = URL.createObjectURL(file);
628
+ this.#revokeObjectURL();
629
+ this.#objectURL = url;
630
+ media.src = url;
631
+ return true;
632
+ }
633
+
634
+ /**
635
+ * 加载失败处理
636
+ * @param message 错误信息
637
+ */
638
+ #fail(message: string): void {
639
+ this.#revokeObjectURL();
640
+ this.#clearMedia();
641
+ this.#setState("error");
642
+ this.dispatchEvent(
643
+ new CustomEvent<FsMediaErrorDetail>("error", {
644
+ detail: { path: this.#targetPath(), message },
645
+ }),
646
+ );
647
+ }
648
+
649
+ /**
650
+ * 确保 Shadow Root 已创建
651
+ */
652
+ #ensureShadow(): ShadowRoot {
653
+ if (!this.#shadow) {
654
+ this.#shadow = this.attachShadow({ mode: "open" });
655
+ const style = document.createElement("style");
656
+ style.textContent = SHADOW_BASE_STYLE + this.shadowCss;
657
+ this.#shadow.appendChild(style);
658
+ this.#slot = document.createElement("slot");
659
+ this.#shadow.appendChild(this.#slot);
660
+ }
661
+ return this.#shadow;
662
+ }
663
+
664
+ /**
665
+ * 获取(或创建)内部媒体元素
666
+ */
667
+ #ensureMedia(): MediaElement {
668
+ const shadow = this.#ensureShadow();
669
+ if (!this.#media) {
670
+ const media = document.createElement(this.mediaTag) as MediaElement;
671
+ // 暴露为 part,便于外部通过 ::part() 定制样式
672
+ media.setAttribute("part", this.partName);
673
+ // 无内容时先隐藏
674
+ media.toggleAttribute("hidden", true);
675
+ media.addEventListener(this.loadEventName, () => {
676
+ if (!this.isConnected) return;
677
+ this.#setState("loaded");
678
+ this.dispatchEvent(
679
+ new CustomEvent<FsMediaLoadDetail>("load", {
680
+ detail: { path: this.#targetPath(), file: this.#currentFile },
681
+ }),
682
+ );
683
+ });
684
+ media.addEventListener("error", () => {
685
+ if (!this.isConnected) return;
686
+ this.#revokeObjectURL();
687
+ this.#setState("error");
688
+ this.dispatchEvent(
689
+ new CustomEvent<FsMediaErrorDetail>("error", {
690
+ detail: { path: this.#targetPath(), message: "媒体加载失败" },
691
+ }),
692
+ );
693
+ });
694
+ this.#media = media;
695
+ }
696
+ if (this.#media.parentNode === null) {
697
+ shadow.insertBefore(this.#media, this.#slot);
698
+ }
699
+ return this.#media;
700
+ }
701
+
702
+ /**
703
+ * 同步 mediaAttrs / defaultAttrs 到内部媒体元素
704
+ */
705
+ #syncAttrs(): void {
706
+ const media = this.#media;
707
+ if (!media) return;
708
+ for (const name of this.mediaAttrs) {
709
+ const value = this.getAttribute(name);
710
+ if (value !== null) media.setAttribute(name, value);
711
+ else if (!this.#attrsInitialized && this.defaultAttrs.includes(name)) {
712
+ media.setAttribute(name, "");
713
+ } else media.removeAttribute(name);
714
+ }
715
+ this.#attrsInitialized = true;
716
+ }
717
+
718
+ /**
719
+ * 同步 watch 监听(路径 / 数据库名 / watch 属性变化时调用)
720
+ * @param fs 已解析的 VVVFS 实例(可选)
721
+ */
722
+ #syncWatch(fs?: VVVFS | null): void {
723
+ const dbname = this.dbname;
724
+ const path = this.#targetPath();
725
+ const watching = this.watch && path.length > 0;
726
+
727
+ // 目标未变化时无需处理
728
+ if (
729
+ watching &&
730
+ this.#watchPath === path &&
731
+ this.#watchDbname === dbname
732
+ ) {
733
+ return;
734
+ }
735
+
736
+ // 先注销旧监听
737
+ if (this.#watchPath !== null && this.#watchDbname !== null) {
738
+ unregisterWatcher(this, this.#watchDbname, this.#watchPath);
739
+ this.#watchDbname = null;
740
+ this.#watchPath = null;
741
+ }
742
+
743
+ if (watching) {
744
+ const target = fs ?? this.#fs;
745
+ if (target) {
746
+ registerWatcher(this, target, dbname, path);
747
+ this.#watchDbname = dbname;
748
+ this.#watchPath = path;
749
+ }
750
+ }
751
+ }
752
+
753
+ /**
754
+ * 注销 watch 监听
755
+ */
756
+ #unregisterWatch(): void {
757
+ if (this.#watchPath !== null && this.#watchDbname !== null) {
758
+ unregisterWatcher(this, this.#watchDbname, this.#watchPath);
759
+ }
760
+ this.#watchDbname = null;
761
+ this.#watchPath = null;
762
+ }
763
+
764
+ /**
765
+ * 清除 watch 刷新重试定时器
766
+ */
767
+ #clearWatchTimer(): void {
768
+ if (this.#watchTimer !== null) {
769
+ window.clearTimeout(this.#watchTimer);
770
+ this.#watchTimer = null;
771
+ }
772
+ }
773
+
774
+ /**
775
+ * 清空内部媒体元素的 src
776
+ */
777
+ #clearMedia(): void {
778
+ this.#currentFile = null;
779
+ if (this.#media) {
780
+ this.#media.removeAttribute("src");
781
+ this.#media.toggleAttribute("hidden", true);
782
+ }
783
+ }
784
+
785
+ /**
786
+ * 释放 ObjectURL
787
+ */
788
+ #revokeObjectURL(): void {
789
+ if (this.#objectURL) {
790
+ URL.revokeObjectURL(this.#objectURL);
791
+ this.#objectURL = null;
792
+ }
793
+ }
794
+
795
+ /**
796
+ * 设置状态(写入 data-state 属性,便于 CSS 定制)
797
+ * @param state 状态
798
+ */
799
+ #setState(state: "idle" | "loading" | "loaded" | "error"): void {
800
+ if (state === "idle") this.removeAttribute("data-state");
801
+ else this.setAttribute("data-state", state);
802
+ }
803
+ }
804
+
805
+ /**
806
+ * 自定义音频元素 <fs-audio>
807
+ * @description 直接读取并播放存储在 vvvfs 中的音频文件
808
+ * @attributes
809
+ * - src / path:音频在 vvvfs 中的路径(src 优先,其次 path)
810
+ * - dbname:数据库名,默认 "vvvfs";未指定且存在全局 vvvfs 实例时直接使用该实例
811
+ * - controls:是否显示控制条(默认显示,可用 removeAttribute("controls") 关闭)
812
+ * - autoplay / loop / muted / preload:透传到内部 <audio> 元素
813
+ * - watch:存在时,文件内容发生变化后自动刷新
814
+ * @events
815
+ * - load:音频数据加载完成(detail: { path, file })
816
+ * - error:音频加载失败(detail: { path, message })
817
+ * @example <fs-audio src="/home/user/Music/demo.mp3"></fs-audio>
818
+ */
819
+ export class FsAudio extends FsMedia {
820
+ protected readonly mediaTag = "audio";
821
+ protected readonly partName = "audio";
822
+ protected readonly mediaLabel = "音频";
823
+ protected readonly acceptPrefix = "audio/";
824
+ protected readonly loadEventName = "loadeddata";
825
+ protected readonly mediaAttrs = ["controls", "autoplay", "loop", "muted", "preload"] as const;
826
+ protected readonly defaultAttrs = ["controls"] as const;
827
+ protected readonly shadowCss = `
828
+ audio {
829
+ display: block;
830
+ max-width: 100%;
831
+ }
832
+ `;
833
+ }
834
+
835
+ /**
836
+ * 自定义视频元素 <fs-video>
837
+ * @description 直接读取并播放存储在 vvvfs 中的视频文件
838
+ * @attributes
839
+ * - src / path:视频在 vvvfs 中的路径(src 优先,其次 path)
840
+ * - dbname:数据库名,默认 "vvvfs";未指定且存在全局 vvvfs 实例时直接使用该实例
841
+ * - controls:是否显示控制条(默认显示,可用 removeAttribute("controls") 关闭)
842
+ * - autoplay / loop / muted / preload / width / height:透传到内部 <video> 元素
843
+ * - watch:存在时,文件内容发生变化后自动刷新
844
+ * @events
845
+ * - load:视频数据加载完成(detail: { path, file })
846
+ * - error:视频加载失败(detail: { path, message })
847
+ * @example <fs-video src="/home/user/Videos/demo.mp4" width="320"></fs-video>
848
+ */
849
+ export class FsVideo extends FsMedia {
850
+ protected readonly mediaTag = "video";
851
+ protected readonly partName = "video";
852
+ protected readonly mediaLabel = "视频";
853
+ protected readonly acceptPrefix = "video/";
854
+ protected readonly loadEventName = "loadeddata";
855
+ protected readonly mediaAttrs = [
856
+ "controls",
857
+ "autoplay",
858
+ "loop",
859
+ "muted",
860
+ "preload",
861
+ "width",
862
+ "height",
863
+ ] as const;
864
+ protected readonly defaultAttrs = ["controls"] as const;
865
+ protected readonly shadowCss = `
866
+ video {
867
+ display: block;
868
+ max-width: 100%;
869
+ height: auto;
870
+ }
871
+ `;
872
+ }
873
+
874
+ // 注册自定义元素(避免重复注册导致报错)
875
+ if (typeof customElements !== "undefined" && !customElements.get("fs-audio")) {
876
+ customElements.define("fs-audio", FsAudio);
877
+ }
878
+ if (typeof customElements !== "undefined" && !customElements.get("fs-video")) {
879
+ customElements.define("fs-video", FsVideo);
880
+ }