forked from mxx1111/mdlook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditorPanel.vue
More file actions
672 lines (598 loc) · 18.5 KB
/
Copy pathEditorPanel.vue
File metadata and controls
672 lines (598 loc) · 18.5 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
<script setup lang="ts">
import { Compartment, EditorState } from '@codemirror/state'
import { EditorView } from '@codemirror/view'
import { markdownSetup, theme } from '@md/shared/editor'
import imageCompression from 'browser-image-compression'
import { SidebarAIToolbar } from '@/components/ai'
import SlashCommandMenu from '@/components/editor/SlashCommandMenu.vue'
import { SearchTab } from '@/components/ui/search-tab'
import { useImageUploader } from '@/composables/useImageUploader'
import { useSlashCommand } from '@/composables/useSlashCommand'
import { isAiFeatureEnabled } from '@/services/product/features'
import { useDesktopStore } from '@/stores/desktop'
import { useEditorStore } from '@/stores/editor'
import { usePostStore } from '@/stores/post'
import { useRenderStore } from '@/stores/render'
import { useThemeStore } from '@/stores/theme'
import { useUIStore } from '@/stores/ui'
import { checkImage, toBase64 } from '@/utils'
import { fileUpload } from '@/utils/file'
import { store } from '@/utils/storage'
const editorStore = useEditorStore()
const desktopStore = useDesktopStore()
const postStore = usePostStore()
const renderStore = useRenderStore()
const themeStore = useThemeStore()
const uiStore = useUIStore()
const { upload } = useImageUploader()
const showAiToolbar = isAiFeatureEnabled()
const slashCommand = useSlashCommand()
const { editor } = storeToRefs(editorStore)
const { isDark } = storeToRefs(uiStore)
const { posts, currentPostIndex } = storeToRefs(postStore)
const {
isMobile,
enableImageReupload,
viewMode,
} = storeToRefs(uiStore)
const { toggleShowUploadImgDialog } = uiStore
const showEditor = computed(() => viewMode.value !== `preview`)
const codeMirrorView = shallowRef<EditorView | null>(null)
const themeCompartment = new Compartment()
const changeTimer = ref<ReturnType<typeof setTimeout>>()
let unregisterContentAdapter: (() => void) | null = null
const editorRef = useTemplateRef<HTMLDivElement>(`editorRef`)
const codeMirrorWrapper = useTemplateRef<HTMLDivElement>(`codeMirrorWrapper`)
const progressValue = ref(0)
const isImgLoading = ref(false)
// Editor refresh function
function editorRefresh() {
themeStore.updateCodeTheme()
const raw = editorStore.getContent()
renderStore.render(raw)
}
// --- Search tab integration ---
const searchTabRef = useTemplateRef<InstanceType<typeof SearchTab>>(`searchTabRef`)
const pendingSearchRequest = ref<{ selected: string } | null>(null)
function openSearchWithSelection(view: EditorView) {
const selection = view.state.selection.main
const selected = view.state.doc.sliceString(selection.from, selection.to).trim()
if (searchTabRef.value) {
if (selected) {
searchTabRef.value.setSearchWord(selected)
}
else {
searchTabRef.value.showSearchTab = true
}
}
else {
pendingSearchRequest.value = { selected }
}
}
function openReplaceWithSelection(view: EditorView) {
const selection = view.state.selection.main
const selected = view.state.doc.sliceString(selection.from, selection.to).trim()
if (searchTabRef.value) {
searchTabRef.value.setSearchWithReplace(selected)
}
else {
uiStore.openSearchTab(selected, true)
}
}
watch(searchTabRef, (newRef) => {
if (newRef && pendingSearchRequest.value) {
const { selected } = pendingSearchRequest.value
if (selected) {
newRef.setSearchWord(selected)
}
else {
newRef.showSearchTab = true
}
pendingSearchRequest.value = null
}
})
const { searchTabRequest } = storeToRefs(uiStore)
watch(searchTabRequest, (request) => {
if (request && searchTabRef.value) {
const { word, showReplace } = request
if (showReplace) {
searchTabRef.value.setSearchWithReplace(word)
}
else {
if (word) {
searchTabRef.value.setSearchWord(word)
}
else {
searchTabRef.value.showSearchTab = true
}
}
uiStore.clearSearchTabRequest()
}
})
function handleGlobalKeydown(e: KeyboardEvent) {
const editorView = codeMirrorView.value
if (e.key === `Escape` && searchTabRef.value?.showSearchTab) {
searchTabRef.value.showSearchTab = false
e.preventDefault()
editorView?.focus()
}
}
// --- Image upload ---
async function beforeImageUpload(file: File) {
const checkResult = checkImage(file)
if (!checkResult.ok) {
toast.error(checkResult.msg)
return false
}
const imgHost = (await store.get(`imgHost`)) || `default`
await store.set(`imgHost`, imgHost)
const config = await store.get(`${imgHost}Config`)
const isValidHost = imgHost === `default` || config
if (!isValidHost) {
toast.error(`请先配置 ${imgHost} 图床参数`)
return false
}
return true
}
function uploaded(imageUrl: string) {
if (!imageUrl) {
toast.error(`上传图片未知异常`)
return
}
setTimeout(() => {
toggleShowUploadImgDialog(false)
}, 1000)
const markdownImage = ``
if (codeMirrorView.value) {
codeMirrorView.value.dispatch(codeMirrorView.value.state.replaceSelection(`\n${markdownImage}\n`))
}
toast.success(`图片上传成功`)
}
function insertMarkdownImage(imageUrl: string, alt = ``) {
const markdownImage = ``
if (codeMirrorView.value) {
codeMirrorView.value.dispatch(codeMirrorView.value.state.replaceSelection(`\n${markdownImage}\n`))
}
}
async function insertLocalAssetImage(file: File): Promise<boolean> {
if (desktopStore.isTauri && !desktopStore.currentFilePath) {
await desktopStore.saveAs()
}
if (!desktopStore.canSaveAssetsLocally())
return false
try {
isImgLoading.value = true
const localPath = await desktopStore.saveImageToAssets(file)
if (!localPath)
return false
insertMarkdownImage(localPath, file.name.replace(/\.[^.]+$/, ``))
toast.success(`图片已保存到 assets`)
return true
}
catch (err) {
toast.error(`保存本地图片失败:${err}`)
return true
}
finally {
isImgLoading.value = false
}
}
async function handleImageFile(file: File) {
const checkResult = checkImage(file)
if (!checkResult.ok) {
toast.error(checkResult.msg)
return
}
if (await insertLocalAssetImage(file))
return
if (await beforeImageUpload(file))
await uploadImage(file)
}
async function compressImage(file: File) {
const options = {
maxSizeMB: 1,
maxWidthOrHeight: 1920,
useWebWorker: true,
}
return await imageCompression(file, options)
}
async function uploadImage(
file: File,
cb?: { (url: any, data: string): void, (arg0: unknown): void } | undefined,
applyUrl?: boolean,
) {
try {
isImgLoading.value = true
const useCompression = (await store.get(`useCompression`)) === `true`
if (useCompression) {
file = await compressImage(file)
}
const base64Content = await toBase64(file)
const url = await fileUpload(base64Content, file)
if (cb) {
cb(url, base64Content)
}
else {
uploaded(url)
}
if (applyUrl) {
return uploaded(url)
}
}
catch (err) {
toast.error((err as any).message)
}
finally {
isImgLoading.value = false
}
}
// --- Drag & drop folder ---
async function getMd({ list }: { list: { path: string, file: File }[] }) {
return new Promise<{ str: string, file: File, path: string }>((resolve) => {
const { path, file } = list.find(item => item.path.match(/\.md$/))!
const reader = new FileReader()
reader.readAsText(file!, `UTF-8`)
reader.onload = (evt) => {
resolve({
str: evt.target!.result as string,
file,
path,
})
}
})
}
async function showFileStructure(root: any) {
const result = []
let cwd = ``
try {
const dirs = [root]
for (const dir of dirs) {
cwd += `${dir.name}/`
for await (const [, handle] of dir) {
if (handle.kind === `file`) {
result.push({
path: cwd + handle.name,
file: await handle.getFile(),
})
}
else {
result.push({
path: `${cwd + handle.name}/`,
})
dirs.push(handle)
}
}
}
}
catch (err) {
console.error(err)
}
return result
}
async function uploadMdImg({
md,
list,
}: {
md: { str: string, path: string, file: File }
list: { path: string, file: File }[]
}) {
const mdImgList = [...(md.str.matchAll(/!\[(.*?)\]\((.*?)\)/g) || [])].filter(item => item)
const root = md.path.match(/.+?\//)![0]
const resList = await Promise.all<{ matchStr: string, url: string }>(
mdImgList.map((item) => {
return new Promise((resolve) => {
let [, , matchStr] = item
matchStr = matchStr.replace(/^.\//, ``)
const { file }
= list.find(f => f.path === `${root}${matchStr}`) || {}
uploadImage(file!, url => resolve({ matchStr, url }))
})
}),
)
resList.forEach((item) => {
md.str = md.str
.replace(`](./${item.matchStr})`, `](${item.url})`)
.replace(`](${item.matchStr})`, `](${item.url})`)
})
if (codeMirrorView.value) {
codeMirrorView.value.dispatch({
changes: { from: 0, to: codeMirrorView.value.state.doc.length, insert: md.str },
})
}
}
function mdLocalToRemote(dom: HTMLDivElement) {
dom.ondragover = evt => evt.preventDefault()
dom.ondrop = async (evt) => {
evt.preventDefault()
if (evt.dataTransfer == null || !Array.isArray(evt.dataTransfer.items)) {
return
}
for (const item of evt.dataTransfer.items.filter(item => item.kind === `file`)) {
item
.getAsFileSystemHandle()
.then(async (handle: { kind: string, getFile: () => any }) => {
if (handle.kind === `directory`) {
const list = (await showFileStructure(handle)) as {
path: string
file: File
}[]
const md = await getMd({ list })
uploadMdImg({ md, list })
}
else {
const file = await handle.getFile()
await handleImageFile(file)
}
})
}
}
}
// --- Image paste handler for CodeMirror ---
function createPasteHandler() {
return (event: ClipboardEvent, view: EditorView) => {
// 1. 处理剪贴板中的文件 (截图/复制文件)
if (event.clipboardData?.items && [...event.clipboardData.items].some(item => item.kind === 'file')) {
if (isImgLoading.value) {
return true
}
Promise.all(
Array.from(event.clipboardData.items, item => item.getAsFile())
.filter(item => item != null)
.map(async item => item),
).then((items) => {
const validItems = items.filter(item => item != null) as File[]
if (validItems.length === 0) {
return
}
const intervalId = setInterval(() => {
const newProgress = progressValue.value + 1
if (newProgress >= 100) {
return
}
progressValue.value = newProgress
}, 100)
const processFiles = async () => {
for (const item of validItems) {
await handleImageFile(item)
}
clearInterval(intervalId)
progressValue.value = 100
setTimeout(() => {
progressValue.value = 0
}, 1000)
}
processFiles()
})
return true
}
// 2. 处理剪贴板中的文本 (检测 Markdown 图片链接)
const text = event.clipboardData?.getData('text/plain')
if (text) {
const mdImgRegex = /!\[(.*?)\]\((https?:\/\/[^)]+)\)/g
const matches = [...text.matchAll(mdImgRegex)]
if (matches.length > 0) {
isImgLoading.value = true
let previewText = text
const placeholderMap = new Map<string, { originalUrl: string, originalAlt: string }>()
let matchIndex = 0
previewText = previewText.replace(mdImgRegex, (_, alt, url) => {
const id = `LOADING_${Date.now()}_${matchIndex++}`
placeholderMap.set(id, { originalUrl: url, originalAlt: alt })
return ``
})
view.dispatch(view.state.replaceSelection(previewText))
const uniqueUrls = [...new Set(matches.map(m => m[2]))]
Promise.all(uniqueUrls.map(async (url) => {
try {
const newUrl = enableImageReupload.value ? await upload(url) : url
for (const [id, info] of placeholderMap.entries()) {
if (info.originalUrl === url) {
const searchStr = ``
const currentDoc = view.state.doc.toString()
const pos = currentDoc.indexOf(searchStr)
if (pos !== -1) {
const newText = ``
view.dispatch({
changes: { from: pos, to: pos + searchStr.length, insert: newText },
})
}
}
}
}
catch (e) {
console.error(`转存失败: ${url}`, e)
for (const [id, info] of placeholderMap.entries()) {
if (info.originalUrl === url) {
const searchStr = ``
const currentDoc = view.state.doc.toString()
const pos = currentDoc.indexOf(searchStr)
if (pos !== -1) {
const newText = ``
view.dispatch({
changes: { from: pos, to: pos + searchStr.length, insert: newText },
})
}
}
}
toast.error(`图片转存失败,已保留原链接`)
}
})).finally(() => {
isImgLoading.value = false
})
return true
}
}
return false
}
}
// --- CodeMirror creation ---
function createFormTextArea(dom: HTMLDivElement) {
const state = EditorState.create({
doc: posts.value[currentPostIndex.value].content,
extensions: [
markdownSetup({
onSearch: openSearchWithSelection,
onReplace: openReplaceWithSelection,
}),
themeCompartment.of(theme(isDark.value)),
EditorView.updateListener.of((update) => {
if (update.docChanged) {
const value = update.state.doc.toString()
const currentPost = posts.value[currentPostIndex.value]
if (value !== currentPost.content) {
currentPost.updateDatetime = new Date()
currentPost.content = value
}
clearTimeout(changeTimer.value)
changeTimer.value = setTimeout(() => {
editorRefresh()
}, 300)
}
}),
EditorView.domEventHandlers({
paste: createPasteHandler(),
}),
...slashCommand.createExtension(() => codeMirrorView.value),
],
})
const view = new EditorView({
state,
parent: dom,
})
codeMirrorView.value = view
return view
}
// --- Lifecycle ---
onMounted(() => {
const editorDom = editorRef.value
if (editorDom == null) {
return
}
renderStore.initRendererInstance({
isMacCodeBlock: themeStore.isMacCodeBlock,
isShowLineNumber: themeStore.isShowLineNumber,
})
themeStore.applyCurrentTheme()
nextTick(() => {
const wrapper = codeMirrorWrapper.value
if (editorRef.value !== editorDom || wrapper == null)
return
const editorView = createFormTextArea(editorDom)
editor.value = editorView
unregisterContentAdapter = editorStore.registerContentAdapter({
getContent: () => editorView.state.doc.toString(),
replaceContent: (content) => {
editorView.dispatch({
changes: { from: 0, to: editorView.state.doc.length, insert: content },
})
},
focus: () => editorView.focus(),
})
editorRefresh()
mdLocalToRemote(wrapper)
})
document.addEventListener(`keydown`, handleGlobalKeydown, { passive: false, capture: false })
})
watch(isDark, () => {
if (codeMirrorView.value) {
codeMirrorView.value.dispatch({
effects: themeCompartment.reconfigure(theme(isDark.value)),
})
}
editorRefresh()
})
watch(currentPostIndex, () => {
if (!codeMirrorView.value)
return
const currentPost = posts.value[currentPostIndex.value]
if (!currentPost)
return
const currentContent = codeMirrorView.value.state.doc.toString()
if (currentContent !== currentPost.content) {
codeMirrorView.value.dispatch({
changes: {
from: 0,
to: codeMirrorView.value.state.doc.length,
insert: currentPost.content,
},
})
editorRefresh()
}
})
// 历史记录的定时器
const historyTimer = ref<ReturnType<typeof setTimeout>>()
onMounted(() => {
historyTimer.value = setInterval(() => {
const currentPost = posts.value[currentPostIndex.value]
const pre = (currentPost.history || [])[0]?.content
if (pre === currentPost.content) {
return
}
currentPost.history ??= []
currentPost.history.unshift({
content: currentPost.content,
datetime: new Date().toLocaleString(`zh-CN`),
})
currentPost.history.length = Math.min(currentPost.history.length, 10)
}, 30 * 1000)
})
onUnmounted(() => {
clearTimeout(historyTimer.value)
clearTimeout(changeTimer.value)
unregisterContentAdapter?.()
unregisterContentAdapter = null
const editorView = codeMirrorView.value
if (editor.value === editorView)
editor.value = null
editorView?.destroy()
codeMirrorView.value = null
document.removeEventListener(`keydown`, handleGlobalKeydown, { capture: false })
})
defineExpose({
codeMirrorView,
editorRefresh,
uploadImage,
progressValue,
})
</script>
<template>
<div
v-show="viewMode !== 'preview'"
ref="codeMirrorWrapper"
class="codeMirror-wrapper relative h-full"
>
<SearchTab v-if="codeMirrorView" ref="searchTabRef" :editor-view="codeMirrorView as any" />
<SlashCommandMenu
:visible="slashCommand.visible.value"
:position="slashCommand.position.value"
:active-index="slashCommand.activeIndex.value"
:basic-commands="slashCommand.basicCommands.value"
:common-commands="slashCommand.commonCommands.value"
:filtered-commands="slashCommand.filteredCommands.value"
@execute="(cmd) => codeMirrorView && slashCommand.executeCommand(codeMirrorView, cmd)"
@close="slashCommand.closeMenu()"
/>
<SidebarAIToolbar
v-if="showAiToolbar"
:is-mobile="isMobile"
:show-editor="showEditor"
/>
<EditorContextMenu>
<div
id="editor"
ref="editorRef"
class="codemirror-container"
/>
</EditorContextMenu>
</div>
</template>
<style lang="less" scoped>
@import url('../../assets/less/app.less');
</style>
<style lang="less" scoped>
.codeMirror-wrapper {
overflow-x: hidden;
height: 100%;
position: relative;
}
</style>