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): type support of slot children #5137

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 27 additions & 17 deletions packages/language-core/lib/codegen/globalTypes.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getSlotsPropertyName } from '../utils/shared';

export function generateGlobalTypes(lib: string, target: number, strictTemplates: boolean) {
const fnPropsType = `(K extends { $props: infer Props } ? Props : any)${strictTemplates ? '' : ' & Record<string, unknown>'}`;
const fnPropsType = `(T extends { $props: infer Props } ? Props : any)${strictTemplates ? '' : ' & Record<string, unknown>'}`;
let text = ``;
if (target < 3.5) {
text += `
Expand Down Expand Up @@ -40,7 +40,6 @@ export function generateGlobalTypes(lib: string, target: number, strictTemplates
type __VLS_GlobalDirectives = import('${lib}').GlobalDirectives;
type __VLS_IsAny<T> = 0 extends 1 & T ? true : false;
type __VLS_PickNotAny<A, B> = __VLS_IsAny<A> extends true ? B : A;
type __VLS_unknownDirective = (arg1: unknown, arg2: unknown, arg3: unknown, arg4: unknown) => void;
type __VLS_WithComponent<N0 extends string, LocalComponents, Self, N1 extends string, N2 extends string, N3 extends string> =
N1 extends keyof LocalComponents ? N1 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N1] } :
N2 extends keyof LocalComponents ? N2 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N2] } :
Expand All @@ -50,10 +49,30 @@ export function generateGlobalTypes(lib: string, target: number, strictTemplates
N2 extends keyof __VLS_GlobalComponents ? N2 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N2] } :
N3 extends keyof __VLS_GlobalComponents ? N3 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N3] } :
${strictTemplates ? '{}' : '{ [K in N0]: unknown }'};
type __VLS_FunctionalComponentProps<T, K> =
'__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: { props?: infer P } } ? NonNullable<P> : never
: T extends (props: infer P, ...args: any) => any ? P :
{};
type __VLS_FunctionalComponentCtx<T, K> = __VLS_PickNotAny<'__ctx' extends keyof __VLS_PickNotAny<K, {}>
? K extends { __ctx?: infer Ctx } ? NonNullable<Ctx> : never : any
, T extends (props: any, ctx: infer Ctx) => any ? Ctx : any
>;
type __VLS_FunctionalComponentProps<T, K> = '__ctx' extends keyof __VLS_PickNotAny<K, {}>
? K extends { __ctx?: { props?: infer P } } ? NonNullable<P> : never
: T extends (props: infer P, ...args: any) => any ? P
: {};
type __VLS_FunctionalGeneralComponent<T> = (props: ${fnPropsType}, ctx?: any) => __VLS_Element & {
__ctx?: {
attrs?: any,
slots?: T extends { ${getSlotsPropertyName(target)}: infer Slots } ? Slots : any,
emit?: T extends { $emit: infer Emit } ? Emit : any,
props?: ${fnPropsType},
expose?(exposed: T): void,
}
};
type __VLS_NormalizeSlotReturns<S, R = ReturnType<NonNullable<S>>> = R extends any[] ? {
[K in keyof R]: R[K] extends infer V
? V extends { __ctx?: any } ? V
: V extends import('${lib}').VNode<infer E> ? E
: ReturnType<__VLS_FunctionalGeneralComponent<V>>
: never
} : R;
type __VLS_IsFunction<T, K> = K extends keyof T
? __VLS_IsAny<T[K]> extends false
? unknown extends T[K]
Expand Down Expand Up @@ -94,10 +113,6 @@ export function generateGlobalTypes(lib: string, target: number, strictTemplates
>
>;
type __VLS_PrettifyGlobal<T> = { [K in keyof T]: T[K]; } & {};
type __VLS_PickFunctionalComponentCtx<T, K> = NonNullable<__VLS_PickNotAny<
'__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: infer Ctx } ? Ctx : never : any
, T extends (props: any, ctx: infer Ctx) => any ? Ctx : any
>>;
type __VLS_UseTemplateRef<T> = Readonly<import('${lib}').ShallowRef<T | null>>;

function __VLS_getVForSourceType(source: number): [number, number, number][];
Expand Down Expand Up @@ -131,16 +146,11 @@ export function generateGlobalTypes(lib: string, target: number, strictTemplates
? NonNullable<T['created' | 'beforeMount' | 'mounted' | 'beforeUpdate' | 'updated' | 'beforeUnmount' | 'unmounted']>
: T extends (...args: any) => any
? T
: __VLS_unknownDirective;
: (arg1: unknown, arg2: unknown, arg3: unknown, arg4: unknown) => void;
function __VLS_withScope<T, K>(ctx: T, scope: K): ctx is T & K;
function __VLS_makeOptional<T>(t: T): { [K in keyof T]?: T[K] };
function __VLS_asFunctionalComponent<T, K = T extends new (...args: any) => any ? InstanceType<T> : unknown>(t: T, instance?: K):
T extends new (...args: any) => any
? (props: ${fnPropsType}, ctx?: any) => __VLS_Element & { __ctx?: {
attrs?: any,
slots?: K extends { ${getSlotsPropertyName(target)}: infer Slots } ? Slots : any,
emit?: K extends { $emit: infer Emit } ? Emit : any
} & { props?: ${fnPropsType}; expose?(exposed: K): void; } }
T extends new (...args: any) => any ? __VLS_FunctionalGeneralComponent<K>
: T extends () => any ? (props: {}, ctx?: any) => ReturnType<T>
: T extends (...args: any) => any ? T
: (_: {}${strictTemplates ? '' : ' & Record<string, unknown>'}, ctx?: any) => { __ctx?: { attrs?: any, expose?: any, slots?: any, emit?: any, props?: {}${strictTemplates ? '' : ' & Record<string, unknown>'} } };
Expand Down
5 changes: 5 additions & 0 deletions packages/language-core/lib/codegen/template/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ export function createTemplateCodegenContext(options: Pick<TemplateCodegenOption
templateRefs,
currentComponent: undefined as {
ctxVar: string;
childNodes: {
name: string;
start: number;
end: number;
}[];
used: boolean;
} | undefined,
singleRootElType: undefined as string | undefined,
Expand Down
29 changes: 18 additions & 11 deletions packages/language-core/lib/codegen/template/element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,21 @@ export function* generateComponent(
const matchImportName = possibleOriginalNames.find(name => options.scriptSetupImportComponentNames.has(name));
const var_originalComponent = matchImportName ?? ctx.getInternalVariable();
const var_functionalComponent = ctx.getInternalVariable();
const var_componentInstance = ctx.getInternalVariable();
const var_componentVnode = ctx.getInternalVariable();
const var_componentEmit = ctx.getInternalVariable();
const var_componentEvents = ctx.getInternalVariable();
const var_defineComponentCtx = ctx.getInternalVariable();
const isComponentTag = node.tag.toLowerCase() === 'component';

ctx.currentComponent?.childNodes.push({
name: var_componentVnode,
start: node.loc.start.offset,
end: node.loc.end.offset
});
ctx.currentComponent = {
ctxVar: var_defineComponentCtx,
used: false
used: false,
childNodes: []
};

let props = node.props;
Expand Down Expand Up @@ -227,7 +233,7 @@ export function* generateComponent(
},
}
},
var_componentInstance
var_componentVnode
);
yield ` = ${var_functionalComponent}`;
yield* generateComponentGeneric(ctx);
Expand Down Expand Up @@ -268,7 +274,7 @@ export function* generateComponent(
}
}

const usedComponentEventsVar = yield* generateElementEvents(options, ctx, node, var_functionalComponent, var_componentInstance, var_componentEvents);
const usedComponentEventsVar = yield* generateElementEvents(options, ctx, node, var_functionalComponent, var_componentVnode, var_componentEvents);
if (usedComponentEventsVar) {
ctx.currentComponent.used = true;
yield `let ${var_componentEmit}!: typeof ${var_defineComponentCtx}.emit${endOfLine}`;
Expand All @@ -282,15 +288,10 @@ export function* generateComponent(
}

const slotDir = node.props.find(p => p.type === CompilerDOM.NodeTypes.DIRECTIVE && p.name === 'slot') as CompilerDOM.DirectiveNode;
if (slotDir) {
yield* generateVSlot(options, ctx, node, slotDir);
}
else {
yield* generateElementChildren(options, ctx, node, true);
}
yield* generateVSlot(options, ctx, node, slotDir);

if (ctx.currentComponent.used) {
yield `var ${var_defineComponentCtx}!: __VLS_PickFunctionalComponentCtx<typeof ${var_originalComponent}, typeof ${var_componentInstance}>${endOfLine}`;
yield `var ${var_defineComponentCtx}!: __VLS_FunctionalComponentCtx<typeof ${var_originalComponent}, typeof ${var_componentVnode}>${endOfLine}`;
}
}

Expand All @@ -306,6 +307,12 @@ export function* generateElement(
: undefined;
const failedPropExps: FailedPropExpression[] = [];

ctx.currentComponent?.childNodes.push({
name: `__VLS_nativeElements.${node.tag}`,
start: node.loc.start.offset,
end: node.loc.end.offset
});

yield `__VLS_asFunctionalElement(__VLS_intrinsicElements`;
yield* generatePropertyAccess(
options,
Expand Down
22 changes: 1 addition & 21 deletions packages/language-core/lib/codegen/template/elementChildren.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import * as CompilerDOM from '@vue/compiler-dom';
import type { Code } from '../../types';
import { endOfLine, wrapWith } from '../utils';
import type { TemplateCodegenContext } from './context';
import type { TemplateCodegenOptions } from './index';
import { generateTemplateChild } from './templateChild';

export function* generateElementChildren(
options: TemplateCodegenOptions,
ctx: TemplateCodegenContext,
node: CompilerDOM.ElementNode,
isDefaultSlot: boolean = false
node: CompilerDOM.ElementNode
): Generator<Code> {
yield* ctx.resetDirectiveComments('end of element children start');
let prev: CompilerDOM.TemplateChildNode | undefined;
Expand All @@ -18,22 +16,4 @@ export function* generateElementChildren(
prev = childNode;
}
yield* ctx.generateAutoImportCompletion();

// fix https://github.com/vuejs/language-tools/issues/932
if (
ctx.currentComponent
&& isDefaultSlot
&& node.children.length
&& node.tagType === CompilerDOM.ElementTypes.COMPONENT
) {
ctx.currentComponent.used = true;
yield `${ctx.currentComponent.ctxVar}.slots!.`;
yield* wrapWith(
node.children[0].loc.start.offset,
node.children[node.children.length - 1].loc.end.offset,
ctx.codeFeatures.navigation,
`default`
);
yield endOfLine;
}
}
8 changes: 4 additions & 4 deletions packages/language-core/lib/codegen/template/elementEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function* generateElementEvents(
ctx: TemplateCodegenContext,
node: CompilerDOM.ElementNode,
componentVar: string,
componentInstanceVar: string,
componentVnodeVar: string,
eventsVar: string
): Generator<Code, boolean> {
let usedComponentEventsVar = false;
Expand All @@ -29,7 +29,7 @@ export function* generateElementEvents(
usedComponentEventsVar = true;
if (!propsVar) {
propsVar = ctx.getInternalVariable();
yield `let ${propsVar}!: __VLS_FunctionalComponentProps<typeof ${componentVar}, typeof ${componentInstanceVar}>${endOfLine}`;
yield `let ${propsVar}!: __VLS_FunctionalComponentProps<typeof ${componentVar}, typeof ${componentVnodeVar}>${endOfLine}`;
}
let source = prop.arg.loc.source;
let start = prop.arg.loc.start.offset;
Expand All @@ -41,11 +41,11 @@ export function* generateElementEvents(
propPrefix = 'onVnode';
emitPrefix = 'vnode-';
}
yield `const ${ctx.getInternalVariable()}: __VLS_NormalizeComponentEvent<typeof ${propsVar}, typeof ${eventsVar}, '${camelize(propPrefix + '-' + source)}', '${emitPrefix}${source}', '${camelize(emitPrefix + source)}'> = {${newLine}`;
yield `(): __VLS_NormalizeComponentEvent<typeof ${propsVar}, typeof ${eventsVar}, '${camelize(propPrefix + '-' + source)}', '${emitPrefix}${source}', '${camelize(emitPrefix + source)}'> => ({${newLine}`;
yield* generateEventArg(ctx, source, start, propPrefix);
yield `: `;
yield* generateEventExpression(options, ctx, prop);
yield `}${endOfLine}`;
yield `})${endOfLine}`;
}
}
return usedComponentEventsVar;
Expand Down
5 changes: 2 additions & 3 deletions packages/language-core/lib/codegen/template/elementProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,16 +138,15 @@ export function* generateElementProps(
propName
)
),
`: (`,
`: `,
...generatePropExp(
options,
ctx,
prop,
prop.exp,
ctx.codeFeatures.all,
enableCodeFeatures
),
`)`
)
);
if (enableCodeFeatures) {
yield* codes;
Expand Down
Loading
Loading