-
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathlanguage-plugin.js
More file actions
100 lines (89 loc) · 2.54 KB
/
language-plugin.js
File metadata and controls
100 lines (89 loc) · 2.54 KB
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
/// <reference types="@volar/typescript" />
/**
* @import {LanguagePlugin} from '@volar/language-service'
* @import {PluggableList} from 'unified'
* @import {URI} from 'vscode-uri'
* @import {VirtualCodePlugin} from './plugins/plugin.js'
*/
import {Parser} from 'acorn'
import acornJsx from 'acorn-jsx'
import {LooseParser} from 'acorn-loose'
import remarkMdx from 'remark-mdx'
import remarkParse from 'remark-parse'
import {unified} from 'unified'
import {VirtualMdxCode} from './virtual-code.js'
const StrictParser = Parser.extend(acornJsx())
const hybridAcorn = {
parse: LooseParser.parse.bind(LooseParser),
parseExpressionAt: StrictParser.parseExpressionAt.bind(StrictParser)
}
/**
* Create a [Volar](https://volarjs.dev) language plugin to support MDX.
*
* @param {PluggableList} [remarkPlugins]
* A list of remark syntax plugins. Only syntax plugins are supported.
* Transformers are unused.
* @param {VirtualCodePlugin[]} [virtualCodePlugins]
* @param {boolean} checkMdx
* If true, check MDX files strictly.
* @param {string} jsxImportSource
* The JSX import source to use in the embedded JavaScript file.
* @returns {LanguagePlugin<string | URI, VirtualMdxCode>}
* A Volar language plugin to support MDX.
*/
export function createMdxLanguagePlugin(
remarkPlugins,
virtualCodePlugins,
checkMdx = false,
jsxImportSource = 'react'
) {
const processor = unified()
.use(remarkParse)
.use(remarkMdx, {acorn: hybridAcorn})
if (remarkPlugins) {
processor.use(remarkPlugins)
}
processor.freeze()
return {
getLanguageId(fileNameOrUri) {
if (String(fileNameOrUri).endsWith('.mdx')) {
return 'mdx'
}
},
createVirtualCode(fileNameOrUri, languageId, snapshot) {
if (languageId === 'mdx') {
return new VirtualMdxCode(
snapshot,
processor,
virtualCodePlugins || [],
checkMdx,
jsxImportSource
)
}
},
typescript: {
extraFileExtensions: [
{extension: 'mdx', isMixedContent: true, scriptKind: 7}
],
getServiceScript(root) {
if (root.embeddedCodes) {
return {
code: root.embeddedCodes[0],
extension: '.jsx',
scriptKind: 2
}
}
},
resolveLanguageServiceHost(host) {
return {
...host,
getCompilationSettings: () => ({
...host.getCompilationSettings(),
// Always allow JS for type checking.
allowJs: true
})
}
}
}
}
}