/
renderLeafBlock.js
239 lines (228 loc) 路 7.47 KB
/
renderLeafBlock.js
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
import katex from 'katex'
import mermaid from 'mermaid'
import prism, { loadedCache } from '../../../prism/'
import { CLASS_OR_ID, DEVICE_MEMORY, PREVIEW_DOMPURIFY_CONFIG, HAS_TEXT_BLOCK_REG } from '../../../config'
import { tokenizer } from '../../parse'
import { snakeToCamel, sanitize, escapeHtml, getLongUniqueId } from '../../../utils'
import { h, htmlToVNode } from '../snabbdom'
import alignLeftIcon from '../../../assets/icons/align_left.svg'
import alignRightIcon from '../../../assets/icons/align_right.svg'
import alignCenterIcon from '../../../assets/icons/align_center.svg'
import tableIcon from '../../../assets/icons/table.svg'
import deleteIcon from '../../../assets/icons/delete.svg'
// todo@jocs any better solutions?
const MARKER_HASK = {
'<': `%${getLongUniqueId()}%`,
'>': `%${getLongUniqueId()}%`,
'"': `%${getLongUniqueId()}%`,
"'": `%${getLongUniqueId()}%`
}
const ICON_MAP = {
'icon-alignright': alignRightIcon,
'icon-alignleft': alignLeftIcon,
'icon-del': deleteIcon,
'icon-table': tableIcon,
'icon-aligncenter': alignCenterIcon
}
const getHighlightHtml = (text, highlights, escape = false) => {
let code = ''
let pos = 0
for (const highlight of highlights) {
const { start, end, active } = highlight
code += text.substring(pos, start)
const className = active ? 'ag-highlight' : 'ag-selection'
code += escape
? `${MARKER_HASK['<']}span class=${MARKER_HASK['"']}${className}${MARKER_HASK['"']}${MARKER_HASK['>']}${text.substring(start, end)}${MARKER_HASK['<']}/span${MARKER_HASK['>']}`
: `<span class="${className}">${text.substring(start, end)}</span>`
pos = end
}
if (pos !== text.length) {
code += text.substring(pos)
}
return code
}
export default function renderLeafBlock (block, cursor, activeBlocks, matches, useCache = false) {
const { loadMathMap } = this
let selector = this.getSelector(block, cursor, activeBlocks)
// highlight search key in block
const highlights = matches.filter(m => m.key === block.key)
const {
text,
type,
headingStyle,
align,
icon,
checked,
key,
lang,
functionType,
editable
} = block
const data = {
props: {},
attrs: {},
dataset: {},
style: {}
}
let children = ''
if (text) {
let tokens = []
if (highlights.length === 0 && this.tokenCache.has(text)) {
tokens = this.tokenCache.get(text)
} else if (
HAS_TEXT_BLOCK_REG.test(type) &&
functionType !== 'codeLine' &&
functionType !== 'languageInput'
) {
const hasBeginRules = /^(h\d|span|hr)/.test(type)
tokens = tokenizer(text, highlights, hasBeginRules)
if (highlights.length === 0 && useCache && DEVICE_MEMORY >= 4) {
this.tokenCache.set(text, tokens)
}
}
children = tokens.reduce((acc, token) => [...acc, ...this[snakeToCamel(token.type)](h, cursor, block, token)], [])
}
if (editable === false) {
Object.assign(data.attrs, {
contenteditable: 'false'
})
}
if (/th|td/.test(type) && align) {
Object.assign(data.attrs, {
style: `text-align:${align}`
})
} else if (type === 'div') {
const code = this.muya.contentState.codeBlocks.get(block.preSibling)
switch (functionType) {
case 'preview': {
selector += `.${CLASS_OR_ID['AG_HTML_PREVIEW']}`
const htmlContent = sanitize(code, PREVIEW_DOMPURIFY_CONFIG)
// handle empty html bock
if (/<([a-z][a-z\d]*).*>\s*<\/\1>/.test(htmlContent)) {
children = htmlToVNode('<div class="ag-empty"><Empty HTML Block></div>')
} else {
children = htmlToVNode(htmlContent)
}
break
}
case 'multiplemath': {
const key = `${code}_display_math`
selector += `.${CLASS_OR_ID['AG_CONTAINER_PREVIEW']}`
if (code === '') {
children = '< Empty Mathematical Formula >'
selector += `.${CLASS_OR_ID['AG_EMPTY']}`
} else if (loadMathMap.has(key)) {
children = loadMathMap.get(key)
} else {
try {
const html = katex.renderToString(code, {
displayMode: true
})
children = htmlToVNode(html)
loadMathMap.set(key, children)
} catch (err) {
children = '< Invalid Mathematical Formula >'
selector += `.${CLASS_OR_ID['AG_MATH_ERROR']}`
}
}
break
}
case 'mermaid': {
selector += `.${CLASS_OR_ID['AG_CONTAINER_PREVIEW']}`
if (code === '') {
children = '< Empty Mermaid Block >'
selector += `.${CLASS_OR_ID['AG_EMPTY']}`
} else {
try {
mermaid.parse(code)
children = code
this.mermaidCache.add(`#${block.key}`)
} catch (err) {
children = '< Invalid Mermaid Codes >'
selector += `.${CLASS_OR_ID['AG_MATH_ERROR']}`
}
}
break
}
case 'flowchart':
case 'sequence':
case 'vega-lite': {
const code = this.muya.contentState.codeBlocks.get(block.preSibling)
selector += `.${CLASS_OR_ID['AG_CONTAINER_PREVIEW']}`
if (code === '') {
children = '< Empty Diagram Block >'
selector += `.${CLASS_OR_ID['AG_EMPTY']}`
} else {
children = ''
this.diagramCache.set(`#${block.key}`, {
code,
functionType
})
}
break
}
}
} else if (type === 'svg' && icon) {
selector += '.icon'
const iconSvg = ICON_MAP[icon]
Object.assign(data.attrs, {
'viewBox': iconSvg.viewBox,
'aria-hidden': 'true'
})
children = [
h('use', {
attrs: {
'xlink:href': `.${iconSvg.url}`
}
})
]
} else if (/^h/.test(type)) {
if (/^h\d$/.test(type)) {
Object.assign(data.dataset, {
head: type,
// TODO(#590): Slugify heading
id: '' // isInElectron ? require('markdown-toc').slugify(text.replace(/^#+\s(.*)/, (_, p1) => p1)) : ''
})
selector += `.${headingStyle}`
}
Object.assign(data.dataset, {
role: type
})
} else if (type === 'input') {
Object.assign(data.attrs, {
type: 'checkbox'
})
selector = `${type}#${key}.${CLASS_OR_ID['AG_TASK_LIST_ITEM_CHECKBOX']}`
if (checked) {
Object.assign(data.attrs, {
checked: true
})
selector += `.${CLASS_OR_ID['AG_CHECKBOX_CHECKED']}`
}
children = ''
} else if (type === 'span' && functionType === 'codeLine') {
const code = escapeHtml(getHighlightHtml(text, highlights, true))
.replace(new RegExp(MARKER_HASK['<'], 'g'), '<')
.replace(new RegExp(MARKER_HASK['>'], 'g'), '>')
.replace(new RegExp(MARKER_HASK['"'], 'g'), '"')
.replace(new RegExp(MARKER_HASK["'"], 'g'), "'")
selector += `.${CLASS_OR_ID['AG_CODE_LINE']}`
if (lang && /\S/.test(code) && loadedCache.has(lang)) {
const wrapper = document.createElement('div')
wrapper.classList.add(`language-${lang}`)
wrapper.innerHTML = code
prism.highlightElement(wrapper, false, function () {
const highlightedCode = this.innerHTML
selector += `.language-${lang}`
children = htmlToVNode(highlightedCode)
})
} else {
children = htmlToVNode(code)
}
} else if (type === 'span' && functionType === 'languageInput') {
const html = getHighlightHtml(text, highlights)
selector += `.${CLASS_OR_ID['AG_LANGUAGE_INPUT']}`
children = htmlToVNode(html)
}
return h(selector, data, children)
}