-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathsyntax-highlight.spec.js
362 lines (325 loc) · 14.7 KB
/
syntax-highlight.spec.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
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
/**
* This source file is part of the Swift.org open source project
*
* Copyright (c) 2021 Apple Inc. and the Swift project authors
* Licensed under Apache License v2.0 with Runtime Library Exception
*
* See https://swift.org/LICENSE.txt for license information
* See https://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
/* eslint-disable */
import {
LanguageAliasEntries,
SupportedLanguagesSet,
sanitizeMultilineNodes,
} from "docc-render/utils/syntax-highlight";
let hljs;
let highlightContent;
let highlight;
let registerHighlightLanguage;
let LanguageAliasCacheMap;
/**
*
* @param {string[]} content
* @param {string} language
* @returns {Promise<{ highlightedCode: string, sanitizedCode: string }>}
*/
async function prepare(content, language) {
// register the language with highlightjs
await registerHighlightLanguage(language);
// use this for a reference
const highlightedCode = highlight(content.join("\n"), language);
const tempElement = document.createElement("code");
tempElement.innerHTML = highlightedCode;
// transform the content
const sanitizedCode = highlightContent(content, language);
return {
highlightedCode: tempElement.innerHTML,
sanitizedCode: sanitizedCode.join("\n"), // revert back to string
};
}
const tryHighlight = (code, lang) => () => highlight(code, lang);
describe("syntax-highlight", () => {
// reset the imported modules between tests
beforeEach(async () => {
jest.resetModules();
hljs = await import("highlight.js/lib/core");
({ highlightContent, highlight, registerHighlightLanguage, LanguageAliasCacheMap } =
await import("docc-render/utils/syntax-highlight"));
});
it("does nothing to single row syntax", async () => {
const content = ['let name = "Rosa"', 'let personalizedGreeting = "Welcome, \\(name)!"'];
const { highlightedCode, sanitizedCode } = await prepare(content, "swift");
expect(sanitizedCode).toEqual(highlightedCode);
expect(sanitizedCode).toMatchInlineSnapshot(`
<span class="syntax-keyword">let</span> name <span class="syntax-operator">=</span> <span class="syntax-string">"Rosa"</span>
<span class="syntax-keyword">let</span> personalizedGreeting <span class="syntax-operator">=</span> <span class="syntax-string">"Welcome, <span class="syntax-subst">\\(name)</span>!"</span>
`);
});
it("wraps multiline blocks into in the same tag as the parent", async () => {
const content = [
'let banner = """',
" __,",
" ( o /) _/_",
" `. , , , , // /",
" (___)(_(_/_(_ //_ (__",
" /)",
" (/",
' """',
];
const { highlightedCode, sanitizedCode } = await prepare(content, "swift");
expect(sanitizedCode).not.toEqual(highlightedCode);
expect(sanitizedCode).toMatchInlineSnapshot(`
<span class="syntax-keyword">let</span> banner <span class="syntax-operator">=</span> <span class="syntax-string">"""</span>
<span class="syntax-string"> __,</span>
<span class="syntax-string"> ( o /) _/_</span>
<span class="syntax-string"> \`. , , , , // /</span>
<span class="syntax-string"> (___)(_(_/_(_ //_ (__</span>
<span class="syntax-string"> /)</span>
<span class="syntax-string"> (/</span>
<span class="syntax-string"> """</span>
`);
});
it('adds extra line breaks to empty lines that wrap', async () => {
const content = [
'let multiline = """',
'Needs',
'',
'Spaces',
'',
'Between',
'',
'Lines',
'"""',
];
const { highlightedCode, sanitizedCode } = await prepare(content, "js");
expect(sanitizedCode).not.toEqual(highlightedCode);
expect(sanitizedCode).toMatchInlineSnapshot(`
<span class="syntax-keyword">let</span> multiline = <span class="syntax-string">""</span><span class="syntax-string">"</span>
<span class="syntax-string">Needs</span>
<span class="syntax-string"></span>
<span class="syntax-string">Spaces</span>
<span class="syntax-string"></span>
<span class="syntax-string">Between</span>
<span class="syntax-string"></span>
<span class="syntax-string">Lines</span>
<span class="syntax-string">"</span><span class="syntax-string">""</span>
`);
});
it("wraps multiline nested highlighted blocks", async () => {
const content = [
"function someName(foo,",
" bar,",
" baz) {",
" foo()",
"}",
];
const { highlightedCode, sanitizedCode } = await prepare(content, "js");
expect(sanitizedCode).not.toEqual(highlightedCode);
expect(sanitizedCode).toMatchInlineSnapshot(`
<span class="syntax-keyword">function</span> <span class="syntax-title function_">someName</span>(<span class="syntax-params">foo,</span>
<span class="syntax-params"> bar,</span>
<span class="syntax-params"> baz</span>) {
<span class="syntax-title function_">foo</span>()
}
`);
});
it('keeps escaped newline tokens on the same line for multiline string literals', async () => {
const content = [
'let multiline = """',
'a \\',
'b',
'',
'c \\',
'd',
'"""',
];
const { highlightedCode, sanitizedCode } = await prepare(content, 'swift');
expect(sanitizedCode).not.toEqual(highlightedCode);
expect(sanitizedCode).toMatchInlineSnapshot(`
<span class="syntax-keyword">let</span> multiline <span class="syntax-operator">=</span> <span class="syntax-string">"""</span>
<span class="syntax-string">a <span class="syntax-subst">\\</span></span>
<span class="syntax-string">b</span>
<span class="syntax-string"></span>
<span class="syntax-string">c <span class="syntax-subst">\\</span></span>
<span class="syntax-string">d</span>
<span class="syntax-string">"""</span>
`);
});
it("wraps multiline nested html elements", () => {
const code = document.createElement("CODE");
code.innerHTML = `<span class="syntax-function">function <span class="syntax-title function_">someName</span>(<span class="syntax-params">foo,
bar,
baz</span>)</span> <span class="syntax-function-body">{
<span class="syntax-title function_">foo</span>()
}</span>`;
sanitizeMultilineNodes(code);
expect(code.innerHTML).toMatchInlineSnapshot(`
<span class="syntax-function">function <span class="syntax-title function_">someName</span>(<span class="syntax-params">foo,</span></span>
<span class="syntax-function"><span class="syntax-params"> bar,</span></span>
<span class="syntax-function"><span class="syntax-params"> baz</span>)</span> <span class="syntax-function-body">{</span>
<span class="syntax-function-body"><span class="syntax-title function_">foo</span>()</span>
<span class="syntax-function-body">}</span>
`);
});
it("tokenizes swift class functions correctly", async () => {
const content = ["class func foo() async throws -> [Bar]"];
const { highlightedCode } = await prepare(content, "swift");
expect(highlightedCode).toMatchInlineSnapshot(
`<span class="syntax-keyword">class</span> <span class="syntax-keyword">func</span> <span class="syntax-title function_">foo</span>() <span class="syntax-keyword">async</span> <span class="syntax-keyword">throws</span> -> [<span class="syntax-type">Bar</span>]`
);
});
it("does not tokenize swift keywords inside words", async () => {
const content = [
"var protocolMock = true // 'protocol' is not highlighted",
"var myenum = true // 'enum' is not highlighted",
"if FooConfig.supportsReconstruction(.someClassification) {",
" configuration.fooReconstruction = .someprotocolextensionclass",
"}",
];
const { highlightedCode } = await prepare(content, "swift");
expect(highlightedCode).toMatchInlineSnapshot(`
<span class="syntax-keyword">var</span> protocolMock <span class="syntax-operator">=</span> <span class="syntax-literal">true</span> <span class="syntax-comment">// 'protocol' is not highlighted</span>
<span class="syntax-keyword">var</span> myenum <span class="syntax-operator">=</span> <span class="syntax-literal">true</span> <span class="syntax-comment">// 'enum' is not highlighted</span>
<span class="syntax-keyword">if</span> <span class="syntax-type">FooConfig</span>.supportsReconstruction(.someClassification) {
configuration.fooReconstruction <span class="syntax-operator">=</span> .someprotocolextensionclass
}
`);
});
it('tokenizes docc "documentation markup" for markdown language', async () => {
const content = [
"# h1",
"## h2",
"### h3",
"",
"paragraph with _italics_ and **bold** and `code`",
"",
"[link](https://example.com) and ",
"",
"* unordered",
"* list",
"",
"1. ordered",
"2. list",
"",
"> Note:",
"> This is a note.",
"",
"> Experiment:",
"> This is an experiment.",
"",
"> Tip:",
"> This is a tip.",
"",
"> Warning:",
"> This is a warning.",
"",
"> Other:",
"> This is a normal blockquote",
"",
"@Directive(time: 42, files: example.zip) {",
" @NestedDirective",
"}",
"",
"``FakeSymbol``",
"",
"<doc:FakeSymbol>",
"",
"<doc:/path/to/fakesymbol>",
];
const { highlightedCode } = await prepare(content, "markdown");
expect(highlightedCode).toMatchInlineSnapshot(`
<span class="syntax-section"># h1</span>
<span class="syntax-section">## h2</span>
<span class="syntax-section">### h3</span>
paragraph with <span class="syntax-emphasis">_italics_</span> and <span class="syntax-strong">**bold**</span> and <span class="syntax-code">\`code\`</span>
[<span class="syntax-string">link</span>](<span class="syntax-link">https://example.com</span>) and 
<span class="syntax-bullet">*</span> unordered
<span class="syntax-bullet">*</span> list
<span class="syntax-bullet">1.</span> ordered
<span class="syntax-bullet">2.</span> list
<span class="syntax-quote">> </span><span class="syntax-type">Note:</span><span class="syntax-quote">
> This is a note.</span>
<span class="syntax-quote">> </span><span class="syntax-type">Experiment:</span><span class="syntax-quote">
> This is an experiment.</span>
<span class="syntax-quote">> </span><span class="syntax-type">Tip:</span><span class="syntax-quote">
> This is a tip.</span>
<span class="syntax-quote">> </span><span class="syntax-type">Warning:</span><span class="syntax-quote">
> This is a warning.</span>
<span class="syntax-quote">> Other:</span>
<span class="syntax-quote">> </span><span class="syntax-quote">This is a normal blockquote</span>
<span class="syntax-title">@Directive</span>(time: <span class="syntax-number">42</span>, files: example.zip) {
<span class="syntax-title">@NestedDirective</span>
}
\`\`<span class="syntax-link">FakeSymbol</span>\`\`
<<span class="syntax-link">doc:FakeSymbol</span>>
<<span class="syntax-link">doc:/path/to/fakesymbol</span>>
`);
});
it("returns false if the language is not supported", async () => {
expect(await registerHighlightLanguage("pascal")).toBe(false);
});
it("returns false if already registered", async () => {
expect(hljs.listLanguages().includes("swift")).toBe(false);
expect(await registerHighlightLanguage("swift")).toBe(true);
expect(await registerHighlightLanguage("swift")).toBe(false);
});
describe("language aliases", () => {
it("registers a primary language, by its alias", async () => {
const [firstAlias] = LanguageAliasEntries;
const [language, aliases] = firstAlias;
// assert the language is not registered
expect(hljs.listLanguages().includes(language)).toBe(false);
// register the first alias
expect(await registerHighlightLanguage(aliases[0])).toBe(true);
// assert the language is registered
expect(hljs.listLanguages().includes(language)).toBe(true);
});
it("once an alias language registered, it silently fails, if registering another alias from the same list", async () => {
const [firstAlias] = LanguageAliasEntries;
const [language, aliases] = firstAlias;
// assert the language is not registered
expect(await registerHighlightLanguage(aliases[0])).toBe(true);
expect(hljs.listLanguages().includes(language)).toBe(true);
// register the second alias, and assert it returns false
expect(await registerHighlightLanguage(aliases[1])).toBe(false);
});
it("caches alias searches for improved performance", async () => {
const [firstAlias, secondAlias] = LanguageAliasEntries;
const [firstLanguage, firstAliases] = firstAlias;
const [secondLanguage, secondAliases] = secondAlias;
// assert the language is not registered
expect(await registerHighlightLanguage(firstAliases[0])).toBe(true);
expect(LanguageAliasCacheMap.get(firstAliases[0])).toBe(firstLanguage);
// register the second alias, and assert it returns false
expect(await registerHighlightLanguage(firstAliases[1])).toBe(false);
expect(LanguageAliasCacheMap.get(firstAliases[1])).toBe(firstLanguage);
expect(await registerHighlightLanguage("invalid")).toBe(false);
expect(LanguageAliasCacheMap.get("invalid")).toBe(null);
expect(await registerHighlightLanguage(secondAliases[0])).toBe(true);
expect(LanguageAliasCacheMap.get(secondAliases[0])).toBe(secondLanguage);
});
});
it.each([...SupportedLanguagesSet])(
'does not thrown an error when the language is "%s"',
async (language) => {
await registerHighlightLanguage(language);
expect(tryHighlight("foo", language)).not.toThrow();
}
);
describe("custom aliases", () => {
it('does not throw an error when the language is "objective-c"', async () => {
const language = "objective-c";
await registerHighlightLanguage(language);
expect(tryHighlight("foo", language)).not.toThrow();
});
});
it("throws an error for unsupported languages", () => {
expect(tryHighlight("foo", "bash")).toThrowError(
/Unsupported language for syntax highlighting: bash/
);
expect(tryHighlight("foo", "fakelanguage")).toThrowError(
/Unsupported language for syntax highlighting: fakelanguage/
);
});
});