@ysgroup/ui 0.1.51 → 0.1.52

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.51",
3
+ "version": "0.1.52",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -11,7 +11,7 @@
11
11
  },
12
12
  "peerDependencies": {
13
13
  "@ysgroup/contracts": ">=0.1.50",
14
- "@ysgroup/core": ">=0.1.28",
14
+ "@ysgroup/core": ">=0.1.29",
15
15
  "@ysgroup/theme": ">=0.3.1",
16
16
  "element-plus": ">=2.9",
17
17
  "vue": ">=3.5"
@@ -26,7 +26,7 @@
26
26
  },
27
27
  "devDependencies": {
28
28
  "@ysgroup/contracts": "^0.1.51",
29
- "@ysgroup/core": "^0.1.28",
29
+ "@ysgroup/core": "^0.1.29",
30
30
  "@ysgroup/theme": "^0.3.1",
31
31
  "docx-preview": "^0.4.1"
32
32
  }
@@ -18,6 +18,9 @@ const props = withDefaults(
18
18
  width?: string | number;
19
19
  /** 有未保存的修改:点右上角关闭、按 Esc、点取消都先问「放弃未保存的修改?」。 */
20
20
  dirty?: boolean;
21
+ /** dirty 时关闭确认的文案和按钮(如还有文件没传完:「关闭会取消这些上传…」「取消上传并关闭」)。 */
22
+ dirtyText?: string;
23
+ dirtyConfirmText?: string;
21
24
  /** 提交中:确认按钮转圈,取消、右上角关闭、Esc 都不起作用。 */
22
25
  confirmLoading?: boolean;
23
26
  confirmText?: string;
@@ -34,6 +37,8 @@ const props = withDefaults(
34
37
  title: "",
35
38
  width: "520px",
36
39
  dirty: false,
40
+ dirtyText: "放弃未保存的修改?",
41
+ dirtyConfirmText: "放弃修改",
37
42
  confirmLoading: false,
38
43
  confirmText: "保存",
39
44
  cancelText: "取消",
@@ -67,7 +72,7 @@ async function allowClose(): Promise<boolean> {
67
72
  if (!props.dirty) return true;
68
73
  asking = true;
69
74
  try {
70
- return await ysConfirm("放弃未保存的修改?", { title: "关闭确认", confirmText: "放弃修改", cancelText: "继续编辑" });
75
+ return await ysConfirm(props.dirtyText, { title: "关闭确认", confirmText: props.dirtyConfirmText, cancelText: "继续编辑" });
71
76
  } finally {
72
77
  asking = false;
73
78
  }
@@ -0,0 +1,138 @@
1
+ <!-- YsFileDropZone —— 拖入与粘贴上传区:把文件拖进区域、或在区域里 Ctrl/⌘+V 粘贴截图,都发 files 事件。
2
+ 规则(规范 8.11):
3
+ - 只接管拖入的「文件」(拖文字、链接、页面元素不管);进出深度计数,在子元素之间移动遮罩不闪;
4
+ 不能接收时也 preventDefault,免得文件掉在页面上浏览器跳去打开它。
5
+ - 嵌套区域加 exclusive:落在内层只给内层(如回复框),不冒泡给外层(如详情面板)。
6
+ - 粘贴:剪贴板里有文件且没有纯文本才当附件(Excel 单元格同时带图和文字,照常粘贴文字);剪贴板默认名改成
7
+ 「截图 MM-DD HHmmss.png」。paste="inside" 只在区域内有焦点时接管(默认),"window" 整页接管,false 不接管。
8
+ - 遮罩跟着区域、不挡操作(pointer-events: none),文案写清上限和粘贴方式。 -->
9
+ <script setup lang="ts">
10
+ import { onBeforeUnmount, onMounted, ref } from "vue";
11
+ import { hasDraggedFiles, pastedFiles } from "../fileRules";
12
+
13
+ const props = withDefaults(
14
+ defineProps<{
15
+ disabled?: boolean;
16
+ exclusive?: boolean;
17
+ paste?: "inside" | "window" | false;
18
+ title?: string;
19
+ hint?: string;
20
+ }>(),
21
+ { disabled: false, exclusive: false, paste: "inside", title: "松开即上传", hint: "" },
22
+ );
23
+
24
+ const emit = defineEmits<{ files: [files: File[]] }>();
25
+
26
+ const root = ref<HTMLElement | null>(null);
27
+ const over = ref(false);
28
+ let depth = 0;
29
+
30
+ function onEnter(event: DragEvent) {
31
+ if (!hasDraggedFiles(event)) return;
32
+ event.preventDefault();
33
+ if (props.exclusive) event.stopPropagation();
34
+ depth += 1;
35
+ over.value = !props.disabled;
36
+ }
37
+
38
+ function onOver(event: DragEvent) {
39
+ if (!hasDraggedFiles(event)) return;
40
+ event.preventDefault();
41
+ if (props.exclusive) event.stopPropagation();
42
+ if (event.dataTransfer) event.dataTransfer.dropEffect = props.disabled ? "none" : "copy";
43
+ }
44
+
45
+ function onLeave(event: DragEvent) {
46
+ if (!hasDraggedFiles(event)) return;
47
+ if (props.exclusive) event.stopPropagation();
48
+ depth = Math.max(0, depth - 1);
49
+ if (depth === 0) over.value = false;
50
+ }
51
+
52
+ function onDrop(event: DragEvent) {
53
+ if (!hasDraggedFiles(event)) return;
54
+ event.preventDefault();
55
+ if (props.exclusive) event.stopPropagation();
56
+ depth = 0;
57
+ over.value = false;
58
+ if (props.disabled) return;
59
+ const files = Array.from(event.dataTransfer?.files ?? []);
60
+ if (files.length) emit("files", files);
61
+ }
62
+
63
+ function onPaste(event: ClipboardEvent) {
64
+ if (props.disabled || !props.paste || event.defaultPrevented) return;
65
+ const files = pastedFiles(event);
66
+ if (!files.length) return;
67
+ event.preventDefault();
68
+ if (props.exclusive) event.stopPropagation();
69
+ emit("files", files);
70
+ }
71
+
72
+ function onWindowPaste(event: ClipboardEvent) {
73
+ // 落在别的上传区里的粘贴由那个区处理。
74
+ const target = event.target as HTMLElement | null;
75
+ if (target?.closest(".ys-drop-zone") && !root.value?.contains(target)) return;
76
+ onPaste(event);
77
+ }
78
+
79
+ function onInsidePaste(event: ClipboardEvent) {
80
+ if (props.paste === "inside") onPaste(event);
81
+ }
82
+
83
+ onMounted(() => {
84
+ if (props.paste === "window") window.addEventListener("paste", onWindowPaste);
85
+ });
86
+ onBeforeUnmount(() => window.removeEventListener("paste", onWindowPaste));
87
+ </script>
88
+
89
+ <template>
90
+ <div
91
+ ref="root"
92
+ class="ys-drop-zone"
93
+ :class="{ 'is-over': over }"
94
+ :tabindex="paste === 'inside' ? -1 : undefined"
95
+ @dragenter="onEnter"
96
+ @dragover="onOver"
97
+ @dragleave="onLeave"
98
+ @drop="onDrop"
99
+ @paste="onInsidePaste"
100
+ >
101
+ <slot :over="over" />
102
+ <div v-if="over" class="ys-drop-zone__overlay" aria-hidden="true">
103
+ <strong>{{ title }}</strong>
104
+ <span v-if="hint">{{ hint }}</span>
105
+ </div>
106
+ </div>
107
+ </template>
108
+
109
+ <style scoped>
110
+ .ys-drop-zone {
111
+ position: relative;
112
+ outline: none;
113
+ }
114
+ .ys-drop-zone__overlay {
115
+ position: absolute;
116
+ inset: 0;
117
+ z-index: 20;
118
+ display: flex;
119
+ flex-direction: column;
120
+ gap: 6px;
121
+ align-items: center;
122
+ justify-content: center;
123
+ padding: 16px;
124
+ border: 2px dashed var(--ys-color-primary);
125
+ border-radius: var(--ys-radius-m);
126
+ color: var(--ys-color-primary);
127
+ background: color-mix(in srgb, var(--ys-color-primary) 8%, var(--ys-color-bg-elevated) 86%);
128
+ text-align: center;
129
+ pointer-events: none;
130
+ }
131
+ .ys-drop-zone__overlay strong {
132
+ font-size: 16px;
133
+ }
134
+ .ys-drop-zone__overlay span {
135
+ color: var(--ys-color-text-2);
136
+ font-size: 13px;
137
+ }
138
+ </style>
@@ -0,0 +1,178 @@
1
+ <!-- YsFileNotes —— 文件标签:文件按文件规范检查后的结论(ys_base.files.file_media_fields 的 notes)。
2
+ 三个级别:不符合规范(红)、建议(橙)、说明(灰)。悬停或聚焦看原因和建议;inline 时直接把原因写出来(详情页、预览头部)。
3
+ 标签按级别排好序(服务端已排),max 之外的折叠成「+N」。 -->
4
+ <script setup lang="ts">
5
+ import { computed } from "vue";
6
+ import type { YsFileNote } from "../fileRules";
7
+
8
+ const props = withDefaults(
9
+ defineProps<{
10
+ notes?: YsFileNote[] | null;
11
+ /** 最多显示几个标签,其余折叠为「+N」(悬停看全部);0 为不限。 */
12
+ max?: number;
13
+ /** 只显示这些级别(如列表里只显示 noncompliant、advice)。 */
14
+ levels?: string[];
15
+ /** 平铺展开:标题 + 原因 + 建议,不用悬停。 */
16
+ inline?: boolean;
17
+ }>(),
18
+ { notes: () => [], max: 0, levels: undefined, inline: false },
19
+ );
20
+
21
+ const shown = computed(() => (props.notes ?? []).filter((note) => !props.levels || props.levels.includes(note.level)));
22
+ const visible = computed(() => (props.max > 0 ? shown.value.slice(0, props.max) : shown.value));
23
+ const hidden = computed(() => shown.value.slice(visible.value.length));
24
+ const tone = (level: string) => (level === "noncompliant" ? "danger" : level === "advice" ? "warning" : "info");
25
+ </script>
26
+
27
+ <template>
28
+ <div v-if="shown.length && inline" class="ys-file-notes is-inline">
29
+ <div v-for="note in shown" :key="note.code" class="ys-file-notes__row" :class="`is-${tone(note.level)}`">
30
+ <span class="ys-file-notes__level">{{ note.level_label }}</span>
31
+ <div class="ys-file-notes__body">
32
+ <strong>{{ note.title }}</strong>
33
+ <p v-if="note.reason">{{ note.reason }}</p>
34
+ <p v-if="note.suggestion" class="ys-file-notes__suggestion">建议:{{ note.suggestion }}</p>
35
+ </div>
36
+ </div>
37
+ </div>
38
+ <span v-else-if="shown.length" class="ys-file-notes">
39
+ <el-popover v-for="note in visible" :key="note.code" trigger="hover" placement="top" :width="320" :show-after="200">
40
+ <template #reference>
41
+ <button type="button" class="ys-file-notes__tag" :class="`is-${tone(note.level)}`" :aria-label="`${note.level_label}:${note.title}`">
42
+ {{ note.title }}
43
+ </button>
44
+ </template>
45
+ <div class="ys-file-notes__pop">
46
+ <div class="ys-file-notes__pop-head" :class="`is-${tone(note.level)}`">
47
+ <span class="ys-file-notes__level">{{ note.level_label }}</span>
48
+ <strong>{{ note.title }}</strong>
49
+ </div>
50
+ <p v-if="note.reason">{{ note.reason }}</p>
51
+ <p v-if="note.suggestion" class="ys-file-notes__suggestion">建议:{{ note.suggestion }}</p>
52
+ </div>
53
+ </el-popover>
54
+ <el-popover v-if="hidden.length" trigger="hover" placement="top" :width="320" :show-after="200">
55
+ <template #reference>
56
+ <button type="button" class="ys-file-notes__tag is-more" :aria-label="`还有 ${hidden.length} 个标签`">+{{ hidden.length }}</button>
57
+ </template>
58
+ <div class="ys-file-notes__pop">
59
+ <div v-for="note in hidden" :key="note.code" class="ys-file-notes__pop-item">
60
+ <div class="ys-file-notes__pop-head" :class="`is-${tone(note.level)}`">
61
+ <span class="ys-file-notes__level">{{ note.level_label }}</span>
62
+ <strong>{{ note.title }}</strong>
63
+ </div>
64
+ <p v-if="note.reason">{{ note.reason }}</p>
65
+ <p v-if="note.suggestion" class="ys-file-notes__suggestion">建议:{{ note.suggestion }}</p>
66
+ </div>
67
+ </div>
68
+ </el-popover>
69
+ </span>
70
+ </template>
71
+
72
+ <style>
73
+ /* 不 scoped:el-popover 的内容挂在 body 下。 */
74
+ .ys-file-notes {
75
+ display: inline-flex;
76
+ flex-wrap: wrap;
77
+ gap: 4px;
78
+ vertical-align: middle;
79
+ }
80
+ .ys-file-notes__tag {
81
+ max-width: 14em;
82
+ overflow: hidden;
83
+ padding: 0 6px;
84
+ border: 1px solid transparent;
85
+ border-radius: var(--ys-radius-s);
86
+ font: inherit;
87
+ font-size: 12px;
88
+ line-height: 18px;
89
+ white-space: nowrap;
90
+ text-overflow: ellipsis;
91
+ cursor: default;
92
+ }
93
+ .ys-file-notes__tag:focus-visible {
94
+ outline: var(--ys-focus-outline);
95
+ }
96
+ .ys-file-notes__tag.is-danger {
97
+ color: var(--ys-color-danger);
98
+ background: color-mix(in srgb, var(--ys-color-danger) 10%, transparent);
99
+ border-color: color-mix(in srgb, var(--ys-color-danger) 28%, transparent);
100
+ }
101
+ .ys-file-notes__tag.is-warning {
102
+ color: color-mix(in srgb, var(--ys-color-warning) 80%, var(--ys-color-text-1));
103
+ background: color-mix(in srgb, var(--ys-color-warning) 12%, transparent);
104
+ border-color: color-mix(in srgb, var(--ys-color-warning) 30%, transparent);
105
+ }
106
+ .ys-file-notes__tag.is-info,
107
+ .ys-file-notes__tag.is-more {
108
+ color: var(--ys-color-text-2);
109
+ background: color-mix(in srgb, var(--ys-color-text-3) 10%, transparent);
110
+ border-color: color-mix(in srgb, var(--ys-color-text-3) 22%, transparent);
111
+ }
112
+ .ys-file-notes__pop p {
113
+ margin: 6px 0 0;
114
+ color: var(--ys-color-text-2);
115
+ font-size: 13px;
116
+ line-height: 1.6;
117
+ }
118
+ .ys-file-notes__pop-item + .ys-file-notes__pop-item {
119
+ margin-top: 10px;
120
+ padding-top: 10px;
121
+ border-top: 1px solid var(--ys-color-border);
122
+ }
123
+ .ys-file-notes__pop-head {
124
+ display: flex;
125
+ align-items: center;
126
+ gap: 6px;
127
+ color: var(--ys-color-text-1);
128
+ }
129
+ .ys-file-notes__level {
130
+ flex: none;
131
+ padding: 0 5px;
132
+ border-radius: var(--ys-radius-s);
133
+ font-size: 12px;
134
+ line-height: 18px;
135
+ color: var(--ys-color-text-2);
136
+ background: color-mix(in srgb, var(--ys-color-text-3) 12%, transparent);
137
+ }
138
+ .is-danger > .ys-file-notes__level {
139
+ color: var(--ys-color-danger);
140
+ background: color-mix(in srgb, var(--ys-color-danger) 12%, transparent);
141
+ }
142
+ .is-warning > .ys-file-notes__level {
143
+ color: color-mix(in srgb, var(--ys-color-warning) 80%, var(--ys-color-text-1));
144
+ background: color-mix(in srgb, var(--ys-color-warning) 14%, transparent);
145
+ }
146
+ .ys-file-notes__suggestion {
147
+ color: var(--ys-color-text-1) !important;
148
+ }
149
+ .ys-file-notes.is-inline {
150
+ display: flex;
151
+ flex-direction: column;
152
+ gap: 8px;
153
+ }
154
+ .ys-file-notes__row {
155
+ display: flex;
156
+ gap: 8px;
157
+ align-items: flex-start;
158
+ padding: 8px 10px;
159
+ border-radius: var(--ys-radius-m);
160
+ background: color-mix(in srgb, var(--ys-color-text-3) 6%, transparent);
161
+ }
162
+ .ys-file-notes__row.is-danger {
163
+ background: color-mix(in srgb, var(--ys-color-danger) 6%, transparent);
164
+ }
165
+ .ys-file-notes__row.is-warning {
166
+ background: color-mix(in srgb, var(--ys-color-warning) 8%, transparent);
167
+ }
168
+ .ys-file-notes__body {
169
+ min-width: 0;
170
+ color: var(--ys-color-text-1);
171
+ font-size: 13px;
172
+ }
173
+ .ys-file-notes__body p {
174
+ margin: 2px 0 0;
175
+ color: var(--ys-color-text-2);
176
+ line-height: 1.6;
177
+ }
178
+ </style>
@@ -4,12 +4,16 @@
4
4
  文件名和 content_type 认不出类型时(如只有材料编号),读到 Blob 后按 Blob 的 type 和文件头识别(sniffFileType)。
5
5
  文件内容由调用方的 load 取回(WS 分块、HTTP 都行),组件负责显示、进度、出错重试、下载、新标签打开、全屏和 ← → 切换;
6
6
  Esc 关闭;焦点在播放器上时 ← → 留给播放器快退快进。窄屏(≤ 640px)自动全屏。关闭后回收 blob 地址。
7
- 重型依赖(pdf.js、SheetJS、docx-preview)打开对应类型才加载。 -->
7
+ 重型依赖(pdf.js、SheetJS、docx-preview)打开对应类型才加载。
8
+ 文件规范:文件带 notes 时头部显示文件标签;可内嵌脚本的类型(SVG、HTML、XML……)不提供「新标签页打开」——
9
+ blob 地址与页面同源,新标签页里脚本会以本系统身份运行;页内的 <img>、文本预览不执行脚本,照常显示。 -->
8
10
  <script setup lang="ts">
9
11
  import { computed, defineAsyncComponent, onBeforeUnmount, onMounted, ref, shallowRef, watch } from "vue";
10
12
  import YsImageViewer from "./YsImageViewer.vue";
11
13
  import YsViewerIcon from "./YsViewerIcon.vue";
12
14
  import YsViewerState from "./YsViewerState.vue";
15
+ import YsFileNotes from "./YsFileNotes.vue";
16
+ import { isActiveContent } from "../fileRules";
13
17
  import "../preview/viewer.css";
14
18
  import {
15
19
  OFFICE_MIME,
@@ -75,7 +79,11 @@ const typeLabel = computed(() => (file.value ? fileTypeLabel(file.value.name, mi
75
79
  const sizeText = computed(() => formatFileSize(file.value?.size));
76
80
  const isFull = computed(() => fullscreen.value || narrow.value);
77
81
  /** 新标签页打开只对浏览器能直接显示的类型有意义。 */
78
- const canOpenInTab = computed(() => ["pdf", "image", "video", "audio"].includes(kind.value));
82
+ const canOpenInTab = computed(
83
+ () =>
84
+ ["pdf", "image", "video", "audio"].includes(kind.value) &&
85
+ !(file.value && isActiveContent({ ...file.value, content_type: mime.value || file.value.content_type })),
86
+ );
79
87
  const isCsv = computed(() => fileExtension(file.value?.name ?? "") === "csv" || /csv/i.test(mime.value));
80
88
  /** 标题栏左侧的类型色块:PDF 红、表格绿、文档蓝、图片橙、音视频紫灰,其他中性。 */
81
89
  const badge = computed(() => {
@@ -88,6 +96,8 @@ const unsupported = computed(() => {
88
96
  const ext = fileExtension(file.value?.name ?? "");
89
97
  if (ext === "doc" || ext === "wps" || mime.value === OFFICE_MIME.doc)
90
98
  return { title: "旧版 Word(.doc)暂不支持在线预览", detail: "下载后用 Word / WPS 打开;另存为 .docx 后上传即可在线预览。" };
99
+ if (ext === "heic" || ext === "heif")
100
+ return { title: "HEIC 照片多数浏览器不能直接显示", detail: "下载后用系统相册打开;iPhone 可在「设置 → 相机 → 格式」选「兼容性最佳」,以后拍的就是 JPG。" };
91
101
  if (["ppt", "pptx", "dps"].includes(ext) || mime.value.includes("presentation") || mime.value === OFFICE_MIME.ppt)
92
102
  return { title: "演示文稿暂不支持在线预览", detail: "下载后用 PowerPoint / WPS 打开。" };
93
103
  return { title: `${typeLabel.value || "此类"}文件暂不支持在线预览`, detail: "下载后用本地软件打开。" };
@@ -249,6 +259,7 @@ function openInTab() {
249
259
  <span v-if="typeLabel" class="ys-file-preview__type">{{ typeLabel }}</span>
250
260
  <span v-if="sizeText">{{ sizeText }}</span>
251
261
  <span v-if="total > 1" class="ys-file-preview__index">{{ current + 1 }} / {{ total }}</span>
262
+ <YsFileNotes v-if="file?.notes?.length" :notes="file.notes" :max="3" />
252
263
  </span>
253
264
  </div>
254
265
  <div class="ys-file-preview__tools">
@@ -0,0 +1,287 @@
1
+ <!-- YsUploadQueue —— 上传队列面板(配 useYsUploadQueue)。
2
+ - 「待上传」:列出会怎么处理(无损转 WebP / 原样保存 / 转码 / 限制打开),能转换的图片可勾「原图」,有「全部原图」;
3
+ 立即上传模式下点「上传 N 个」开始,待提交模式(staged)显示「提交后上传」、不出确认按钮。
4
+ - 进行中:校验中 / 上传中(从 N% 续传)/ 处理中;完成:秒传完成 / 已上传,带服务端的文件标签;
5
+ 已中断显示「继续」,失败显示原因和「重试」,移除会清掉服务端半截的上传。
6
+ - 本地检查不通过、超过数量、重复加入的提示显示在顶部,可关闭。 -->
7
+ <script setup lang="ts" generic="T extends Record<string, unknown>">
8
+ import { computed } from "vue";
9
+ import { fileExtension, formatFileSize } from "../filePreview";
10
+ import type { YsFileNote } from "../fileRules";
11
+ import { uploadStateText, type YsUploadItem, type YsUploadQueue } from "../uploadQueue";
12
+ import YsFileNotes from "./YsFileNotes.vue";
13
+
14
+ const props = withDefaults(
15
+ defineProps<{
16
+ queue: YsUploadQueue<T>;
17
+ /** 待提交模式:待上传行显示「提交后上传」,不出「取消 / 上传」按钮(由业务的提交按钮触发 start)。 */
18
+ staged?: boolean;
19
+ /** 完成的行是否继续显示(默认显示,可「清除已完成」)。 */
20
+ showDone?: boolean;
21
+ }>(),
22
+ { staged: false, showDone: true },
23
+ );
24
+
25
+ const items = computed(() =>
26
+ props.showDone ? props.queue.items.value : props.queue.items.value.filter((item) => item.state !== "done"),
27
+ );
28
+ const pending = computed(() => props.queue.pending.value);
29
+ const convertible = computed(() => pending.value.filter((item) => item.handling.canKeepOriginal));
30
+ const allAsIs = computed(() => convertible.value.length > 0 && convertible.value.every((item) => item.asIs));
31
+ const someAsIs = computed(() => convertible.value.some((item) => item.asIs) && !allAsIs.value);
32
+ const pendingSize = computed(() => pending.value.reduce((sum, item) => sum + item.file.size, 0));
33
+
34
+ function nameParts(name: string): [string, string] {
35
+ const ext = fileExtension(name);
36
+ return ext ? [name.slice(0, -(ext.length + 1)), `.${name.slice(-ext.length)}`] : [name, ""];
37
+ }
38
+
39
+ function badge(item: YsUploadItem<T>): string {
40
+ return (fileExtension(item.file.name) || "file").slice(0, 4).toUpperCase();
41
+ }
42
+
43
+ function resultNotes(item: YsUploadItem<T>): YsFileNote[] {
44
+ const notes = (item.result as { notes?: unknown } | null)?.notes;
45
+ return Array.isArray(notes) ? (notes as YsFileNote[]) : [];
46
+ }
47
+
48
+ function resultName(item: YsUploadItem<T>): string {
49
+ const name = (item.result as { name?: unknown } | null)?.name;
50
+ return typeof name === "string" && name !== item.file.name ? name : "";
51
+ }
52
+
53
+ const progressing = (item: YsUploadItem<T>) => item.state === "hashing" || item.state === "uploading";
54
+ </script>
55
+
56
+ <template>
57
+ <div v-if="items.length || queue.notices.value.length" class="ys-upload-queue">
58
+ <div v-for="(text, index) in queue.notices.value" :key="`${index}-${text}`" class="ys-upload-queue__notice" role="status">
59
+ <span>{{ text }}</span>
60
+ <button type="button" class="ys-upload-queue__close" aria-label="关闭提示" @click="queue.dismissNotice(index)">×</button>
61
+ </div>
62
+
63
+ <div v-if="pending.length" class="ys-upload-queue__confirm">
64
+ <div class="ys-upload-queue__confirm-head">
65
+ <strong>待上传 {{ pending.length }} 个</strong>
66
+ <span class="ys-upload-queue__muted">
67
+ {{ staged ? "提交后上传。" : "" }}无损图片默认转为无损 WebP(逐像素一致、体积更小),勾「原图」则原样保存
68
+ </span>
69
+ <el-checkbox
70
+ v-if="convertible.length > 1"
71
+ :model-value="allAsIs"
72
+ :indeterminate="someAsIs"
73
+ @change="queue.setAllAsIs(Boolean($event))"
74
+ >
75
+ 全部原图
76
+ </el-checkbox>
77
+ </div>
78
+ </div>
79
+
80
+ <ul class="ys-upload-queue__list">
81
+ <li v-for="item in items" :key="item.key" class="ys-upload-queue__row" :class="`is-${item.state}`">
82
+ <span class="ys-upload-queue__badge" aria-hidden="true">{{ badge(item) }}</span>
83
+ <div class="ys-upload-queue__main">
84
+ <div class="ys-upload-queue__line">
85
+ <span class="ys-upload-queue__name" :title="item.file.name">
86
+ <span class="ys-upload-queue__stem">{{ nameParts(item.file.name)[0] }}</span><span>{{ nameParts(item.file.name)[1] }}</span>
87
+ </span>
88
+ <span class="ys-upload-queue__muted">{{ formatFileSize(item.file.size) }}</span>
89
+ </div>
90
+ <div class="ys-upload-queue__line is-sub">
91
+ <template v-if="item.state === 'pending'">
92
+ <span class="ys-upload-queue__handling" :class="`is-${item.asIs ? 'keep' : item.handling.action}`">
93
+ {{ item.asIs ? "原样保存" : item.handling.label }}
94
+ </span>
95
+ <span v-if="!item.asIs && item.handling.detail" class="ys-upload-queue__muted">{{ item.handling.detail }}</span>
96
+ </template>
97
+ <template v-else>
98
+ <span class="ys-upload-queue__state">{{ uploadStateText(item) }}</span>
99
+ <span v-if="item.state === 'done' && resultName(item)" class="ys-upload-queue__muted">保存为 {{ resultName(item) }}</span>
100
+ <YsFileNotes v-if="item.state === 'done'" :notes="resultNotes(item)" :max="2" />
101
+ </template>
102
+ </div>
103
+ <el-progress
104
+ v-if="progressing(item)"
105
+ :percentage="Math.round(item.progress * 100)"
106
+ :stroke-width="3"
107
+ :show-text="false"
108
+ />
109
+ </div>
110
+ <div class="ys-upload-queue__actions">
111
+ <el-checkbox
112
+ v-if="item.state === 'pending' && item.handling.canKeepOriginal"
113
+ :model-value="item.asIs"
114
+ @change="queue.setAsIs(item, Boolean($event))"
115
+ >
116
+ 原图
117
+ </el-checkbox>
118
+ <el-button v-if="item.state === 'paused'" link type="primary" @click="queue.retry(item)">继续</el-button>
119
+ <el-button v-if="item.state === 'failed'" link type="primary" @click="queue.retry(item)">重试</el-button>
120
+ <el-button
121
+ v-if="item.state !== 'done' && item.state !== 'processing'"
122
+ link
123
+ :type="item.state === 'paused' ? 'danger' : undefined"
124
+ @click="queue.remove(item)"
125
+ >
126
+ {{ item.state === "hashing" || item.state === "uploading" ? "取消" : item.state === "paused" ? "放弃" : "移除" }}
127
+ </el-button>
128
+ </div>
129
+ </li>
130
+ </ul>
131
+
132
+ <div class="ys-upload-queue__foot">
133
+ <template v-if="pending.length && !staged">
134
+ <span class="ys-upload-queue__muted">共 {{ pending.length }} 个 · {{ formatFileSize(pendingSize) }}</span>
135
+ <el-button size="small" @click="queue.cancelPending()">取消</el-button>
136
+ <el-button size="small" type="primary" @click="queue.start()">上传 {{ pending.length }} 个</el-button>
137
+ </template>
138
+ <template v-else>
139
+ <el-button v-if="queue.paused.value.length + queue.failed.value.length > 1" size="small" @click="queue.retryAll()">
140
+ 全部继续
141
+ </el-button>
142
+ <el-button v-if="queue.done.value.length" size="small" link @click="queue.clearDone()">清除已完成</el-button>
143
+ </template>
144
+ </div>
145
+ </div>
146
+ </template>
147
+
148
+ <style scoped>
149
+ .ys-upload-queue {
150
+ display: flex;
151
+ flex-direction: column;
152
+ gap: 8px;
153
+ padding: 10px 12px;
154
+ border: 1px solid var(--ys-color-border);
155
+ border-radius: var(--ys-radius-m);
156
+ background: var(--ys-color-bg-elevated);
157
+ }
158
+ .ys-upload-queue__notice {
159
+ display: flex;
160
+ gap: 8px;
161
+ align-items: flex-start;
162
+ justify-content: space-between;
163
+ padding: 6px 10px;
164
+ border-radius: var(--ys-radius-s);
165
+ color: color-mix(in srgb, var(--ys-color-warning) 80%, var(--ys-color-text-1));
166
+ background: color-mix(in srgb, var(--ys-color-warning) 10%, transparent);
167
+ font-size: 13px;
168
+ }
169
+ .ys-upload-queue__close {
170
+ border: 0;
171
+ background: none;
172
+ color: inherit;
173
+ font-size: 16px;
174
+ line-height: 1;
175
+ cursor: pointer;
176
+ }
177
+ .ys-upload-queue__confirm-head {
178
+ display: flex;
179
+ flex-wrap: wrap;
180
+ gap: 4px 12px;
181
+ align-items: center;
182
+ }
183
+ .ys-upload-queue__list {
184
+ display: flex;
185
+ flex-direction: column;
186
+ gap: 2px;
187
+ margin: 0;
188
+ padding: 0;
189
+ list-style: none;
190
+ }
191
+ .ys-upload-queue__row {
192
+ display: flex;
193
+ gap: 10px;
194
+ align-items: center;
195
+ padding: 6px 4px;
196
+ border-radius: var(--ys-radius-s);
197
+ }
198
+ .ys-upload-queue__row:hover {
199
+ background: var(--ys-color-bg-hover);
200
+ }
201
+ .ys-upload-queue__badge {
202
+ flex: none;
203
+ width: 34px;
204
+ height: 34px;
205
+ border-radius: var(--ys-radius-s);
206
+ color: var(--ys-color-primary);
207
+ background: color-mix(in srgb, var(--ys-color-primary) 10%, transparent);
208
+ font-size: 11px;
209
+ font-weight: 600;
210
+ line-height: 34px;
211
+ text-align: center;
212
+ }
213
+ .ys-upload-queue__main {
214
+ flex: 1;
215
+ min-width: 0;
216
+ display: flex;
217
+ flex-direction: column;
218
+ gap: 2px;
219
+ }
220
+ .ys-upload-queue__line {
221
+ display: flex;
222
+ gap: 8px;
223
+ align-items: center;
224
+ min-width: 0;
225
+ }
226
+ .ys-upload-queue__line.is-sub {
227
+ flex-wrap: wrap;
228
+ font-size: 12px;
229
+ }
230
+ .ys-upload-queue__name {
231
+ display: flex;
232
+ min-width: 0;
233
+ color: var(--ys-color-text-1);
234
+ }
235
+ .ys-upload-queue__stem {
236
+ overflow: hidden;
237
+ white-space: nowrap;
238
+ text-overflow: ellipsis;
239
+ }
240
+ .ys-upload-queue__muted {
241
+ flex: none;
242
+ color: var(--ys-color-text-3);
243
+ font-size: 12px;
244
+ }
245
+ .ys-upload-queue__state {
246
+ color: var(--ys-color-text-2);
247
+ }
248
+ .is-failed .ys-upload-queue__state {
249
+ color: var(--ys-color-danger);
250
+ }
251
+ .is-paused .ys-upload-queue__state {
252
+ color: color-mix(in srgb, var(--ys-color-warning) 80%, var(--ys-color-text-1));
253
+ }
254
+ .is-done .ys-upload-queue__state {
255
+ color: var(--ys-color-success);
256
+ }
257
+ .ys-upload-queue__handling {
258
+ padding: 0 6px;
259
+ border-radius: var(--ys-radius-s);
260
+ color: var(--ys-color-text-2);
261
+ background: color-mix(in srgb, var(--ys-color-text-3) 10%, transparent);
262
+ }
263
+ .ys-upload-queue__handling.is-convert,
264
+ .ys-upload-queue__handling.is-video {
265
+ color: var(--ys-color-primary);
266
+ background: color-mix(in srgb, var(--ys-color-primary) 10%, transparent);
267
+ }
268
+ .ys-upload-queue__handling.is-active {
269
+ color: var(--ys-color-danger);
270
+ background: color-mix(in srgb, var(--ys-color-danger) 10%, transparent);
271
+ }
272
+ .ys-upload-queue__actions {
273
+ flex: none;
274
+ display: flex;
275
+ gap: 8px;
276
+ align-items: center;
277
+ }
278
+ .ys-upload-queue__foot {
279
+ display: flex;
280
+ gap: 8px;
281
+ align-items: center;
282
+ justify-content: flex-end;
283
+ }
284
+ .ys-upload-queue__foot:empty {
285
+ display: none;
286
+ }
287
+ </style>
@@ -1,6 +1,8 @@
1
1
  /* 文件预览的辅助函数:判断能怎么预览、文件类型标签、大小格式化、把 Blob 存成下载。
2
2
  * 与 YsFilePreview 配合使用,也可单独用在文件列表里。 */
3
3
 
4
+ import type { YsFileNote } from "./fileRules";
5
+
4
6
  /** 预览方式。excel:xlsx/xlsm/xls/xlsb/ods/csv 表格;word:docx(旧版 .doc 不支持,为 none)。 */
5
7
  export type YsPreviewKind = "pdf" | "image" | "text" | "video" | "audio" | "excel" | "word" | "none";
6
8
 
@@ -11,6 +13,10 @@ export type YsPreviewFile = {
11
13
  size?: number;
12
14
  /** 上传时记录的 MIME,可空。 */
13
15
  content_type?: string;
16
+ /** 文件标签(服务端 file_media_fields 的 notes),预览头部显示。 */
17
+ notes?: YsFileNote[];
18
+ /** 系统自带、可信的文件(如仓库里的 SVG Logo):可内嵌脚本的类型也允许新标签页打开。用户上传的文件不要设。 */
19
+ trusted?: boolean;
14
20
  };
15
21
 
16
22
  const IMAGE_EXT = new Set(["png", "jpg", "jpeg", "gif", "webp", "bmp", "svg", "avif", "ico"]);
@@ -276,6 +282,7 @@ const TYPE_LABELS: [string[], string][] = [
276
282
  [["xls", "xlsx", "xlsm", "xlsb", "et", "ods", "csv"], "Excel"],
277
283
  [["ppt", "pptx", "dps", "odp"], "PPT"],
278
284
  [["zip", "rar", "7z", "gz", "tgz", "tar", "bz2", "xz"], "压缩包"],
285
+ [["heic", "heif"], "HEIC 照片"],
279
286
  [["txt", "md", "markdown", "log"], "文本"],
280
287
  ];
281
288
 
@@ -0,0 +1,154 @@
1
+ /* 文件规范(前端部分):上传前本地检查、可执行类型判断、处理方式预估、粘贴与拖入的识别、文件标签类型。
2
+ * 服务端的权威规则在 ys_base.media(真实类型识别、无损转 WebP、视频转码、打标签);这里只做「上传前就能知道」的部分,
3
+ * 两边口径一致:文件名不超过 120 个字符、不含控制字符,可内嵌脚本的类型限制打开(不给新标签页打开),无损图片转无损 WebP、有损图片原样保存。 */
4
+
5
+ import { fileExtension } from "./filePreview";
6
+
7
+ /** 文件名最多字符数(与 ys_base.files.MAX_NAME 一致,按 Unicode 码点计,一个 emoji 算一个)。 */
8
+ export const FILE_NAME_MAX = 120;
9
+
10
+ /** 能内嵌脚本的扩展名:页面里不提供「新标签页打开」,服务端打「可内嵌脚本」标签。与 ys_base.media.ACTIVE_EXTENSIONS 一致。 */
11
+ export const ACTIVE_CONTENT_EXT = new Set(["svg", "svgz", "html", "htm", "xhtml", "xht", "xml", "xsl", "xslt", "js", "mjs"]);
12
+ const ACTIVE_MIME = /^(text\/html|application\/(xhtml\+xml|xml|javascript|ecmascript)|text\/(xml|javascript|ecmascript)|image\/svg\+xml)\b/i;
13
+
14
+ /** 文件标签(服务端 ys_base.files.file_media_fields 展开后的 notes 一项)。 */
15
+ export type YsFileNote = {
16
+ code: string;
17
+ /** info 说明、advice 建议、noncompliant 不符合规范。 */
18
+ level: "info" | "advice" | "noncompliant" | string;
19
+ level_label: string;
20
+ title: string;
21
+ reason: string;
22
+ suggestion: string;
23
+ };
24
+
25
+ /** 列表行里与文件规范有关的字段(服务端 file_media_fields)。 */
26
+ export type YsFileMediaFields = {
27
+ notes?: YsFileNote[];
28
+ media?: Record<string, unknown>;
29
+ spec_version?: string;
30
+ has_original?: boolean;
31
+ original_name?: string;
32
+ original_size?: number;
33
+ /** 后台处理状态:queued 排队转码、running 转码中,空为已处理完。 */
34
+ processing?: string;
35
+ };
36
+
37
+ /** 可内嵌脚本的文件:按扩展名或 MIME 判断。trusted 为真(系统自带素材)时不算。 */
38
+ export function isActiveContent(file: { name: string; content_type?: string; trusted?: boolean }): boolean {
39
+ if (file.trusted) return false;
40
+ return ACTIVE_CONTENT_EXT.has(fileExtension(file.name)) || ACTIVE_MIME.test(String(file.content_type || ""));
41
+ }
42
+
43
+ /** 按码点数文件名长度("😀" 是 1 个字符,与 Python len 一致)。 */
44
+ export function fileNameLength(name: string): number {
45
+ return Array.from(name).length;
46
+ }
47
+
48
+ export type YsFileCheckOptions = {
49
+ /** 单个文件上限(字节),默认 50 MB。 */
50
+ maxSize?: number;
51
+ maxName?: number;
52
+ };
53
+
54
+ /**
55
+ * 上传前本地检查(与服务端 begin 的检查同口径),不通过返回原因,通过返回空字符串。
56
+ * 顺序:空文件 → 超过大小 → 文件名为空 → 超长 → 控制字符。
57
+ */
58
+ export function checkUploadFile(file: { name: string; size: number }, options: YsFileCheckOptions = {}): string {
59
+ const maxSize = options.maxSize ?? 50 * 1024 * 1024;
60
+ const maxName = options.maxName ?? FILE_NAME_MAX;
61
+ const name = String(file.name || "").trim();
62
+ if (file.size <= 0) return "文件内容为空";
63
+ if (file.size > maxSize) return `超过 ${sizeLimitText(maxSize)}`;
64
+ if (!name || name === "." || name === "..") return "文件名不能为空";
65
+ if (fileNameLength(name) > maxName) return `文件名超过 ${maxName} 个字符`;
66
+ if ([...name].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)) return "文件名含换行等控制字符";
67
+ return "";
68
+ }
69
+
70
+ function sizeLimitText(bytes: number): string {
71
+ const mb = bytes / 1024 / 1024;
72
+ return mb >= 1 ? `${Number.isInteger(mb) ? mb : mb.toFixed(1)} MB` : `${Math.round(bytes / 1024)} KB`;
73
+ }
74
+
75
+ /** 上传前预估的处理方式(服务端按真实内容判断,结果以上传后的标签为准)。 */
76
+ export type YsExpectedHandling = {
77
+ /** convert 无损转 WebP、keep 原样保存、video 后台转码、active 可内嵌脚本、限制打开。 */
78
+ action: "convert" | "keep" | "video" | "active";
79
+ label: string;
80
+ detail: string;
81
+ /** 能否勾「原图」(只有会被转换的才有意义)。 */
82
+ canKeepOriginal: boolean;
83
+ };
84
+
85
+ const LOSSLESS_EXT = new Set(["png", "bmp", "dib"]);
86
+ const LOSSY_EXT = new Set(["jpg", "jpeg", "jpe", "jfif", "heic", "heif"]);
87
+ const MODERN_EXT = new Set(["webp", "avif", "jxl"]);
88
+ const VIDEO_EXT = new Set(["mp4", "mov", "m4v", "avi", "mkv", "webm", "flv", "wmv", "3gp", "mts", "m2ts", "ts"]);
89
+
90
+ /** 按扩展名和 MIME 预估服务端会怎么处理(给「待上传」面板显示,以及决定能否勾「原图」)。 */
91
+ export function expectedHandling(file: { name: string; type?: string }, videoCodec = "AV1"): YsExpectedHandling {
92
+ const ext = fileExtension(file.name);
93
+ const mime = String(file.type || "").toLowerCase();
94
+ if (isActiveContent({ name: file.name, content_type: mime }))
95
+ return { action: "active", label: "限制打开", detail: "可内嵌脚本:只按图片或源码显示,不在新标签页打开", canKeepOriginal: false };
96
+ if (LOSSLESS_EXT.has(ext) || mime === "image/png" || mime === "image/bmp")
97
+ return { action: "convert", label: "无损转 WebP", detail: "逐像素一致,通常省三到七成", canKeepOriginal: true };
98
+ if (ext === "gif" || mime === "image/gif")
99
+ return { action: "convert", label: "静态图转 WebP", detail: "动图原样保存", canKeepOriginal: true };
100
+ if (LOSSY_EXT.has(ext) || mime === "image/jpeg" || mime === "image/heic")
101
+ return { action: "keep", label: "原样保存", detail: "有损格式,再编码会损失画质", canKeepOriginal: false };
102
+ if (MODERN_EXT.has(ext)) return { action: "keep", label: "原样保存", detail: "已是高效格式", canKeepOriginal: false };
103
+ if (VIDEO_EXT.has(ext) || mime.startsWith("video/"))
104
+ return { action: "video", label: `转码为 ${videoCodec}`, detail: "上传后后台转码,转好前播放原视频", canKeepOriginal: false };
105
+ return { action: "keep", label: "原样保存", detail: "", canKeepOriginal: false };
106
+ }
107
+
108
+ function pad(value: number): string {
109
+ return String(value).padStart(2, "0");
110
+ }
111
+
112
+ /** 截图文件名:「截图 MM-DD HHmmss.png」,同一次粘贴的第 2、3 张加 -2、-3。 */
113
+ export function screenshotName(at: Date, index = 0, ext = "png"): string {
114
+ const stamp = `${pad(at.getMonth() + 1)}-${pad(at.getDate())} ${pad(at.getHours())}${pad(at.getMinutes())}${pad(at.getSeconds())}`;
115
+ return `截图 ${stamp}${index > 0 ? `-${index + 1}` : ""}.${ext}`;
116
+ }
117
+
118
+ /** 剪贴板默认名(各浏览器、系统粘贴截图时给的名字),这类文件改成「截图 …」。 */
119
+ const CLIPBOARD_NAMES = /^(image|clipboard|screenshot|截图|屏幕截图|pasted)[-_ ]?\d*\.(png|jpe?g|gif|webp|bmp)$/i;
120
+
121
+ /**
122
+ * 从粘贴事件里取文件:剪贴板里有文件、且没有纯文本时才当附件(Excel 单元格同时带图和文字,照常粘贴文字)。
123
+ * 剪贴板默认名改成「截图 MM-DD HHmmss.png」。没有文件返回空数组。
124
+ */
125
+ export function pastedFiles(event: ClipboardEvent, now = new Date()): File[] {
126
+ const data = event.clipboardData;
127
+ if (!data) return [];
128
+ const types = Array.from(data.types || []);
129
+ if (types.includes("text/plain")) return [];
130
+ const files = Array.from(data.files || []);
131
+ let shot = 0;
132
+ return files.map((file) => {
133
+ if (!CLIPBOARD_NAMES.test(file.name || "image.png") && file.name) return file;
134
+ const ext = fileExtension(file.name) || (file.type.split("/")[1] ?? "png").replace("jpeg", "jpg");
135
+ const renamed = new File([file], screenshotName(now, shot, ext), { type: file.type, lastModified: file.lastModified });
136
+ shot += 1;
137
+ return renamed;
138
+ });
139
+ }
140
+
141
+ /** 拖动内容里有文件才接管(拖文字、链接、页面里的元素不管)。 */
142
+ export function hasDraggedFiles(event: DragEvent): boolean {
143
+ return Array.from(event.dataTransfer?.types || []).includes("Files");
144
+ }
145
+
146
+ /** 是不是视频(按扩展名或 MIME),用来给视频单独的大小上限。 */
147
+ export function isVideoFile(file: { name: string; type?: string }): boolean {
148
+ return VIDEO_EXT.has(fileExtension(file.name)) || String(file.type || "").startsWith("video/");
149
+ }
150
+
151
+ /** 两个本地文件是否「同一个选择」:名字、大小、修改时间都相同(重新选中断过的文件时复用原来那一行)。 */
152
+ export function sameLocalFile(a: File, b: File): boolean {
153
+ return a.name === b.name && a.size === b.size && a.lastModified === b.lastModified;
154
+ }
package/src/index.ts CHANGED
@@ -33,6 +33,38 @@ export { default as YsBoolMark } from "./components/YsBoolMark.vue";
33
33
  export { default as YsSegmented } from "./components/YsSegmented.vue";
34
34
  export { default as YsCountBadge } from "./components/YsCountBadge.vue";
35
35
  export { default as YsFilePreview } from "./components/YsFilePreview.vue";
36
+ // 文件规范:上传队列、拖入与粘贴、文件标签(服务端规则在 ys_base.media)。
37
+ export { default as YsFileNotes } from "./components/YsFileNotes.vue";
38
+ export { default as YsFileDropZone } from "./components/YsFileDropZone.vue";
39
+ export { default as YsUploadQueue } from "./components/YsUploadQueue.vue";
40
+ export {
41
+ useYsUploadQueue,
42
+ uploadStateText,
43
+ isResumableError,
44
+ YS_UPLOAD_EVENTS,
45
+ type YsUploadItem,
46
+ type YsUploadQueue as YsUploadQueueState,
47
+ type YsUploadQueueOptions,
48
+ type YsUploadState,
49
+ type YsUploadEvents,
50
+ } from "./uploadQueue";
51
+ export {
52
+ ACTIVE_CONTENT_EXT,
53
+ FILE_NAME_MAX,
54
+ checkUploadFile,
55
+ expectedHandling,
56
+ fileNameLength,
57
+ hasDraggedFiles,
58
+ isActiveContent,
59
+ isVideoFile,
60
+ pastedFiles,
61
+ sameLocalFile,
62
+ screenshotName,
63
+ type YsExpectedHandling,
64
+ type YsFileCheckOptions,
65
+ type YsFileMediaFields,
66
+ type YsFileNote,
67
+ } from "./fileRules";
36
68
  // 单独的查看器,业务页可直接内嵌(重型依赖都在打开时才按需加载)。
37
69
  export { default as YsPdfViewer } from "./components/YsPdfViewer.vue";
38
70
  export { default as YsImageViewer } from "./components/YsImageViewer.vue";
@@ -0,0 +1,399 @@
1
+ /* 上传队列(无界面):选择、拖入、粘贴进来的文件排队上传,统一状态、进度、续传、重试、取消和「原图」选择。
2
+ * 传输用 @ysgroup/core 的 uploadChunked(整份 sha256 → 秒传 / 续传 / 分块),界面用 YsUploadQueue 显示。
3
+ *
4
+ * 两种模式:
5
+ * - 立即上传(autoStart,默认):加入即传;批次里有会被转换的图片时先进「待上传」,确认后再传(confirm: "convertible")。
6
+ * - 待提交(autoStart: false):文件留在本地,业务对象建好后调 start(extra) 再传(新建表单、回复框)。
7
+ */
8
+
9
+ import { computed, reactive, ref, shallowRef, type Ref } from "vue";
10
+ import {
11
+ YsLocalFileError,
12
+ uploadChunked,
13
+ type YsFileCall,
14
+ type YsFileDuplicate,
15
+ type YsUploadStage,
16
+ } from "@ysgroup/core";
17
+ import { checkUploadFile, expectedHandling, sameLocalFile, type YsExpectedHandling } from "./fileRules";
18
+
19
+ /**
20
+ * 行状态:pending 待确认 / 待提交,waiting 排队,hashing 校验中,uploading 上传中,processing 服务端核对与转换,
21
+ * done 完成,paused 已中断(可继续),failed 失败(可重试)。
22
+ */
23
+ export type YsUploadState = "pending" | "waiting" | "hashing" | "uploading" | "processing" | "done" | "paused" | "failed";
24
+
25
+ export type YsUploadItem<T = Record<string, unknown>> = {
26
+ key: number;
27
+ file: File;
28
+ state: YsUploadState;
29
+ /** 本阶段进度 0~1(校验中是算 sha256 的进度,上传中是发块进度)。 */
30
+ progress: number;
31
+ /** 续传时上传阶段的起点(0~1),0 表示从头传。 */
32
+ resumedFrom: number;
33
+ instant: boolean;
34
+ error: string;
35
+ /** 选了「原图」:原样保存,不做格式转换。 */
36
+ asIs: boolean;
37
+ handling: YsExpectedHandling;
38
+ duplicates: YsFileDuplicate[];
39
+ result: T | null;
40
+ /** 服务端分配的上传编号(放弃已中断的上传时用)。 */
41
+ uploadId: string;
42
+ };
43
+
44
+ export type YsUploadEvents = {
45
+ begin: string;
46
+ chunk: string;
47
+ finish: string;
48
+ cancel: string;
49
+ prove: string;
50
+ };
51
+
52
+ export const YS_UPLOAD_EVENTS: YsUploadEvents = {
53
+ begin: "begin_file_upload",
54
+ chunk: "upload_file_chunk",
55
+ finish: "finish_file_upload",
56
+ cancel: "cancel_file_upload",
57
+ prove: "prove_file_upload",
58
+ };
59
+
60
+ export type YsUploadQueueOptions<T> = {
61
+ call: YsFileCall;
62
+ events?: Partial<YsUploadEvents>;
63
+ /** begin 时附带的业务字段(如所属对象),start(extra) 的 extra 会合并进来。 */
64
+ beginData?: (item: YsUploadItem<T>) => Record<string, unknown>;
65
+ /** 区分「同一文件传给不同业务对象」的续传键(如所属对象编号)。 */
66
+ resumeKey?: (item: YsUploadItem<T>) => string;
67
+ /** 单个文件上限(字节),可按文件给(如视频 200 MB、其他 50 MB),默认 50 MB。 */
68
+ maxSize?: number | ((file: File) => number);
69
+ maxName?: number;
70
+ /** 最多几个文件同时上传,默认 2(服务端每人最多 6 个进行中的上传)。 */
71
+ concurrency?: number;
72
+ /** 最多加入几个文件(含已完成的行),不限为 0。 */
73
+ limit?: number;
74
+ autoStart?: boolean;
75
+ /** 立即上传模式下什么时候先进「待上传」让用户选「原图」:convertible 有会被转换的图片时(默认)、always、never。 */
76
+ confirm?: "convertible" | "always" | "never";
77
+ /** 视频转码目标的显示名,默认 AV1。 */
78
+ videoCodec?: string;
79
+ onDone?: (item: YsUploadItem<T>, result: T) => void;
80
+ onDuplicates?: (item: YsUploadItem<T>, list: YsFileDuplicate[]) => void;
81
+ /** 本地检查不通过、超过数量、重复加入时的提示(默认什么都不做,由 YsUploadQueue 显示 notices)。 */
82
+ onNotice?: (text: string) => void;
83
+ };
84
+
85
+ const TRANSIENT_CODES = new Set([408, 429, 502, 503, 504]);
86
+
87
+ /** 网络中断、超时、服务暂不可用:已收到的块还在服务端,可以续传。 */
88
+ export function isResumableError(error: unknown): boolean {
89
+ if (error instanceof YsLocalFileError) return false;
90
+ const code = (error as { code?: unknown } | null)?.code;
91
+ if (typeof code === "number") return TRANSIENT_CODES.has(code);
92
+ return (error as { name?: unknown } | null)?.name !== "AbortError";
93
+ }
94
+
95
+ function errorText(error: unknown): string {
96
+ if (error instanceof YsLocalFileError) return error.message;
97
+ const message = (error as { message?: unknown } | null)?.message;
98
+ return typeof message === "string" && message ? message : "上传失败";
99
+ }
100
+
101
+ let seq = 0;
102
+
103
+ export function useYsUploadQueue<T = Record<string, unknown>>(options: YsUploadQueueOptions<T>) {
104
+ const events = { ...YS_UPLOAD_EVENTS, ...options.events };
105
+ const items: Ref<YsUploadItem<T>[]> = ref([]);
106
+ const notices = ref<string[]>([]);
107
+ const extra = shallowRef<Record<string, unknown>>({});
108
+ const controllers = new Map<number, AbortController>();
109
+ let running = 0;
110
+ let waiters: (() => void)[] = [];
111
+
112
+ const concurrency = Math.max(1, options.concurrency ?? 2);
113
+ const autoStart = options.autoStart ?? true;
114
+ const confirmMode = options.confirm ?? "convertible";
115
+
116
+ const pending = computed(() => items.value.filter((item) => item.state === "pending"));
117
+ const active = computed(() =>
118
+ items.value.filter((item) => ["waiting", "hashing", "uploading", "processing"].includes(item.state)),
119
+ );
120
+ const busy = computed(() => active.value.length > 0);
121
+ const paused = computed(() => items.value.filter((item) => item.state === "paused"));
122
+ const failed = computed(() => items.value.filter((item) => item.state === "failed"));
123
+ const done = computed(() => items.value.filter((item) => item.state === "done"));
124
+ /** 离开页面前要提醒的:还在传、已中断或待确认。 */
125
+ const unfinished = computed(() => busy.value || paused.value.length > 0 || pending.value.length > 0);
126
+
127
+ function notify(text: string) {
128
+ notices.value = [...notices.value, text].slice(-5);
129
+ options.onNotice?.(text);
130
+ }
131
+
132
+ function dismissNotice(index: number) {
133
+ notices.value = notices.value.filter((_, at) => at !== index);
134
+ }
135
+
136
+ /** 加入文件(选择、拖入、粘贴)。本地检查不通过的不加入,原因进 notices;返回加入的行。 */
137
+ function add(input: File[] | FileList): YsUploadItem<T>[] {
138
+ const list = Array.from(input);
139
+ const added: YsUploadItem<T>[] = [];
140
+ const skipped = new Map<string, string[]>();
141
+ for (const file of list) {
142
+ const maxSize = typeof options.maxSize === "function" ? options.maxSize(file) : options.maxSize;
143
+ const reason = checkUploadFile(file, { maxSize, maxName: options.maxName });
144
+ if (reason) {
145
+ skipped.set(reason, [...(skipped.get(reason) ?? []), file.name || "未命名"]);
146
+ continue;
147
+ }
148
+ const same = items.value.find((item) => item.state !== "done" && sameLocalFile(item.file, file));
149
+ if (same) {
150
+ if (same.state === "paused" || same.state === "failed") {
151
+ same.file = file;
152
+ same.state = "waiting";
153
+ added.push(same);
154
+ } else skipped.set("已在列表里", [...(skipped.get("已在列表里") ?? []), file.name]);
155
+ continue;
156
+ }
157
+ if (options.limit && items.value.length >= options.limit) {
158
+ skipped.set(`最多 ${options.limit} 个`, [...(skipped.get(`最多 ${options.limit} 个`) ?? []), file.name]);
159
+ continue;
160
+ }
161
+ const handling = expectedHandling(file, options.videoCodec);
162
+ const item = reactive({
163
+ key: ++seq,
164
+ file,
165
+ state: "waiting",
166
+ progress: 0,
167
+ resumedFrom: 0,
168
+ instant: false,
169
+ error: "",
170
+ asIs: false,
171
+ handling,
172
+ duplicates: [],
173
+ result: null,
174
+ uploadId: "",
175
+ }) as YsUploadItem<T>;
176
+ items.value.push(item);
177
+ added.push(item);
178
+ }
179
+ for (const [reason, names] of skipped) notify(`${reason},没有加入:${names.join("、")}`);
180
+ const fresh = added.filter((item) => item.state === "waiting" && item.progress === 0 && !item.uploadId);
181
+ const needConfirm =
182
+ !autoStart ||
183
+ confirmMode === "always" ||
184
+ (confirmMode === "convertible" && (pending.value.length > 0 || fresh.some((item) => item.handling.canKeepOriginal)));
185
+ if (needConfirm) for (const item of fresh) item.state = "pending";
186
+ pump();
187
+ return added;
188
+ }
189
+
190
+ function setAsIs(item: YsUploadItem<T>, value: boolean) {
191
+ if (item.state === "pending" || item.state === "waiting" || item.state === "failed") item.asIs = value;
192
+ }
193
+
194
+ /** 待上传里能勾「原图」的行全部勾上 / 全部取消。 */
195
+ function setAllAsIs(value: boolean) {
196
+ for (const item of pending.value) if (item.handling.canKeepOriginal) item.asIs = value;
197
+ }
198
+
199
+ /** 确认「待上传」(立即上传模式),或开始上传待提交的文件(待提交模式,extra 合并进 begin)。全部结束时 resolve。 */
200
+ function start(more: Record<string, unknown> = {}): Promise<void> {
201
+ extra.value = { ...extra.value, ...more };
202
+ for (const item of pending.value) item.state = "waiting";
203
+ pump();
204
+ return settled();
205
+ }
206
+
207
+ /** 等到没有在传的文件。 */
208
+ function settled(): Promise<void> {
209
+ if (!busy.value) return Promise.resolve();
210
+ return new Promise((resolve) => waiters.push(resolve));
211
+ }
212
+
213
+ function pump() {
214
+ while (running < concurrency) {
215
+ const next = items.value.find((item) => item.state === "waiting");
216
+ if (!next) break;
217
+ running += 1;
218
+ void upload(next).finally(() => {
219
+ running -= 1;
220
+ pump();
221
+ if (!busy.value) {
222
+ const list = waiters;
223
+ waiters = [];
224
+ list.forEach((resolve) => resolve());
225
+ }
226
+ });
227
+ }
228
+ }
229
+
230
+ async function upload(item: YsUploadItem<T>) {
231
+ const controller = new AbortController();
232
+ controllers.set(item.key, controller);
233
+ item.state = "hashing";
234
+ item.progress = 0;
235
+ item.resumedFrom = 0;
236
+ item.instant = false;
237
+ item.error = "";
238
+ let firstUpload = true;
239
+ const call: YsFileCall = async (event, data, callOptions) => {
240
+ const result = await options.call(event, data, callOptions);
241
+ if (event === events.begin && result && typeof result === "object" && "upload_id" in result)
242
+ item.uploadId = String((result as { upload_id: unknown }).upload_id ?? "");
243
+ return result;
244
+ };
245
+ try {
246
+ const result = await uploadChunked<T & object>(call, item.file, {
247
+ begin: {
248
+ event: events.begin,
249
+ data: {
250
+ content_type: item.file.type,
251
+ as_is: item.asIs,
252
+ ...extra.value,
253
+ ...(options.beginData?.(item) ?? {}),
254
+ },
255
+ },
256
+ chunkEvent: events.chunk,
257
+ finishEvent: events.finish,
258
+ cancelEvent: events.cancel,
259
+ proveEvent: events.prove,
260
+ idKey: "upload_id",
261
+ resume: { key: options.resumeKey?.(item) ?? "" },
262
+ signal: controller.signal,
263
+ onPhase: (stage: YsUploadStage) => {
264
+ if (stage === "hash") item.state = "hashing";
265
+ else if (stage === "upload") item.state = "uploading";
266
+ else item.state = "processing";
267
+ },
268
+ onProgress: (_ratio, phase = "upload", phaseRatio = 0) => {
269
+ if (phase === "upload" && firstUpload) {
270
+ firstUpload = false;
271
+ if (phaseRatio > 0 && phaseRatio < 1) item.resumedFrom = phaseRatio;
272
+ }
273
+ item.progress = phaseRatio;
274
+ },
275
+ onDuplicates: (list) => {
276
+ item.duplicates = list;
277
+ options.onDuplicates?.(item, list);
278
+ },
279
+ });
280
+ item.state = "done";
281
+ item.progress = 1;
282
+ item.instant = Boolean((result as { instant?: unknown }).instant);
283
+ item.uploadId = "";
284
+ item.result = result as T;
285
+ options.onDone?.(item, result as T);
286
+ } catch (error) {
287
+ if (controller.signal.aborted) return;
288
+ if (isResumableError(error)) {
289
+ item.state = "paused";
290
+ item.error = "网络中断,已收到的部分保留在服务器上,点「继续」接着传";
291
+ } else {
292
+ item.state = "failed";
293
+ item.progress = 0;
294
+ item.uploadId = "";
295
+ item.error = errorText(error);
296
+ }
297
+ } finally {
298
+ controllers.delete(item.key);
299
+ }
300
+ }
301
+
302
+ /** 「继续」与「重试」同一个动作:先按内容续传,续不上再从头传。 */
303
+ function retry(item: YsUploadItem<T>) {
304
+ if (item.state !== "paused" && item.state !== "failed") return;
305
+ item.state = "waiting";
306
+ pump();
307
+ }
308
+
309
+ function retryAll() {
310
+ for (const item of items.value) if (item.state === "paused" || item.state === "failed") item.state = "waiting";
311
+ pump();
312
+ }
313
+
314
+ /**
315
+ * 移除一行:在传的中止(core 发 cancel 清掉半截),已中断的用上传编号发 cancel,服务端立即删掉已传的块、
316
+ * 不占同时上传的名额(不必等 24 小时过期)。
317
+ */
318
+ function remove(item: YsUploadItem<T>) {
319
+ controllers.get(item.key)?.abort();
320
+ if (item.state === "paused" && item.uploadId)
321
+ void Promise.resolve(options.call(events.cancel, { upload_id: item.uploadId })).catch(() => undefined);
322
+ items.value = items.value.filter((row) => row !== item);
323
+ pump();
324
+ }
325
+
326
+ /** 取消「待上传」:只丢掉还没开始的行。 */
327
+ function cancelPending() {
328
+ items.value = items.value.filter((item) => item.state !== "pending");
329
+ }
330
+
331
+ function cancelAll() {
332
+ for (const item of [...items.value]) if (item.state !== "done") remove(item);
333
+ }
334
+
335
+ function clearDone() {
336
+ items.value = items.value.filter((item) => item.state !== "done");
337
+ }
338
+
339
+ /** 清空(切换业务对象、卸载时):中止在传的,不发 cancel 给已中断的(留给续传或过期清理)。 */
340
+ function reset() {
341
+ for (const controller of controllers.values()) controller.abort();
342
+ controllers.clear();
343
+ items.value = [];
344
+ notices.value = [];
345
+ extra.value = {};
346
+ }
347
+
348
+ return {
349
+ items,
350
+ notices,
351
+ pending,
352
+ active,
353
+ paused,
354
+ failed,
355
+ done,
356
+ busy,
357
+ unfinished,
358
+ add,
359
+ start,
360
+ settled,
361
+ setAsIs,
362
+ setAllAsIs,
363
+ retry,
364
+ retryAll,
365
+ remove,
366
+ cancelPending,
367
+ cancelAll,
368
+ clearDone,
369
+ reset,
370
+ dismissNotice,
371
+ };
372
+ }
373
+
374
+ export type YsUploadQueue<T = Record<string, unknown>> = ReturnType<typeof useYsUploadQueue<T>>;
375
+
376
+ /** 行状态文字(与规范的进度文案一致)。 */
377
+ export function uploadStateText(item: Pick<YsUploadItem, "state" | "progress" | "resumedFrom" | "instant" | "error">): string {
378
+ const percent = (ratio: number) => `${Math.round(ratio * 100)}%`;
379
+ switch (item.state) {
380
+ case "pending":
381
+ return "待上传";
382
+ case "waiting":
383
+ return item.progress > 0 ? "等待继续" : "排队中";
384
+ case "hashing":
385
+ return `校验中 ${percent(item.progress)}`;
386
+ case "uploading":
387
+ return item.resumedFrom
388
+ ? `上传中 ${percent(item.progress)}(从 ${percent(item.resumedFrom)} 续传)`
389
+ : `上传中 ${percent(item.progress)}`;
390
+ case "processing":
391
+ return "处理中(核对与格式检查)";
392
+ case "done":
393
+ return item.instant ? "秒传完成" : item.resumedFrom ? "已上传(续传完成)" : "已上传";
394
+ case "paused":
395
+ return item.progress > 0 ? `已中断,停在 ${percent(item.progress)}` : "已中断";
396
+ default:
397
+ return item.error || "上传失败";
398
+ }
399
+ }