-
Notifications
You must be signed in to change notification settings - Fork 21
/
MDCRenderer.vue
448 lines (384 loc) · 12 KB
/
MDCRenderer.vue
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
<script lang="ts">
import { h, resolveComponent, Text, Comment, defineComponent, toRaw, computed, getCurrentInstance } from 'vue'
import destr from 'destr'
import { kebabCase, pascalCase } from 'scule'
import { find, html } from 'property-information'
import type { VNode, ConcreteComponent, PropType, DefineComponent } from 'vue'
import type { MDCElement, MDCNode, MDCRoot, MDCData } from '@nuxtjs/mdc'
import htmlTags from '../parser/utils/html-tags-list'
import { flatUnwrap } from '../utils/node'
type CreateElement = typeof h
/**
* Default slot name
*/
const DEFAULT_SLOT = 'default'
const rxOn = /^@|^v-on:/
const rxBind = /^:|^v-bind:/
const rxModel = /^v-model/
const nativeInputs = ['select', 'textarea', 'input']
const proseComponentMap = Object.fromEntries(['p', 'a', 'blockquote', 'code', 'pre', 'code', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'img', 'ul', 'ol', 'li', 'strong', 'table', 'thead', 'tbody', 'td', 'th', 'tr', 'script'].map(t => [t, `prose-${t}`]))
export default defineComponent({
name: 'MDCRenderer',
props: {
/**
* Content to render
*/
body: {
type: Object as PropType<MDCRoot>,
required: true
},
/**
* Document meta data
*/
data: {
type: Object,
default: () => ({})
},
/**
* Root tag to use for rendering
*/
class: {
type: [String, Object],
default: undefined
},
/**
* Root tag to use for rendering
*/
tag: {
type: [String, Boolean],
default: undefined
},
/**
* Whether or not to render Prose components instead of HTML tags
*/
prose: {
type: Boolean,
default: undefined
},
/**
* The map of custom components to use for rendering.
*/
components: {
type: Object as PropType<Record<string, string | DefineComponent<any, any, any>>>,
default: () => ({})
},
/**
* Tags to unwrap separated by spaces
* Example: 'ul li'
*/
unwrap: {
type: [Boolean, String],
default: false
}
},
async setup(props) {
const $nuxt = getCurrentInstance()?.appContext?.app?.$nuxt
const route = $nuxt?.$route || $nuxt?._route
const { mdc } = $nuxt?.$config?.public || {}
const tags = {
...(mdc?.components?.prose && props.prose !== false ? proseComponentMap : {}),
...(mdc?.components?.map || {}),
...toRaw(props.data?.mdc?.components || {}),
...props.components
}
const contentKey = computed(() => {
const components = (props.body?.children || [])
.map(n => (n as any).tag || n.type)
.filter(t => !htmlTags.includes(t))
return Array.from(new Set(components)).sort().join('.')
})
await resolveContentComponents(props.body, { tags })
return { tags, contentKey, route }
},
render(ctx: any) {
const { tags, tag, body, data, contentKey, route, unwrap } = ctx
if (!body) {
return null
}
const meta = { ...data, tags, $route: route }
// Resolve root component
const component: string | ConcreteComponent = tag !== false ? resolveVueComponent((tag || meta.component?.name || meta.component || 'div') as string) : undefined
// Return Vue component
return component
? h(component as any, { ...meta.component?.props, class: ctx.class, ...this.$attrs, key: contentKey }, { default: defaultSlotRenderer })
: defaultSlotRenderer?.()
function defaultSlotRenderer() {
if (unwrap) {
return flatUnwrap(
renderSlots(body, h, meta, meta).default(),
typeof unwrap === 'string' ? unwrap.split(' ') : ['*']
)
}
return renderSlots(body, h, meta, meta).default()
}
}
})
/**
* Render a markdown node
*/
function renderNode(node: MDCNode, h: CreateElement, documentMeta: MDCData, parentScope: any = {}): VNode {
/**
* Render Text node
*/
if (node.type === 'text') {
return h(Text, node.value)
}
if (node.type === 'comment') {
return h(Comment, null, node.value)
}
const originalTag = node.tag!
// `_ignoreMap` is an special prop to disables tag-mapper
const renderTag: string = findMappedTag(node as MDCElement, documentMeta.tags)
if (node.tag === 'binding') {
return renderBinding(node, h, documentMeta, parentScope)
}
const component = resolveVueComponent(renderTag)
if (typeof component === 'object') {
component.tag = originalTag
}
const props = propsToData(node, documentMeta)
return h(
component as any,
props,
renderSlots(node, h, documentMeta, { ...parentScope, ...props })
)
}
function renderBinding(node: MDCElement, h: CreateElement, documentMeta: MDCData, parentScope: any = {}): VNode {
const data = {
...parentScope,
$document: documentMeta,
$doc: documentMeta
}
const splitter = /\.|\[(\d+)\]/
const keys: string[] = node.props?.value.trim().split(splitter).filter(Boolean)
const value = keys.reduce((data, key) => {
if (data && key in data) {
if (typeof data[key] === 'function') {
return data[key]()
} else {
return data[key]
}
}
return undefined
}, data)
const defaultValue = node.props?.defaultValue
return h(Text, value ?? defaultValue ?? '')
}
/**
* Create slots from `node` template children.
*/
function renderSlots(node: MDCNode, h: CreateElement, documentMeta: MDCData, parentProps: any): Record<string, () => VNode[]> {
const children: MDCNode[] = (node as MDCElement).children || []
const slotNodes: Record<string, MDCNode[]> = children.reduce((data, node) => {
if (!isTemplate(node)) {
data[DEFAULT_SLOT].push(node)
return data
}
const slotName = getSlotName(node)
data[slotName] = data[slotName] || []
if (node.type === 'element') {
// Append children to slot
data[slotName].push(...(node.children || []))
}
return data
}, {
[DEFAULT_SLOT]: [] as any[]
} as Record<string, any[]>)
const slots = Object.entries(slotNodes).reduce((slots, [name, children]) => {
if (!children.length) {
return slots
}
slots[name] = () => {
const vNodes = children.map(child => renderNode(child, h, documentMeta, parentProps))
return mergeTextNodes(vNodes)
}
return slots
}, {} as Record<string, () => VNode[]>)
return slots
}
/**
* Create component data from node props.
*/
function propsToData(node: MDCElement, documentMeta: MDCData) {
const { tag = '', props = {} } = node
return Object.keys(props).reduce(function (data, key) {
// Ignore internal `__ignoreMap` prop.
if (key === '__ignoreMap') {
return data
}
const value = props[key]
// `v-model="foo"`
if (rxModel.test(key) && !nativeInputs.includes(tag)) {
return propsToDataRxModel(key, value, data, documentMeta)
}
// `v-bind="{foo: 'bar'}"`
if (key === 'v-bind') {
return propsToDataVBind(key, value, data, documentMeta)
}
// `v-on="foo"`
if (rxOn.test(key)) {
return propsToDataRxOn(key, value, data, documentMeta)
}
// `:foo="bar"`, `v-bind:foo="bar"`
if (rxBind.test(key)) {
return propsToDataRxBind(key, value, data, documentMeta)
}
const { attribute } = find(html, key)
// Join string arrays using space, see: https://github.com/nuxt/content/issues/247
if (Array.isArray(value) && value.every(v => typeof v === 'string')) {
data[attribute] = value.join(' ')
return data
}
data[attribute] = value
return data
}, {} as any)
}
/**
* Handle `v-model`
*/
function propsToDataRxModel(key: string, value: any, data: any, documentMeta: MDCData) {
// Model modifiers
const number = (d: any) => +d
const trim = (d: any) => d.trim()
const noop = (d: any) => d
const mods = key
.replace(rxModel, '')
.split('.')
.filter(d => d)
.reduce((d, k) => {
d[k] = true
return d
}, {} as any)
// As of yet we don't resolve custom v-model field/event names from components
const field = 'value'
const event = mods.lazy ? 'change' : 'input'
const processor = mods.number ? number : mods.trim ? trim : noop
data[field] = evalInContext(value, documentMeta)
data.on = data.on || {}
data.on[event] = (e: any) => ((documentMeta as any)[value] = processor(e))
return data
}
/**
* Handle object binding `v-bind`
*/
function propsToDataVBind(_key: string, value: any, data: any, documentMeta: MDCData) {
const val = evalInContext(value, documentMeta)
data = Object.assign(data, val)
return data
}
/**
* Handle `v-on` and `@`
*/
function propsToDataRxOn(key: string, value: any, data: any, documentMeta: MDCData) {
key = key.replace(rxOn, '')
data.on = data.on || {}
data.on[key] = () => evalInContext(value, documentMeta)
return data
}
/**
* Handle single binding `v-bind:` and `:`
*/
function propsToDataRxBind(key: string, value: any, data: any, documentMeta: MDCData) {
key = key.replace(rxBind, '')
data[key] = evalInContext(value, documentMeta)
return data
}
/**
* Resolve component if it's a Vue component
*/
const resolveVueComponent = (component: any) => {
// Check if node is not a native HTML tag
if (!htmlTags.includes(component) && !component?.render && !component?.ssrRender) {
const componentFn = resolveComponent(pascalCase(component), false)
// If component exists
if (typeof componentFn === 'object') {
return componentFn
}
}
return component
}
/**
* Evaluate value in specific context
*/
function evalInContext(code: string, context: any) {
// Retrive value from context
const result = code
.split('.')
.reduce((o: any, k) => typeof o === 'object' ? o[k] : undefined, context)
return typeof result === 'undefined' ? destr(code) : result
}
/**
* Get slot name out of a node
*/
function getSlotName(node: MDCNode) {
let name = ''
for (const propName of Object.keys((node as MDCElement).props || {})) {
// Check if prop name correspond to a slot
if (!propName.startsWith('#') && !propName.startsWith('v-slot:')) {
continue
}
// Get slot name
name = propName.split(/[:#]/, 2)[1]
break
}
return name || DEFAULT_SLOT
}
/**
* Check if node is Vue template tag
*/
function isTemplate(node: MDCNode) {
return (node as MDCElement).tag === 'template'
}
/**
* Merge consequent Text nodes into single node
*/
function mergeTextNodes(nodes: Array<VNode>) {
const mergedNodes: Array<VNode> = []
for (const node of nodes) {
const previousNode = mergedNodes[mergedNodes.length - 1]
if (node.type === Text && previousNode?.type === Text) {
previousNode.children = (previousNode.children as string) + node.children
} else {
mergedNodes.push(node)
}
}
return mergedNodes
}
async function resolveContentComponents(body: MDCRoot, meta: Record<string, any>) {
if (!body) {
return
}
const components = Array.from(new Set(loadComponents(body, meta)))
await Promise.all(components.map(async (c: any) => {
if (c?.render || c?.ssrRender || c?.__ssrInlineRender) {
return
}
const resolvedComponent = resolveVueComponent(c) as any
if (resolvedComponent?.__asyncLoader && !resolvedComponent.__asyncResolved) {
await resolvedComponent.__asyncLoader()
}
}))
function loadComponents(node: MDCRoot | MDCNode, documentMeta: Record<string, any>) {
const tag = (node as MDCElement).tag
if (node.type === 'text' || tag === 'binding' || node.type === 'comment') {
return []
}
const renderTag: string = findMappedTag(node as MDCElement, documentMeta.tags)
const components: string[] = []
if (node.type !== 'root' && !htmlTags.includes(renderTag as any)) {
components.push(renderTag)
}
for (const child of (node.children || [])) {
components.push(...loadComponents(child, documentMeta))
}
return components
}
}
function findMappedTag(node: MDCElement, tags: Record<string, string>) {
const tag = node.tag
if (!tag || typeof (node as MDCElement).props?.__ignoreMap !== 'undefined') {
return tag
}
return tags[tag] || tags[pascalCase(tag)] || tags[kebabCase(node.tag)] || tag
}
</script>