/
useSfcTemplateScript.ts
431 lines (408 loc) · 13.7 KB
/
useSfcTemplateScript.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
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
import { CodeGen, createCodeGen, margeCodeGen } from '@volar/code-gen';
import * as shared from '@volar/shared';
import { computed, ref, Ref } from '@vue/reactivity';
import * as upath from 'upath';
import type * as css from 'vscode-css-languageservice';
import { TextDocument } from 'vscode-languageserver-textdocument';
import * as templateGen from '../generators/template';
import * as cssClasses from '../parsers/cssClasses';
import { IDescriptor, ITemplateScriptData, LanguageServiceContext } from '../types';
import * as SourceMaps from '../utils/sourceMaps';
import { SearchTexts } from '../utils/string';
export function useSfcTemplateScript(
getUnreactiveDoc: () => TextDocument,
template: Ref<IDescriptor['template']>,
styles: Ref<IDescriptor['styles']>,
templateScriptData: ITemplateScriptData,
styleDocuments: Ref<{
textDocument: TextDocument;
stylesheet: css.Stylesheet | undefined;
links: {
textDocument: TextDocument;
stylesheet: css.Stylesheet;
}[];
module: string | undefined;
scoped: boolean;
}[]>,
styleSourceMaps: Ref<SourceMaps.CssSourceMap[]>,
templateData: Ref<{
sourceLang: 'html' | 'pug',
html: string,
htmlToTemplate: (start: number, end: number) => number | undefined,
} | undefined>,
sfcTemplateCompileResult: ReturnType<(typeof import('./useSfcTemplateCompileResult'))['useSfcTemplateCompileResult']>,
sfcStyles: ReturnType<(typeof import('./useSfcStyles'))['useSfcStyles']>['textDocuments'],
context: LanguageServiceContext,
) {
let version = 0;
const _vueDoc = getUnreactiveDoc();
const vueUri = _vueDoc.uri;
const vueFileName = upath.basename(shared.uriToFsPath(_vueDoc.uri));
const cssModuleClasses = computed(() =>
styleDocuments.value.reduce((map, style) => {
if (style.module) {
map.set(style.module, cssClasses.parse(context.modules.css, [style], context));
}
return map;
}, new Map<string, ReturnType<typeof cssClasses.parse>>())
);
const cssScopedClasses = computed(() => cssClasses.parse(context.modules.css, styleDocuments.value.filter(style => style.scoped), context));
const templateCodeGens = computed(() => {
if (!templateData.value)
return;
if (!sfcTemplateCompileResult.value?.ast)
return;
return templateGen.generate(
templateData.value.sourceLang,
sfcTemplateCompileResult.value.ast,
context.isVue2Mode,
templateScriptData.components,
templateScriptData.setupReturns,
[...cssScopedClasses.value.values()].map(map => [...map.keys()]).flat(),
templateData.value.htmlToTemplate,
);
});
const data = computed(() => {
const codeGen = createCodeGen<SourceMaps.TsMappingData>();
codeGen.addText(`import { __VLS_options, __VLS_name, __VLS_component } from './${vueFileName}';\n`);
codeGen.addText(`declare var __VLS_ctxRaw: InstanceType<typeof __VLS_component>;\n`);
codeGen.addText(`declare var __VLS_ctx: __VLS_ExtractRawComponents<typeof __VLS_ctxRaw>;\n`);
codeGen.addText(`declare var __VLS_vmUnwrap: typeof __VLS_options & { components: { } };\n`);
/* Components */
codeGen.addText('/* Components */\n');
codeGen.addText('declare var __VLS_ownComponent: __VLS_SelfComponent<typeof __VLS_name, typeof __VLS_component & { __VLS_raw: typeof __VLS_component, __VLS_options: typeof __VLS_options, __VLS_slots: typeof __VLS_slots }>;\n');
codeGen.addText('declare var __VLS_components_0: __VLS_GlobalComponents & typeof __VLS_vmUnwrap.components & __VLS_PickComponents<typeof __VLS_ctxRaw> & typeof __VLS_ownComponent;\n'); // has __VLS_options
codeGen.addText('declare var __VLS_components: __VLS_ExtractRawComponents<__VLS_GlobalComponents> & __VLS_ExtractRawComponents<typeof __VLS_vmUnwrap.components> & __VLS_ExtractRawComponents<__VLS_PickComponents<typeof __VLS_ctxRaw>> & __VLS_ExtractRawComponents<typeof __VLS_ownComponent> & JSX.IntrinsicElements;\n'); // sort by priority
codeGen.addText('declare var __VLS_componentPropsBase: __VLS_MapPropsTypeBase<typeof __VLS_components>;\n');
codeGen.addText('declare var __VLS_componentProps: __VLS_MapPropsType<typeof __VLS_components>;\n');
codeGen.addText('declare var __VLS_componentEmits: __VLS_MapEmitType<typeof __VLS_components>;\n');
if (templateCodeGens.value) {
/* Completion */
codeGen.addText(`({} as __VLS_GlobalAttrs).${SearchTexts.GlobalAttrs};\n`);
codeGen.addText('/* Completion: Emits */\n');
for (const name of templateCodeGens.value.usedComponents) {
codeGen.addText(`// @ts-ignore\n`);
codeGen.addText(`__VLS_componentEmits['${name}']('');\n`); // TODO
}
codeGen.addText('/* Completion: Props */\n');
for (const name of templateCodeGens.value.usedComponents) {
codeGen.addText(`// @ts-ignore\n`);
codeGen.addText(`__VLS_componentPropsBase['${name}'][''];\n`); // TODO
}
}
/* CSS Module */
codeGen.addText('/* CSS Module */\n');
const cssModuleMappingsArr: ReturnType<typeof writeCssClassProperties>[] = [];
for (const [moduleName, moduleClasses] of cssModuleClasses.value) {
codeGen.addText(`declare var ${moduleName}: Record<string, string> & {\n`);
cssModuleMappingsArr.push(writeCssClassProperties(moduleClasses, true));
codeGen.addText('};\n');
}
/* Style Scoped */
codeGen.addText('/* Style Scoped */\n');
codeGen.addText('declare var __VLS_styleScopedClasses: {\n');
const cssScopedMappings = writeCssClassProperties(cssScopedClasses.value, true);
codeGen.addText('};\n');
/* Props */
codeGen.addText(`/* Props */\n`);
const ctxMappings = writeProps();
codeGen.addText(`/* CSS variable injection */\n`);
writeCssVars();
if (templateCodeGens.value) {
margeCodeGen(codeGen as CodeGen, templateCodeGens.value.codeGen as CodeGen);
}
return {
...codeGen,
cssModuleMappingsArr,
cssScopedMappings,
ctxMappings,
};
function writeCssClassProperties(data: Map<string, Map<string, Set<[number, number]>>>, patchRename: boolean) {
const mappings = new Map<string, {
tsRange: {
start: number,
end: number,
},
cssRanges: {
start: number,
end: number,
}[],
mode: SourceMaps.Mode,
patchRename: boolean,
}[]>();
for (const [uri, classes] of data) {
if (!mappings.has(uri)) {
mappings.set(uri, []);
}
for (const [className, ranges] of classes) {
mappings.get(uri)!.push({
tsRange: {
start: codeGen.getText().length + 1, // + '
end: codeGen.getText().length + 1 + className.length,
},
cssRanges: [...ranges].map(range => ({
start: range[0],
end: range[1],
})),
mode: SourceMaps.Mode.Offset,
patchRename,
});
mappings.get(uri)!.push({
tsRange: {
start: codeGen.getText().length,
end: codeGen.getText().length + className.length + 2,
},
cssRanges: [...ranges].map(range => ({
start: range[0],
end: range[1],
})),
mode: SourceMaps.Mode.Totally,
patchRename,
});
codeGen.addText(`'${className}': string,\n`);
}
}
return mappings;
}
function writeProps() {
const propsSet = new Set(templateScriptData.props);
const mappings: SourceMaps.Mapping<SourceMaps.TeleportMappingData>[] = [];
for (const propName of templateScriptData.context) {
codeGen.addText(`declare var `);
const templateSideRange = codeGen.addText(propName);
codeGen.addText(`: typeof __VLS_ctx.`);
const scriptSideRange = codeGen.addText(propName);
codeGen.addText(`;`);
mappings.push({
data: {
isAdditionalReference: false,
toSource: {
capabilities: {
definitions: true,
references: true,
rename: true,
},
},
toTarget: {
capabilities: {
definitions: true,
references: true,
rename: true,
},
},
},
mode: SourceMaps.Mode.Offset,
sourceRange: scriptSideRange,
mappedRange: templateSideRange,
});
if (propsSet.has(propName)) {
codeGen.addText(` __VLS_options.props.`);
const scriptSideRange2 = codeGen.addText(propName);
codeGen.addText(`;`);
mappings.push({
data: {
isAdditionalReference: true,
toSource: {
capabilities: {
definitions: true,
references: true,
rename: true,
},
},
toTarget: {
capabilities: {
definitions: true,
references: true,
rename: true,
},
},
},
mode: SourceMaps.Mode.Offset,
sourceRange: scriptSideRange2,
mappedRange: templateSideRange,
});
}
codeGen.addText(`\n`);
}
return mappings;
}
function writeCssVars() {
for (let i = 0; i < sfcStyles.value.length; i++) {
const style = sfcStyles.value[i];
const docText = style.textDocument.getText();
for (const cssBind of style.binds) {
const bindText = docText.substring(cssBind.start, cssBind.end);
codeGen.addCode(
bindText,
cssBind,
SourceMaps.Mode.Offset,
{
vueTag: 'style',
vueTagIndex: i,
capabilities: {
basic: true,
references: true,
definitions: true,
diagnostic: true,
rename: true,
completion: true,
semanticTokens: true,
},
},
);
codeGen.addText(';\n');
}
}
}
});
const sourceMap = computed(() => {
if (textDoc.value) {
const vueDoc = getUnreactiveDoc();
const sourceMap = new SourceMaps.TsSourceMap(
vueDoc,
textDoc.value,
'template',
true,
{
foldingRanges: false,
formatting: false,
documentSymbol: false,
codeActions: false,
},
data.value.getMappings(parseMappingSourceRange),
);
for (const [uri, mappings] of [
...data.value.cssModuleMappingsArr.flatMap(m => [...m]),
...data.value.cssScopedMappings,
]) {
const cssSourceMap = styleSourceMaps.value.find(sourceMap => sourceMap.mappedDocument.uri === uri);
if (!cssSourceMap) continue;
for (const maped of mappings) {
const tsRange = maped.tsRange;
for (const cssRange of maped.cssRanges) {
const vueRange = cssSourceMap.getSourceRange2(cssRange.start, cssRange.end);
if (!vueRange) continue;
sourceMap.add({
data: {
vueTag: 'style',
capabilities: {
references: true,
rename: true,
referencesCodeLens: maped.mode === SourceMaps.Mode.Totally, // has 2 modes
},
beforeRename: maped.patchRename ? beforeCssRename : undefined,
doRename: maped.patchRename ? doCssRename : undefined,
},
mode: maped.mode,
sourceRange: vueRange,
mappedRange: tsRange,
});
}
}
}
return sourceMap;
}
});
const formatSourceMap = computed(() => {
if (templateCodeGens.value && formatTextDoc.value && template.value) {
const vueDoc = getUnreactiveDoc();
const sourceMap = new SourceMaps.TsSourceMap(
vueDoc,
formatTextDoc.value,
'template',
true,
{
foldingRanges: false,
formatting: true,
documentSymbol: false,
codeActions: false,
},
templateCodeGens.value.formatCodeGen.getMappings(parseMappingSourceRange),
);
return sourceMap;
}
});
const cssTextDocument = computed(() => {
if (templateCodeGens.value && template.value) {
const textDocument = TextDocument.create(vueUri + '.template.css', 'css', 0, templateCodeGens.value.cssCodeGen.getText());
const stylesheet = context.getCssLs('css')!.parseStylesheet(textDocument);
return {
textDocument,
stylesheet,
links: [],
module: false,
scoped: false,
};
}
});
const cssSourceMap = computed(() => {
if (templateCodeGens.value && cssTextDocument.value && template.value) {
const vueDoc = getUnreactiveDoc();
const sourceMap = new SourceMaps.CssSourceMap(
vueDoc,
cssTextDocument.value.textDocument,
cssTextDocument.value.stylesheet,
undefined,
false,
[],
{ foldingRanges: false, formatting: false },
templateCodeGens.value.cssCodeGen.getMappings(parseMappingSourceRange),
);
return sourceMap;
}
});
const textDoc = ref<TextDocument>();
const formatTextDoc = ref<TextDocument>();
const teleportSourceMap = ref<SourceMaps.TeleportSourceMap>();
return {
templateCodeGens,
sourceMap,
textDocument: textDoc,
textDocumentForFormatting: formatTextDoc,
sourceMapForFormatting: formatSourceMap,
teleportSourceMap,
cssTextDocument,
cssSourceMap,
update, // TODO: cheapComputed
};
function parseMappingSourceRange(data: any, range: SourceMaps.Range) {
if (data.vueTag === 'style' && data.vueTagIndex !== undefined) {
return {
start: styles.value[data.vueTagIndex].loc.start + range.start,
end: styles.value[data.vueTagIndex].loc.start + range.end,
};
}
const templateOffset = template.value?.loc.start ?? 0;
return {
start: templateOffset + range.start,
end: templateOffset + range.end,
};
}
function update() {
if (data.value.getText() !== textDoc.value?.getText()) {
if (data.value) {
const _version = version++;
textDoc.value = TextDocument.create(vueUri + '.__VLS_template.ts', shared.syntaxToLanguageId('ts'), _version, data.value.getText());
formatTextDoc.value = templateCodeGens.value
? TextDocument.create(vueUri + '.__VLS_template.format.ts', shared.syntaxToLanguageId('ts'), _version, templateCodeGens.value.formatCodeGen.getText())
: undefined;
const sourceMap = new SourceMaps.TeleportSourceMap(textDoc.value, true);
for (const maped of data.value.ctxMappings) {
sourceMap.add(maped);
}
teleportSourceMap.value = sourceMap;
}
else {
textDoc.value = undefined;
teleportSourceMap.value = undefined;
formatTextDoc.value = undefined;
}
}
}
}
function beforeCssRename(newName: string) {
return newName.startsWith('.') ? newName.substr(1) : newName;
}
function doCssRename(oldName: string, newName: string) {
return '.' + newName;
}