Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(language-core): auto infer type for $refs & useTemplateRef #4644

Merged
merged 17 commits into from
Aug 25, 2024
Merged
Prev Previous commit
Next Next commit
feat: add template-ref
  • Loading branch information
zhiyuanzmj committed Aug 9, 2024
commit 31c8350966f3f477644f6f052ff5b06db8f10ea8
1 change: 1 addition & 0 deletions packages/language-core/lib/codegen/script/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export function* generateComponent(
if (options.sfc.script && options.scriptRanges) {
yield* generateScriptOptions(options.sfc.script, options.scriptRanges);
}
yield `__typeRefs: {} as __VLS_Refs,${newLine}`
yield `})`;
}

Expand Down
8 changes: 8 additions & 0 deletions packages/language-core/lib/codegen/script/globalTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,14 @@ declare global {
>
>;
type __VLS_PrettifyGlobal<T> = { [K in keyof T]: T[K]; } & {};
type __VLS_PickRefsExpose<T> = T extends object
? { [K in keyof T]: 'expose' extends keyof T[K]
// @ts-ignore
? Parameters<T[K]['expose']>[0] | null
: T[K] extends any[]
? Parameters<T[K][0]['expose']>[0][]
: T[K] }
: never;
}
export const __VLS_globalTypesEnd = {};
`;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export function* generateInternalComponent(
]) {
for (const expose of bindings) {
const varName = content.substring(expose.start, expose.end);
if (!templateUsageVars.has(varName) && !templateCodegenCtx.accessExternalVariables.has(varName)) {
if ((!templateUsageVars.has(varName) && !templateCodegenCtx.accessExternalVariables.has(varName)) || options.scriptSetupRanges.templateRefs.some(ref => ref.name == varName)) {
continue;
}
const templateOffset = options.getGeneratedLength();
Expand Down
22 changes: 20 additions & 2 deletions packages/language-core/lib/codegen/script/scriptSetup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export function* generateScriptSetup(
+ ` props: ${ctx.helperTypes.Prettify.name}<typeof __VLS_functionalComponentProps & __VLS_PublicProps> & __VLS_BuiltInPublicProps,${newLine}`
+ ` expose(exposed: import('${options.vueCompilerOptions.lib}').ShallowUnwrapRef<${scriptSetupRanges.expose.define ? 'typeof __VLS_exposed' : '{}'}>): void,${newLine}`
+ ` attrs: any,${newLine}`
+ ` slots: ReturnType<typeof __VLS_template>,${newLine}`
+ ` slots: ReturnType<typeof __VLS_template>['slots'],${newLine}`
+ ` emit: ${emitTypes.join(' & ')},${newLine}`
+ ` }${endOfLine}`;
yield ` })(),${newLine}`; // __VLS_setup = (async () => {
Expand Down Expand Up @@ -211,6 +211,11 @@ function* generateSetupFunction(
]);
}
}
for (const { define } of scriptSetupRanges.templateRefs) {
if (define?.arg) {
setupCodeModifies.push([[`<__VLS_Refs[${scriptSetup.content.slice(define.arg.start, define.arg.end)}], keyof __VLS_Refs>`], define.arg.start - 1, define.arg.start - 1]);
}
}
setupCodeModifies = setupCodeModifies.sort((a, b) => a[1] - b[1]);

if (setupCodeModifies.length) {
Expand Down Expand Up @@ -242,6 +247,8 @@ function* generateSetupFunction(

yield* generateComponentProps(options, ctx, scriptSetup, scriptSetupRanges, definePropMirrors);
yield* generateModelEmits(options, scriptSetup, scriptSetupRanges);
yield* generateRefsType(options, scriptSetupRanges);

yield* generateTemplate(options, ctx, false);

if (syntax) {
Expand All @@ -250,7 +257,7 @@ function* generateSetupFunction(
yield* generateComponent(options, ctx, scriptSetup, scriptSetupRanges);
yield endOfLine;
yield `${syntax} `;
yield `{} as ${ctx.helperTypes.WithTemplateSlots.name}<typeof __VLS_component, ReturnType<typeof __VLS_template>>${endOfLine}`;
yield `{} as ${ctx.helperTypes.WithTemplateSlots.name}<typeof __VLS_component, ReturnType<typeof __VLS_template>['slots']>${endOfLine}`;
}
else {
yield `${syntax} `;
Expand Down Expand Up @@ -423,3 +430,14 @@ function* generateDefinePropType(scriptSetup: NonNullable<Sfc['scriptSetup']>, p
yield `any`;
}
}

function* generateRefsType(options: ScriptCodegenOptions, scriptSetupRanges: ScriptSetupRanges) {
yield `type __VLS_TypeRefs = import('${options.vueCompilerOptions.lib}').UnwrapRef<{${newLine}`;
for (const { name } of scriptSetupRanges.templateRefs) {
if (name) {
yield `${name}: typeof ${name}${newLine}`;
}
}
yield `}>${newLine}`;
yield `type __VLS_Refs = ReturnType<typeof __VLS_template>['refs']${endOfLine}`;
}
8 changes: 6 additions & 2 deletions packages/language-core/lib/codegen/script/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ function* generateCtx(
}
yield `}`;
}
yield endOfLine;
yield ` & __VLS_TypeRefs & { $refs: __VLS_TypeRefs }${endOfLine}`;
}

function* generateTemplateContext(
Expand Down Expand Up @@ -154,10 +154,14 @@ function* generateTemplateContext(
yield `// no template${newLine}`;
if (!options.scriptSetupRanges?.slots.define) {
yield `const __VLS_slots = {}${endOfLine}`;
yield `const __VLS_refs = {}${endOfLine}`;
}
}

yield `return ${options.scriptSetupRanges?.slots.name ?? '__VLS_slots'}${endOfLine}`;
yield `return {${newLine}`;
yield `slots: ${options.scriptSetupRanges?.slots.name ?? '__VLS_slots'},${newLine}`;
yield `refs: __VLS_refs as __VLS_PickRefsExpose<typeof __VLS_refs>,${newLine}`;
yield `}${endOfLine}`;
}

function* generateCssClassProperty(
Expand Down
34 changes: 31 additions & 3 deletions packages/language-core/lib/codegen/template/element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,13 +258,26 @@ export function* generateComponent(
yield endOfLine;
}

yield* generateVScope(options, ctx, node, props);
const refName = yield* generateVScope(options, ctx, node, props);

ctx.usedComponentCtxVars.add(componentCtxVar);
const usedComponentEventsVar = yield* generateElementEvents(options, ctx, node, var_functionalComponent, var_componentInstance, var_componentEmit, var_componentEvents);

if (var_defineComponentCtx && ctx.usedComponentCtxVars.has(var_defineComponentCtx)) {
yield `const ${componentCtxVar} = __VLS_nonNullable(__VLS_pickFunctionalComponentCtx(${var_originalComponent}, ${var_componentInstance}))${endOfLine}`;
if (refName) {
yield `// @ts-ignore${newLine}`;
if (node.codegenNode?.type === CompilerDOM.NodeTypes.VNODE_CALL
&& node.codegenNode.props?.type === CompilerDOM.NodeTypes.JS_OBJECT_EXPRESSION
&& node.codegenNode.props.properties.find(({ key }) => key.type === CompilerDOM.NodeTypes.SIMPLE_EXPRESSION && key.content === 'ref_for')
) {
yield `(${refName} ??= []).push(${var_defineComponentCtx})`;
} else {
yield `${refName} = ${var_defineComponentCtx}`;
}

yield endOfLine;
}
}
if (usedComponentEventsVar) {
yield `let ${var_componentEmit}!: typeof ${componentCtxVar}.emit${endOfLine}`;
Expand Down Expand Up @@ -340,7 +353,17 @@ export function* generateElement(
yield endOfLine;
}

yield* generateVScope(options, ctx, node, node.props);
const refName = yield* generateVScope(options, ctx, node, node.props);
if (refName) {
yield `// @ts-ignore${newLine}`;
yield `${refName} = __VLS_intrinsicElements`;
yield* generatePropertyAccess(
options,
ctx,
node.tag
);
yield endOfLine;
}

const slotDir = node.props.find(p => p.type === CompilerDOM.NodeTypes.DIRECTIVE && p.name === 'slot') as CompilerDOM.DirectiveNode;
if (slotDir && componentCtxVar) {
Expand Down Expand Up @@ -380,13 +403,14 @@ function* generateVScope(
}

yield* generateElementDirectives(options, ctx, node);
yield* generateReferencesForElements(options, ctx, node); // <el ref="foo" />
const refName = yield* generateReferencesForElements(options, ctx, node); // <el ref="foo" />
yield* generateReferencesForScopedCssClasses(ctx, node);

if (inScope) {
yield `}${newLine}`;
ctx.blockConditions.length = originalConditionsNum;
}
return refName;
}

export function getCanonicalComponentName(tagText: string) {
Expand Down Expand Up @@ -554,6 +578,10 @@ function* generateReferencesForElements(
')'
);
yield endOfLine;

const refName = CompilerDOM.toValidAssetId(prop.value.content, '_VLS_refs' as any);
options.templateRefNames.set(prop.value.content, refName);
return refName;
}
}
}
Expand Down
14 changes: 14 additions & 0 deletions packages/language-core/lib/codegen/template/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export interface TemplateCodegenOptions {
template: NonNullable<Sfc['template']>;
scriptSetupBindingNames: Set<string>;
scriptSetupImportComponentNames: Set<string>;
templateRefNames: Map<string, string>;
hasDefineSlots?: boolean;
slotsAssignName?: string;
propsAssignName?: string;
Expand Down Expand Up @@ -45,8 +46,21 @@ export function* generateTemplate(options: TemplateCodegenOptions): Generator<Co

yield* ctx.generateAutoImportCompletion();

yield* generateRefs()

return ctx;

function* generateRefs(): Generator<Code>{
for (const [, validId] of options.templateRefNames) {
yield `let ${validId}${newLine}`;
}
yield `const __VLS_refs = {${newLine}`;
for (const [name, validId] of options.templateRefNames) {
yield `'${name}': ${validId}!,${newLine}`;
}
yield `}${endOfLine}`;
}

function* generateSlotsType(): Generator<Code> {
for (const { expVar, varName } of ctx.dynamicSlots) {
ctx.hasSlot = true;
Expand Down
13 changes: 11 additions & 2 deletions packages/language-core/lib/parsers/scriptSetupRanges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ export function parseScriptSetupRanges(
expose,
defineProp,
options,
templateRefs,
};

function _getStartEnd(node: ts.Node) {
Expand Down Expand Up @@ -293,9 +294,17 @@ export function parseScriptSetupRanges(
}
}
} else if (vueCompilerOptions.macros.templateRef.includes(callText)) {
const define = parseDefineFunction(node);
if (node.arguments.length) {
define.arg = _getStartEnd(node.arguments[0]);
}
let name;
if (ts.isVariableDeclaration(parent)) {
name = getNodeText(ts, parent.name, ast);
}
templateRefs.push({
name: ts.isVariableDeclaration(parent) ? getNodeText(ts, parent.name, ast) : undefined,
define: parseDefineFunction(node)
name,
define
});
}
}
Expand Down
1 change: 1 addition & 0 deletions packages/language-core/lib/plugins/vue-tsx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ function createTsx(
template: _sfc.template,
scriptSetupBindingNames: scriptSetupBindingNames(),
scriptSetupImportComponentNames: scriptSetupImportComponentNames(),
templateRefNames: new Map(),
hasDefineSlots: hasDefineSlots(),
slotsAssignName: slotsAssignName(),
propsAssignName: propsAssignName(),
Expand Down
Loading
Loading