feat: handle nested defineEmits
I'm not sure whether this is a fix or a feature.
This PR allows calling defineEmits as an argument of another method.
const transformed = transform(defineEmits(['foo', 'bar']));
My Usecase
const { foo, bar } = splitEmitFunctions(defineEmits(['foo', 'bar']));
foo(); // equivalent to emit('foo') including correct argument typing
splitEmitFunctions definition
import { getCurrentInstance } from 'vue';
type EmitterOverloads<T extends (event: string, ...args: unknown[]) => void> =
T extends {
(event: infer N0, ...args: infer A0): void;
(event: infer N1, ...args: infer A1): void;
(event: infer N2, ...args: infer A2): void;
(event: infer N3, ...args: infer A3): void;
(event: infer N4, ...args: infer A4): void;
(event: infer N5, ...args: infer A5): void;
(event: infer N6, ...args: infer A6): void;
(event: infer N7, ...args: infer A7): void;
(event: infer N8, ...args: infer A8): void;
(event: infer N9, ...args: infer A9): void;
}
? [
[N0, (...args: A0) => void],
[N1, N0 extends N1 ? never : (...args: A1) => void],
[N2, N1 extends N2 ? never : (...args: A2) => void],
[N3, N2 extends N3 ? never : (...args: A3) => void],
[N4, N3 extends N4 ? never : (...args: A4) => void],
[N5, N4 extends N5 ? never : (...args: A5) => void],
[N6, N5 extends N6 ? never : (...args: A6) => void],
[N7, N6 extends N7 ? never : (...args: A7) => void],
[N8, N7 extends N8 ? never : (...args: A8) => void],
[N9, N8 extends N9 ? never : (...args: A9) => void],
]
: never;
type TupleToRecord<T extends ReadonlyArray<[string, unknown]>> = {
[K in T[number] as K[0]]: K[1];
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function splitEmitFunctions<T extends (...args: any) => void>(
emit: T
): TupleToRecord<EmitterOverloads<T>> {
const instance = getCurrentInstance();
if (!instance) {
throw new Error('splitEmitFunctions must be called within setup()');
}
return new Proxy(
{},
{
get(_, key: string) {
return (...args: unknown[]) => emit(key, ...args);
},
}
) as TupleToRecord<EmitterOverloads<T>>;
}
Without this patch, you have to use the following code:
const emit = defineEmits(['foo', 'bar']); // This must be on a separate line
const { foo, bar } = splitEmitFunctions(emit);
foo();
poluting the scope with the emit variable, that shouldn't be used after this.
[!IMPORTANT]
Review skipped
Auto reviews are disabled on base/target branches other than the default branch.
Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.
🪧 Tips
Chat
There are 3 ways to chat with CodeRabbit:
- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
I pushed a fix in commit <commit_id>, please review it.Generate unit testing code for this file.Open a follow-up GitHub issue for this discussion.
- Files and specific lines of code (under the "Files changed" tab): Tag
@coderabbitaiin a new review comment at the desired location with your query. Examples:@coderabbitai generate unit testing code for this file.@coderabbitai modularize this function.
- PR comments: Tag
@coderabbitaiin a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:@coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.@coderabbitai read src/utils.ts and generate unit testing code.@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.@coderabbitai help me debug CodeRabbit configuration file.
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.
CodeRabbit Commands (Invoked using PR comments)
@coderabbitai pauseto pause the reviews on a PR.@coderabbitai resumeto resume the paused reviews.@coderabbitai reviewto trigger an incremental review. This is useful when automatic reviews are disabled for the repository.@coderabbitai full reviewto do a full review from scratch and review all the files again.@coderabbitai summaryto regenerate the summary of the PR.@coderabbitai generate docstringsto generate docstrings for this PR.@coderabbitai generate sequence diagramto generate a sequence diagram of the changes in this PR.@coderabbitai resolveresolve all the CodeRabbit review comments.@coderabbitai configurationto show the current CodeRabbit configuration for the repository.@coderabbitai helpto get help.
Other keywords and placeholders
- Add
@coderabbitai ignoreanywhere in the PR description to prevent this PR from being reviewed. - Add
@coderabbitai summaryto generate the high-level summary at a specific location in the PR description. - Add
@coderabbitaianywhere in the PR title to generate the title automatically.
CodeRabbit Configuration File (.coderabbit.yaml)
- You can programmatically configure CodeRabbit by adding a
.coderabbit.yamlfile to the root of your repository. - Please see the configuration documentation for more information.
- If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation:
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
Documentation and Community
- Visit our Documentation for detailed information on how to use CodeRabbit.
- Join our Discord Community to get help, request features, and share feedback.
- Follow us on X/Twitter for updates and announcements.
Can you provide more context? What was emit not able to achieve at the moment? Calling emit directly looks more explicit and easier to understand to me.
@Justineo My request is not about emit but defineEmits.
Basically, I want defineEmits() to behave like an actual function call (or more specifically the transpiled property __emit) and not like a special thing that only works when used with const emit = defineEmits().
Neglible: Also I don't like the empty assignment in the compiled code const emit = __emit; especially since I don't want emit variable in the first place.
As for splitEmitFunctions:
I prefer individual event functions to keep the usage symetrical between the publishing side and the consumer side:
ComponentA:
const { onValidChanged } = splitEmitFunctions(defineEmits<{ onValidChanged: [valid: boolean] }>());
// const emit = defineEmits<{ onValidChanged: [valid: boolean] }>();
// const onValidChanged: (valid : boolean) => void = (value) => emit('onValidChanged ', value);
watch(valid, (value) -> onValidChanged(value))
ComponentB:
<script setup lang="ts">
const onValidChanged: (valid: boolean) => void = (value) => continue.disabled = value;
</script>
<template>
<ComponentA @onValidChanged="onValidChanged" />
</template>
So that: ComponentA's onValidChanged has the same type as ComponentB's onValidChanged:
ComponentA:
const { onValidChanged } = splitEmitFunctions(defineEmits<{ onValidChanged: OnValueChanged }>());
ComponentB:
<script setup lang="ts">
const onValidChanged: OnValueChanged = (value) => continue.disabled = value;
</script>
But you could also use it for different usecases such as simplified debug logging:
function logToConsole<T>(emit: T): T {
return (...args) => {
console.log("Event", ...args);
emit(...args);
}
}
const emit = logToConsole(defineEmits<{ onValidChanged: [valid: boolean] }>());
watch(valid, (value) -> emit('onValidChanged ', value))
Here a link with a simple demonstration of the change:
https://deploy-preview-13262--vue-sfc-playground.netlify.app/#eNp9UsFO4zAQ/ZWRL021KN3V7glatLuoBzgAAm6YQ5ROiiEZW/a4VIry74wdWnJAnBLPe2/m+Y179c+5chdRnaplqL1xDAE5unNNpnPWM/TgsYEBGm87mAl1pklTbSkw4A6JL2wkhlWiFT/nZwltItVsLEGdsHVihQI7w3PoNYFQOXqCoizLym/DHFbnIwCTluWuaiP+WP2Slgn5EKU2R2GGhjPQNExcCUP8TGdvsDGEawFC8ThjDDx7mo9eR039XNEWRVVkM3nIyEus5WLMRlKRA2Pn2opRTgB9/+l4EBMAS0MuMvzNn5VWY2utFsJfLiZidaI4yPjGbMuXYEl2kEMQie2cadHfuJRi0Or0EI9WVdvat6tcYx/x5FCvn7F+/aL+EvapptWtx4B+J06OGEuIyCO8vr/Gvfwfwc5uYivsb8A7DLaNyeNI+x9pI7YnvOz2Mr8kQ9uHsN4zUjhcKhnNG8x8reR1XXxz9U+7v8s/WSd7V8M7TBPt3w==