forked from mxx1111/mdlook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocalImageUploadDialog.vue
More file actions
312 lines (280 loc) · 9.62 KB
/
Copy pathLocalImageUploadDialog.vue
File metadata and controls
312 lines (280 loc) · 9.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
<script setup lang="ts">
import { Check, FileImage, FolderOpen, Loader2, X } from '@lucide/vue'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { progress as Progress } from '@/components/ui/progress'
import { useImageUploader } from '@/composables/useImageUploader'
import { useUIStore } from '@/stores/ui'
const uiStore = useUIStore()
const { upload } = useImageUploader()
// 批次上传状态(覆盖整个上传循环)
const isUploading = ref(false)
const isDialogOpen = computed({
get: () => uiStore.isShowLocalImageUpload,
set: (val) => {
uiStore.isShowLocalImageUpload = val
},
})
// 用户勾选要上传的路径
const selectedPaths = ref<Set<string>>(new Set())
// 上传进度
const progressValue = ref(0)
const uploadResults = ref<Record<string, string>>({})
const uploadErrors = ref<Record<string, string>>({})
// 用户选择的文件夹中的文件列表
const folderFiles = ref<File[]>([])
// 匹配状态
const matchedCount = computed(() => {
let count = 0
for (const path of selectedPaths.value) {
if (findMatchedFile(path))
count++
}
return count
})
// 是否已有上传结果(成功或失败)
const hasUploadAttempt = computed(() =>
Object.keys(uploadResults.value).length > 0 || Object.keys(uploadErrors.value).length > 0,
)
// 是否全部上传成功(选中的图片都有结果且无报错)
const isAllUploaded = computed(() => {
const paths = Array.from(selectedPaths.value)
return paths.length > 0 && paths.every(p => uploadResults.value[p] && !uploadErrors.value[p])
})
watch(() => uiStore.localImageUploadData, (data) => {
if (data) {
selectedPaths.value = new Set(data.detectedPaths)
progressValue.value = 0
uploadResults.value = {}
uploadErrors.value = {}
folderFiles.value = []
}
}, { immediate: true })
// 选择包含图片的文件夹
function handleFolderSelect(event: Event) {
const files = (event.target as HTMLInputElement).files
if (!files || files.length === 0)
return
folderFiles.value = Array.from(files)
// 自动选中已匹配的路径
for (const path of selectedPaths.value) {
if (!findMatchedFile(path)) {
selectedPaths.value.delete(path)
}
}
for (const path of uiStore.localImageUploadData?.detectedPaths || []) {
if (findMatchedFile(path)) {
selectedPaths.value.add(path)
}
}
// 重置 input
;(event.target as HTMLInputElement).value = ''
}
/**
* 根据路径从文件夹文件中查找匹配的文件
*/
function findMatchedFile(path: string): File | undefined {
const pathFileName = path.split(/[/\\]/).pop()!.toLowerCase()
const fileArray = folderFiles.value
// 第一轮:精确匹配文件名
for (const file of fileArray) {
if (file.name.toLowerCase() === pathFileName)
return file
}
// 第二轮:去扩展名匹配
const pathBase = pathFileName.replace(/\.[^.]+$/, '')
for (const file of fileArray) {
const fileBase = file.name.toLowerCase().replace(/\.[^.]+$/, '')
if (fileBase === pathBase)
return file
}
return undefined
}
// 开始上传
async function handleUpload() {
if (!uiStore.localImageUploadData)
return
const pathsToUpload = Array.from(selectedPaths.value)
const total = pathsToUpload.length
if (total === 0) {
toast.warning('请至少勾选一项')
return
}
// 检查未匹配的
const unmatched = pathsToUpload.filter(p => !findMatchedFile(p))
if (unmatched.length > 0) {
toast.error(`以下图片未在文件夹中找到:${unmatched.join(', ')}`)
return
}
progressValue.value = 0
uploadResults.value = {}
uploadErrors.value = {}
isUploading.value = true
// 文件 → URL 缓存,避免同文件重复上传
const fileUrlMap = new WeakMap<File, string>()
for (let i = 0; i < pathsToUpload.length; i++) {
const path = pathsToUpload[i]!
try {
const file = findMatchedFile(path)!
let url = fileUrlMap.get(file)
if (!url) {
url = await upload(file)
fileUrlMap.set(file, url)
}
uploadResults.value[path] = url
}
catch (err: unknown) {
uploadErrors.value[path] = (err as Error).message || '上传失败'
}
progressValue.value = Math.round(((i + 1) / total) * 100)
}
isUploading.value = false
}
// 关闭并应用
function handleApply() {
if (!uiStore.localImageUploadData)
return
// 仅替换图片语法 `` 中的路径为上传后的 URL
let content = uiStore.localImageUploadData.markdownContent
for (const [path, url] of Object.entries(uploadResults.value)) {
const escaped = path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
content = content
.replace(new RegExp(`(!\\[[^\\]]*\\]\\()${escaped}\\)`, 'g'), `$1${url})`)
.replace(new RegExp(`(!\\[[^\\]]*\\]\\(\\.\\/)${escaped}\\)`, 'g'), `$1${url})`)
}
uiStore.localImageUploadData = {
markdownContent: content,
detectedPaths: [],
processed: true,
}
isDialogOpen.value = false
}
// 关闭并跳过上传
function handleSkip() {
if (uiStore.localImageUploadData) {
uiStore.localImageUploadData = {
...uiStore.localImageUploadData,
processed: true,
skipUpload: true,
}
}
isDialogOpen.value = false
}
function onOpenChange(val: boolean) {
if (!val) {
isDialogOpen.value = false
uiStore.localImageUploadData = null
}
}
</script>
<template>
<Dialog :open="isDialogOpen" @update:open="onOpenChange">
<DialogContent class="sm:max-w-lg">
<DialogHeader>
<DialogTitle>检测到本地图片</DialogTitle>
<DialogDescription>
文档中包含本地图片路径,请选择包含这些图片的文件夹,系统将自动匹配并上传。
</DialogDescription>
</DialogHeader>
<div v-if="uiStore.localImageUploadData" class="space-y-4">
<!-- 图片路径列表 -->
<div class="rounded-md border">
<div class="flex items-center justify-between border-b px-4 py-2">
<span class="text-sm font-medium">
检测到 {{ uiStore.localImageUploadData.detectedPaths.length }} 张本地图片
</span>
<span v-if="folderFiles.length > 0" class="text-xs text-muted-foreground">
已匹配 {{ matchedCount }} / {{ selectedPaths.size }}
</span>
</div>
<div class="max-h-48 overflow-auto p-2">
<div
v-for="path in uiStore.localImageUploadData.detectedPaths"
:key="path"
class="flex items-center gap-2 rounded px-2 py-1.5 text-xs"
:class="{
'bg-primary/5': selectedPaths.has(path),
'text-muted-foreground': !selectedPaths.has(path),
}"
>
<input
type="checkbox"
:checked="selectedPaths.has(path)"
:aria-label="path"
class="h-3.5 w-3.5 shrink-0 accent-primary"
@change="selectedPaths.has(path) ? selectedPaths.delete(path) : selectedPaths.add(path)"
>
<FileImage class="h-3.5 w-3.5 shrink-0" />
<span class="truncate" :title="path">{{ path }}</span>
<span v-if="uploadResults[path]" class="ml-auto shrink-0 text-green-600">
<Check class="h-3.5 w-3.5" />
</span>
<span v-else-if="uploadErrors[path]" class="ml-auto shrink-0 text-destructive" :title="uploadErrors[path]">
<X class="h-3.5 w-3.5" />
</span>
</div>
</div>
</div>
<!-- 进度条 -->
<Progress v-if="isUploading || progressValue > 0" :model-value="progressValue" class="h-1.5" />
<!-- 选择文件夹按钮 -->
<label v-if="!isAllUploaded" class="block">
<input
type="file"
webkitdirectory
multiple
accept="image/*"
class="hidden"
@change="handleFolderSelect"
>
<Button variant="outline" class="w-full" as="span">
<FolderOpen class="mr-2 h-4 w-4" />
{{ folderFiles.length > 0 ? `已选择文件夹 (${folderFiles.length} 个文件)` : '选择包含图片的文件夹' }}
</Button>
</label>
<!-- 底部操作区 -->
<div v-if="isAllUploaded" class="flex justify-end pt-2">
<Button @click="handleApply">
完成
</Button>
</div>
<div v-else-if="hasUploadAttempt" class="flex items-center justify-between gap-2 pt-2">
<Button variant="link" class="px-2 text-muted-foreground" @click="handleSkip">
跳过
</Button>
<div class="flex gap-2">
<Button
v-if="Object.keys(uploadResults).length > 0"
@click="handleApply"
>
完成
</Button>
<Button variant="outline" @click="handleUpload">
重新上传
</Button>
</div>
</div>
<div v-else class="flex items-center justify-between gap-2 pt-2">
<Button variant="link" class="px-2 text-muted-foreground" @click="handleSkip">
跳过
</Button>
<div class="flex gap-2">
<Button
:disabled="isUploading || selectedPaths.size === 0 || matchedCount === 0"
@click="handleUpload"
>
<Loader2 v-if="isUploading" class="mr-2 h-4 w-4 animate-spin" />
{{ isUploading ? '上传中...' : '上传图片' }}
</Button>
</div>
</div>
</div>
</DialogContent>
</Dialog>
</template>