@ysgroup/ui 0.1.41 → 0.1.42

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ysgroup/ui",
3
- "version": "0.1.41",
3
+ "version": "0.1.42",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -29,7 +29,10 @@ const text = computed(() => {
29
29
  <span
30
30
  v-if="text"
31
31
  class="ys-count-badge"
32
- :class="{ 'ys-count-badge--corner': corner, 'ys-count-badge--inverse': inverse }"
32
+ :class="{
33
+ 'ys-count-badge--corner': corner,
34
+ 'ys-count-badge--inverse': inverse,
35
+ }"
33
36
  aria-hidden="true"
34
37
  >{{ text }}</span
35
38
  >
@@ -1,6 +1,7 @@
1
1
  <!-- YsFilePreview —— 文件预览弹窗,全平台统一的文件预览入口。
2
2
  PDF 用浏览器自带阅读器(iframe 打开 blob 地址,支持翻页、缩放、搜索、打印),
3
- 图片、文本、音视频直接显示,其他类型提示下载。文件内容由调用方的 load 取回(WS 分块、HTTP 都行),
3
+ 图片、文本、音视频直接显示,其他类型提示下载。文件名和 content_type 认不出类型时(如只有材料编号),
4
+ 读到 Blob 后按 Blob 的 type 和文件头识别(sniffFileType,只读开头几 KB)。文件内容由调用方的 load 取回(WS 分块、HTTP 都行),
4
5
  组件只负责显示、进度、出错重试、下载、新标签打开、全屏和 ← → 切换。关闭后回收 blob 地址。 -->
5
6
  <script setup lang="ts">
6
7
  import { computed, onBeforeUnmount, ref, watch } from "vue";
@@ -19,7 +20,7 @@ import {
19
20
  formatFileSize,
20
21
  previewKindOf,
21
22
  saveBlob,
22
- sniffPreviewKind,
23
+ sniffFileType,
23
24
  type YsPreviewFile,
24
25
  type YsPreviewKind,
25
26
  } from "../filePreview";
@@ -51,6 +52,8 @@ const url = ref("");
51
52
  const text = ref("");
52
53
  const textCut = ref(false);
53
54
  const kind = ref<YsPreviewKind>("none");
55
+ /** 按内容识别出的 MIME;文件名、content_type 已能确定类型时为空。 */
56
+ const sniffedMime = ref("");
54
57
  const fullscreen = ref(false);
55
58
  let token = 0;
56
59
 
@@ -58,10 +61,15 @@ const file = computed<YsPreviewFile | null>(() => props.files[current.value] ??
58
61
  const total = computed(() => props.files.length);
59
62
  const canPrev = computed(() => current.value > 0);
60
63
  const canNext = computed(() => current.value < total.value - 1);
64
+ /** 类型标签:按内容识别出类型时用识别结果。 */
65
+ const typeLabel = computed(() => {
66
+ if (!file.value) return "";
67
+ return fileTypeLabel(file.value.name, sniffedMime.value || file.value.content_type);
68
+ });
61
69
  const meta = computed(() => {
62
70
  if (!file.value) return "";
63
71
  const size = formatFileSize(file.value.size);
64
- return [fileTypeLabel(file.value.name, file.value.content_type), size].filter(Boolean).join(" · ");
72
+ return [typeLabel.value, size].filter(Boolean).join(" · ");
65
73
  });
66
74
 
67
75
  function release() {
@@ -78,6 +86,7 @@ async function open() {
78
86
  release();
79
87
  error.value = "";
80
88
  progress.value = 0;
89
+ sniffedMime.value = "";
81
90
  if (!target) return;
82
91
  kind.value = previewKindOf(target);
83
92
  loading.value = true;
@@ -86,13 +95,16 @@ async function open() {
86
95
  if (mine === token) progress.value = Math.max(0, Math.min(1, ratio));
87
96
  });
88
97
  if (mine !== token) return;
89
- if (kind.value === "none") kind.value = await sniffPreviewKind(data);
90
- if (mine !== token) return;
91
- // PDF 必须带 application/pdf 类型,浏览器才会用自带阅读器打开。
92
- const typed =
93
- kind.value === "pdf" && data.type !== "application/pdf"
94
- ? new Blob([data], { type: "application/pdf" })
95
- : data;
98
+ let mime = kind.value === "pdf" ? "application/pdf" : "";
99
+ if (kind.value === "none") {
100
+ const sniffed = await sniffFileType(data);
101
+ if (mine !== token) return;
102
+ kind.value = sniffed.kind;
103
+ mime = sniffed.mime;
104
+ sniffedMime.value = sniffed.mime;
105
+ }
106
+ // 补上识别出的类型:PDF 必须带 application/pdf,浏览器才会用自带阅读器;新标签页打开也靠它。
107
+ const typed = mime && data.type !== mime ? new Blob([data], { type: mime }) : data;
96
108
  blob.value = typed;
97
109
  if (kind.value === "text") {
98
110
  textCut.value = typed.size > TEXT_PREVIEW_LIMIT;
@@ -265,7 +277,7 @@ function openInTab() {
265
277
  </div>
266
278
  <div v-else class="ys-file-preview__state">
267
279
  <el-icon :size="40" class="ys-file-preview__placeholder"><Document /></el-icon>
268
- <strong>{{ fileTypeLabel(file.name, file.content_type) }} 文件暂不支持在线预览</strong>
280
+ <strong>{{ typeLabel }} 文件暂不支持在线预览</strong>
269
281
  <span>下载后用本地软件打开</span>
270
282
  <el-button type="primary" :icon="Download" @click="download">下载</el-button>
271
283
  </div>
@@ -41,11 +41,109 @@ export function previewKindOf(file: Pick<YsPreviewFile, "name" | "content_type">
41
41
  return "none";
42
42
  }
43
43
 
44
- /** 扩展名或 MIME 认不出时看文件头:%PDF 按 PDF 预览。 */
44
+ /** 按内容识别出的类型:kind 决定怎么预览,mime 用来给 Blob 补上类型(新标签页打开、浏览器阅读器要用)。 */
45
+ export type YsSniffedType = { kind: YsPreviewKind; mime: string };
46
+
47
+ const UNKNOWN: YsSniffedType = { kind: "none", mime: "" };
48
+ /** 识别要读的文件头字节数:魔数只看前几十字节,文本看这一段能否按 UTF-8 严格解码。 */
49
+ export const SNIFF_HEAD_BYTES = 4096;
50
+ /** PDF 规范允许 %PDF- 前面有少量字节,在开头这么多字节内找。 */
51
+ const PDF_SEARCH_BYTES = 1024;
52
+ /** BMP 的 DIB 头长度只有这几种,用来排除以 BM 开头的文本。 */
53
+ const BMP_DIB_SIZES = new Set([12, 40, 52, 56, 64, 108, 124]);
54
+
55
+ function ascii(bytes: Uint8Array, start: number, text: string): boolean {
56
+ if (bytes.length < start + text.length) return false;
57
+ for (let i = 0; i < text.length; i += 1) if (bytes[start + i] !== text.charCodeAt(i)) return false;
58
+ return true;
59
+ }
60
+
61
+ function hasPdfMarker(bytes: Uint8Array): boolean {
62
+ const end = Math.min(bytes.length, PDF_SEARCH_BYTES) - 5;
63
+ for (let i = 0; i <= end; i += 1) if (bytes[i] === 0x25 && ascii(bytes, i, "%PDF-")) return true;
64
+ return false;
65
+ }
66
+
67
+ function ftypType(brand: string): YsSniffedType {
68
+ if (brand === "avif" || brand === "avis") return { kind: "image", mime: "image/avif" };
69
+ if (brand === "qt ") return { kind: "video", mime: "video/quicktime" };
70
+ if (brand.startsWith("M4A") || brand.startsWith("M4B")) return { kind: "audio", mime: "audio/mp4" };
71
+ // HEIC 浏览器大多不能显示,按未知处理(提示下载)。
72
+ if (brand.startsWith("hei") || brand.startsWith("hev") || brand === "mif1" || brand === "msf1") return UNKNOWN;
73
+ return { kind: "video", mime: "video/mp4" };
74
+ }
75
+
76
+ function isBinaryControl(byte: number): boolean {
77
+ // NUL 和除 \t \n \v \f \r ESC 以外的控制字符基本只出现在二进制文件里。
78
+ return byte < 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0b && byte !== 0x0c && byte !== 0x0d && byte !== 0x1b;
79
+ }
80
+
81
+ function looksLikeText(bytes: Uint8Array, complete: boolean): boolean {
82
+ if (bytes.length === 0 || bytes.some(isBinaryControl)) return false;
83
+ try {
84
+ // 只读了开头时用 stream,末尾被截断的多字节字符不算错。
85
+ new TextDecoder("utf-8", { fatal: true }).decode(bytes, { stream: !complete });
86
+ return true;
87
+ } catch {
88
+ return false;
89
+ }
90
+ }
91
+
92
+ /**
93
+ * 按文件头识别类型(纯函数)。head 是文件开头的字节(读 SNIFF_HEAD_BYTES 个即可),size 是整个文件的字节数。
94
+ * 认得 PDF、PNG、JPEG、GIF、WebP、BMP、AVIF,MP4/MOV/M4A(ftyp)、WebM/MKV、MP3、AAC、OGG、WAV、FLAC;
95
+ * 都不是时,文件不超过 TEXT_PREVIEW_LIMIT、开头能按 UTF-8 严格解码且没有二进制控制字符就当文本。
96
+ */
97
+ export function sniffFileHead(head: Uint8Array, size = head.length): YsSniffedType {
98
+ const b = head;
99
+ if (hasPdfMarker(b)) return { kind: "pdf", mime: "application/pdf" };
100
+ if (ascii(b, 0, "\x89PNG\r\n\x1a\n")) return { kind: "image", mime: "image/png" };
101
+ if (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { kind: "image", mime: "image/jpeg" };
102
+ if (ascii(b, 0, "GIF87a") || ascii(b, 0, "GIF89a")) return { kind: "image", mime: "image/gif" };
103
+ if (ascii(b, 0, "RIFF") && ascii(b, 8, "WEBP")) return { kind: "image", mime: "image/webp" };
104
+ if (ascii(b, 0, "RIFF") && ascii(b, 8, "WAVE")) return { kind: "audio", mime: "audio/wav" };
105
+ if (ascii(b, 0, "BM") && b.length >= 18) {
106
+ const view = new DataView(b.buffer, b.byteOffset, b.byteLength);
107
+ if (view.getUint32(6, true) === 0 && BMP_DIB_SIZES.has(view.getUint32(14, true)))
108
+ return { kind: "image", mime: "image/bmp" };
109
+ }
110
+ if (b.length >= 12 && ascii(b, 4, "ftyp")) return ftypType(String.fromCharCode(b[8], b[9], b[10], b[11]));
111
+ if (b[0] === 0x1a && b[1] === 0x45 && b[2] === 0xdf && b[3] === 0xa3) return { kind: "video", mime: "video/webm" };
112
+ if (ascii(b, 0, "OggS")) return { kind: "audio", mime: "audio/ogg" };
113
+ if (ascii(b, 0, "fLaC")) return { kind: "audio", mime: "audio/flac" };
114
+ if (ascii(b, 0, "ID3")) return { kind: "audio", mime: "audio/mpeg" };
115
+ // 没有 ID3 的 MP3(Layer III 帧同步 FF E2/E3/F2/F3/FA/FB)和 AAC(ADTS,FF F1/F9)。
116
+ // 只认这几种,避免把 UTF-16 的 FF FE 当成音频。
117
+ if (b.length >= 3 && b[0] === 0xff && b[2] >> 4 !== 0x0f) {
118
+ if ((b[1] & 0xe6) === 0xe2 && (b[1] & 0x18) !== 0x08) return { kind: "audio", mime: "audio/mpeg" };
119
+ if ((b[1] & 0xf6) === 0xf0) return { kind: "audio", mime: "audio/aac" };
120
+ }
121
+ if (size <= TEXT_PREVIEW_LIMIT && looksLikeText(b, b.length >= size))
122
+ return { kind: "text", mime: "text/plain;charset=utf-8" };
123
+ return UNKNOWN;
124
+ }
125
+
126
+ /** Blob 自带的 type 能确定预览方式时直接用;空或 application/octet-stream 这类兜底类型返回 null。 */
127
+ function typeFromBlob(blob: Blob): YsSniffedType | null {
128
+ const kind = previewKindOf({ name: "", content_type: blob.type });
129
+ return kind === "none" ? null : { kind, mime: blob.type };
130
+ }
131
+
132
+ /**
133
+ * 文件名、content_type 认不出时按内容识别:先看 Blob 自带的 type,再只读开头 SNIFF_HEAD_BYTES 字节看魔数和文本,
134
+ * 不读整个文件。
135
+ */
136
+ export async function sniffFileType(blob: Blob): Promise<YsSniffedType> {
137
+ const typed = typeFromBlob(blob);
138
+ if (typed) return typed;
139
+ if (blob.size === 0) return UNKNOWN;
140
+ const head = new Uint8Array(await blob.slice(0, SNIFF_HEAD_BYTES).arrayBuffer());
141
+ return sniffFileHead(head, blob.size);
142
+ }
143
+
144
+ /** 扩展名或 MIME 认不出时按内容判断预览方式(见 sniffFileType)。 */
45
145
  export async function sniffPreviewKind(blob: Blob): Promise<YsPreviewKind> {
46
- const head = new Uint8Array(await blob.slice(0, 5).arrayBuffer());
47
- const text = String.fromCharCode(...head);
48
- return text.startsWith("%PDF") ? "pdf" : "none";
146
+ return (await sniffFileType(blob)).kind;
49
147
  }
50
148
 
51
149
  const TYPE_LABELS: [string[], string][] = [
@@ -62,6 +160,7 @@ export function fileTypeLabel(name: string, contentType = ""): string {
62
160
  const ext = fileExtension(name);
63
161
  for (const [exts, label] of TYPE_LABELS) if (exts.includes(ext)) return label;
64
162
  const kind = previewKindOf({ name, content_type: contentType });
163
+ if (kind === "pdf") return "PDF";
65
164
  if (kind === "image") return "图片";
66
165
  if (kind === "video") return "视频";
67
166
  if (kind === "audio") return "音频";
package/src/index.ts CHANGED
@@ -26,6 +26,9 @@ export { default as YsFilePreview } from "./components/YsFilePreview.vue";
26
26
  export {
27
27
  previewKindOf,
28
28
  sniffPreviewKind,
29
+ sniffFileType,
30
+ sniffFileHead,
31
+ SNIFF_HEAD_BYTES,
29
32
  fileExtension,
30
33
  fileTypeLabel,
31
34
  formatFileSize,
@@ -33,6 +36,7 @@ export {
33
36
  TEXT_PREVIEW_LIMIT,
34
37
  type YsPreviewFile,
35
38
  type YsPreviewKind,
39
+ type YsSniffedType,
36
40
  } from "./filePreview";
37
41
  export { enumOptions, enumLabel, type EnumOption } from "./tokens-runtime";
38
42
  export {