forked from mxx1111/mdlook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImportMarkdownDialog.vue
More file actions
336 lines (304 loc) · 9.94 KB
/
Copy pathImportMarkdownDialog.vue
File metadata and controls
336 lines (304 loc) · 9.94 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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
<script setup lang="ts">
import { FileText, Globe, Loader2, Upload } from '@lucide/vue'
import { usePostStore } from '@/stores/post'
import { useUIStore } from '@/stores/ui'
const postStore = usePostStore()
const uiStore = useUIStore()
const { isShowImportMdDialog } = storeToRefs(uiStore)
// 当前选中的 tab
const activeTab = ref<'url' | 'file'>(`file`)
// ==================== 检测本地图片路径 ====================
/**
* 从 Markdown 内容中检测本地图片路径
* 排除 http/https URL、data URI 和空路径
*/
function detectLocalImagePaths(content: string): string[] {
const regex = /!\[[^\]]*\]\((?!https?:\/\/|data:)([^)]+)\)/g
const paths = new Set<string>()
let match = regex.exec(content)
while (match != null) {
const path = match[1]!.trim()
if (path) {
paths.add(path)
}
match = regex.exec(content)
}
return Array.from(paths)
}
/**
* 导入内容,如果包含本地图片则弹出上传对话框
*/
async function importContent(title: string, content: string) {
const localPaths = detectLocalImagePaths(content)
if (localPaths.length === 0) {
// 没有本地图片,直接导入
postStore.addPost(title)
postStore.updatePostContent(postStore.currentPostId, content)
closeDialog()
return
}
// 有本地图片,弹出上传对话框
uiStore.localImageUploadData = {
markdownContent: content,
detectedPaths: localPaths,
}
uiStore.isShowLocalImageUpload = true
// 等待上传对话框处理完成
await new Promise<void>((resolve) => {
const unwatch = watch(
() => uiStore.localImageUploadData,
(data) => {
if (data && data.processed) {
unwatch()
if (data.skipUpload) {
// 用户选择跳过,按原样导入
postStore.addPost(title)
postStore.updatePostContent(postStore.currentPostId, content)
}
else {
// 用户已上传并应用,使用替换后的内容
postStore.addPost(title)
postStore.updatePostContent(postStore.currentPostId, data!.markdownContent)
}
closeDialog()
resolve()
}
},
)
})
// 清理
uiStore.localImageUploadData = null
}
// ==================== 网络链接导入 ====================
const url = ref(``)
const isUrlLoading = ref(false)
const urlError = ref(``)
let abortController: AbortController | null = null
/** 判断链接是否直接指向 Markdown 文件 */
function isMarkdownUrl(rawUrl: string): boolean {
try {
const { pathname } = new URL(rawUrl)
return /\.(?:md|markdown|txt)$/i.test(pathname)
}
catch {
return false
}
}
/** 直接获取 Markdown 文件内容 */
async function fetchMarkdownFile(rawUrl: string, signal: AbortSignal): Promise<string> {
const response = await fetch(rawUrl, { signal })
if (!response.ok) {
throw new Error(`请求失败: ${response.status} ${response.statusText}`)
}
const content = await response.text()
if (!content.trim()) {
throw new Error(`该链接返回的内容为空`)
}
return content
}
async function importFromUrl() {
const rawUrl = url.value.trim()
if (!rawUrl) {
urlError.value = `请输入链接`
return
}
if (!URL.canParse(rawUrl) || !/^https?:\/\//i.test(rawUrl)) {
urlError.value = `请输入有效的 URL 地址(仅支持 http/https)`
return
}
if (!isMarkdownUrl(rawUrl)) {
urlError.value = `当前仅支持以 .md、.markdown 或 .txt 结尾的直链;网页自动转换将在自有服务上线后开放。`
return
}
urlError.value = ``
isUrlLoading.value = true
abortController?.abort()
abortController = new AbortController()
const { signal } = abortController
try {
const content = await fetchMarkdownFile(rawUrl, signal)
// 从 URL 中提取标题
const urlTitle = (() => {
try {
const { pathname } = new URL(rawUrl)
const name = pathname.split(`/`).filter(Boolean).pop() || `untitled`
return name.replace(/\.(md|markdown|txt)$/i, ``)
}
catch {
return `untitled`
}
})()
await importContent(urlTitle, content)
}
catch (err) {
if ((err as Error).name === `AbortError`)
return
urlError.value = (err as Error).message || `导入失败,请检查链接是否有效`
}
finally {
isUrlLoading.value = false
}
}
// ==================== 本地文件导入 ====================
const isDragover = ref(false)
const { open: openFileDialog, reset: resetFileDialog, onChange: onFileChange } = useFileDialog({
accept: `.md,.markdown,.txt`,
multiple: true,
})
onFileChange((files) => {
if (files == null || files.length === 0)
return
readAndImportFiles(Array.from(files))
})
function handleDrop(event: DragEvent) {
event.preventDefault()
isDragover.value = false
const files = event.dataTransfer?.files
if (!files || files.length === 0)
return
const validFiles = Array.from(files).filter(file =>
file.name.match(/\.(md|markdown|txt)$/i),
)
if (validFiles.length === 0) {
toast.error(`请拖入 Markdown 文件(.md / .markdown / .txt)`)
return
}
readAndImportFiles(validFiles)
}
function readFileAsText(file: File): Promise<string> {
return new Promise((resolve) => {
const reader = new FileReader()
reader.readAsText(file, `UTF-8`)
reader.onload = (event) => {
resolve((event.target?.result as string) || ``)
}
reader.onerror = () => resolve(``)
})
}
async function readAndImportFiles(files: File[]) {
const results = await Promise.all(
files.map(async (file) => {
const content = await readFileAsText(file)
return { file, content }
}),
)
const validResults = results.filter(r => r.content.trim())
if (validResults.length === 0)
return
for (const { file, content } of validResults) {
const title = file.name.replace(/\.(md|markdown|txt)$/i, ``)
await importContent(title, content)
}
if (validResults.length > 0) {
toast.success(validResults.length === 1 ? `已导入 1 篇文章` : `已批量导入 ${validResults.length} 篇文章`)
}
}
// ==================== 对话框控制 ====================
function closeDialog() {
abortController?.abort()
abortController = null
isShowImportMdDialog.value = false
url.value = ``
urlError.value = ``
isUrlLoading.value = false
isDragover.value = false
resetFileDialog()
}
function onOpenChange(val: boolean) {
if (!val) {
closeDialog()
}
}
// URL 参数 open 传入的链接:打开对话框时自动填入并执行导入
watch(isShowImportMdDialog, (visible) => {
if (!visible || !uiStore.importMdOpenUrl)
return
const urlToImport = uiStore.importMdOpenUrl
uiStore.importMdOpenUrl = null
url.value = urlToImport
activeTab.value = `url`
urlError.value = ``
nextTick(() => importFromUrl())
})
</script>
<template>
<Dialog :open="isShowImportMdDialog" @update:open="onOpenChange">
<DialogContent class="sm:max-w-xl">
<DialogHeader>
<DialogTitle>导入 Markdown</DialogTitle>
<DialogDescription>
从网络链接或本地文件导入内容,支持公众号文章、博客等任意网页链接
</DialogDescription>
</DialogHeader>
<Tabs v-model="activeTab" class="w-full">
<TabsList class="grid w-full grid-cols-2">
<TabsTrigger value="file">
<span class="inline-flex items-center">
<Upload class="mr-2 size-4 shrink-0" />
本地文件
</span>
</TabsTrigger>
<TabsTrigger value="url">
<span class="inline-flex items-center">
<Globe class="mr-2 size-4 shrink-0" />
网络链接
</span>
</TabsTrigger>
</TabsList>
<!-- 本地文件导入 -->
<TabsContent value="file" class="mt-4">
<div
class="relative flex h-40 cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed transition-colors"
:class="{
'border-primary bg-primary/5': isDragover,
'border-muted-foreground/25 hover:border-muted-foreground/50': !isDragover,
}"
@click="openFileDialog()"
@dragover.prevent="isDragover = true"
@dragleave.prevent="isDragover = false"
@drop="handleDrop"
>
<FileText class="mb-3 size-10 text-muted-foreground" />
<p class="text-sm text-muted-foreground">
点击选择文件或拖拽文件到此处
</p>
<p class="mt-1 text-xs text-muted-foreground/70">
支持 .md、.markdown、.txt 格式
</p>
</div>
</TabsContent>
<!-- 网络链接导入 -->
<TabsContent value="url" class="mt-4">
<div class="space-y-4">
<div class="space-y-2">
<Input
v-model="url"
placeholder="如:https://example.com/article.md"
:class="{ 'border-destructive': urlError }"
@keydown.enter="importFromUrl"
@input="urlError = ``"
/>
<p v-if="urlError" class="text-xs text-destructive">
{{ urlError }}
</p>
<p v-else class="text-xs text-muted-foreground">
仅支持 Markdown / TXT 文件直链;网页自动转换暂未开放
</p>
</div>
<Button
class="w-full"
:disabled="isUrlLoading || !url.trim()"
@click="importFromUrl"
>
<Loader2 v-if="isUrlLoading" class="mr-2 size-4 animate-spin" />
{{ isUrlLoading ? '导入中...' : '导入' }}
</Button>
<p class="text-center text-xs leading-5 text-muted-foreground/60">
直链由浏览器直接读取,不会转发给第三方网页转换服务
</p>
</div>
</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
</template>