-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathcode.js
65 lines (57 loc) · 1.39 KB
/
code.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
/**
* @import {State} from 'hast-util-to-mdast'
* @import {Element} from 'hast'
* @import {Code} from 'mdast'
*/
import {toText} from 'hast-util-to-text'
import {trimTrailingLines} from 'trim-trailing-lines'
const prefix = 'language-'
/**
* @param {State} state
* State.
* @param {Readonly<Element>} node
* hast element to transform.
* @returns {Code}
* mdast node.
*/
export function code(state, node) {
const children = node.children
let index = -1
/** @type {Array<number | string> | undefined} */
let classList
/** @type {string | undefined} */
let lang
if (node.tagName === 'pre') {
while (++index < children.length) {
const child = children[index]
if (
child.type === 'element' &&
child.tagName === 'code' &&
child.properties &&
child.properties.className &&
Array.isArray(child.properties.className)
) {
classList = child.properties.className
break
}
}
}
if (classList) {
index = -1
while (++index < classList.length) {
if (String(classList[index]).slice(0, prefix.length) === prefix) {
lang = String(classList[index]).slice(prefix.length)
break
}
}
}
/** @type {Code} */
const result = {
type: 'code',
lang: lang || null,
meta: null,
value: trimTrailingLines(toText(node))
}
state.patch(node, result)
return result
}