Skip to content

feat: handle nested defineEmits #13262

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

Open
wants to merge 2 commits into
base: minor
Choose a base branch
from

Conversation

ST-DDT
Copy link

@ST-DDT ST-DDT commented Apr 30, 2025

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, A0 extends A1 ? never : (...args: A1) => void],
        [N2, A1 extends A2 ? never : (...args: A2) => void],
        [N3, A2 extends A3 ? never : (...args: A3) => void],
        [N4, A3 extends A4 ? never : (...args: A4) => void],
        [N5, A4 extends A5 ? never : (...args: A5) => void],
        [N6, A5 extends A6 ? never : (...args: A6) => void],
        [N7, A6 extends A7 ? never : (...args: A7) => void],
        [N8, A7 extends A8 ? never : (...args: A8) => void],
        [N9, A8 extends A9 ? 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.

Copy link

coderabbitai bot commented Apr 30, 2025

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.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in 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 @coderabbitai in 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 @coderabbitai in 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 pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file 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.

@ST-DDT ST-DDT marked this pull request as ready for review April 30, 2025 11:19
@Justineo
Copy link
Member

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.

@ST-DDT
Copy link
Author

ST-DDT commented Apr 30, 2025

@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))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants