forked from mxx1111/mdlook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseCursorSync.ts
More file actions
179 lines (151 loc) · 4.94 KB
/
Copy pathuseCursorSync.ts
File metadata and controls
179 lines (151 loc) · 4.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
import type { MaybeRefOrGetter } from 'vue'
import { EditorView } from '@codemirror/view'
import { useUIStore } from '@/stores/ui'
/**
* 点击预览区元素时,定位回编辑器对应位置。
*/
export function useCursorSync(
codeMirrorViewRef: MaybeRefOrGetter<EditorView | null>,
) {
const getEditorView = () => toValue(codeMirrorViewRef)
const uiStore = useUIStore()
function normalizeText(text: string) {
return text
.replace(/\s+/g, ` `)
.trim()
}
function parseMarkdownHeadingLine(line: string): { level: number, title: string } | null {
if (!line.startsWith(`#`))
return null
let level = 0
while (level < line.length && line[level] === `#` && level < 6)
level++
if (level === 0 || line[level] !== ` `)
return null
const title = normalizeText(line.slice(level + 1).replace(/#+\s*$/, ``))
if (!title)
return null
return { level, title }
}
function findHeadingPosInEditor(title: string, level?: number) {
const view = getEditorView()
if (!view)
return null
const doc = view.state.doc
const normalizedTitle = normalizeText(title)
for (let lineNo = 1; lineNo <= doc.lines; lineNo++) {
const line = doc.line(lineNo)
const parsed = parseMarkdownHeadingLine(line.text)
if (!parsed)
continue
if (level && parsed.level !== level)
continue
const headingTitle = parsed.title
if (headingTitle === normalizedTitle || headingTitle.includes(normalizedTitle) || normalizedTitle.includes(headingTitle)) {
return line.from
}
}
return null
}
function findTextPosInEditor(text: string) {
const view = getEditorView()
if (!view)
return null
const docText = view.state.doc.toString()
const normalized = normalizeText(text)
if (!normalized)
return null
const candidates = [
normalized,
normalized.slice(0, 80),
normalized.slice(0, 40),
normalized.slice(0, 20),
].filter(item => item.length >= 6)
for (const candidate of candidates) {
const pos = docText.indexOf(candidate)
if (pos !== -1)
return pos
}
return null
}
function syncEditorToPreviewElement(el: HTMLElement) {
const tag = el.tagName.toLowerCase()
let pos: number | null = null
if (/^h[1-6]$/.test(tag)) {
const level = Number(tag.slice(1))
const title = normalizeText(el.textContent || ``)
pos = findHeadingPosInEditor(title, level)
}
else if (tag === `img`) {
const img = el as HTMLImageElement
const alt = normalizeText(img.alt || ``)
pos = alt ? findTextPosInEditor(alt) : null
if (pos == null && img.src) {
pos = findTextPosInEditor(img.src)
}
}
else {
const text = normalizeText(el.textContent || ``)
pos = findTextPosInEditor(text)
}
if (pos != null) {
const view = getEditorView()
if (!view)
return
view.dispatch({
selection: { anchor: pos },
effects: EditorView.scrollIntoView(pos, { y: `center` }),
})
view.focus()
}
}
function handlePreviewContentClick(event: MouseEvent) {
const target = event.target as HTMLElement | null
if (!target)
return
// 拦截预览区角标 a 标签(以及其他内部锚点链接,如脚注),手动平滑滚动
const linkEl = target.closest(`a`) as HTMLAnchorElement | null
if (linkEl) {
const href = linkEl.getAttribute(`href`)
if (href && href.startsWith(`#`)) {
let targetId = ``
try {
targetId = decodeURIComponent(href.slice(1))
}
catch {}
if (targetId) {
const targetEl = document.getElementById(targetId)
if (targetEl) {
const container = target.closest(`.preview-wrapper`) || document.getElementById(`preview`)
if (container && container.contains(targetEl)) {
event.preventDefault()
event.stopPropagation()
const containerRect = container.getBoundingClientRect()
const elementRect = targetEl.getBoundingClientRect()
const targetScrollTop = elementRect.top - containerRect.top + container.scrollTop
container.scrollTo({
top: targetScrollTop,
behavior: `smooth`,
})
return
}
}
}
}
}
const formulaEl = target.closest(`[data-math-raw]`) as HTMLElement | null
if (formulaEl) {
const raw = formulaEl.getAttribute(`data-math-raw`) ?? ``
const display = formulaEl.getAttribute(`data-math-display`) === `true`
uiStore.openFormulaEditor({ value: raw, displayMode: display, sourceRaw: raw })
return
}
const block = target.closest(`h1,h2,h3,h4,h5,h6,p,li,blockquote,pre,td,th,img`) as HTMLElement | null
if (!block)
return
syncEditorToPreviewElement(block)
}
return {
handlePreviewContentClick,
}
}