/
file-html.ts
89 lines (74 loc) · 2.72 KB
/
file-html.ts
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
import { CodeGen } from '@volar/code-gen';
import { SourceMapBase } from '@volar/source-map';
import { parse, SFCBlock } from '@vue/compiler-sfc';
import { VueLanguagePlugin } from '../sourceFile';
const plugin: VueLanguagePlugin = () => {
return {
parseSFC(fileName, content) {
if (fileName.endsWith('.html')) {
let newContent = content;
let isTs = false;
const sfcBlockReg = /\<(script|style)[\s\S]*?\>([\s\S]*?)\<\/\1\>/g;
const codeGen = new CodeGen();
for (const match of content.matchAll(sfcBlockReg)) {
if (match.index !== undefined) {
const matchText = match[0];
// ignore `<script src="...">`
if (matchText.startsWith('<script') && matchText.indexOf('src=') >= 0) {
newContent = newContent.substring(0, match.index) + ' '.repeat(matchText.length) + newContent.substring(match.index + matchText.length);
}
else if (matchText.startsWith('<style')) {
codeGen.addCode2(matchText, match.index, undefined);
codeGen.addText('\n\n');
newContent = newContent.substring(0, match.index) + ' '.repeat(matchText.length) + newContent.substring(match.index + matchText.length);
}
if (matchText.startsWith('<script') && (
matchText.indexOf('lang="ts"') >= 0 ||
matchText.indexOf('lang="tsx"') >= 0
)) {
isTs = true;
}
}
}
newContent = newContent.replace(/<script[\s\S]*?>/g, str => `<vls-sr${' '.repeat(str.length - '<script>'.length)}>`);
newContent = newContent.replace(/<\/script>/g, '</vls-sr>');
codeGen.addText('<template>\n');
codeGen.addCode2(newContent, 0, undefined);
codeGen.addText('\n</template>');
if (isTs) {
codeGen.addText('\n<script setup lang="ts"></script>');
}
const file2VueSourceMap = new SourceMapBase(codeGen.mappings);
const sfc = parse(codeGen.getText(), { sourceMap: false, ignoreEmpty: false });
if (sfc.descriptor.template) {
transformRange(sfc.descriptor.template);
}
if (sfc.descriptor.script) {
transformRange(sfc.descriptor.script);
}
if (sfc.descriptor.scriptSetup) {
transformRange(sfc.descriptor.scriptSetup);
}
for (const style of sfc.descriptor.styles) {
transformRange(style);
}
for (const customBlock of sfc.descriptor.customBlocks) {
transformRange(customBlock);
}
return sfc;
function transformRange(block: SFCBlock) {
const fileRange = file2VueSourceMap.getSourceRange(block.loc.start.offset, block.loc.end.offset)?.[0];
if (fileRange) {
block.loc.start.offset = fileRange.start;
block.loc.end.offset = fileRange.end;
}
else {
block.loc.start.offset = -1;
block.loc.end.offset = -1;
}
}
};
}
};
}
export = plugin;