This repository has been archived by the owner on Feb 6, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathutils.js
103 lines (84 loc) · 2.58 KB
/
utils.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
const toString = require("mdast-util-to-string");
const _ = require(`lodash`);
/**
* Returns the parsed language and the highlighted lines.
* For example, ```dart{3, 2, 5-9} will output {lang: 'dart', highlightLines: '3 2 5,9'}
* which is compatible with the <deckdeckgo-highlight-code> component (https://docs.deckdeckgo.com/?path=/story/components-highlight-code--highlight-code)
* @param {Markdown Node} node
*/
const parseLanguageAndHighlightedLines = ({ lang: nodeLang, meta }) => {
const highlightLinesRegex = /{(.*?)}/g;
const joinedNodeLang = `${nodeLang}${
meta !== null && meta !== undefined ? meta : ""
}`;
let lang = joinedNodeLang;
let highlightLines = "";
const regexExecResults = highlightLinesRegex.exec(joinedNodeLang);
if (!regexExecResults) {
// no lines to highlight
return {
lang,
highlightLines,
};
}
let [highlightText, numbersAndGroups] = regexExecResults;
lang = lang.replace(highlightText, "").trim();
highlightLines = numbersAndGroups
.split(",")
.reduce((acc, chunk) => {
const numbOrGroup = chunk.trim();
if (numbOrGroup.includes("-")) {
// is a group of numbers. e.g. {3-10}
return [...acc, numbOrGroup.replace("-", ",")];
}
return [...acc, numbOrGroup];
}, [])
.join(" ");
return {
lang,
highlightLines,
};
};
function generatePropsString(pluginOptions) {
if (!pluginOptions) {
return "";
}
let str = "";
const { terminal, lineNumbers, editable, theme } = pluginOptions;
if (terminal) {
str += `terminal="${pluginOptions.terminal}" `;
}
if (theme) {
str += `theme="${pluginOptions.theme}" `;
}
if (lineNumbers === true) {
str += `line-numbers="true" `;
}
if (editable === true) {
str += `editable="true" `;
}
return str;
}
function parseNodeHtml(node, pluginOptions) {
let lang = "",
highlightLines = undefined;
if (node && node.lang !== null) {
({ lang, highlightLines } = parseLanguageAndHighlightedLines(node));
}
const text = toString(node);
const properties = generatePropsString(pluginOptions);
const renderLang =
lang !== "" && lang !== undefined ? `language="${lang}"` : "";
const renderHighlightLines =
highlightLines !== "" && highlightLines !== undefined
? `highlight-lines="${highlightLines}"`
: "";
return `<deckgo-highlight-code ${renderLang} ${properties} ${renderHighlightLines}>
<code slot="code">${_.escape(text)}</code>
</deckgo-highlight-code>
`.trim();
}
module.exports = {
parseLanguageAndHighlightedLines,
parseNodeHtml,
};