/
vue-typescript-template.ts
301 lines (268 loc) · 10.4 KB
/
vue-typescript-template.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
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
import { CodeGen, mergeCodeGen } from '@volar/code-gen';
import * as SourceMaps from '@volar/source-map';
import { EmbeddedFileMappingData, getSlotsPropertyName, getVueLibraryName, TextRange } from '@volar/vue-code-gen';
import * as templateGen from '@volar/vue-code-gen/out/generators/template';
import type { parseScriptSetupRanges } from '@volar/vue-code-gen/out/parsers/scriptSetupRanges';
import { walkInterpolationFragment } from '@volar/vue-code-gen/out/transform';
import { ComputedRef } from '@vue/reactivity';
import * as path from 'path';
import { VueCompilerOptions } from '../types';
import { SearchTexts } from '../utils/string';
import { EmbeddedFile, useStyleCssClasses, useCssVars, VueLanguagePlugin } from '../sourceFile';
export default function (
ts: typeof import('typescript/lib/tsserverlibrary'),
cssModuleClasses: ReturnType<typeof useStyleCssClasses>,
cssScopedClasses: ReturnType<typeof useStyleCssClasses>,
templateCodeGens: ComputedRef<ReturnType<typeof templateGen['generate']> | undefined>,
cssVars: ReturnType<typeof useCssVars>,
scriptSetupRanges: ComputedRef<ReturnType<typeof parseScriptSetupRanges> | undefined>,
scriptLang: ComputedRef<string>,
compilerOptions: VueCompilerOptions,
disableTemplateScript: boolean,
useGlobalThisTypeInCtx: boolean,
): VueLanguagePlugin {
return {
getEmbeddedFilesCount(fileName, sfc) {
return 3;
},
getEmbeddedFile(fileName, sfc, i) {
const baseFileName = path.basename(fileName);
if (i === 0 && !disableTemplateScript) {
let scriptLeadingComments: string[] = [];
if (compilerOptions.experimentalUseScriptLeadingCommentInTemplate ?? true) {
for (const _script of [sfc.script, sfc.scriptSetup]) {
if (_script) {
const commentRanges = ts.getLeadingCommentRanges(_script.content, 0);
if (commentRanges) {
scriptLeadingComments = commentRanges.map(range => _script!.content.substring(range.pos, range.end));
}
}
}
}
const scriptLeadingComment = scriptLeadingComments.join('\n');
const tsxCodeGen = new CodeGen<EmbeddedFileMappingData>();
tsxCodeGen.addText(scriptLeadingComment + '\n');
tsxCodeGen.addText(`import * as __VLS_types from './__VLS_types';\n`);
if (sfc.script || sfc.scriptSetup) {
tsxCodeGen.addText(`import { __VLS_options, __VLS_name } from './${baseFileName}.__VLS_script';\n`);
tsxCodeGen.addText(`import __VLS_component from './${baseFileName}.__VLS_script';\n`);
}
else {
tsxCodeGen.addText(`var __VLS_name = undefined;\n`);
tsxCodeGen.addText(`var __VLS_options = {};\n`);
tsxCodeGen.addText(`var __VLS_component = (await import('${getVueLibraryName(compilerOptions.target ?? 3)}')).defineComponent({});\n`);
}
writeImportTypes();
tsxCodeGen.addText(`declare var __VLS_ctx: ${useGlobalThisTypeInCtx ? 'typeof globalThis &' : ''} InstanceType<__VLS_types.PickNotAny<typeof __VLS_component, new () => {}>> & {\n`);
/* CSS Module */
for (const cssModule of cssModuleClasses.value) {
tsxCodeGen.addText(`${cssModule.style.module}: Record<string, string>`);
for (const classNameRange of cssModule.classNameRanges) {
writeCssClassProperty(
cssModule.index,
cssModule.style.content.substring(classNameRange.start + 1, classNameRange.end),
classNameRange,
'string',
false,
);
}
tsxCodeGen.addText(';\n');
}
tsxCodeGen.addText(`};\n`);
tsxCodeGen.addText(`declare var __VLS_vmUnwrap: typeof __VLS_options & { components: { } };\n`);
/* Components */
tsxCodeGen.addText('/* Components */\n');
tsxCodeGen.addText('declare var __VLS_otherComponents: NonNullable<typeof __VLS_component extends { components: infer C } ? C : {}> & __VLS_types.GlobalComponents & typeof __VLS_vmUnwrap.components & __VLS_types.PickComponents<typeof __VLS_ctx>;\n');
tsxCodeGen.addText(`declare var __VLS_selfComponent: __VLS_types.SelfComponent<typeof __VLS_name, typeof __VLS_component & (new () => { ${getSlotsPropertyName(compilerOptions.target ?? 3)}: typeof __VLS_slots })>;\n`);
tsxCodeGen.addText('declare var __VLS_components: typeof __VLS_otherComponents & Omit<typeof __VLS_selfComponent, keyof typeof __VLS_otherComponents>;\n');
tsxCodeGen.addText(`__VLS_components.${SearchTexts.Components};\n`);
tsxCodeGen.addText(`({} as __VLS_types.GlobalAttrs).${SearchTexts.GlobalAttrs};\n`);
/* Style Scoped */
tsxCodeGen.addText('/* Style Scoped */\n');
tsxCodeGen.addText('type __VLS_StyleScopedClasses = {}');
for (const scopedCss of cssScopedClasses.value) {
for (const classNameRange of scopedCss.classNameRanges) {
writeCssClassProperty(
scopedCss.index,
scopedCss.style.content.substring(classNameRange.start + 1, classNameRange.end),
classNameRange,
'boolean',
true,
);
}
}
tsxCodeGen.addText(';\n');
tsxCodeGen.addText('declare var __VLS_styleScopedClasses: __VLS_StyleScopedClasses | keyof __VLS_StyleScopedClasses | (keyof __VLS_StyleScopedClasses)[];\n');
tsxCodeGen.addText(`/* CSS variable injection */\n`);
writeCssVars();
if (templateCodeGens.value) {
mergeCodeGen(tsxCodeGen, templateCodeGens.value.codeGen);
}
tsxCodeGen.addText(`export default __VLS_slots;\n`);
const lang = scriptLang.value === 'js' ? 'jsx' : scriptLang.value === 'ts' ? 'tsx' : scriptLang.value;
const embeddedFile: EmbeddedFile = {
parentFileName: fileName + '.' + sfc.template?.lang,
fileName: fileName + '.__VLS_template.' + lang,
content: tsxCodeGen.getText(),
capabilities: {
diagnostics: true,
foldingRanges: false,
formatting: false,
documentSymbol: false,
codeActions: false,
inlayHints: true,
},
isTsHostFile: true,
mappings: tsxCodeGen.getMappings(),
};
return embeddedFile;
function writeImportTypes() {
const bindingsArr: {
typeBindings: { start: number, end: number; }[],
content: string,
}[] = [];
if (scriptSetupRanges.value && sfc.scriptSetup) {
bindingsArr.push({
typeBindings: scriptSetupRanges.value.typeBindings,
content: sfc.scriptSetup.content,
});
}
// if (scriptRanges.value && script.value) {
// bindingsArr.push({
// typeBindings: scriptRanges.value.typeBindings,
// content: script.value.content,
// });
// }
tsxCodeGen.addText('import {\n');
for (const bindings of bindingsArr) {
for (const typeBinding of bindings.typeBindings) {
const text = bindings.content.substring(typeBinding.start, typeBinding.end);
tsxCodeGen.addText(`__VLS_types_${text} as ${text},\n`);
}
}
tsxCodeGen.addText(`} from './${baseFileName}.__VLS_script';\n`);
}
function writeCssClassProperty(styleIndex: number, className: string, classRange: TextRange, propertyType: string, optional: boolean) {
tsxCodeGen.addText(`\n & { `);
tsxCodeGen.addMapping2({
mappedRange: {
start: tsxCodeGen.getText().length,
end: tsxCodeGen.getText().length + className.length + 2,
},
sourceRange: classRange,
mode: SourceMaps.Mode.Totally,
additional: [{
mappedRange: {
start: tsxCodeGen.getText().length + 1, // + '
end: tsxCodeGen.getText().length + 1 + className.length,
},
sourceRange: classRange,
mode: SourceMaps.Mode.Offset,
}],
data: {
vueTag: 'style',
vueTagIndex: styleIndex,
capabilities: {
references: true,
rename: true,
referencesCodeLens: true,
},
normalizeNewName: beforeCssRename,
applyNewName: doCssRename,
},
});
tsxCodeGen.addText(`'${className}'${optional ? '?' : ''}: ${propertyType}`);
tsxCodeGen.addText(` }`);
}
function writeCssVars() {
const emptyLocalVars: Record<string, number> = {};
const identifiers = new Set<string>();
for (const cssVar of cssVars.value) {
for (const cssBind of cssVar.ranges) {
walkInterpolationFragment(
ts,
cssVar.style.content.substring(cssBind.start, cssBind.end),
(frag, fragOffset, isJustForErrorMapping) => {
if (fragOffset === undefined) {
tsxCodeGen.addText(frag);
}
else {
tsxCodeGen.addCode(
frag,
{
start: cssBind.start + fragOffset,
end: cssBind.start + fragOffset + frag.length,
},
SourceMaps.Mode.Offset,
{
vueTag: 'style',
vueTagIndex: cssVar.styleIndex,
capabilities: isJustForErrorMapping ? {
diagnostic: true,
} : {
basic: true,
references: true,
definitions: true,
diagnostic: true,
rename: true,
completion: true,
semanticTokens: true,
},
},
);
}
},
emptyLocalVars,
identifiers,
);
tsxCodeGen.addText(';\n');
}
}
}
}
else if (i === 1 && templateCodeGens.value) {
const lang = scriptLang.value === 'js' ? 'jsx' : scriptLang.value === 'ts' ? 'tsx' : scriptLang.value;
const embeddedFile: EmbeddedFile = {
parentFileName: fileName + '.' + sfc.template?.lang,
fileName: fileName + '.__VLS_template.format.' + lang,
content: templateCodeGens.value.formatCodeGen.getText(),
capabilities: {
diagnostics: false,
foldingRanges: false,
formatting: true,
documentSymbol: true,
codeActions: false,
inlayHints: false,
},
isTsHostFile: false,
mappings: templateCodeGens.value.formatCodeGen.getMappings(),
};
return embeddedFile;
}
else if (i === 2 && templateCodeGens.value) {
const file: EmbeddedFile = {
parentFileName: fileName + '.' + sfc.template?.lang,
fileName: fileName + '.template.css',
content: templateCodeGens.value.cssCodeGen.getText(),
capabilities: {
diagnostics: false,
foldingRanges: false,
formatting: false,
codeActions: false,
documentSymbol: false,
inlayHints: false,
},
isTsHostFile: false,
mappings: templateCodeGens.value.cssCodeGen.getMappings(),
};
return file;
}
},
};
}
function beforeCssRename(newName: string) {
return newName.startsWith('.') ? newName.slice(1) : newName;
}
function doCssRename(oldName: string, newName: string) {
return '.' + newName;
}